重新按英文命名,修改成相对路径
This commit is contained in:
223
CostReview/app/server/license_client/verify.py
Normal file
223
CostReview/app/server/license_client/verify.py
Normal file
@@ -0,0 +1,223 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""license-v2 / lease-v2 信封验签(ECDSA P-256 + SHA-256)。
|
||||
|
||||
规范要点(license-platform 接入包 protocol.md):
|
||||
- 规范化串不是 JSON:固定顺序 key=value、单个 LF 连接、无末尾 LF、UTF-8 编码;
|
||||
整数字段输出正十进制;时间字段用收到的原始字符串(验签前不得格式化/重序列化)。
|
||||
- signature 是 ASN.1 DER ECDSA 的标准 Base64,不带 = 填充(不是 Base64URL,
|
||||
也不是固定 64 字节 r||s)。
|
||||
- canonical_sha256 是规范化字节的 SHA-256 十六进制,仅辅助校验,不能代替公钥验签。
|
||||
- 拒绝:未知版本、缺字段/多字段、非法类型、含 CR/LF/NUL 的字段、未知或已撤销
|
||||
key_id、非 P-256 公钥、绑定到其他实例的信封、legacy v1。
|
||||
|
||||
信任根:只信随软件/受控渠道固定分发的公钥(pinned_keys.json),绝不在线发现。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
LICENSE_V2 = "license-v2"
|
||||
LEASE_V2 = "lease-v2"
|
||||
ALGORITHM = "ECDSA-P256-SHA256"
|
||||
|
||||
# 固定字段顺序 = canonical 顺序;payload 必须恰好等于这些键,缺一个多一个都拒
|
||||
FIELDSETS = {
|
||||
LICENSE_V2: ("version", "instance_id", "license_id", "customer_id",
|
||||
"product_id", "starts_at", "expires_at", "key_id"),
|
||||
LEASE_V2: ("version", "instance_id", "state", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at", "key_id"),
|
||||
}
|
||||
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||||
re.IGNORECASE)
|
||||
RFC3339_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
|
||||
LEASE_STATES = ("active", "frozen", "revoked", "expired", "not_started", "not_activated")
|
||||
|
||||
# 两种信封的固定键集合(缺一个多一个都拒)
|
||||
CERT_ENVELOPE_KEYS = {"version", "payload", "signature", "canonical_sha256"}
|
||||
LEASE_ENVELOPE_KEYS = {"payload", "signature", "canonical_sha256", "algorithm",
|
||||
"next_heartbeat_seconds"}
|
||||
|
||||
|
||||
class VerifyError(Exception):
|
||||
"""验签/结构校验失败。消息只写原因,不含任何凭据。"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 时间工具
|
||||
|
||||
def parse_rfc3339(s):
|
||||
"""RFC3339 → UTC aware datetime。形状不对抛 VerifyError。"""
|
||||
if not isinstance(s, str) or not RFC3339_RE.match(s):
|
||||
raise VerifyError("时间格式不是 RFC3339:%r" % (s,))
|
||||
from datetime import datetime, timezone
|
||||
v = s.strip()
|
||||
if v.endswith(("Z", "z")):
|
||||
v = v[:-1] + "+00:00"
|
||||
dt = datetime.fromisoformat(v)
|
||||
if dt.tzinfo is None:
|
||||
raise VerifyError("时间缺时区:%r" % (s,))
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def rfc3339(dt):
|
||||
"""aware datetime → RFC3339 UTC(Z 后缀,秒精度)。"""
|
||||
from datetime import timezone
|
||||
dt = dt.astimezone(timezone.utc).replace(microsecond=0)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
# ------------------------------------------------------------- keyring 管理
|
||||
|
||||
def build_keyring(entries):
|
||||
"""[{key_id, public_key_pem, revoked}] → {key_id: {"key": pub, "revoked": bool}}。
|
||||
|
||||
pinned 文件本身配置错(非 P-256 / 解不开)要立刻暴露,不能静默当不可信。
|
||||
"""
|
||||
ring = {}
|
||||
for e in entries or []:
|
||||
kid, pem = e.get("key_id"), e.get("public_key_pem")
|
||||
if not kid or not pem:
|
||||
raise VerifyError("pinned_keys 条目缺 key_id/public_key_pem")
|
||||
key = serialization.load_pem_public_key(pem.encode("utf-8"))
|
||||
if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1):
|
||||
raise VerifyError("key_id=%s 的公钥不是 EC P-256" % kid)
|
||||
ring[kid] = {"key": key, "revoked": bool(e.get("revoked", False))}
|
||||
return ring
|
||||
|
||||
|
||||
def load_keyring_file(path):
|
||||
"""读取随软件分发的 pinned_keys.json(不存在/为空 = 未配置信任根,fail closed)。"""
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return build_keyring(data.get("pinned_keys"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 规范化
|
||||
|
||||
# 字段类型白名单:ID 三兄弟必须真整数(bool 也拒);时间字段必须合法 RFC3339
|
||||
_INT_FIELDS = {"license_id", "customer_id", "product_id"}
|
||||
_TIME_FIELDS = {"starts_at", "expires_at", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at"}
|
||||
|
||||
|
||||
def _field_value(payload, name):
|
||||
v = payload[name]
|
||||
if isinstance(v, bool) or v is None or isinstance(v, (list, dict, float)):
|
||||
raise VerifyError("字段 %s 类型非法" % name)
|
||||
if isinstance(v, int) or name in _INT_FIELDS:
|
||||
if not isinstance(v, int) or v <= 0:
|
||||
raise VerifyError("字段 %s 必须是正整数" % name)
|
||||
return str(v) # ID:正十进制整数
|
||||
if not isinstance(v, str):
|
||||
raise VerifyError("字段 %s 类型非法" % name)
|
||||
if any(c in v for c in ("\r", "\n", "\x00")):
|
||||
raise VerifyError("字段 %s 含 CR/LF/NUL" % name)
|
||||
if name in _TIME_FIELDS:
|
||||
parse_rfc3339(v) # 时间字段必须是合法 RFC3339
|
||||
elif not v:
|
||||
raise VerifyError("字段 %s 不能为空" % name)
|
||||
return v
|
||||
|
||||
|
||||
def canonical_bytes(payload, version):
|
||||
"""规范化字节串:固定顺序 key=value、LF 连接、无末尾 LF、UTF-8。"""
|
||||
if version not in FIELDSETS:
|
||||
raise VerifyError("未知信封版本:%r" % (version,))
|
||||
out = []
|
||||
for name in FIELDSETS[version]:
|
||||
if name not in payload:
|
||||
raise VerifyError("payload 缺字段 %s" % name)
|
||||
out.append("%s=%s" % (name, _field_value(payload, name)))
|
||||
return "\n".join(out).encode("utf-8")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 结构校验
|
||||
|
||||
def _check_payload(payload, version, expected_instance):
|
||||
if not isinstance(payload, dict):
|
||||
raise VerifyError("payload 不是对象")
|
||||
if set(payload.keys()) != set(FIELDSETS[version]):
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
if payload["version"] != version:
|
||||
raise VerifyError("payload.version=%r 不是 %s" % (payload["version"], version))
|
||||
for name in FIELDSETS[version]:
|
||||
_field_value(payload, name) # 类型/字符白名单
|
||||
if not UUID_RE.match(str(payload["instance_id"])):
|
||||
raise VerifyError("instance_id 不是 UUID")
|
||||
if expected_instance and str(payload["instance_id"]).lower() != str(expected_instance).lower():
|
||||
raise VerifyError("信封绑定到其他实例")
|
||||
if version == LICENSE_V2:
|
||||
parse_rfc3339(payload["starts_at"])
|
||||
parse_rfc3339(payload["expires_at"])
|
||||
else:
|
||||
if payload["state"] not in LEASE_STATES:
|
||||
raise VerifyError("租约状态非法:%r" % (payload["state"],))
|
||||
parse_rfc3339(payload["server_time"])
|
||||
parse_rfc3339(payload["entitlement_expires_at"])
|
||||
parse_rfc3339(payload["lease_expires_at"])
|
||||
|
||||
|
||||
def _decode_signature(sig):
|
||||
if not isinstance(sig, str) or not sig:
|
||||
raise VerifyError("signature 缺失或非法")
|
||||
if "-" in sig or "_" in sig: # Base64URL 字母表 → 拒
|
||||
raise VerifyError("signature 疑似 Base64URL 编码")
|
||||
pad = "=" * (-len(sig) % 4)
|
||||
try:
|
||||
return base64.b64decode(sig + pad, validate=True)
|
||||
except Exception:
|
||||
raise VerifyError("signature 不是标准 Base64")
|
||||
|
||||
|
||||
def _check_aux_sha(envelope, canonical):
|
||||
want = envelope.get("canonical_sha256")
|
||||
if not isinstance(want, str):
|
||||
raise VerifyError("canonical_sha256 缺失或非法")
|
||||
got = hashlib.sha256(canonical).hexdigest()
|
||||
if want.lower() != got:
|
||||
raise VerifyError("canonical_sha256 不符(载荷与规范化串不一致)")
|
||||
|
||||
|
||||
def _verify_with_keyring(envelope_keys, envelope, version, expected_instance, keyring):
|
||||
if not isinstance(envelope, dict) or set(envelope.keys()) != envelope_keys:
|
||||
raise VerifyError("信封字段集不符(缺/多字段)")
|
||||
payload = envelope.get("payload")
|
||||
_check_payload(payload, version, expected_instance)
|
||||
kid = payload["key_id"]
|
||||
ent = keyring.get(kid) if isinstance(keyring, dict) else None
|
||||
if ent is None:
|
||||
raise VerifyError("未知 key_id:%r(不在可信公钥清单)" % (kid,))
|
||||
if ent["revoked"]:
|
||||
raise VerifyError("key_id=%s 已撤销" % kid)
|
||||
canonical = canonical_bytes(payload, version)
|
||||
_check_aux_sha(envelope, canonical)
|
||||
der = _decode_signature(envelope.get("signature"))
|
||||
try:
|
||||
ent["key"].verify(der, canonical, ec.ECDSA(hashes.SHA256()))
|
||||
except InvalidSignature:
|
||||
raise VerifyError("签名无效")
|
||||
return payload
|
||||
|
||||
|
||||
def verify_certificate(envelope, expected_instance, keyring):
|
||||
"""激活证书(license-v2):信封含 version 字段。"""
|
||||
return _verify_with_keyring(CERT_ENVELOPE_KEYS, envelope, LICENSE_V2,
|
||||
expected_instance, keyring)
|
||||
|
||||
|
||||
def verify_lease(envelope, expected_instance, keyring):
|
||||
"""运行租约(lease-v2):信封含 algorithm / next_heartbeat_seconds。"""
|
||||
if envelope.get("algorithm") != ALGORITHM:
|
||||
raise VerifyError("algorithm=%r 不是 %s" % (envelope.get("algorithm"), ALGORITHM))
|
||||
nhs = envelope.get("next_heartbeat_seconds")
|
||||
if isinstance(nhs, bool) or not isinstance(nhs, int) or nhs < 60:
|
||||
raise VerifyError("next_heartbeat_seconds 必须是 ≥60 的整数")
|
||||
return _verify_with_keyring(LEASE_ENVELOPE_KEYS, envelope, LEASE_V2,
|
||||
expected_instance, keyring)
|
||||
Reference in New Issue
Block a user