You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/engine/virsh_panel/engine_security.py

101 lines
4.3 KiB
Python

"""Non-browser HMAC transport: signed actors, payloads, time and replay defense."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import re
import secrets
import time
class EngineAuthError(Exception):
def __init__(self, message="内部服务认证失败", status=401):
super().__init__(message)
self.status = status
def canonical(method: str, target: str, digest: str, timestamp: str,
nonce: str, encoded_actor: str) -> bytes:
return "\n".join((method.upper(), target, digest, timestamp, nonce, encoded_actor)).encode("utf-8")
def decode_secret(encoded: str) -> bytes:
try:
value = base64.b64decode(encoded, validate=True)
except (ValueError, TypeError) as exc:
raise ValueError("Engine service secret must be base64-encoded 32 bytes") from exc
if len(value) != 32:
raise ValueError("Engine service secret must be base64-encoded 32 bytes")
return value
def encode_actor(value: dict) -> str:
return base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":"),
ensure_ascii=True).encode()).decode().rstrip("=")
def signed_headers(secret: bytes, method: str, target: str, body: bytes, actor: dict,
*, timestamp: int | None = None, nonce: str | None = None) -> dict:
timestamp_raw = str(int(time.time()) if timestamp is None else timestamp)
nonce = nonce or secrets.token_urlsafe(24)
encoded = encode_actor(actor)
digest = hashlib.sha256(body).hexdigest()
signature = hmac.new(secret, canonical(method, target, digest, timestamp_raw, nonce, encoded),
hashlib.sha256).hexdigest()
return {"X-Cloud-Timestamp": timestamp_raw, "X-Cloud-Nonce": nonce,
"X-Cloud-Actor": encoded, "X-Cloud-Signature": signature}
def parse_actor(encoded: str) -> dict:
if not encoded or len(encoded) > 8192 or not re.fullmatch(r"[A-Za-z0-9_-]+", encoded):
raise EngineAuthError()
try:
raw = base64.b64decode(encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True)
value = json.loads(raw)
except (ValueError, UnicodeError) as exc:
raise EngineAuthError() from exc
if not isinstance(value, dict):
raise EngineAuthError()
user_id = value.get("user_id")
if isinstance(user_id, bool) or not isinstance(user_id, int) or not 1 <= user_id < 2**63:
raise EngineAuthError()
for key in ("is_admin", "is_super_admin", "can_manage"):
if not isinstance(value.get(key), bool):
raise EngineAuthError()
if value["is_super_admin"] and not value["is_admin"]:
raise EngineAuthError()
for key in ("can_provision", "system_cleanup"):
if key in value and not isinstance(value[key], bool):
raise EngineAuthError()
if "operation_id" in value and not re.fullmatch(r"[A-Za-z0-9_-]{8,80}", str(value["operation_id"])):
raise EngineAuthError()
session_id = value.get("session_id", "")
if not isinstance(session_id, str) or len(session_id) > 256 or any(ord(c) < 33 for c in session_id):
raise EngineAuthError()
return value
def authenticate(headers: dict, secret: bytes, method: str, target: str,
digest: str, nonce_store, *, now: int | None = None) -> dict:
now = int(time.time()) if now is None else now
timestamp_raw = headers.get("x-cloud-timestamp", "")
nonce = headers.get("x-cloud-nonce", "")
encoded_actor = headers.get("x-cloud-actor", "")
signature = headers.get("x-cloud-signature", "")
if (not re.fullmatch(r"[0-9]{1,12}", timestamp_raw)
or abs(now - int(timestamp_raw)) > 60
or not re.fullmatch(r"[A-Za-z0-9_-]{16,128}", nonce)
or not re.fullmatch(r"[0-9a-f]{64}", signature)
or not re.fullmatch(r"[0-9a-f]{64}", digest)):
raise EngineAuthError()
expected = hmac.new(secret, canonical(method, target, digest, timestamp_raw, nonce, encoded_actor),
hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
raise EngineAuthError()
value = parse_actor(encoded_actor)
if not nonce_store.consume_nonce(nonce, now + 121, now):
raise EngineAuthError("内部服务请求已使用,已拒绝重放")
return value