245 lines
8.0 KiB
Python

"""Offline Ed25519 license verification + entitlement for Sanad packages.
A license file is JSON:
{
"payload": {
"robot_id": "G1-SN-0001",
"machine_fingerprint": "<sha256 hex>", # optional; checked iff binding on
"packages": {"P1": true, "P2": false, "P3": true, "P4": false},
"features": {"language": "ar", "multilingual": false, ...},
"issued": "2026-06-01",
"expires": "2027-06-01" # optional; null = perpetual
},
"sig": "<base64 ed25519 signature over the CANONICAL payload>"
}
The vendor holds the Ed25519 private key; every image ships the public key.
Verification is fully OFFLINE (no network), suitable for a robot that may be
disconnected.
Search order (highest first):
license : $SANAD_LICENSE else /etc/sanad/sanad.lic
pubkey : $SANAD_PUBKEY else /etc/sanad/pubkey.ed25519
else <this dir>/pubkey.ed25519
Env knobs:
SANAD_LICENSE_BIND=1 enforce machine_fingerprint == this machine
SANAD_LICENSE_DEV=1 if `cryptography` is missing, accept UNSIGNED licenses
(development only — never set on a shipped robot)
Kept Python-3.8 compatible.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
try: # optional — present in every shipped image, maybe not on a bare dev box
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature
_HAVE_CRYPTO = True
except Exception: # pragma: no cover
_HAVE_CRYPTO = False
# Keep IN SYNC with licensing/sign_license.py::canonical()
def canonical(payload: Dict[str, Any]) -> bytes:
"""Deterministic byte serialization signed/verified on both sides."""
return json.dumps(
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
).encode("utf-8")
def _default_license_path() -> Path:
return Path(os.environ.get("SANAD_LICENSE", "/etc/sanad/sanad.lic"))
def _default_pubkey_path() -> Path:
env = os.environ.get("SANAD_PUBKEY")
if env:
return Path(env)
etc = Path("/etc/sanad/pubkey.ed25519")
if etc.exists():
return etc
return Path(__file__).resolve().parent / "pubkey.ed25519"
def machine_fingerprint(iface: Optional[str] = None) -> str:
"""Stable per-robot id = sha256(eth0 MAC + /etc/machine-id).
Binds a license to one G1 so a copied license fails on another machine.
Best-effort: missing inputs are simply omitted from the hash.
"""
iface = iface or os.environ.get("SANAD_DDS_INTERFACE", "eth0")
parts = []
try:
mac = Path("/sys/class/net/%s/address" % iface).read_text().strip()
if mac:
parts.append(mac)
except Exception:
pass
for mid in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
try:
v = Path(mid).read_text().strip()
if v:
parts.append(v)
break
except Exception:
pass
return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()
def _load_pubkey():
"""Return an Ed25519PublicKey, or None if unavailable.
pubkey file format: base64 of the raw 32-byte public key (one line),
or 64-char hex. Whitespace tolerated.
"""
if not _HAVE_CRYPTO:
return None
path = _default_pubkey_path()
raw_text = path.read_text().strip()
try:
if len(raw_text) == 64 and all(c in "0123456789abcdefABCDEF" for c in raw_text):
key_bytes = bytes.fromhex(raw_text)
else:
key_bytes = base64.b64decode(raw_text)
except Exception as exc:
raise ValueError("unreadable public key at %s: %s" % (path, exc))
return Ed25519PublicKey.from_public_bytes(key_bytes)
class License(object):
"""A loaded + verified (or rejected) license."""
def __init__(self, payload: Dict[str, Any], valid: bool, reason: str = ""):
self.payload = payload or {}
self.valid = valid
self.reason = reason
# -- entitlement queries --
def package(self, pkg: str) -> bool:
if not self.valid:
return False
return bool(self.payload.get("packages", {}).get(pkg, False))
def feature(self, name: str, default: Any = False) -> Any:
if not self.valid:
return default
return self.payload.get("features", {}).get(name, default)
@property
def robot_id(self) -> str:
return str(self.payload.get("robot_id", ""))
@property
def expires(self) -> Optional[str]:
return self.payload.get("expires")
def summary(self) -> Dict[str, Any]:
pkgs = self.payload.get("packages", {}) if self.valid else {}
return {
"valid": self.valid,
"reason": self.reason,
"robot_id": self.robot_id,
"expires": self.expires,
"packages": {k: bool(v) for k, v in pkgs.items()},
"features": self.payload.get("features", {}) if self.valid else {},
}
def _check_expiry(payload: Dict[str, Any]) -> Tuple[bool, str]:
exp = payload.get("expires")
if not exp:
return True, ""
try:
# accept "YYYY-MM-DD" or full ISO
dt = datetime.fromisoformat(str(exp))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
except Exception:
return False, "unparseable expires=%r" % exp
if datetime.now(timezone.utc) > dt:
return False, "license expired %s" % exp
return True, ""
def load(path: Optional[str] = None) -> License:
"""Load + fully verify the license. Never raises — returns an invalid
License with a `reason` on any failure (fail-closed)."""
lpath = Path(path) if path else _default_license_path()
if not lpath.exists():
return License({}, False, "license file not found: %s" % lpath)
try:
doc = json.loads(lpath.read_text(encoding="utf-8"))
except Exception as exc:
return License({}, False, "license JSON unreadable: %s" % exc)
payload = doc.get("payload")
sig_b64 = doc.get("sig")
if not isinstance(payload, dict):
return License({}, False, "license missing 'payload'")
# 1) signature
if _HAVE_CRYPTO:
if not sig_b64:
return License(payload, False, "license missing 'sig'")
try:
pub = _load_pubkey()
if pub is None:
return License(payload, False, "public key unavailable")
pub.verify(base64.b64decode(sig_b64), canonical(payload))
except InvalidSignature:
return License(payload, False, "signature verification FAILED")
except Exception as exc:
return License(payload, False, "signature check error: %s" % exc)
else:
if os.environ.get("SANAD_LICENSE_DEV") == "1":
# dev box without cryptography — accept unsigned, but say so
pass
else:
return License(payload, False,
"cryptography unavailable and SANAD_LICENSE_DEV != 1")
# 2) expiry
ok, reason = _check_expiry(payload)
if not ok:
return License(payload, False, reason)
# 3) machine binding (optional)
if os.environ.get("SANAD_LICENSE_BIND") == "1":
want = payload.get("machine_fingerprint")
if want:
have = machine_fingerprint()
if want != have:
return License(payload, False,
"machine fingerprint mismatch (license bound to another robot)")
return License(payload, True, "ok")
# module-level convenience (one cached load)
_CACHED = None # type: Optional[License]
def current(reload: bool = False) -> License:
global _CACHED
if _CACHED is None or reload:
_CACHED = load()
return _CACHED
def entitled(pkg: str) -> bool:
return current().package(pkg)
def feature(name: str, default: Any = False) -> Any:
return current().feature(name, default)