fix(m190): r1 复审——0x01 修成 \1 + YAML 门禁、被调方声明 secret、拆两个超限测试文件、验签换 ed25519-dalek
四条 P1 + 四条 P2 一并处置(不变的是判据,变的是「谁在承重」)。
P1-1 `.github/workflows/release-build.yml` 的 sed 替换串是裸 0x01(本意 `\1`):GitHub 解析该文件会
失败 ⇒ 整个 run 起不来;即便容忍,版本号也会被求值成单字节,PE 判据报「与 Cargo.toml 不同源?」把
排障引向错方向。修成字面 `\1`,并新增 `packaging/check_workflows_yaml.py`(真 YAML 解析器 parse
全部 workflow + 裸 C0 控制字符字节判据;带 --self-test 注入 0x01/坏结构断言必红),接进
`release-guard.yml` 两步。文本扫描型守卫看不见这类字节,这道门禁专门挡它。
P1-2 `release-publish.yml` 没在 `on.workflow_call.secrets` 里声明 `ULL_MANIFEST_SIGNING_KEY`,调用方
却传了:可复用工作流只拿得到自己声明过的 secret ⇒ 用户配好钥也会在签名步红,而错误文案反过来指控
Secret 没配。补声明(required: false,fail-closed 由步内 ::error:: + exit 1 承担,同
ULL_MSA_CLIENT_ID 的模式)。
P1-3 两个测试支撑文件越过 400 行守卫:签名夹具拆到 `tests/support_sign.rs`(support.rs 458→392),
CLI e2e 的签名部分拆到 `support/update_e2e_sign.rs`(update_e2e.rs 406→348)。纯搬家。
P2-2 「唯一收口点」改成结构事实:从 `UpdateSource` 删掉 `fetch_manifest` 默认实现,调用方只能拿
`verified_manifest(&source, channel)`(源只交原文,想绕过验签就得自己重写解析与渠道判据)。
P2-3 文档写的第 ④ 条命令补进流水线:`sign_manifest.py --verify-pinned` 用 trust.rs 里钉住的公钥
回验刚落盘的 .sig(不碰私钥),发布侧因此验证的是「客户端的判据」而不是「签名脚本的自我声明」。
P2-4 随自写实现一起删除(`Fe` 的错误 PartialEq 不再存在)。
P2-5 app-iced/build.rs 注释里那个 windows_subsystem 属性本分支不存在(M196 才有),改为说明
「本文件只写版本资源,子系统由 rustc 属性决定,check_pe_version.py 会把 subsystem 打出来」。
P2-6 坏清单不再带 error.path 是有意降级(来源 id 在 message 里),保持。
裁定项:自写 Ed25519 换成 `ed25519-dalek::verify_strict`(信任锚不许自写密码学;此刻信任表还是空表,
零兼容负担)。删除 `update/ed25519/{field,group,mod}.rs`(含只服务它们的单测),新 `update/ed25519.rs`
只剩一个薄封装;拒绝类用例(可锻 S+L / 小阶公钥 / 非规范 R / 空签名 / 未知 key)**一条没删**,
改成钉 dalek 的 strict 语义——实测 dalek 对全部五类的结论与旧实现一致(非规范 R 的拒绝理由不同:
dalek 走「小阶点」而非「编码非规范」,用例注释里写明)。签名侧留在 `packaging/ed25519_ref.py`
(纯 Python、零 pip 依赖),`--self-test` 用 RFC 8032 同一组向量钉两边。
This commit is contained in:
1 parent
b7d9b99e12
commit
918d826645
28 files changed
+860
-1085
No files matched your search
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Parse every workflow file with a **real YAML parser** (M190 r1 复审 P1-1).
|
||||
|
||||
Why this exists: a raw 0x01 byte slipped into `.github/workflows/release-build.yml` (a `sed` replacement
|
||||
string that should have been `\\1`). GitHub refuses to parse such a file, so the whole run would not even
|
||||
start — and no other guard noticed, because they all read workflow files as *text* (`check_release_semantics.py`
|
||||
does `yaml_scalars()`, the file-size job only counts lines). A text scanner cannot see a control byte that
|
||||
a YAML 1.2 reader rejects outright.
|
||||
|
||||
So: hand every `.github/workflows/*.yml` to PyYAML. Two checks, both cheap:
|
||||
① it parses (real error message with position, not a mystery red);
|
||||
② no C0 control character other than TAB/LF/CR is present (YAML 1.2 forbids them; parsers differ in
|
||||
whether they reject, so this is the belt-and-braces half).
|
||||
|
||||
PyYAML is preinstalled on GitHub-hosted runners; if it is not, this script installs it. If that fails too
|
||||
the gate **fails** rather than degrading to a text scan ("工具缺失也 fail" — same rule as the other guards).
|
||||
|
||||
python3 packaging/check_workflows_yaml.py
|
||||
python3 packaging/check_workflows_yaml.py --self-test
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
WORKFLOW_DIR = Path(__file__).resolve().parent.parent / ".github/workflows"
|
||||
ALLOWED_CONTROL = {0x09, 0x0A, 0x0D}
|
||||
|
||||
|
||||
def load_yaml():
|
||||
"""Import PyYAML, installing it once if the runner lacks it."""
|
||||
try:
|
||||
import yaml # noqa: PLC0415
|
||||
|
||||
return yaml
|
||||
except ImportError:
|
||||
print("PyYAML 缺失,尝试安装一次(pip install --quiet pyyaml)…", file=sys.stderr)
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "--quiet", "pyyaml"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if done.returncode != 0:
|
||||
print(
|
||||
"error: 装不上 PyYAML,YAML 门禁无法运行(门禁不降级)。输出:\n" + done.stdout + done.stderr,
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(2) from None
|
||||
import yaml # noqa: PLC0415
|
||||
|
||||
return yaml
|
||||
|
||||
|
||||
def control_characters(data: bytes) -> list[tuple[int, int]]:
|
||||
"""`[(位置, 字节)]`:YAML 1.2 不许出现的 C0 控制字符(TAB/LF/CR 除外)。"""
|
||||
return [(index, byte) for index, byte in enumerate(data) if byte < 0x20 and byte not in ALLOWED_CONTROL]
|
||||
|
||||
|
||||
def check_file(path: Path, yaml) -> list[str]:
|
||||
"""返回该文件没过的判据(空 = 通过)。"""
|
||||
failures: list[str] = []
|
||||
data = path.read_bytes()
|
||||
for index, byte in control_characters(data):
|
||||
line = data[:index].count(b"\n") + 1
|
||||
failures.append(
|
||||
f"::error file={path},line={line}::第 {line} 行含裸控制字符 {byte:#04x}(YAML 1.2 禁止;"
|
||||
"常见成因是 sed/printf 把 `\\1` 写成了 0x01)"
|
||||
)
|
||||
try:
|
||||
text = data.decode("utf-8")
|
||||
except UnicodeDecodeError as error:
|
||||
failures.append(f"::error file={path}::不是合法 UTF-8({error})")
|
||||
return failures
|
||||
try:
|
||||
yaml.safe_load(text)
|
||||
except Exception as error: # noqa: BLE001 - 解析器的异常类型随版本变,这里只关心「没通过」
|
||||
first = str(error).splitlines()[0] if str(error) else repr(error)
|
||||
failures.append(f"::error file={path}::YAML 解析失败:{first}")
|
||||
return failures
|
||||
|
||||
|
||||
def self_test() -> int:
|
||||
"""注入一枚 0x01 到临时副本,断言门禁**会红**(否则这条门禁对任何输入都绿)。"""
|
||||
import tempfile
|
||||
|
||||
yaml = load_yaml()
|
||||
failures = 0
|
||||
sample = "name: x\non: push\njobs:\n a:\n runs-on: ubuntu-latest\n steps:\n - run: |\n echo hi\n"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
good = Path(tmp) / "good.yml"
|
||||
good.write_text(sample, encoding="utf-8")
|
||||
if check_file(good, yaml):
|
||||
print("FAIL: 合法 YAML 被判红(误杀)", file=sys.stderr)
|
||||
failures += 1
|
||||
bad = Path(tmp) / "bad.yml"
|
||||
bad.write_bytes(sample.replace('"/\\1/p"', "").encode("utf-8") + b'x\n v=$(s/"' + bytes([1]) + b'/p)\n')
|
||||
if not check_file(bad, yaml):
|
||||
print("FAIL: 含裸 0x01 的 YAML 竟然通过(判据失效)", file=sys.stderr)
|
||||
failures += 1
|
||||
# 只让 PyYAML 判的那一半也要能红:把控制字节换成合法字符,但结构坏掉。
|
||||
broken = Path(tmp) / "broken.yml"
|
||||
broken.write_text("a: [1, 2\nb: 3\n", encoding="utf-8")
|
||||
if not check_file(broken, yaml):
|
||||
print("FAIL: 结构坏的 YAML 竟然通过", file=sys.stderr)
|
||||
failures += 1
|
||||
print("self-test:", "ok" if failures == 0 else f"{failures} 处失败")
|
||||
return 0 if failures == 0 else 1
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="用真 YAML 解析器 parse 全部 workflow(M190 r1 P1-1)")
|
||||
parser.add_argument("--self-test", action="store_true", help="自检:注入 0x01 / 坏结构必须红")
|
||||
parser.add_argument("--dir", type=Path, default=WORKFLOW_DIR, help="workflow 目录(默认 .github/workflows)")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.self_test:
|
||||
return self_test()
|
||||
|
||||
yaml = load_yaml()
|
||||
files = sorted(args.dir.glob("*.yml")) + sorted(args.dir.glob("*.yaml"))
|
||||
if not files:
|
||||
print(f"error: {args.dir} 里一个 workflow 都没有(路径错了?门禁不降级)", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
failures: list[str] = []
|
||||
for path in files:
|
||||
failures.extend(check_file(path, yaml))
|
||||
|
||||
for line in failures:
|
||||
print(line, file=sys.stderr)
|
||||
if failures:
|
||||
print(f"FAIL:{len(failures)} 条判据没过({len(files)} 个文件)", file=sys.stderr)
|
||||
return 1
|
||||
print(f"ok: {len(files)} 个 workflow 全部能被真 YAML 解析器 parse,且无裸控制字符")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -77,12 +77,15 @@ python3 packaging/sign_manifest.py --generate-key --key-id ull-release-2026a
|
||||
在 `manifest.json` 生成之后、`gh release create/upload` 之前,多了一步:
|
||||
|
||||
```bash
|
||||
python3 packaging/sign_manifest.py --self-test # RFC 8032 向量自检
|
||||
python3 packaging/sign_manifest.py --check-pinned-keyring # 密钥 ↔ trust.rs 必须对得上
|
||||
python3 packaging/sign_manifest.py --sign dist/manifest.json # 产出 dist/manifest.json.sig
|
||||
python3 packaging/sign_manifest.py --verify dist/manifest.json dist/manifest.json.sig --public-key <keyring 里的那把>
|
||||
python3 packaging/sign_manifest.py --self-test # ① RFC 8032 向量自检
|
||||
python3 packaging/sign_manifest.py --check-pinned-keyring # ② 密钥 ↔ trust.rs 必须对得上
|
||||
python3 packaging/sign_manifest.py --sign dist/manifest.json # ③ 产出 dist/manifest.json.sig
|
||||
python3 packaging/sign_manifest.py --verify-pinned dist/manifest.json # ④ 用钉住的公钥回验产出
|
||||
```
|
||||
|
||||
第 ④ 步复现「客户端会怎么判」:它**不碰私钥**,只拿 `trust.rs` 里那把公钥去验刚落盘的 `.sig`。
|
||||
因此「签名脚本自己说签好了」不构成证据,证据是「按客户端的判据能验过」。
|
||||
|
||||
四条命令任何一条非零退出 ⇒ **这一步红 ⇒ 整个 Release job 红 ⇒ 本次不出 Release**。常见红法:
|
||||
|
||||
| 现象 | 原因 | 怎么补 |
|
||||
@@ -124,7 +127,19 @@ python3 packaging/sign_manifest.py --verify dist/manifest.json dist/manifest.jso
|
||||
另外 CI 的构建槽位会跑 `check_pe_version.py`(`release-build.yml`):Windows 槽位上直接读
|
||||
`target/release/unlucky-launcher-iced.exe` 与 `ull.exe` 的字节,断言 `CompanyName` 等字符串在。
|
||||
|
||||
## 7. 本地自测(不需要私钥)
|
||||
## 7. 实现分工(M190 r1 复审后)
|
||||
|
||||
| 哪一半 | 在哪 | 用什么 |
|
||||
|---|---|---|
|
||||
| **验签**(进二进制) | `crates/core/src/update/ed25519.rs` | `ed25519-dalek::verify_strict`(拒非规范编码 / 小阶点 / 非规范 `S`) |
|
||||
| **签名**(只在发布侧) | `packaging/ed25519_ref.py` + `packaging/sign_manifest.py` | 纯 Python 参考实现,零第三方依赖(CI 不装 pip 包) |
|
||||
|
||||
两套实现互相独立,`--self-test` 用 RFC 8032 §7.1 的同一组向量把两边各自钉住。**第一版曾把验签写成
|
||||
仓内自写**(5x51 素域 + 扩展坐标);r1 复审裁定不安全——信任锚的微妙错误后果是「验签通过但本不该通过」,
|
||||
因此整段删除,改为官方实现。`crates/core/src/update/tests/ed25519_cases.rs` 现在钉的是
|
||||
**dalek 的 strict 语义**:谁把 `verify_strict` 换成 `verify`(不做小阶/可锻检查),那批用例当场红。
|
||||
|
||||
## 8. 本地自测(不需要私钥)
|
||||
|
||||
```bash
|
||||
python3 packaging/sign_manifest.py --self-test # RFC 8032 向量 + 标记解析
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Ed25519 的**参考实现**(RFC 8032),只给发布侧签名脚本用(M190)。
|
||||
|
||||
为什么这里自写一套:发布侧签名必须**零第三方依赖**(CI 不装 pip 包),而仓里 `crates/core` 的验签
|
||||
用的是 `ed25519-dalek`。两套实现互相独立,`sign_manifest.py --self-test` 用 RFC 8032 §7.1 的同一组
|
||||
向量把两边各自钉住 —— 任何一边坏了,向量那一半会红;两边都「一致地错」的概率极低。
|
||||
|
||||
⚠ 这里的私钥路径(`sign`)**只在发布侧**(`packaging/sign_manifest.py --sign`)跑,不进任何产物;
|
||||
二进制里只有验签(`ed25519-dalek::verify_strict`)。扩展坐标公式与 dalek/ref10 同源,向量自检兜底。
|
||||
|
||||
import ed25519_ref as ref
|
||||
seed = bytes.fromhex("…") # 32 字节种子
|
||||
pk = ref.public_key(seed)
|
||||
sig = ref.sign(seed, b"message") # 64 字节
|
||||
assert ref.verify(pk, b"message", sig)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
ALG = "ed25519"
|
||||
|
||||
Q = 2**255 - 19
|
||||
L = 2**252 + 27742317777372353535851937790883648493
|
||||
|
||||
def _inv(x: int) -> int:
|
||||
return pow(x, Q - 2, Q)
|
||||
|
||||
D = -121665 * _inv(121666) % Q
|
||||
_D2 = 2 * D % Q
|
||||
_SQRT_M1 = pow(2, (Q - 1) // 4, Q)
|
||||
|
||||
def _recover_x(y: int, sign: int) -> int | None:
|
||||
u = (y * y - 1) % Q
|
||||
v = (D * y * y + 1) % Q
|
||||
v3 = pow(v, 3, Q)
|
||||
v7 = pow(v, 7, Q)
|
||||
x = u * v3 % Q * pow(u * v7 % Q, (Q - 5) // 8, Q) % Q
|
||||
if (v * x * x - u) % Q != 0:
|
||||
x = x * _SQRT_M1 % Q
|
||||
if (v * x * x - u) % Q != 0:
|
||||
return None
|
||||
if x % 2 != sign:
|
||||
x = (Q - x) % Q
|
||||
return x
|
||||
|
||||
def _decompress(data: bytes) -> tuple[int, int, int, int] | None:
|
||||
if len(data) != 32:
|
||||
return None
|
||||
y = int.from_bytes(data, "little")
|
||||
sign = (y >> 255) & 1
|
||||
y &= (1 << 255) - 1
|
||||
if y >= Q:
|
||||
return None
|
||||
x = _recover_x(y, sign)
|
||||
if x is None:
|
||||
return None
|
||||
return (x, y, 1, x * y % Q)
|
||||
|
||||
def _add(p: tuple[int, int, int, int], r: tuple[int, int, int, int]):
|
||||
x1, y1, z1, t1 = p
|
||||
x2, y2, z2, t2 = r
|
||||
a = (y1 - x1) * (y2 - x2) % Q
|
||||
b = (y1 + x1) * (y2 + x2) % Q
|
||||
c = t1 * _D2 * t2 % Q
|
||||
d = 2 * z1 * z2 % Q
|
||||
e, f, g, h = (b - a) % Q, (d - c) % Q, (d + c) % Q, (b + a) % Q
|
||||
return (e * f % Q, g * h % Q, f * g % Q, e * h % Q)
|
||||
|
||||
def _double(p: tuple[int, int, int, int]):
|
||||
x1, y1, z1, _ = p
|
||||
a = x1 * x1 % Q
|
||||
b = y1 * y1 % Q
|
||||
c = 2 * z1 * z1 % Q
|
||||
d = -a % Q
|
||||
e = ((x1 + y1) * (x1 + y1) - a - b) % Q
|
||||
g = (d + b) % Q
|
||||
f = (g - c) % Q
|
||||
h = (d - b) % Q
|
||||
return (e * f % Q, g * h % Q, f * g % Q, e * h % Q)
|
||||
|
||||
def _scalarmult(p, e: int):
|
||||
acc = (0, 1, 1, 0)
|
||||
for bit in bin(e)[2:] if e else "":
|
||||
acc = _double(acc)
|
||||
if bit == "1":
|
||||
acc = _add(acc, p)
|
||||
return acc
|
||||
|
||||
def _encode(p) -> bytes:
|
||||
x, y, z, _ = p
|
||||
zi = _inv(z)
|
||||
x, y = x * zi % Q, y * zi % Q
|
||||
return (y | ((x & 1) << 255)).to_bytes(32, "little")
|
||||
|
||||
def _base():
|
||||
encoded = (4 * _inv(5) % Q).to_bytes(32, "little")
|
||||
return _decompress(encoded)
|
||||
|
||||
def _hint(data: bytes) -> int:
|
||||
return int.from_bytes(hashlib.sha512(data).digest(), "little") % L
|
||||
|
||||
def public_key(seed: bytes) -> bytes:
|
||||
h = hashlib.sha512(seed).digest()
|
||||
a = int.from_bytes(_clamp(bytearray(h[:32])), "little")
|
||||
return _encode(_scalarmult(_base(), a))
|
||||
|
||||
def _clamp(scalar: bytearray) -> bytes:
|
||||
scalar[0] &= 248
|
||||
scalar[31] &= 127
|
||||
scalar[31] |= 64
|
||||
return bytes(scalar)
|
||||
|
||||
def sign(seed: bytes, message: bytes) -> bytes:
|
||||
if len(seed) != 32:
|
||||
raise SystemExit("error: Ed25519 种子必须 32 字节")
|
||||
h = hashlib.sha512(seed).digest()
|
||||
a = int.from_bytes(_clamp(bytearray(h[:32])), "little")
|
||||
prefix = h[32:]
|
||||
r = _hint(prefix + message)
|
||||
r_encoded = _encode(_scalarmult(_base(), r))
|
||||
pk = _encode(_scalarmult(_base(), a))
|
||||
k = _hint(r_encoded + pk + message)
|
||||
s = (r + k * a) % L
|
||||
return r_encoded + s.to_bytes(32, "little")
|
||||
|
||||
def verify(pk: bytes, message: bytes, signature: bytes) -> bool:
|
||||
if len(pk) != 32 or len(signature) != 64:
|
||||
return False
|
||||
r_bytes, s_bytes = signature[:32], signature[32:]
|
||||
if int.from_bytes(s_bytes, "little") >= L:
|
||||
return False
|
||||
a = _decompress(pk)
|
||||
r_point = _decompress(r_bytes)
|
||||
if a is None or r_point is None:
|
||||
return False
|
||||
k = _hint(r_bytes + pk + message)
|
||||
left = _scalarmult(_base(), int.from_bytes(s_bytes, "little"))
|
||||
return _encode(left) == _encode(_add(r_point, _scalarmult(a, k)))
|
||||
|
||||
|
||||
|
||||
+41
-122
@@ -13,10 +13,9 @@ Key discipline: the **private key** lives only in the repository Secret
|
||||
is not pinned (a release signed with a key clients do not trust is worse than no release).
|
||||
Manual: `packaging/docs/signing.md`.
|
||||
|
||||
Usage:
|
||||
python3 packaging/sign_manifest.py --generate-key --key-id ull-release-2026a
|
||||
ULL_MANIFEST_SIGNING_KEY='{"key_id":"…","seed_hex":"…"}' python3 packaging/sign_manifest.py --sign dist/manifest.json
|
||||
python3 packaging/sign_manifest.py --check-pinned-keyring | --self-test
|
||||
Usage: `--generate-key [--key-id K]` / `--sign dist/manifest.json`(钥从环境变量
|
||||
`ULL_MANIFEST_SIGNING_KEY` 取)/ `--check-pinned-keyring`(钥必须已钉住)/ `--verify-pinned
|
||||
dist/manifest.json`(用 trust.rs 里钉的公钥回验产出,复现客户端判据)/ `--self-test`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -41,125 +40,12 @@ KID_RE = re.compile(r'key_id:\s*"([^"]+)"\s*,\s*public_key_hex:\s*"([0-9a-fA-F]{
|
||||
# `crates/core/src/update/ed25519/*`). Validated against the RFC 8032 §7.1 vectors in
|
||||
# `--self-test`; the Rust verifier is validated against the *same* vectors, so the two
|
||||
# implementations cross-check each other. No third-party dependency: CI needs no pip install.
|
||||
Q = 2**255 - 19
|
||||
L = 2**252 + 27742317777372353535851937790883648493
|
||||
|
||||
def _inv(x: int) -> int:
|
||||
return pow(x, Q - 2, Q)
|
||||
|
||||
D = -121665 * _inv(121666) % Q
|
||||
_D2 = 2 * D % Q
|
||||
_SQRT_M1 = pow(2, (Q - 1) // 4, Q)
|
||||
|
||||
def _recover_x(y: int, sign: int) -> int | None:
|
||||
u = (y * y - 1) % Q
|
||||
v = (D * y * y + 1) % Q
|
||||
v3 = pow(v, 3, Q)
|
||||
v7 = pow(v, 7, Q)
|
||||
x = u * v3 % Q * pow(u * v7 % Q, (Q - 5) // 8, Q) % Q
|
||||
if (v * x * x - u) % Q != 0:
|
||||
x = x * _SQRT_M1 % Q
|
||||
if (v * x * x - u) % Q != 0:
|
||||
return None
|
||||
if x % 2 != sign:
|
||||
x = (Q - x) % Q
|
||||
return x
|
||||
|
||||
def _decompress(data: bytes) -> tuple[int, int, int, int] | None:
|
||||
if len(data) != 32:
|
||||
return None
|
||||
y = int.from_bytes(data, "little")
|
||||
sign = (y >> 255) & 1
|
||||
y &= (1 << 255) - 1
|
||||
if y >= Q:
|
||||
return None
|
||||
x = _recover_x(y, sign)
|
||||
if x is None:
|
||||
return None
|
||||
return (x, y, 1, x * y % Q)
|
||||
|
||||
def _add(p: tuple[int, int, int, int], r: tuple[int, int, int, int]):
|
||||
x1, y1, z1, t1 = p
|
||||
x2, y2, z2, t2 = r
|
||||
a = (y1 - x1) * (y2 - x2) % Q
|
||||
b = (y1 + x1) * (y2 + x2) % Q
|
||||
c = t1 * _D2 * t2 % Q
|
||||
d = 2 * z1 * z2 % Q
|
||||
e, f, g, h = (b - a) % Q, (d - c) % Q, (d + c) % Q, (b + a) % Q
|
||||
return (e * f % Q, g * h % Q, f * g % Q, e * h % Q)
|
||||
|
||||
def _double(p: tuple[int, int, int, int]):
|
||||
x1, y1, z1, _ = p
|
||||
a = x1 * x1 % Q
|
||||
b = y1 * y1 % Q
|
||||
c = 2 * z1 * z1 % Q
|
||||
d = -a % Q
|
||||
e = ((x1 + y1) * (x1 + y1) - a - b) % Q
|
||||
g = (d + b) % Q
|
||||
f = (g - c) % Q
|
||||
h = (d - b) % Q
|
||||
return (e * f % Q, g * h % Q, f * g % Q, e * h % Q)
|
||||
|
||||
def _scalarmult(p, e: int):
|
||||
acc = (0, 1, 1, 0)
|
||||
for bit in bin(e)[2:] if e else "":
|
||||
acc = _double(acc)
|
||||
if bit == "1":
|
||||
acc = _add(acc, p)
|
||||
return acc
|
||||
|
||||
def _encode(p) -> bytes:
|
||||
x, y, z, _ = p
|
||||
zi = _inv(z)
|
||||
x, y = x * zi % Q, y * zi % Q
|
||||
return (y | ((x & 1) << 255)).to_bytes(32, "little")
|
||||
|
||||
def _base():
|
||||
encoded = (4 * _inv(5) % Q).to_bytes(32, "little")
|
||||
return _decompress(encoded)
|
||||
|
||||
def _hint(data: bytes) -> int:
|
||||
return int.from_bytes(hashlib.sha512(data).digest(), "little") % L
|
||||
|
||||
def public_key(seed: bytes) -> bytes:
|
||||
h = hashlib.sha512(seed).digest()
|
||||
a = int.from_bytes(_clamp(bytearray(h[:32])), "little")
|
||||
return _encode(_scalarmult(_base(), a))
|
||||
|
||||
def _clamp(scalar: bytearray) -> bytes:
|
||||
scalar[0] &= 248
|
||||
scalar[31] &= 127
|
||||
scalar[31] |= 64
|
||||
return bytes(scalar)
|
||||
|
||||
def sign(seed: bytes, message: bytes) -> bytes:
|
||||
if len(seed) != 32:
|
||||
raise SystemExit("error: Ed25519 种子必须 32 字节")
|
||||
h = hashlib.sha512(seed).digest()
|
||||
a = int.from_bytes(_clamp(bytearray(h[:32])), "little")
|
||||
prefix = h[32:]
|
||||
r = _hint(prefix + message)
|
||||
r_encoded = _encode(_scalarmult(_base(), r))
|
||||
pk = _encode(_scalarmult(_base(), a))
|
||||
k = _hint(r_encoded + pk + message)
|
||||
s = (r + k * a) % L
|
||||
return r_encoded + s.to_bytes(32, "little")
|
||||
|
||||
def verify(pk: bytes, message: bytes, signature: bytes) -> bool:
|
||||
if len(pk) != 32 or len(signature) != 64:
|
||||
return False
|
||||
r_bytes, s_bytes = signature[:32], signature[32:]
|
||||
if int.from_bytes(s_bytes, "little") >= L:
|
||||
return False
|
||||
a = _decompress(pk)
|
||||
r_point = _decompress(r_bytes)
|
||||
if a is None or r_point is None:
|
||||
return False
|
||||
k = _hint(r_bytes + pk + message)
|
||||
left = _scalarmult(_base(), int.from_bytes(s_bytes, "little"))
|
||||
return _encode(left) == _encode(_add(r_point, _scalarmult(a, k)))
|
||||
|
||||
# Ed25519 的参考实现搬到了 `packaging/ed25519_ref.py`(M190 r1:本文件贴着 400 行红线)。
|
||||
# 目的与路径都写在那边的文件头:发布侧签名必须零第三方依赖,而仓里验签用的是 ed25519-dalek ——
|
||||
# 两套实现互相独立,`--self-test` 用 RFC 8032 的同一组向量把两边各自钉住。
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from ed25519_ref import ALG, sign, verify, public_key # noqa: E402
|
||||
|
||||
def load_key(text: str) -> tuple[str, bytes]:
|
||||
"""Parse the secret JSON (`{"key_id":…,"seed_hex":…}`) or a bare 64-char hex seed."""
|
||||
@@ -313,6 +199,36 @@ def do_check_pinned(key_path: str | None) -> int:
|
||||
print("error: 手册:packaging/docs/signing.md §3/§5", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
def do_verify_pinned(manifest: Path) -> int:
|
||||
"""用 trust.rs 里钉住的公钥回验 `<manifest>.sig` —— 复现「客户端会怎么判」,不需要私钥。"""
|
||||
keys = pinned_keys(TRUST_RS.read_text(encoding="utf-8"))
|
||||
if not keys:
|
||||
print("error: 信任表是空的,无从回验(先钉公钥,见 --check-pinned-keyring)", file=sys.stderr)
|
||||
return 1
|
||||
sig_path = manifest.with_name(manifest.name + SIG_SUFFIX)
|
||||
if not sig_path.is_file():
|
||||
print(f"error: 没有签名文件 {sig_path}", file=sys.stderr)
|
||||
return 1
|
||||
raw = manifest.read_bytes()
|
||||
envelope = json.loads(sig_path.read_text(encoding="utf-8"))
|
||||
for item in envelope.get("signatures", []):
|
||||
if item.get("alg") != ALG:
|
||||
continue
|
||||
try:
|
||||
signature = bytes.fromhex(item.get("sig", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
for pinned_id, pinned_hex in keys:
|
||||
if verify(bytes.fromhex(pinned_hex), raw, signature):
|
||||
print(f"ok: {sig_path.name} 用钉住的公钥 {pinned_id} 能验过(客户端会接受)")
|
||||
return 0
|
||||
print(
|
||||
"error: 拿 trust.rs 里钉住的公钥回验不过 —— 这份 Release 的用户会全部拒装。别发版",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
def do_self_test() -> int:
|
||||
vectors = [
|
||||
("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
|
||||
@@ -360,6 +276,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--verify", nargs=2, metavar=("MANIFEST", "SIG"), help="手工验一份签名")
|
||||
parser.add_argument("--public-key", metavar="HEX", help="--verify 用的公钥")
|
||||
parser.add_argument("--check-pinned-keyring", action="store_true", help="检查密钥是否已被钉进 trust.rs")
|
||||
parser.add_argument("--verify-pinned", metavar="MANIFEST", type=Path, help="用 trust.rs 里钉的公钥回验产出")
|
||||
parser.add_argument("--self-test", action="store_true", help="跑 RFC 8032 向量与解析器自检")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
@@ -376,6 +293,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return do_verify(Path(args.verify[0]), Path(args.verify[1]), args.public_key)
|
||||
if args.check_pinned_keyring:
|
||||
return do_check_pinned(args.key)
|
||||
if args.verify_pinned:
|
||||
return do_verify_pinned(args.verify_pinned)
|
||||
parser.print_help()
|
||||
return 2
|
||||
|
||||
|
||||
Reference in new issue
Block a user