lebrel-encrypted 0.4.2__tar.gz → 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lebrel_encrypted-0.5.0/CHANGELOG.md +59 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/PKG-INFO +37 -1
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/README.md +34 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/pyproject.toml +3 -1
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/__init__.py +1 -1
- lebrel_encrypted-0.5.0/src/lebrel_encrypted/attestation.py +266 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/client.py +152 -17
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/proxy.py +12 -2
- lebrel_encrypted-0.5.0/tests/fixtures/router-attestation-a.json +1 -0
- lebrel_encrypted-0.5.0/tests/test_attestation.py +114 -0
- lebrel_encrypted-0.5.0/tests/test_client_routed.py +313 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/test_proxy.py +19 -0
- lebrel_encrypted-0.4.2/CHANGELOG.md +0 -34
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/.gitignore +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/LICENSE +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/THIRD_PARTY_NOTICES.md +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/VENDORED_SHA256.json +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/examples/chat.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/examples/stream.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/__main__.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/__init__.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/LICENSE +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/__init__.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/_http.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/client.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/derive.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/errors.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/identity.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/protocol.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/py.typed +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/session.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/_vendor/ehbp/transport.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/anthropic_messages.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/cli.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/openai_responses.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/src/lebrel_encrypted/proof.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/interop/go.mod +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/interop/go.sum +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/interop/main.go +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/test_cli.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/test_client.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/test_proof.py +0 -0
- {lebrel_encrypted-0.4.2 → lebrel_encrypted-0.5.0}/tests/test_proxy_formats.py +0 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `lebrel-encrypted`. Versions follow [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## 0.5.0 — 2026-11-05
|
|
6
|
+
|
|
7
|
+
- Pinned to router 1.3.5 (LEBREL-AI/router, tag `v1.3.5`, image
|
|
8
|
+
`sha256:b31316b3d211ded8cf320a87f8c02334f787cd0b9113560274e98eeb8800345a`): the measured compose
|
|
9
|
+
of the router that serves a route must be one of `675613867a396b1a453c8d6315b48b343fc57aa41ee4693a701075bb8a65b58a`
|
|
10
|
+
(router-tee.lebrel.ai) or `dabc6a3469d4d9c773e273479397906b4bd1737f437b107a90d1a3ef6df85383` (the
|
|
11
|
+
replica), the rows of that version in the router's RELEASES.md. A later router release needs a
|
|
12
|
+
client release with its composes, or `allowed_compose_hashes` passed by hand after checking the
|
|
13
|
+
ledger. Every routed request carries a salt and the moment of sending inside the ciphertext, as
|
|
14
|
+
router 1.3.3 and later require.
|
|
15
|
+
- Routed models (DeepSeek, GLM, Kimi and Qwen through Lebrel) are encrypted end to end, like the
|
|
16
|
+
edition: `create(model="deepseek/deepseek-v4.1-flash", ...)` attests the router that serves the
|
|
17
|
+
route, verifies the route's signed key document with the receipt key the hardware quote binds,
|
|
18
|
+
encrypts the request to that key and names the model in `X-Lebrel-Model`; the answer, streamed or
|
|
19
|
+
not, is decrypted in your process. The local proxy accepts any routed model id.
|
|
20
|
+
- `lebrel_encrypted.attestation`: the router's Intel TDX quote is verified in your process (report
|
|
21
|
+
data bound to our nonce and both keys, event log recomputed and replayed, app id and KMS pinned,
|
|
22
|
+
OS measurements compared with the pinned reference, `mr_config_id` recomputed); Intel's signature
|
|
23
|
+
chain and the TCB status through `dcap-qvl`, installed with `pip install 'lebrel-encrypted[attestation]'`.
|
|
24
|
+
Without it the client refuses routed models unless `allow_unverified_chain=True` is passed.
|
|
25
|
+
- `routed_model_id()` tells a routed model id from the edition's.
|
|
26
|
+
- The proxy turns the edition's thinking on (`thinking: true`) when a request says nothing about
|
|
27
|
+
reasoning: coding tools never do, and the edition thinks only when asked. A request that names
|
|
28
|
+
`thinking`, `profile`, `chat_template_kwargs`, `reasoning_effort` or `custom_params` is forwarded as it is.
|
|
29
|
+
|
|
30
|
+
## 0.4.2 — 2026-10-29
|
|
31
|
+
|
|
32
|
+
- The local proxy and the command line answer with the platform's own reason when a request cannot be
|
|
33
|
+
served (`error.code` and a plain message): in line and the wait ran out, line full, place in line lapsed,
|
|
34
|
+
model paused, too many requests at once, not enough balance, platform or node unreachable. A generic
|
|
35
|
+
failure message is no longer the only thing an application sees.
|
|
36
|
+
- `service_tier="priority"` on `create()` sends `X-Lebrel-Service-Tier: priority`; the proxy forwards the
|
|
37
|
+
OpenAI `service_tier` parameter the same way. Priority is an account setting (Dashboard → Billing); the
|
|
38
|
+
parameter is accepted as well.
|
|
39
|
+
|
|
40
|
+
## 0.4.1 — 2026-10-26
|
|
41
|
+
|
|
42
|
+
- README: where hardware attestation stands, and what the runtime signature proves until then.
|
|
43
|
+
|
|
44
|
+
## 0.4.0 — 2026-10-15
|
|
45
|
+
|
|
46
|
+
- The local proxy speaks OpenAI Responses (`/v1/responses`) and Anthropic Messages (`/v1/messages`,
|
|
47
|
+
`/v1/messages/count_tokens`) beside OpenAI chat completions, every format ending as the same encrypted
|
|
48
|
+
completion. Function tools reach the model; hosted and namespaced tools are refused.
|
|
49
|
+
- `--max-output-tokens` on the proxy caps what clients ask for; read from the public catalog when omitted.
|
|
50
|
+
|
|
51
|
+
## 0.3.0 — 2026-10-08
|
|
52
|
+
|
|
53
|
+
- The client serves DeepSeek V4.1 Flash · Lebrel Uncensored (`lebrel/deepseek-v4.1-flash-uncensored`).
|
|
54
|
+
|
|
55
|
+
## 0.2.0 — 2026-09-26
|
|
56
|
+
|
|
57
|
+
- First release on PyPI: encrypted chat completions, streaming with authenticated completion, the signed
|
|
58
|
+
receipt of every answer fetched and checked, the local proxy for OpenAI-compatible applications, the
|
|
59
|
+
`lebrel-encrypted infer` command.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lebrel-encrypted
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Encrypted, verifiable Python client for DeepSeek V4.1 Flash · Lebrel Uncensored
|
|
5
5
|
Project-URL: Homepage, https://lebrel.ai
|
|
6
6
|
Project-URL: Repository, https://github.com/LEBREL-AI/lebrel-encrypted-python
|
|
@@ -28,6 +28,8 @@ Requires-Python: >=3.9
|
|
|
28
28
|
Requires-Dist: cryptography==46.0.7
|
|
29
29
|
Requires-Dist: httpx==0.28.1
|
|
30
30
|
Requires-Dist: pyhpke==0.6.3
|
|
31
|
+
Provides-Extra: attestation
|
|
32
|
+
Requires-Dist: dcap-qvl==0.7.1; extra == 'attestation'
|
|
31
33
|
Provides-Extra: test
|
|
32
34
|
Requires-Dist: pytest==8.4.2; extra == 'test'
|
|
33
35
|
Description-Content-Type: text/markdown
|
|
@@ -104,6 +106,13 @@ not automatically start it or modify application configuration.
|
|
|
104
106
|
|
|
105
107
|
The console entry point `lebrel-encrypted proxy --port 11437` is equivalent.
|
|
106
108
|
|
|
109
|
+
## Reasoning
|
|
110
|
+
|
|
111
|
+
DeepSeek V4.1 Flash thinks only when asked. Through the proxy the edition gets `thinking: true` unless
|
|
112
|
+
your request names `thinking` (`true`/`false`), `profile` (`chat` or `thinking_50`), `chat_template_kwargs`,
|
|
113
|
+
`reasoning_effort` or `custom_params`, which are forwarded as they are. With the client, pass
|
|
114
|
+
`thinking=True` to `create()`.
|
|
115
|
+
|
|
107
116
|
## Terminal requests
|
|
108
117
|
|
|
109
118
|
Put a normal OpenAI completion request in a local JSON file, then:
|
|
@@ -230,6 +239,33 @@ The default timeout is 900 seconds for cold starts; configure `Lebrel(timeout=..
|
|
|
230
239
|
when needed. Environment HTTP proxy settings are disabled. HTTPS certificate
|
|
231
240
|
verification remains enabled.
|
|
232
241
|
|
|
242
|
+
## Routed models, encrypted to the attested router
|
|
243
|
+
|
|
244
|
+
The models Lebrel routes to their labs (`deepseek/deepseek-v4.1-flash`, `deepseek/deepseek-v4-pro`,
|
|
245
|
+
`z-ai/glm-5.3`, `z-ai/glm-5.3-flash`, `moonshotai/kimi-k3`, `qwen/qwen3.8-max`, `qwen/qwen3.8-flash`)
|
|
246
|
+
are served by Lebrel's router inside an Intel TDX confidential VM. The client asks that machine for
|
|
247
|
+
a quote with a fresh nonce, verifies it in your process (see `lebrel_encrypted.attestation`), checks
|
|
248
|
+
that the route's key document is signed by the receipt key the quote binds and names the encryption
|
|
249
|
+
key the quote binds, and only then encrypts your request to it. Nothing between you and the router
|
|
250
|
+
reads the prompt or the answer: not Lebrel's edge, not Cloudflare, not the machine's host. The router
|
|
251
|
+
sends the plaintext to the lab over the lab's own API; what the lab does with it is the lab's policy.
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
from lebrel_encrypted import Lebrel
|
|
255
|
+
|
|
256
|
+
client = Lebrel() # LEBREL_API_KEY
|
|
257
|
+
answer = client.chat.completions.create(
|
|
258
|
+
model="deepseek/deepseek-v4.1-flash",
|
|
259
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
260
|
+
)
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Intel's signature chain over the quote is checked with `dcap-qvl`: `pip install 'lebrel-encrypted[attestation]'`.
|
|
264
|
+
Without it the client refuses routed models; `Lebrel(allow_unverified_chain=True)` proceeds on the
|
|
265
|
+
binding checks alone, a weaker guarantee you should choose knowingly. The router's code, its
|
|
266
|
+
reproducible build and the ledger of what each version measures are public at
|
|
267
|
+
https://github.com/LEBREL-AI/router.
|
|
268
|
+
|
|
233
269
|
## What is verified
|
|
234
270
|
|
|
235
271
|
The client retrieves `https://api.lebrel.ai/.well-known/lebrel-encryption` without
|
|
@@ -70,6 +70,13 @@ not automatically start it or modify application configuration.
|
|
|
70
70
|
|
|
71
71
|
The console entry point `lebrel-encrypted proxy --port 11437` is equivalent.
|
|
72
72
|
|
|
73
|
+
## Reasoning
|
|
74
|
+
|
|
75
|
+
DeepSeek V4.1 Flash thinks only when asked. Through the proxy the edition gets `thinking: true` unless
|
|
76
|
+
your request names `thinking` (`true`/`false`), `profile` (`chat` or `thinking_50`), `chat_template_kwargs`,
|
|
77
|
+
`reasoning_effort` or `custom_params`, which are forwarded as they are. With the client, pass
|
|
78
|
+
`thinking=True` to `create()`.
|
|
79
|
+
|
|
73
80
|
## Terminal requests
|
|
74
81
|
|
|
75
82
|
Put a normal OpenAI completion request in a local JSON file, then:
|
|
@@ -196,6 +203,33 @@ The default timeout is 900 seconds for cold starts; configure `Lebrel(timeout=..
|
|
|
196
203
|
when needed. Environment HTTP proxy settings are disabled. HTTPS certificate
|
|
197
204
|
verification remains enabled.
|
|
198
205
|
|
|
206
|
+
## Routed models, encrypted to the attested router
|
|
207
|
+
|
|
208
|
+
The models Lebrel routes to their labs (`deepseek/deepseek-v4.1-flash`, `deepseek/deepseek-v4-pro`,
|
|
209
|
+
`z-ai/glm-5.3`, `z-ai/glm-5.3-flash`, `moonshotai/kimi-k3`, `qwen/qwen3.8-max`, `qwen/qwen3.8-flash`)
|
|
210
|
+
are served by Lebrel's router inside an Intel TDX confidential VM. The client asks that machine for
|
|
211
|
+
a quote with a fresh nonce, verifies it in your process (see `lebrel_encrypted.attestation`), checks
|
|
212
|
+
that the route's key document is signed by the receipt key the quote binds and names the encryption
|
|
213
|
+
key the quote binds, and only then encrypts your request to it. Nothing between you and the router
|
|
214
|
+
reads the prompt or the answer: not Lebrel's edge, not Cloudflare, not the machine's host. The router
|
|
215
|
+
sends the plaintext to the lab over the lab's own API; what the lab does with it is the lab's policy.
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
from lebrel_encrypted import Lebrel
|
|
219
|
+
|
|
220
|
+
client = Lebrel() # LEBREL_API_KEY
|
|
221
|
+
answer = client.chat.completions.create(
|
|
222
|
+
model="deepseek/deepseek-v4.1-flash",
|
|
223
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
224
|
+
)
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Intel's signature chain over the quote is checked with `dcap-qvl`: `pip install 'lebrel-encrypted[attestation]'`.
|
|
228
|
+
Without it the client refuses routed models; `Lebrel(allow_unverified_chain=True)` proceeds on the
|
|
229
|
+
binding checks alone, a weaker guarantee you should choose knowingly. The router's code, its
|
|
230
|
+
reproducible build and the ledger of what each version measures are public at
|
|
231
|
+
https://github.com/LEBREL-AI/router.
|
|
232
|
+
|
|
199
233
|
## What is verified
|
|
200
234
|
|
|
201
235
|
The client retrieves `https://api.lebrel.ai/.well-known/lebrel-encryption` without
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "lebrel-encrypted"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.5.0"
|
|
8
8
|
authors = [{ name = "Lebrel" }]
|
|
9
9
|
description = "Encrypted, verifiable Python client for DeepSeek V4.1 Flash · Lebrel Uncensored"
|
|
10
10
|
readme = "README.md"
|
|
@@ -44,6 +44,8 @@ lebrel-encrypted = "lebrel_encrypted.cli:main"
|
|
|
44
44
|
|
|
45
45
|
[project.optional-dependencies]
|
|
46
46
|
test = ["pytest==8.4.2"]
|
|
47
|
+
# Intel's signature chain over the router's quote, verified in your process (routed models).
|
|
48
|
+
attestation = ["dcap-qvl==0.7.1"]
|
|
47
49
|
|
|
48
50
|
[tool.hatch.build.targets.wheel]
|
|
49
51
|
packages = ["src/lebrel_encrypted"]
|
|
@@ -13,5 +13,5 @@ from .client import (
|
|
|
13
13
|
)
|
|
14
14
|
from .proof import Check, Manifest, Receipt
|
|
15
15
|
|
|
16
|
-
__version__ = "0.
|
|
16
|
+
__version__ = "0.5.0"
|
|
17
17
|
__all__ = ["Lebrel", "MODEL_ID", "Completion", "CompletionStream", "Receipt", "Manifest", "Check", "LebrelError", "EncryptionError", "TransportError", "APIError", "StreamError"]
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Hardware attestation of Lebrel's router, verified in your process before a routed model is used.
|
|
2
|
+
|
|
3
|
+
A routed model (DeepSeek, GLM, Kimi, Qwen through Lebrel) is served by Lebrel's router inside an
|
|
4
|
+
Intel TDX confidential VM. Before the client encrypts a request to that router it asks the machine
|
|
5
|
+
for a quote with a fresh nonce and checks, here, with the same steps as
|
|
6
|
+
https://github.com/LEBREL-AI/router/blob/main/scripts/verify-attestation.py:
|
|
7
|
+
|
|
8
|
+
1. Intel's signature chain over the quote and the platform's TCB status (``dcap-qvl``, installed
|
|
9
|
+
with ``lebrel-encrypted[attestation]``); without it the chain is not checked and the client
|
|
10
|
+
refuses unless told to proceed.
|
|
11
|
+
2. The quote's report data commits to the receipt-signing key, the encryption key and our nonce,
|
|
12
|
+
each behind its one-byte length (``SHA-512("lebrel-router-attestation-v3" || len || public_key
|
|
13
|
+
|| len || encryption_public_key || len || nonce)``), and each key id is the digest of its key.
|
|
14
|
+
3. Every runtime event of the log recomputes from its payload and the log replays into the RTMRs
|
|
15
|
+
the quote carries; only then are the measured app id, compose hash, instance id and key provider
|
|
16
|
+
believed.
|
|
17
|
+
4. The measured app id and key provider equal the pinned ones; the OS measurements equal the
|
|
18
|
+
pinned reference (values observed on Lebrel's machines, see the router's RELEASES.md).
|
|
19
|
+
5. The measured compose hash is one of the releases this client knows (``PINNED_COMPOSE_HASHES``,
|
|
20
|
+
the rows of the router's RELEASES.md at the time of this release): the app owner can register
|
|
21
|
+
other composes under the same app id, and a quote for one of those is refused. Pass your own
|
|
22
|
+
``allowed_compose_hashes`` after checking RELEASES.md yourself, or ``None`` to leave the compose
|
|
23
|
+
unpinned (then ``compose_pinned`` is reported as not checked).
|
|
24
|
+
6. ``mr_config_id`` recomputes from the measured app id, compose hash, instance id and KMS.
|
|
25
|
+
|
|
26
|
+
What this proves: the key the client encrypts to was born at random inside a measured, published
|
|
27
|
+
build of the router on genuine Intel hardware, and exists nowhere else (never in a key service: the
|
|
28
|
+
router's KMS derives keys per app, so a key taken from it could be derived again by any compose the
|
|
29
|
+
app's owner registers). The receipt-signing key is such an app key, derived inside the machine for
|
|
30
|
+
Lebrel's router app: a receipt proves it was signed by that app, and the attestation names the
|
|
31
|
+
measured compose that served the request. What it does not prove: what the lab at the other end
|
|
32
|
+
does with the request.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import hashlib
|
|
38
|
+
import json
|
|
39
|
+
import struct
|
|
40
|
+
from dataclasses import dataclass
|
|
41
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
42
|
+
|
|
43
|
+
from ._vendor.ehbp.errors import EHBPError
|
|
44
|
+
from ._vendor.ehbp.identity import ServerIdentity
|
|
45
|
+
|
|
46
|
+
DOMAIN_V3 = b"lebrel-router-attestation-v3"
|
|
47
|
+
QUOTE_HEADER = 48
|
|
48
|
+
TD_REPORT_OFFSETS = {
|
|
49
|
+
"mr_td": (136, 48), "mr_config_id": (184, 48), "rtmr0": (328, 48), "rtmr1": (376, 48),
|
|
50
|
+
"rtmr2": (424, 48), "rtmr3": (472, 48), "report_data": (520, 64),
|
|
51
|
+
}
|
|
52
|
+
TD_REPORT10_SIZE = 584
|
|
53
|
+
TEE_TYPE_TDX = 0x81
|
|
54
|
+
MAX_DOCUMENT_BYTES = 512 * 1024
|
|
55
|
+
|
|
56
|
+
# Lebrel's router app on Phala Cloud (dstack): the app id every row of the router's RELEASES.md
|
|
57
|
+
# runs under, the KMS that derives its keys, and the OS measurements as observed on its quotes.
|
|
58
|
+
PINNED_APP_ID = "4d72eae647c67ad42c972d24175d7c32ce9c871a"
|
|
59
|
+
PINNED_KMS_ID = ("3059301306072a8648ce3d020106082a8648ce3d030107034200048844eb42ccdf8c52fd4f174f362fcb9bbd19c45fd48f1edec2d8f1ca2"
|
|
60
|
+
"3536ec1a74021b4cee610c074f8294d431b2b7fee2c39e5333fdaf0a4522d43fb159d9f")
|
|
61
|
+
PINNED_OS = {
|
|
62
|
+
"os_image_hash": "ec43cb8c5e04b6bb6c53b33b16076a01d83d01f7f4b703f2f78a0d947d6247e6",
|
|
63
|
+
"mr_td": "2a674327c50218dba880066b349b8d559d749ed68dce33fd651c184a877d084b07a9e583767a7ad5da13ed91deec2b70",
|
|
64
|
+
"rtmr0": "fb14dc139f33d6fcf474bc8332cac001259fb31cfbcb6b34d4ceeb552a2c4466884a0cbde45ad98a05c5c060c23ad65a",
|
|
65
|
+
"rtmr1": "89ef86c5125b986c325f0a94acfa87718a4ef3a4d4f237dbb72dda3cf777fd2c054555fb4407eb53338d7d67329a7333",
|
|
66
|
+
"rtmr2": "e9000e338f33233e8f51b7fd031e1c158bdcf8572eab041c0bc8eb7fef48b23259a6a556e6c8e2af99999fc39c793179",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# The router composes this release knows: the rows of https://github.com/LEBREL-AI/router/blob/main/RELEASES.md
|
|
71
|
+
# deployed when it was published (instance A behind router-tee.lebrel.ai, and the replica).
|
|
72
|
+
PINNED_COMPOSE_HASHES: Tuple[str, ...] = (
|
|
73
|
+
"675613867a396b1a453c8d6315b48b343fc57aa41ee4693a701075bb8a65b58a", # 1.3.5, instance A (router-tee.lebrel.ai)
|
|
74
|
+
"dabc6a3469d4d9c773e273479397906b4bd1737f437b107a90d1a3ef6df85383", # 1.3.5, the replica
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def report_data(public_key: bytes, encryption_key: bytes, nonce: bytes) -> bytes:
|
|
79
|
+
"""What the quote's report data must equal (v3): the domain, then each field behind its length."""
|
|
80
|
+
digest = hashlib.sha512(DOMAIN_V3)
|
|
81
|
+
for field in (public_key, encryption_key, nonce):
|
|
82
|
+
digest.update(bytes([len(field)]) + field)
|
|
83
|
+
return digest.digest()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class AttestationError(Exception):
|
|
87
|
+
"""The machine did not prove what it claims; the request was not sent."""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class Check:
|
|
92
|
+
id: str
|
|
93
|
+
ok: bool
|
|
94
|
+
detail: str
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class AttestedRouter:
|
|
99
|
+
"""What a verified attestation says about the router: the keys the quote binds and the measured identity."""
|
|
100
|
+
receipt_public_key: bytes
|
|
101
|
+
receipt_key_id: str
|
|
102
|
+
encryption_key_id: str
|
|
103
|
+
encryption_public_key: bytes
|
|
104
|
+
app_id: str
|
|
105
|
+
compose_hash: str
|
|
106
|
+
instance_id: str
|
|
107
|
+
chain_checked: bool
|
|
108
|
+
checks: Tuple[Check, ...]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def td_report(quote: bytes) -> Dict[str, bytes]:
|
|
112
|
+
if len(quote) < QUOTE_HEADER + 6:
|
|
113
|
+
raise AttestationError("quote too short")
|
|
114
|
+
version = int.from_bytes(quote[0:2], "little")
|
|
115
|
+
if int.from_bytes(quote[4:8], "little") != TEE_TYPE_TDX:
|
|
116
|
+
raise AttestationError("not a TDX quote")
|
|
117
|
+
if version == 4:
|
|
118
|
+
start = QUOTE_HEADER
|
|
119
|
+
elif version == 5:
|
|
120
|
+
if int.from_bytes(quote[QUOTE_HEADER:QUOTE_HEADER + 2], "little") not in (2, 3):
|
|
121
|
+
raise AttestationError("quote v5 body is not a TD report")
|
|
122
|
+
start = QUOTE_HEADER + 6
|
|
123
|
+
else:
|
|
124
|
+
raise AttestationError("unsupported quote version")
|
|
125
|
+
body = quote[start:start + TD_REPORT10_SIZE]
|
|
126
|
+
if len(body) < TD_REPORT10_SIZE:
|
|
127
|
+
raise AttestationError("quote truncated")
|
|
128
|
+
return {name: body[offset:offset + size] for name, (offset, size) in TD_REPORT_OFFSETS.items()}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def event_digest(event: Dict[str, Any]) -> bytes:
|
|
132
|
+
payload = str(event.get("event_payload", ""))
|
|
133
|
+
try:
|
|
134
|
+
payload_bytes = bytes.fromhex(payload)
|
|
135
|
+
except ValueError:
|
|
136
|
+
payload_bytes = payload.encode()
|
|
137
|
+
return hashlib.sha384(struct.pack("<I", int(event.get("event_type", 0))) + b":" + str(event.get("event", "")).encode() + b":" + payload_bytes).digest()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def replay(event_log: List[Dict[str, Any]]) -> Tuple[Dict[int, bytes], List[str]]:
|
|
141
|
+
rtmrs = {i: bytes(48) for i in range(4)}
|
|
142
|
+
unverified: List[str] = []
|
|
143
|
+
for event in event_log:
|
|
144
|
+
imr = int(event.get("imr", -1))
|
|
145
|
+
digest = bytes.fromhex(str(event.get("digest", "")))
|
|
146
|
+
if imr not in rtmrs or len(digest) != 48:
|
|
147
|
+
raise AttestationError("event log malformed")
|
|
148
|
+
if imr == 3 and event_digest(event) != digest:
|
|
149
|
+
unverified.append(str(event.get("event", "?")))
|
|
150
|
+
rtmrs[imr] = hashlib.sha384(rtmrs[imr] + digest).digest()
|
|
151
|
+
return rtmrs, unverified
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def verified_payload(event_log: List[Dict[str, Any]], name: str) -> Optional[str]:
|
|
155
|
+
for event in event_log:
|
|
156
|
+
if int(event.get("imr", -1)) == 3 and event.get("event") == name:
|
|
157
|
+
return str(event.get("event_payload", "")) if event_digest(event) == bytes.fromhex(str(event.get("digest", ""))) else None
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _chain(quote: bytes) -> Tuple[Optional[bool], str]:
|
|
162
|
+
"""Intel's chain and the TCB status through dcap-qvl: (True, detail) verified, (False, detail)
|
|
163
|
+
failed, (None, detail) not checkable here."""
|
|
164
|
+
try:
|
|
165
|
+
import dcap_qvl # type: ignore
|
|
166
|
+
except ImportError:
|
|
167
|
+
return None, "dcap-qvl is not installed: pip install 'lebrel-encrypted[attestation]'"
|
|
168
|
+
try:
|
|
169
|
+
report = _run(dcap_qvl.get_collateral_and_verify(quote, None))
|
|
170
|
+
except Exception as error: # noqa: BLE001
|
|
171
|
+
return False, f"quote verification failed: {type(error).__name__}"
|
|
172
|
+
status = str(getattr(report, "status", "") or "")
|
|
173
|
+
if status != "UpToDate":
|
|
174
|
+
return False, f"TCB status {status or 'unknown'}"
|
|
175
|
+
return True, "signature chain ok, TCB UpToDate"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _run(awaitable: Any) -> Any:
|
|
179
|
+
"""Runs dcap-qvl's coroutine to completion, from inside or outside an event loop."""
|
|
180
|
+
import asyncio
|
|
181
|
+
import concurrent.futures
|
|
182
|
+
if not asyncio.iscoroutine(awaitable):
|
|
183
|
+
return awaitable
|
|
184
|
+
try:
|
|
185
|
+
asyncio.get_running_loop()
|
|
186
|
+
except RuntimeError:
|
|
187
|
+
return asyncio.run(awaitable)
|
|
188
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
|
189
|
+
return pool.submit(asyncio.run, awaitable).result()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def verify_attestation(document: Dict[str, Any], nonce: bytes, *, allow_unverified_chain: bool = False, pinned_app_id: str = PINNED_APP_ID,
|
|
193
|
+
pinned_kms_id: str = PINNED_KMS_ID, pinned_os: Optional[Dict[str, str]] = PINNED_OS,
|
|
194
|
+
allowed_compose_hashes: Optional[Iterable[str]] = PINNED_COMPOSE_HASHES) -> AttestedRouter:
|
|
195
|
+
"""Verifies the router's attestation document for our nonce; raises AttestationError otherwise."""
|
|
196
|
+
checks: List[Check] = []
|
|
197
|
+
|
|
198
|
+
def check(id_: str, ok: bool, detail: str) -> None:
|
|
199
|
+
checks.append(Check(id_, ok, detail))
|
|
200
|
+
if not ok:
|
|
201
|
+
raise AttestationError(f"{id_}: {detail}")
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
scheme = str(document.get("scheme", ""))
|
|
205
|
+
if "attestation-v3" not in scheme:
|
|
206
|
+
raise AttestationError("the document is not a v3 attestation (an older router: its fields are bound without their lengths)")
|
|
207
|
+
public_key = bytes.fromhex(str(document.get("public_key", "")))
|
|
208
|
+
encryption_key = bytes.fromhex(str(document.get("encryption_public_key", "")))
|
|
209
|
+
encryption_key_id = str(document.get("encryption_key_id", ""))
|
|
210
|
+
receipt_key_id = str(document.get("signing_key_id", ""))
|
|
211
|
+
quote = bytes.fromhex(str(document.get("quote", "")))
|
|
212
|
+
if len(public_key) != 32 or len(encryption_key) != 32 or len(encryption_key_id) != 64 or len(receipt_key_id) != 64:
|
|
213
|
+
raise AttestationError("the document names no usable keys")
|
|
214
|
+
report = td_report(quote)
|
|
215
|
+
expected = report_data(public_key, encryption_key, nonce)
|
|
216
|
+
check("report_data", report["report_data"] == expected and document.get("report_data") == expected.hex(), "binds the receipt key, the encryption key and our nonce, each behind its length")
|
|
217
|
+
bound_config = ServerIdentity.from_public_key_bytes(encryption_key).marshal_public_config()
|
|
218
|
+
check("key_ids", receipt_key_id == hashlib.sha256(public_key).hexdigest() and encryption_key_id == hashlib.sha256(bound_config).hexdigest(),
|
|
219
|
+
"each key id is the digest of the key the quote binds")
|
|
220
|
+
event_log = document.get("event_log")
|
|
221
|
+
if isinstance(event_log, str):
|
|
222
|
+
event_log = json.loads(event_log)
|
|
223
|
+
if not isinstance(event_log, list):
|
|
224
|
+
raise AttestationError("no event log")
|
|
225
|
+
rtmrs, unverified = replay(event_log)
|
|
226
|
+
check("rtmr_replay", all(rtmrs[i] == report[f"rtmr{i}"] for i in range(4)), "event log replays into the quote's RTMRs")
|
|
227
|
+
check("event_digests", not unverified, "every runtime event recomputes from its payload" if not unverified else "unverified: " + ", ".join(unverified))
|
|
228
|
+
app_id = verified_payload(event_log, "app-id")
|
|
229
|
+
compose = verified_payload(event_log, "compose-hash")
|
|
230
|
+
instance_id = verified_payload(event_log, "instance-id")
|
|
231
|
+
os_image = verified_payload(event_log, "os-image-hash")
|
|
232
|
+
key_provider = verified_payload(event_log, "key-provider")
|
|
233
|
+
info = document.get("info") or {}
|
|
234
|
+
check("app_id", app_id is not None and app_id == pinned_app_id and info.get("app_id") == app_id, f"measured app id {app_id}")
|
|
235
|
+
check("compose_hash", compose is not None and len(compose) == 64 and info.get("compose_hash") == compose, f"measured compose {compose}")
|
|
236
|
+
if allowed_compose_hashes is None:
|
|
237
|
+
checks.append(Check("compose_pinned", False, "not checked: no list of composes was given"))
|
|
238
|
+
else:
|
|
239
|
+
allowed = {str(h).lower() for h in allowed_compose_hashes}
|
|
240
|
+
check("compose_pinned", str(compose).lower() in allowed,
|
|
241
|
+
f"measured compose {compose} is a release this client knows" if str(compose).lower() in allowed
|
|
242
|
+
else f"measured compose {compose} is not a release this client knows: upgrade lebrel-encrypted, or check the router's RELEASES.md and pass allowed_compose_hashes")
|
|
243
|
+
check("instance_id", instance_id is not None and len(instance_id) == 40, f"measured instance {instance_id}")
|
|
244
|
+
provider = json.loads(bytes.fromhex(key_provider).decode()) if key_provider else {}
|
|
245
|
+
check("kms", provider.get("name") == "kms" and str(provider.get("id", "")).lower() == pinned_kms_id.lower(), "key provider is the pinned KMS")
|
|
246
|
+
if pinned_os:
|
|
247
|
+
check("os_image_hash", os_image == pinned_os.get("os_image_hash"), f"measured os image {os_image}")
|
|
248
|
+
for field in ("mr_td", "rtmr0", "rtmr1", "rtmr2"):
|
|
249
|
+
check(field, report[field].hex() == pinned_os.get(field, "").lower(), "equals the pinned reference (observed on Lebrel's machines)")
|
|
250
|
+
record = {"app_id": app_id, "compose_hash": compose, "init_script_hashes": [], "instance_id": instance_id,
|
|
251
|
+
"key_provider": provider.get("name"), "key_provider_id": provider.get("id"), "version": 3}
|
|
252
|
+
jcs = json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
|
|
253
|
+
expected_config = (b"\x03" + hashlib.sha256(b"dstack-mr-config-v3:" + b"\x00" + jcs).digest()).ljust(48, b"\x00")
|
|
254
|
+
check("mr_config_id", report["mr_config_id"] == expected_config, "recomputes from app id, compose, instance and KMS")
|
|
255
|
+
chain, detail = _chain(quote)
|
|
256
|
+
if chain is None:
|
|
257
|
+
checks.append(Check("intel_chain", False, detail))
|
|
258
|
+
if not allow_unverified_chain:
|
|
259
|
+
raise AttestationError("Intel's chain was not checked: " + detail)
|
|
260
|
+
else:
|
|
261
|
+
check("intel_chain", chain, detail)
|
|
262
|
+
return AttestedRouter(public_key, receipt_key_id, encryption_key_id, encryption_key, str(app_id), str(compose), str(instance_id), chain is True, tuple(checks))
|
|
263
|
+
except AttestationError:
|
|
264
|
+
raise
|
|
265
|
+
except (ValueError, TypeError, KeyError, json.JSONDecodeError, EHBPError):
|
|
266
|
+
raise AttestationError("the attestation document is malformed") from None
|