Files
Crypto_Scam/LinuxServer/keystore.py
T
listik efd4e1dcf4
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
linux
2026-10-23 21:36:08 +03:00

140 lines
5.3 KiB
Python

"""Exchange API keys for real trading, one pair (key + secret) per exchange.
Stored in web_sim_data/api_keys.bin encrypted with Windows DPAPI (CryptProtectData, current user): the file can be
read back only by this Windows user on this computer. The page never receives a secret — only a masked key.
"""
from __future__ import annotations
import ctypes
import json
import os
import secrets
import threading
from ctypes import wintypes
from pathlib import Path
ROOT = Path(__file__).resolve().parent
KEYS_FILE = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")) / "api_keys.bin"
EXCHANGES = {"bybit": "Bybit", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"}
_lock = threading.Lock()
class _Blob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
def _blob(data: bytes) -> _Blob:
buf = ctypes.create_string_buffer(data, len(data))
return _Blob(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
def _take(blob: _Blob) -> bytes:
try:
return ctypes.string_at(blob.pbData, blob.cbData)
finally:
ctypes.windll.kernel32.LocalFree(blob.pbData)
def protect(data: bytes) -> bytes:
if os.name != "nt":
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
nonce = secrets.token_bytes(12)
return b"CSK1" + nonce + AESGCM(_linux_master_key()).encrypt(nonce, data, b"crypto-scam-api-keys-v1")
out = _Blob()
if not ctypes.windll.crypt32.CryptProtectData(ctypes.byref(_blob(data)), "simulator api keys", None, None, None,
0, ctypes.byref(out)):
raise OSError("не удалось зашифровать ключи (DPAPI)")
return _take(out)
def unprotect(data: bytes) -> bytes:
if os.name != "nt":
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
if not data.startswith(b"CSK1") or len(data) < 32:
raise OSError("неподдерживаемый формат или повреждённый файл ключей")
nonce = data[4:16]
try:
return AESGCM(_linux_master_key()).decrypt(nonce, data[16:], b"crypto-scam-api-keys-v1")
except Exception as exc:
raise OSError("не удалось расшифровать API-ключи Linux") from exc
out = _Blob()
if not ctypes.windll.crypt32.CryptUnprotectData(ctypes.byref(_blob(data)), None, None, None, None, 0,
ctypes.byref(out)):
raise OSError("не удалось расшифровать ключи (другой пользователь Windows или другой компьютер?)")
return _take(out)
def _linux_master_key() -> bytes:
path = Path(os.environ.get("CRYPTO_SCAM_MASTER_KEY_FILE", "/etc/crypto-scam/master.key"))
try:
key = path.read_bytes()
except OSError as exc:
raise OSError(f"нет серверного ключа шифрования: {path}") from exc
if len(key) != 32:
raise OSError("серверный ключ шифрования должен быть ровно 32 байта")
return key
def load(path: Path | None = None) -> dict[str, dict]:
path = path or KEYS_FILE
try:
raw = path.read_bytes()
except OSError:
return {}
try:
data = json.loads(unprotect(raw).decode("utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def _save(data: dict, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
tmp = path.with_suffix(".tmp")
tmp.write_bytes(protect(json.dumps(data).encode("utf-8")))
try:
os.chmod(tmp, 0o600)
os.chmod(path.parent, 0o700)
except OSError:
pass
tmp.replace(path)
def set_keys(exchange: str, api_key: str, api_secret: str, path: Path | None = None) -> str:
if exchange not in EXCHANGES:
return "неизвестная биржа"
api_key, api_secret = (api_key or "").strip(), (api_secret or "").strip()
if not api_key or not api_secret:
return "нужны и API key, и secret"
if len(api_key) > 200 or len(api_secret) > 400 or any(c.isspace() for c in api_key + api_secret):
return "ключ выглядит неверно (пробелы или слишком длинный)"
with _lock:
data = load(path)
data[exchange] = {"key": api_key, "secret": api_secret}
_save(data, path or KEYS_FILE)
return ""
def delete_keys(exchange: str, path: Path | None = None) -> None:
with _lock:
data = load(path)
if data.pop(exchange, None) is not None:
_save(data, path or KEYS_FILE)
def get(exchange: str, path: Path | None = None) -> tuple[str, str] | None:
d = load(path).get(exchange)
return (d["key"], d["secret"]) if d and d.get("key") and d.get("secret") else None
def mask(key: str) -> str:
return key[:4] + "…" + key[-4:] if len(key) > 10 else "…" + key[-2:]
def summary(path: Path | None = None) -> dict[str, dict]:
"""What the page may see: whether keys are set and a masked key — never the secret."""
data = load(path)
return {ex: {"name": name, "set": ex in data, "key": mask(data[ex]["key"]) if ex in data else ""}
for ex, name in EXCHANGES.items()}