修复:向导认证成功后卡死、配置不持久化
根因:非 Windows 走 keyring 加密,无桌面环境的服务器上 keyring 后端不可用, 保存时抛异常/挂起 → 第2步不出现且配置未落盘。 - storage: 非 Windows 改为明文保存 + 文件权限 600(与 ~/.ssh 私钥同级),不再依赖 keyring - cli: 顶层异常兜底(打印堆栈,不再无声退出);向导显示配置文件路径 - 兼容读取旧 kr: 前缀配置;install.sh 去掉 keyring 依赖
This commit is contained in:
+12
-20
@@ -77,35 +77,21 @@ def _dpapi_unprotect(text: str) -> str:
|
||||
ctypes.windll.kernel32.LocalFree(ctypes.c_void_p(dst.pbData))
|
||||
|
||||
|
||||
# ---------- keyring(Linux/macOS) ----------
|
||||
# ---------- keyring(仅兼容读取旧配置;不再用于写入) ----------
|
||||
# 实践证明无桌面环境的服务器上 keyring 后端"注册了但不可用",
|
||||
# 调用时抛异常甚至挂起,会连累配置保存。非 Windows 改为明文 + 文件权限 600。
|
||||
|
||||
def _keyring():
|
||||
try:
|
||||
import keyring # noqa: PLC0415
|
||||
if keyring.get_keyring().priority >= 0: # 有真实后端(非 fail/null)
|
||||
if keyring.get_keyring().priority >= 0:
|
||||
return keyring
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _kr_protect(text: str) -> str:
|
||||
import base64
|
||||
kr = _keyring()
|
||||
if kr is None:
|
||||
return text # 无后端:明文(加载时会告警)
|
||||
import hashlib
|
||||
key = hashlib.sha256((kr.get_password("ssh-tunnel-manager", "salt")
|
||||
or "fixed-salt").encode()).digest()[:16]
|
||||
nonce = os.urandom(12)
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
ct = AESGCM(key).encrypt(nonce, text.encode("utf-8"), None)
|
||||
return _PREFIX2 + base64.b64encode(nonce + ct).decode("ascii")
|
||||
|
||||
|
||||
def _kr_unprotect(text: str) -> str:
|
||||
if not text.startswith(_PREFIX2):
|
||||
return text
|
||||
import base64
|
||||
raw = base64.b64decode(text[len(_PREFIX2):])
|
||||
kr = _keyring()
|
||||
@@ -121,11 +107,15 @@ def _kr_unprotect(text: str) -> str:
|
||||
# ---------- 统一入口 ----------
|
||||
|
||||
def protect(text: str) -> str:
|
||||
"""Windows: DPAPI 加密。其他平台:明文(文件权限已收紧到 600)。"""
|
||||
if not text:
|
||||
return text
|
||||
if sys.platform == "win32":
|
||||
return _dpapi_protect(text)
|
||||
return _kr_protect(text)
|
||||
try:
|
||||
return _dpapi_protect(text)
|
||||
except Exception:
|
||||
return text
|
||||
return text
|
||||
|
||||
|
||||
def unprotect(text: str) -> str:
|
||||
@@ -185,6 +175,8 @@ class Store:
|
||||
h[k] = protect(h[k])
|
||||
tmp = self.path.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
if sys.platform != "win32":
|
||||
os.chmod(tmp, 0o600) # 明文机密:至少限制为仅本用户可读
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
@staticmethod
|
||||
|
||||
Reference in New Issue
Block a user