"""Keyfern client for Python. One file, one dependency: `pip install cryptography`. from keyfern import Keyfern, KeyfernError, KeyfernNetworkError kf = Keyfern(product="prod_xxx", public_key="", url="https://your-keyfern-host", cache_path="license.cache") try: lic = kf.activate_or_cached("ABCDE-FGHIJ-KLMNO-PQRST") # online, falls back to the cache offline except KeyfernError as e: # server said no: blocked, expired, machine_limit... print(e.code, e) if 5 in lic.features: ... Security model: every answer is signed with the product's Ed25519 key and this client only trusts answers whose signature verifies with the PUBLIC key you embed. A fake server cannot unlock anything. The nonce stops replay of an old answer; `lease_until` bounds offline use; a monotonic clock guard in the cache makes setting the PC clock back useless. """ import base64 import hashlib import json import os import platform import secrets import subprocess import time import urllib.error import urllib.request from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey __all__ = ["Keyfern", "License", "KeyfernError", "KeyfernNetworkError", "machine_code"] class KeyfernError(Exception): """The server (or the signature check) refused. `code` is the machine-readable reason.""" def __init__(self, code, message=""): super().__init__(message or code) self.code = code class KeyfernNetworkError(Exception): """The server could not be reached: the caller may fall back to the cached license.""" def _b64d(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def machine_code(salt="keyfern"): """Stable per-PC id (hashed, never leaves the PC raw). Pass your own string to activate() if you prefer.""" raw = "" try: if platform.system() == "Windows": import winreg with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography", 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as k: raw = winreg.QueryValueEx(k, "MachineGuid")[0] elif platform.system() == "Darwin": out = subprocess.run(["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], capture_output=True, text=True, timeout=5).stdout raw = next((l.split('"')[-2] for l in out.splitlines() if "IOPlatformUUID" in l), "") else: for p in ("/etc/machine-id", "/var/lib/dbus/machine-id"): if os.path.exists(p): raw = open(p).read().strip() break except Exception: pass raw = raw or platform.node() + str(__import__("uuid").getnode()) return hashlib.sha256(f"{salt}|{raw}".encode()).hexdigest()[:32] class License: """The verified license. Attribute access to every field of the signed payload.""" def __init__(self, payload): self.raw = payload self.key = payload["key"] self.status = payload["status"] self.expires = payload["expires"] # unix seconds or None (never) self.lease_until = payload["lease_until"] # offline use allowed until then (None = no limit) self.features = payload["features"] # e.g. [1, 5] self.max_machines = payload["max_machines"] self.machines_used = payload["machines_used"] self.customer = payload["customer"] # {"name":..., "email":...} self.meta = payload["meta"] # your custom data self.usage = payload["usage"] # {"count":..., "limit":...} self.issued_at = payload["iat"] def has(self, feature): return feature in self.features @property def days_left(self): return None if self.expires is None else max(0, (self.expires - time.time()) / 86400) def __repr__(self): return f"" class Keyfern: def __init__(self, product, public_key, url="https://keyfern.com", cache_path=None, timeout=15): self.product = product self._pub = Ed25519PublicKey.from_public_bytes(_b64d(public_key)) self.url = url.rstrip("/") self.cache_path = cache_path self.timeout = timeout # ---- transport ---- def _post(self, path, body): req = urllib.request.Request(self.url + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST") try: with urllib.request.urlopen(req, timeout=self.timeout) as r: return json.loads(r.read()) except urllib.error.HTTPError as e: try: j = json.loads(e.read()) except Exception: raise KeyfernNetworkError(f"HTTP {e.code}") from None if e.code >= 500 or e.code == 429: raise KeyfernNetworkError(j.get("message") or f"HTTP {e.code}") from None raise KeyfernError(j.get("error", "error"), j.get("message", "")) from None except (urllib.error.URLError, TimeoutError, OSError) as e: raise KeyfernNetworkError(str(e)) from None # ---- verification ---- def _verify(self, resp, nonce=None): try: payload_bytes = _b64d(resp["payload"]) self._pub.verify(_b64d(resp["sig"]), payload_bytes) except (InvalidSignature, KeyError, ValueError): raise KeyfernError("bad_signature", "License answer failed signature verification") from None p = json.loads(payload_bytes) if p.get("product") != self.product: raise KeyfernError("bad_signature", "License answer is for another product") if nonce is not None and p.get("nonce") != nonce: raise KeyfernError("replay", "License answer does not match this request") return p def _call(self, path, extra): nonce = secrets.token_urlsafe(16) resp = self._post(path, {"product": self.product, "nonce": nonce, **extra}) return resp, nonce # ---- API ---- def activate(self, key, machine=None, name=None): machine = machine or machine_code() resp, nonce = self._call("/v1/activate", {"key": key, "machine": machine, "name": name or platform.node()}) p = self._verify(resp, nonce) if p["status"] != "active": raise KeyfernError(p["status"], f"License is {p['status']}") self._save(resp, machine) return License(p) def validate(self, key, machine=None): """Read-only (does not register this PC). Also answers for expired keys, e.g. to show a Renew button.""" resp, nonce = self._call("/v1/validate", {"key": key, **({"machine": machine} if machine else {})}) return License(self._verify(resp, nonce)) def deactivate(self, key, machine=None): self._post("/v1/deactivate", {"product": self.product, "key": key, "machine": machine or machine_code()}) self.clear_cache() def trial(self, machine=None): machine = machine or machine_code() resp, nonce = self._call("/v1/trial", {"machine": machine}) p = self._verify(resp, nonce) self._save(resp, machine) return License(p) # ---- offline cache ---- def _save(self, resp, machine): if not self.cache_path: return data = {"resp": resp, "machine": machine, "last_seen": time.time()} tmp = self.cache_path + ".tmp" with open(tmp, "w") as f: json.dump(data, f) os.replace(tmp, self.cache_path) def clear_cache(self): if self.cache_path and os.path.exists(self.cache_path): os.remove(self.cache_path) def cached(self, machine=None): """Verified license from the cache, or raise KeyfernError (no cache / forged / expired lease / clock rolled back).""" if not self.cache_path or not os.path.exists(self.cache_path): raise KeyfernError("no_cache", "No cached license") try: data = json.load(open(self.cache_path)) except Exception: raise KeyfernError("no_cache", "Cache unreadable") from None p = self._verify(data["resp"]) now = time.time() if p["machine"] != (machine or machine_code()): raise KeyfernError("wrong_machine", "Cached license belongs to another PC") if now < max(data.get("last_seen", 0), p["iat"]) - 3600: # 1 h tolerance for clock fixes raise KeyfernError("clock_rollback", "System clock was set back") if p["expires"] is not None and p["expires"] <= now: raise KeyfernError("expired", "License has expired") if p["lease_until"] is not None and p["lease_until"] <= now: raise KeyfernError("lease_expired", "Offline period is over: connect to the internet once") data["last_seen"] = now json.dump(data, open(self.cache_path, "w")) return License(p) def activate_or_cached(self, key, machine=None): """Normal start-up call: online check when possible, cached license when offline.""" try: return self.activate(key, machine) except KeyfernNetworkError: return self.cached(machine) except KeyfernError as e: if e.code in ("blocked", "expired", "invalid_key", "machine_limit"): self.clear_cache() raise