Everyone thinks DRM is encryption. “Encrypt the video with a key, hand the key to the player when the user is entitled, done.” Then the interviewer asks the questions that decide whether the thing actually protects anything: what stops the user from reading that key out of their own device’s memory and posting it online so a million people decrypt the same file; what stops them from copying a valid license to a second device, or to a thousand devices, and watching everywhere on one subscription; what stops them from capturing a license today and replaying it next year after they cancelled; and how do you serve license requests for 80 million subscribers starting playback at 8pm without the license server becoming the thing that keeps everyone from watching. Now it is a real problem.
DRM is deceptive because the naive “encrypt and hand over the key” design is correct in exactly the world where the user’s device is trustworthy and the user is honest. In the real world the attacker owns the hardware the decryption runs on. They control the OS, they can attach a debugger, they can snapshot RAM, they can patch the player binary. The entire discipline is about one brutal constraint: you must deliver a decryption key to a machine whose operator is your adversary, and keep it usable only inside a boundary that operator cannot cross. That single constraint - never trust the client, but still run the decryption on it - drives every decision below. And unlike a soft gate, this one fails closed: when in doubt, deny.
Let me do it properly.
Functional Requirements (FR)
In scope:
- Issue a license to play a specific piece of encrypted content to a specific entitled user. A license carries the content key (or the material to derive it) plus a usage policy (expiry, output rules, offline allowance).
- Bind every license to one verified device. A license minted for device A must be cryptographically useless on device B. Copying the token file to another machine must not grant playback.
- Make licenses short-lived. A playback license expires quickly (minutes to a session). A captured license must not be replayable tomorrow, next week, or after the user cancels, without going back to the license server and re-authenticating.
- Verify the playback client before issuing. Only a genuine, untampered player on genuine, attested hardware should receive a key. A patched player or an emulator should be refused.
- Protect the key in use. The content key must be delivered and used inside a protected boundary (a hardware-backed secure environment / TEE where available) so it is never exposed in plaintext to ordinary application memory.
- Support entitlement policy. Subscription active, rental window, geo/output constraints (e.g. no HD on an unprotected HDMI path), concurrent-device caps.
- Support offline/download playback with a longer-lived but still bounded and revocable persistent license.
- Revocation. Revoke a compromised device, a leaked key, or a cancelled user quickly.
Explicitly out of scope (say it so you control scope):
- The content encryption/packaging pipeline and CDN delivery of the encrypted bytes. We assume content is already encrypted at rest with per-title content keys and served by a CDN. We design the license and key-delivery system, not the transcoder. (That is a separate build.)
- The browser/OS CDM implementation itself (Widevine/PlayReady/FairPlay internals). We design a platform that behaves like and integrates with a CDM-backed client, including our own attested native player; we do not reimplement a CDM.
- Billing and the entitlement source of truth. We read entitlements; we do not sell subscriptions.
- Account login / identity. We assume an authenticated
user_idarrives with the request. - Forensic watermarking / piracy tracing. Related and worth a sentence (watermark so a captured stream can be traced to a leaker), but a distinct subsystem.
The one decision that drives everything: the device, not the user, is the unit of trust, and that trust must be re-proven cryptographically on every license request. We do not hand out a key because “the account is valid.” We hand out a key because this specific attested device proved, in this request, that it is genuine, untampered, and the one the key will be locked to.
Non-Functional Requirements (NFR)
- Scale: 80M subscribers, assume ~250M registered devices (phones, TVs, tablets, laptops, consoles). Peak license issuance at prime time is the spike that matters: budget ~200K-400K license requests/sec at peak, because every title start, every quality switch that re-keys, and every short-lived license renewal is a request. Attestation checks ride along with issuance.
- Latency: the license fetch sits between “user pressed play” and “video decrypts.” Target under ~150ms at p99 for license issuance including attestation verification. It is a hard gate - the video literally cannot decode until the key arrives - so it must be fast, but correctness beats speed here (unlike a soft concurrency gate).
- Availability: 99.99%+ for issuance. But note the asymmetry versus a soft gate: this system fails closed. If we cannot verify a device, we deny the key. We buy availability through replication and caching of verification material, never by skipping verification. We would rather briefly block playback than leak a key to an unverified device.
- Consistency: entitlement and revocation reads must be strongly consistent on the deny path - a revoked device or a cancelled subscription must stop getting keys quickly. Issuing a key to someone who just lost entitlement is a real loss. Device-registration state is read-heavy and can be served from strongly-consistent-on-write, replicated-for-read stores.
- Durability: high for the long-lived secrets - device public keys, the root/content-key-wrapping keys (in an HSM), revocation lists, and audit logs. Low for the ephemeral per-session keys, which are derived on demand and never stored.
- Security (the real NFR): keys must never transit or rest in plaintext outside a protected boundary; every license is bound to one device and one short time window; a full database compromise must not expose usable content keys (they are wrapped by HSM-held keys); every issuance is auditable.
Back-of-the-Envelope Estimation (BoE)
Let me ground it in numbers.
License issuance rate (the write/compute that matters):
Subscribers: 80,000,000
Registered devices: ~250,000,000
Concurrent streams at peak: ~20,000,000
A license is short-lived. Say a playback license lives ~5 min
and must be renewed for the duration of a ~2 hour movie:
renewals per session = 120 min / 5 min = ~24 license ops/session
(first issue + ~23 renewals)
Steady issuance from 20M concurrent sessions:
20,000,000 sessions * (1 op / 5 min) / 60
= 20,000,000 / 300
≈ 66,000 license ops/sec steady
Peak (prime-time starts + launches, 3-6x steady):
budget ~200,000 - 400,000 license ops/sec
That is the core load, and every one of those ops does an attestation / signature verification plus a key-wrap - CPU-bound crypto, not I/O. That reframes the whole system: the license server is a crypto farm, not a database. Sizing is dominated by signature verifications/sec.
Crypto cost:
Per request: verify client attestation signature (ECDSA P-256 verify ~ tens of us)
+ derive session key (HKDF, cheap)
+ wrap content key for the device (ECIES / ECDH + AES-GCM, ~tens of us)
A modern core does ~20k-40k ECDSA verifies/sec.
400,000 verifies/sec / ~25k per core ≈ 16 cores of pure verify
-> a few dozen modest license-server instances. Trivial to scale horizontally.
Storage:
Device registry: 250M devices * ~500 bytes
(device_id, user_id, device_pubkey ~65-91B, attestation metadata,
model, created_at, status)
≈ 125 GB. Small. Fits comfortably in a sharded SQL/NoSQL store with replicas.
Content keys: #titles (say 500k assets * a few keys each, HD/UHD/audio)
~ a few million keys * (wrapped key 48B + metadata)
≈ under 1 GB. Tiny, but it is the crown jewels - stored WRAPPED by an HSM key.
Revocation list: compromised devices + leaked keys.
Even 1M revoked devices * 20B ≈ 20 MB. Fits in memory / a bloom filter at the edge.
Audit log: every issuance, for forensics.
400k/sec * ~300B * 86400s ≈ ~10 TB/day -> stream to cheap append-only
object storage / log pipeline, tiered out. This, not the keys, is the bulk.
Bandwidth: a license request + response is a couple of KB (attestation blob in, wrapped key + policy out). 400K/sec * ~2KB ≈ ~800 MB/sec of license traffic spread across the fleet. Trivial next to the video bytes (which the CDN serves and we never touch). Confirms it again: the challenge is crypto throughput, trust verification, and revocation latency - not bytes and not storage.
High-Level Design (HLD)
DRM is not something the video bytes route through; the encrypted media streams from the CDN completely independently. Our system is consulted to mint a key the player can only use inside its secure boundary, bound to that device, for a few minutes. Here is the end-to-end picture: a one-time device enrollment that establishes a hardware-attested identity, then a per-playback license flow that verifies that identity live and derives a per-session, device-wrapped key.
┌───────────────────────────────────────────────────────────────┐
│ Playback client: secure player + TEE/CDM (secure boundary) │
│ - holds device private key inside hardware-backed keystore │
│ - generates hardware attestation of its integrity │
└───────┬───────────────────────────────────────────────┬───────┘
│ (A) ENROLL once: attest hardware, register pubkey │
│ (B) PLAY: request license w/ fresh attestation │ encrypted
▼ │ media
┌───────────────────────────────┐ │ (separate)
│ API Gateway / LB │ ▼
│ TLS, rate-limit, route by │ ┌─────────────────┐
│ device_id / user_id │ │ CDN / Origin │
└───────┬─────────────────────────┘ │ encrypted .cmaf │
│ │ segments (AES) │
▼ └─────────────────┘
┌──────────────────────────────────────────────┐
│ License Server (stateless) │
│ 1. verify attestation signature + freshness │
│ 2. check entitlement + revocation (fail closed)│
│ 3. ECDH w/ device pubkey -> per-session key │
│ 4. unwrap content key (HSM), rewrap for device │
│ 5. sign short-lived license (expiry, policy) │
└───┬────────┬────────────┬───────────┬──────────┘
│ │ │ │
▼ ▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────────┐ ┌──────────────┐
│ Device │ │Entitle-│ │Content │ │ HSM / KMS │
│Registry│ │ ment │ │Key Store │ │ root wrap keys │
│(pubkeys│ │ DB │ │(wrapped │ │ unwrap/sign │
│ +state)│ │ │ │ keys) │ │ (keys never │
└────────┘ └────────┘ └──────────┘ │ leave HSM) │
▲ └──────────────┘
│ enrollment verifies attestation roots
┌───────────────────────────────────────┐
│ Attestation Verifier (Google/Apple/ │
│ platform attestation root certs, │
│ SafetyNet/Play Integrity/DeviceCheck) │
└───────────────────────────────────────┘
Revocation list (device + key CRL) is pushed to every License Server
instance and cached in-memory / bloom-filtered for O(1) deny checks.
Request flow - enrollment (once per device):
- On first use, the client generates a device key pair inside the hardware-backed keystore (StrongBox / Secure Enclave / TPM). The private key never leaves that hardware.
- The client produces a hardware attestation: a platform-signed statement (“this public key lives in genuine secure hardware on an unrooted device, this app is the genuine signed binary”). On Android that is a Key Attestation certificate chain + Play Integrity verdict; on iOS, DeviceCheck/App Attest; on desktop, a TPM quote.
- The client sends
POST /enrollwith the device public key + attestation blob. The server verifies the attestation chains to a trusted platform root, that the integrity verdict is clean, and that the app signature matches ours. If good, it storesdevice_id -> device_pubkey -> user_idwith statusactive.
Request flow - playback (every few minutes):
- User presses play. The player asks its secure boundary to produce a fresh, nonce-bound attestation/proof that it still controls the enrolled private key (a signature over a server-issued challenge/nonce + timestamp).
POST /licensecarriesdevice_id,content_id, the signed challenge, and the requested quality. The gateway routes bydevice_id.- The License Server verifies the signature against the stored device public key, checks the nonce is fresh (anti-replay) and unexpired, then checks entitlement (subscription active, geo, rental window) and revocation (device not revoked, key not revoked). Any failure -> deny (fail closed).
- It derives a per-session key via ECDH between a server ephemeral key and the device’s public key, feeds it through HKDF with the session nonce, fetches the wrapped content key, asks the HSM to unwrap it, and re-wraps the content key for this device/session so only this device’s secure boundary can unwrap it.
- It builds a short-lived signed license: the wrapped key + policy (expiry e.g. +5 min, output protections, device binding) + a signature. Returns it.
- The player hands the license to its secure boundary, which unwraps the content key inside the TEE, and decrypts media segments there. The plaintext key and plaintext frames ideally never touch normal app memory (secure video path).
- Before expiry, the player renews (back to step 1). After cancel/revoke, the next renewal is denied and playback stops within one license window.
The architectural heart is steps 1, 4, and 5 together: a key the server mints is wrapped so only one device’s hardware can open it, derived freshly per session, and valid for only minutes. Copy the license anywhere else and it is ciphertext that no other device’s enclave can unwrap; hold it past expiry and it is dead.
Component Deep Dive
Four hard parts: (1) how to deliver a key to an adversary-controlled device and keep it from being extracted, (2) how to bind a license to one device so a copy is useless, (3) how to trust that the device is genuine (attestation), and (4) how to make licenses short-lived and revocable without the renewal traffic or the revocation check becoming the bottleneck. I will walk each from naive to the real design.
1. Delivering the Key Without Leaking It: Plaintext Key -> HSM-Wrapped, TEE-Only Key
Approach A: ship the content key in the license response (the naive instinct)
Encrypt each title with a key K. When the user is entitled, return K in the JSON license. The player decrypts.
GET /license?content=123 -> { "key": "a1b2c3...the AES key..." }
player: AES_decrypt(segment, key) # key sits in app memory
Dead simple. Where it breaks: the key is in plaintext in the memory of a machine the attacker owns. They attach a debugger or dump RAM and read K straight out. Worse, K is the key for the whole title and the same for every user, so one extraction lets anyone decrypt the content forever - a single leaked key breaks the asset globally. There is no client-side obfuscation that fixes this; obfuscation only raises the cost of an attack that still fundamentally works, because you handed the plaintext key to the adversary. This is the original sin of DIY DRM.
Approach B: wrap the key for the device, decrypt only inside a secure boundary (the fix)
Two moves. First, never deliver a bare key; deliver a key wrapped so only this device’s hardware-held private key can unwrap it. The content key K is encrypted to the device’s public key (ECIES: ECDH to the device pubkey + AES-GCM). The matching private key lives in the Secure Enclave / StrongBox / TPM and cannot be exported, so the unwrap can only happen on that one device.
Second, the unwrap and the AES decryption of video happen inside a Trusted Execution Environment (TEE) / CDM’s secure boundary, not in ordinary app memory. The plaintext content key and ideally the decoded frames live in protected memory the main OS cannot read (secure video path, HDCP on output). The app orchestrates; it never sees the key.
Server side (per request):
K = content key for this title+quality (from key store)
wrapped_K = ECIES_encrypt(device_pubkey, K) # only this device unwraps
license = sign( wrapped_K + policy + expiry )
Device side (inside TEE):
K = ECIES_decrypt(device_privkey_in_hardware, wrapped_K)
frame = AES_decrypt(segment, K) # in secure memory
-> secure decode/render path; app never touches K or plaintext frame
And the content keys at rest on our side are themselves wrapped by an HSM-held master key; the License Server asks the HSM to unwrap just-in-time. So even a full dump of our content-key database yields only ciphertext - the unwrapping key never leaves the HSM. A database breach does not hand attackers usable keys.
Verdict: the key is never plaintext outside hardware - not on our servers (HSM-wrapped at rest), not in flight (device-wrapped), and not on the client (TEE-only). The attacker owning the device is downgraded from “reads the key” to “must break the hardware secure boundary,” which is a vastly higher bar and, crucially, does not scale to every other user.
2. Binding a License to One Device: Shared Key -> Per-Device, Per-Session Derived Key
Wrapping to the device pubkey (part 1) already means a copied license is ciphertext elsewhere. But we want more: even two sessions on the same device should not share key material, and a captured license should not be replayable even on its own device after expiry. That needs per-session derivation and an anti-replay binding.
Naive: one wrapped key per device, reused across sessions
Wrap K to the device once, cache it, reuse for every play. Where it breaks: the wrapped blob is static, so capturing one network response and replaying the request gets a predictable, reusable artifact; there is nothing tying the license to this play session or time, so a replay of an old license (or the request that produced it) can resurrect access after cancellation. And if the device’s secure boundary is ever cracked, every past and future session falls at once because they all share the same material.
Better: ECDH + HKDF per session, bound to a server nonce
Each license request carries a fresh server-issued nonce/challenge and timestamp, signed by the device’s hardware key. The server does an ephemeral-static ECDH (server ephemeral key x device static pubkey) and runs the shared secret through HKDF salted with the session nonce to derive a one-time session key SK. The content key is wrapped under SK. SK is never stored; it is re-derivable only by that device (it holds the static private key) for that nonce.
request: nonce = server_challenge (short TTL, single-use)
sig = Sign_device_hw( nonce || ts || content_id )
server: verify sig w/ device_pubkey; assert nonce fresh & unused; |ts - now| small
e_priv, e_pub = ephemeral_keypair()
shared = ECDH(e_priv, device_pubkey)
SK = HKDF(shared, salt=nonce, info="drm-session")
wrapped_K = AES_GCM_wrap(SK, K)
license = sign( e_pub || wrapped_K || policy || expiry(now+5m) )
device (TEE): shared = ECDH(device_priv_hw, e_pub)
SK = HKDF(shared, salt=nonce, info="drm-session")
K = AES_GCM_unwrap(SK, wrapped_K)
Now every property we wanted holds:
| Threat | Why it fails |
|---|---|
| Copy license to device B | wrapped_K is under SK derived from device A’s private key; B cannot derive SK. Useless ciphertext. |
| Replay old license on device A after expiry | Policy expiry is signed; player/TEE enforces it. Past expiry the license is rejected before decode. |
| Replay the license request | Nonce is single-use with a short TTL; a replayed request is rejected, and the device signature over `nonce |
| One cracked session leaks all | Each session derives an independent SK via a fresh ephemeral ECDH; cracking one yields one session’s key, not the device’s long-term secret. |
Verdict: per-session ECDH+HKDF binds the key to one device and one time-boxed session, so the three attacks the prompt names - key extraction reuse, cross-device replay, post-expiry replay - all collapse into “break fresh hardware-held crypto, per session, per device.” Nonce freshness is the anti-replay backbone; device-bound ECDH is the anti-copy backbone.
3. Trusting the Device Is Genuine: “It Said So” -> Hardware Attestation
Everything above assumes the private key really lives in genuine secure hardware on an untampered device. If it does not - if it is an emulator, a rooted phone, or a patched player extracting keys - the crypto is theater.
Naive: trust a client-reported device ID / “I am a real TV”
The client sends device_id and maybe a software fingerprint (user agent, model string, a hash of its own binary). Where it breaks: every one of those is attacker-controlled and trivially spoofable. A pirate runs the player under a debugger, reports whatever device_id and “I’m genuine” flag the server wants, and extracts keys at will. Software fingerprinting is a speed bump; the attacker owns the software. You cannot ask the adversary’s machine to honestly self-report its own compromise.
Better: hardware-rooted attestation chained to a platform root of trust
The device must prove its integrity with a statement signed by a key it cannot control - a manufacturer/platform key burned into secure hardware. The flow:
- Key generation with attestation. When the device creates its DRM key pair in StrongBox/Secure Enclave/TPM, the hardware issues a key attestation certificate signed by a chain rooting in the platform vendor’s attestation root CA. That cert asserts: this key is non-exportable, hardware-backed, generated on a device with a verified boot state, bound to our app’s signing identity.
- Runtime integrity verdict. On enrollment and periodically, the client fetches a platform integrity verdict (Android Play Integrity, iOS App Attest/DeviceCheck, Windows TPM quote) attesting the OS is not rooted/jailbroken, the bootloader is locked, and the running app binary matches the genuine signed one.
- Server verification. The License Server verifies the attestation certificate chain terminates at a pinned platform root, the integrity verdict is
MEETS_STRONG_INTEGRITY(or equivalent), the app identity matches, and the device is not on the revocation list. Only then does it register the device (enrollment) or honor a license request.
enroll:
attestation_chain = [ device_key_cert -> intermediate -> PLATFORM_ROOT ]
integrity_verdict = { basicIntegrity: true, strongIntegrity: true,
appRecognitionVerdict: "PLAY_RECOGNIZED",
rooted: false, emulator: false }
server:
assert chain verifies to pinned PLATFORM_ROOT
assert key is hardware-backed & non-exportable (per cert extension)
assert integrity_verdict strong && app signature == ours
else -> REJECT enrollment (fail closed)
Crucially, attestation is checked again, freshly, at license time (the signed nonce proves current control of the attested key), and the heavier integrity verdict is re-pulled periodically (say hourly) rather than every request, to keep the hot path cheap while still catching a device that got rooted mid-session.
Verdict: trust is rooted in hardware the attacker does not control, not in software self-reports. An emulator or rooted device cannot produce a chain terminating at the genuine platform root with a strong integrity verdict, so it never enrolls, so it never holds a key the wrapping targets. This is what makes parts 1 and 2 meaningful rather than ceremonial.
4. Short-Lived + Revocable Without a Bottleneck: Long License -> Renew + Pushed CRL
Short-lived licenses are the anti-replay story, but naively they multiply traffic and the revocation check can become a per-request database hit.
Naive: long-lived license, or a DB lookup per request for revocation
Option one: issue a license good for the whole movie (2h). Then a captured license is replayable for 2 hours and survives a cancellation for 2 hours - the window is huge. Option two: make it short-lived but check revocation by querying a central revoked table on every one of 400K req/sec. Where it breaks: the central revocation DB becomes a synchronous dependency on the hot path at 400K QPS, a single point of failure, and a latency tax on every play. Long licenses weaken security; naive short ones hammer a shared table.
Better: minutes-long licenses with cheap renewal, and a pushed in-memory CRL
Short license + renewal. Licenses expire in ~5 minutes; the player silently renews. The exposure window for a captured/replayed license shrinks to one renewal interval, and a cancelled/revoked user stops playing within ~5 minutes because the next renewal is denied. Renewal is the same crypto path, and we sized for it in the BoE - this is why the license server is a horizontally-scalable stateless crypto farm, so renewal traffic is just more cheap verifies.
Revocation as pushed state, not a per-request query. The revocation list (revoked device_ids and revoked content keys) is small (tens of MB even with millions of entries). It is published from a central revocation service to every stateless License Server instance and held in memory, fronted by a bloom filter for an O(1) “definitely-not-revoked” fast path. A revocation event propagates in seconds via the push channel (pub/sub); the deny check is a memory lookup, no DB round trip on the hot path.
revocation service (source of truth, SQL) --push/pubsub--> every License Server
License Server holds: bloom_filter(revoked) + in-mem set
deny check: if bloom says "maybe" -> confirm in set -> DENY ; else O(1) ALLOW
new revocation -> propagated in ~seconds -> all instances deny within one license window
Offline/download licenses are the explicit exception: they are longer-lived (the download window, e.g. 48h or 30 days per policy) and still device-bound and signed, but because they cannot renew while offline, they carry a stricter policy and are the primary reason the CRL exists - a revoked offline device is denied the moment it reconnects, and the content key is wrapped per-device so the offline file is useless if copied.
Verdict: short licenses + cheap renewal keep the replay window tiny and make cancellation take effect fast, while a pushed in-memory CRL keeps the revocation check off the hot-path database. The renewal volume is absorbed by stateless horizontal scaling, which the whole server is designed for.
API Design & Data Schema
Client-facing API
POST /v1/enroll # one-time device enrollment
Body: { user_id, device_pubkey,
attestation_chain, integrity_verdict, app_signature }
201: { device_id, enrollment_status: "active" }
403: { error: "attestation_failed", reason: "emulator|rooted|chain_invalid" }
GET /v1/challenge?device_id=... # fetch a fresh single-use nonce
200: { nonce, nonce_ttl_sec: 30 }
POST /v1/license # play-start / renewal: mint a license
Body: { device_id, content_id, quality,
nonce, device_signature, is_offline: false }
200: { license_id,
e_pub, # server ephemeral pubkey for ECDH
wrapped_key, # content key wrapped under session key
policy: { expires_at, output_protection: "hdcp2.2",
max_resolution: "UHD", offline: false },
signature } # server signature over the license
403: { error: "not_entitled|device_revoked|attestation_stale" }
410: { error: "nonce_expired", action: "refetch_challenge" }
POST /v1/license/renew # same as /license, short-circuits entitlement cache
Body: { license_id, device_id, nonce, device_signature }
200: { ... new short-lived license ... }
POST /v1/devices/{device_id}/revoke # admin/internal: revoke a device
200: { ok: true, propagation: "pushed" }
GET /v1/accounts/{user_id}/devices # list/manage enrolled devices (device cap UI)
200: { limit: 6, devices: [ {device_id, model, last_seen, status} ] }
Design notes:
/challenge+ signednonceis the anti-replay spine. The nonce is single-use, short-TTL, stored in a fast ephemeral store (Redis) keyed bydevice_id; consumed on use.- Entitlement and revocation are checked on every
/license; renewal re-verifies the signed nonce (freshness) but can serve entitlement from a short in-memory cache, so a revocation still bites within a license window via the pushed CRL. - The content key is never in a response in plaintext - only
wrapped_key+e_pub, meaningless without the device’s hardware private key.
Data stores: the right tool per dataset
| Dataset | Store | Why |
|---|---|---|
| Device registry (pubkeys, status) | Sharded SQL / NoSQL, replicated, key by device_id | Point lookups, strong-consistent writes, 125 GB, no cross-device joins |
| Entitlements | SQL (source), read-replicated + cached | Must be correct and strongly consistent on the deny path |
| Content keys (wrapped) | Small KV / SQL, keys stored HSM-wrapped | Tiny, crown jewels, never stored in plaintext |
| Nonces / challenges | In-memory KV (Redis), TTL | Ephemeral, single-use, hot |
| Revocation list | Source in SQL, pushed to in-memory + bloom on every server | O(1) hot-path deny, fast propagation |
| Audit log | Append-only log pipeline -> object storage, tiered | ~10 TB/day, write-once, read-rarely (forensics) |
| Root/wrapping/signing keys | HSM / KMS | Never leave hardware; unwrap and sign happen inside |
Device registry (sharded SQL, keyed by device_id)
device_id UUID PK -- shard key = hash(device_id)
user_id BIGINT FK, INDEX
device_pubkey BYTEA -- P-256 public key (static)
attested BOOL -- passed hardware attestation
platform ENUM -- android | ios | tvos | windows | tizen
secure_level ENUM -- l1 (tee+secure path) | l3 (sw only)
status ENUM -- active | revoked | retired
enrolled_at TIMESTAMP
last_seen TIMESTAMP
INDEX (user_id) -- device-cap enforcement & device list
INDEX (status) -- revocation sweeps
Content key store (wrapped at rest)
content_id UUID
quality ENUM -- sd | hd | uhd | audio
wrapped_cek BYTEA -- content key ENCRYPTED under HSM master key
key_id UUID -- which HSM master key wrapped it (rotation)
PK (content_id, quality)
SQL vs NoSQL: entitlement and content-key integrity want SQL (correctness, transactions on the deny path, rare writes). The device registry is point-lookup, high-volume, horizontally partitioned - fine as sharded SQL or a wide-column NoSQL keyed by device_id; either works because there are no cross-device transactions. Nonces and the CRL want in-memory. The audit firehose wants an append-only log/object store, never a transactional DB.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix:
1. Key extraction on the adversary-owned device (breaks first, and worst). The original sin: a plaintext key in the client’s memory is read and shared globally. Fix: device-wrapped, HSM-protected, TEE-only keys. Content keys are HSM-wrapped at rest, wrapped to the device’s hardware public key in flight, and unwrapped+used only inside the TEE’s secure boundary. A device breach no longer scales to everyone else, and a DB breach yields only ciphertext.
2. Cross-device / post-expiry replay of a license. A copied or captured license reused elsewhere or later. Fix: per-session ECDH + HKDF keyed by a fresh single-use nonce, with a signed short expiry enforced in the TEE. A copy is ciphertext on any other device; a replay past expiry is rejected; a replayed request fails the nonce check.
3. Spoofed / emulated clients. Software self-reports are forgeable. Fix: hardware attestation chained to a pinned platform root plus a strong integrity verdict, checked at enrollment and re-proven (signed nonce) at license time. Emulators and rooted devices never enroll.
4. License server CPU (crypto farm) at 400K verifies/sec. The hot path is signature verify + ECDH + wrap, all CPU. Fix: the License Server is stateless and horizontally scaled behind the LB; add instances linearly (BoE: a few dozen cores). Offload bulk symmetric wrap to AES-NI; keep only unwrap-of-content-key and license-signing in the HSM. Cache entitlement per device for a few seconds to skip redundant lookups on renewals.
5. HSM throughput as a choke point. If every request does an HSM operation, the HSM caps the system.
Fix: minimize HSM calls on the hot path. The HSM holds master wrapping/signing keys; unwrap each content key once, cache the plaintext CEK briefly inside the server’s protected memory (or use HSM key-caching), and do the per-request device-wrap with AES-NI in the app. Scale HSMs in a cluster and shard by key_id. The HSM signs licenses - batch/parallelize, and use a fleet of networked HSMs sized to signing throughput.
6. Revocation latency and the revocation DB as a SPOF/hot query. A per-request revocation lookup at 400K QPS would melt the DB and add latency. Fix: push the CRL to every stateless instance, hold it in memory behind a bloom filter. Deny checks are O(1) in memory; revocation events propagate in seconds via pub/sub. The source DB is off the hot path entirely. Combined with 5-minute licenses, a revoked device stops within one license window.
7. Nonce store hot key / challenge traffic. Every license op needs a fresh nonce. Fix: nonces live in a sharded in-memory KV (Redis) keyed by device_id, single-use with short TTL, so they self-evict; sharding by device spreads load and no device is a hot key. Optionally make nonces stateless and self-verifying (a server-HMAC’d timestamp+random token) so the server need not store them at all, trading a tiny replay window (TTL) for zero nonce-store load.
8. Fail-closed availability trap. Because we deny on any verification failure, an outage in entitlement/attestation/HSM could block all playback. Fix: replicate every verification dependency (HSM cluster, entitlement read-replicas, pushed CRL present on every node so it has no runtime dependency) and cache verification material. We buy availability through redundancy, never by skipping a check. A brief issuance outage blocks new license fetches but in-flight licenses keep playing until their next renewal, so the user impact is softened without weakening security. This is the deliberate inverse of a soft gate: when uncertain, deny.
Shard/partition keys: device registry and nonces shard by device_id (every op is scoped to one device, no cross-device transaction); content keys partition by content_id; the CRL is replicated whole to every node (small, read-everywhere). The stateless License Servers themselves hold no sharded state, so they scale by simply adding instances.
Wrap-Up
The trade-offs that define this design:
- Device as the unit of trust, re-proven cryptographically every request, over “the account is valid.” We hand a key to an attested, non-exportable, hardware-held device identity - never to a user claim - because the operator of the device is the adversary.
- Device-wrapped, HSM-protected, TEE-only keys over a plaintext key in the response. The content key is ciphertext everywhere outside secure hardware: HSM-wrapped at rest, device-wrapped in flight, unwrapped only inside the TEE. A device compromise does not scale; a database compromise yields no usable keys.
- Per-session ECDH + HKDF bound to a single-use nonce over a static, reusable key. This is what makes a leaked token worthless on any other device and dead after expiry, which is the core challenge: anti-copy via device-bound ECDH, anti-replay via fresh nonces and signed short expiry.
- Hardware attestation over software self-reporting. Trust is rooted in a platform key the attacker cannot control, so emulators and rooted devices never get in - without which all the crypto above is ceremony.
- Short licenses + cheap stateless renewal + pushed in-memory CRL over long licenses or per-request revocation queries. Tiny replay window, fast cancellation effect, and revocation that never touches the hot-path database.
- Fail closed, not open. This is a security system, the opposite of a soft concurrency gate: when verification is uncertain, deny, and buy availability through replication, not by skipping checks.
One-line summary: a DRM platform where each device enrolls a hardware-attested, non-exportable key, then every few minutes fetches a short-lived license whose content key is derived per session via device-bound ECDH+HKDF over a single-use nonce, wrapped so only that device’s TEE can unwrap it, HSM-protected end to end and revocable through a pushed in-memory CRL, so a leaked token is useless on any other device or after expiry and the system fails closed under doubt.
Comments