211 lines
7.0 KiB
Python
211 lines
7.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""授权状态受保护存储。
|
||
|
||
- LicenseStateStore:激活证书 / 运行租约 / enabled / 本地与服务端时间高水位的
|
||
原子落盘(tmp + fsync + os.replace)。协议要求"先原子保存再启用业务",
|
||
保存失败必须让调用方走 fail closed。
|
||
- SecretStore 接口 + Windows DPAPI 实现:实例 secret 只进系统级保护存储
|
||
(DPAPI CurrentUser),绝不写入源码/日志/普通明文文件;非 Windows 退化为
|
||
仅当前用户可读的明文文件(开发环境兜底,交付环境只支持 Windows)。
|
||
|
||
协议自带声明:一般受控存储不能抵抗完全控制主机的攻击者和磁盘快照回滚,
|
||
本模块不宣称硬件绑定或防克隆。
|
||
"""
|
||
import base64
|
||
import json
|
||
import os
|
||
import threading
|
||
|
||
|
||
class StorageError(Exception):
|
||
"""状态读写失败(磁盘满/权限等)。调用方必须 fail closed。"""
|
||
|
||
|
||
class LicenseStateStore:
|
||
"""接口:load() → dict;save(state) 原子写。"""
|
||
|
||
def load(self):
|
||
raise NotImplementedError
|
||
|
||
def save(self, state):
|
||
raise NotImplementedError
|
||
|
||
|
||
class JsonFileStore(LicenseStateStore):
|
||
"""JSON 文件原子存储。进程内加锁;跨进程不做(本应用本就不支持双实例共库)。"""
|
||
|
||
def __init__(self, path):
|
||
self.path = path
|
||
self._lock = threading.Lock()
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
|
||
def load(self):
|
||
with self._lock:
|
||
return self._load_unlocked()
|
||
|
||
def _load_unlocked(self):
|
||
try:
|
||
with open(self.path, encoding="utf-8") as f:
|
||
st = json.load(f)
|
||
except FileNotFoundError:
|
||
return {}
|
||
except Exception as e:
|
||
raise StorageError("授权状态读取失败:%s" % e)
|
||
return st if isinstance(st, dict) else {}
|
||
|
||
def save(self, state):
|
||
with self._lock:
|
||
tmp = self.path + ".tmp"
|
||
try:
|
||
with open(tmp, "w", encoding="utf-8") as f:
|
||
json.dump(state, f, ensure_ascii=False, indent=1)
|
||
f.flush()
|
||
os.fsync(f.fileno())
|
||
os.replace(tmp, self.path)
|
||
except Exception as e:
|
||
try:
|
||
os.unlink(tmp)
|
||
except OSError:
|
||
pass
|
||
raise StorageError("授权状态保存失败:%s" % e)
|
||
|
||
def update(self, fn):
|
||
"""原子读改写:fn(state) → state'(原地改传入 dict 即可),返回新状态。"""
|
||
with self._lock:
|
||
st = self._load_unlocked()
|
||
fn(st)
|
||
self._save_unlocked(st)
|
||
return st
|
||
|
||
def _save_unlocked(self, state):
|
||
tmp = self.path + ".tmp"
|
||
try:
|
||
with open(tmp, "w", encoding="utf-8") as f:
|
||
json.dump(state, f, ensure_ascii=False, indent=1)
|
||
f.flush()
|
||
os.fsync(f.fileno())
|
||
os.replace(tmp, self.path)
|
||
except Exception as e:
|
||
try:
|
||
os.unlink(tmp)
|
||
except OSError:
|
||
pass
|
||
raise StorageError("授权状态保存失败:%s" % e)
|
||
|
||
|
||
# ---------------------------------------------------------------- secret
|
||
|
||
class SecretStore:
|
||
"""接口:get() → str|None;set(secret);clear()。"""
|
||
|
||
def get(self):
|
||
raise NotImplementedError
|
||
|
||
def set(self, secret):
|
||
raise NotImplementedError
|
||
|
||
def clear(self):
|
||
raise NotImplementedError
|
||
|
||
|
||
if os.name == "nt":
|
||
import ctypes
|
||
from ctypes import wintypes
|
||
|
||
class _DATA_BLOB(ctypes.Structure):
|
||
_fields_ = [("cbData", wintypes.DWORD),
|
||
("pbData", ctypes.POINTER(ctypes.c_char))]
|
||
|
||
_CRYPTPROTECT_UI_FORBIDDEN = 0x1
|
||
|
||
def _dpapi(data, protect):
|
||
crypt32 = ctypes.windll.crypt32
|
||
k32 = ctypes.windll.kernel32
|
||
buf = ctypes.create_string_buffer(data, len(data))
|
||
inb = _DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
|
||
out = _DATA_BLOB()
|
||
if protect:
|
||
ok = crypt32.CryptProtectData(
|
||
ctypes.byref(inb), "pricing-review-license", None, None, None,
|
||
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
|
||
else:
|
||
ok = crypt32.CryptUnprotectData(
|
||
ctypes.byref(inb), None, None, None, None,
|
||
_CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out))
|
||
if not ok:
|
||
raise StorageError("DPAPI %s 失败(错误码 %s)"
|
||
% ("加密" if protect else "解密", ctypes.GetLastError()))
|
||
try:
|
||
return ctypes.string_at(out.pbData, out.cbData)
|
||
finally:
|
||
k32.LocalFree(out.pbData)
|
||
|
||
class DpapiSecretStore(SecretStore):
|
||
"""Windows DPAPI(CurrentUser)加密落盘:换用户/拷走文件都解不开,
|
||
源码里没有也不需要任何硬编码密钥。"""
|
||
|
||
def __init__(self, path):
|
||
self.path = path
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
|
||
def get(self):
|
||
try:
|
||
with open(self.path, "rb") as f:
|
||
raw = f.read()
|
||
except FileNotFoundError:
|
||
return None
|
||
except OSError as e:
|
||
raise StorageError("secret 读取失败:%s" % e)
|
||
if not raw:
|
||
return None
|
||
try:
|
||
return _dpapi(base64.b64decode(raw), False).decode("utf-8")
|
||
except Exception as e:
|
||
raise StorageError("secret 解密失败(可能换了系统用户):%s" % e)
|
||
|
||
def set(self, secret):
|
||
enc = _dpapi(secret.encode("utf-8"), True)
|
||
tmp = self.path + ".tmp"
|
||
with open(tmp, "wb") as f:
|
||
f.write(base64.b64encode(enc))
|
||
f.flush()
|
||
os.fsync(f.fileno())
|
||
os.replace(tmp, self.path)
|
||
|
||
def clear(self):
|
||
try:
|
||
os.unlink(self.path)
|
||
except FileNotFoundError:
|
||
pass
|
||
|
||
else: # 非 Windows 兜底(开发环境)
|
||
|
||
class DpapiSecretStore(SecretStore):
|
||
"""占位实现:明文落盘(权限收窄到当前用户)。交付环境不支持。"""
|
||
|
||
def __init__(self, path):
|
||
self.path = path
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
|
||
def get(self):
|
||
try:
|
||
with open(self.path, encoding="utf-8") as f:
|
||
v = f.read().strip()
|
||
except FileNotFoundError:
|
||
return None
|
||
return base64.b64decode(v).decode("utf-8") if v else None
|
||
|
||
def set(self, secret):
|
||
with open(self.path, "w", encoding="utf-8") as f:
|
||
f.write(base64.b64encode(secret.encode("utf-8")).decode("ascii"))
|
||
try:
|
||
os.chmod(self.path, 0o600)
|
||
except OSError:
|
||
pass
|
||
|
||
def clear(self):
|
||
try:
|
||
os.unlink(self.path)
|
||
except FileNotFoundError:
|
||
pass
|