lukuid-sdk 1.0.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.
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: lukuid-sdk
3
+ Version: 1.0.0
4
+ Summary: Python .luku archive support for the LukuID SDK
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/lukuid/sdk
7
+ Project-URL: Repository, https://github.com/lukuid/sdk
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+
11
+ # LukuID SDK for Python
12
+
13
+ Python helpers for opening, exporting, and verifying `.luku` forensic evidence archives.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ python -m pip install lukuid-sdk
19
+ ```
20
+
21
+ Requires Python 3.11 or newer.
22
+
23
+ ## Quick start
24
+
25
+ ```python
26
+ from lukuid_sdk import LukuFile
27
+
28
+ result = LukuFile.parse("identity.luku")
29
+ print(result.verified)
30
+ ```
31
+
32
+ For fuller documentation, see [docs/python.md](../../docs/python.md).
@@ -0,0 +1,22 @@
1
+ # LukuID SDK for Python
2
+
3
+ Python helpers for opening, exporting, and verifying `.luku` forensic evidence archives.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ python -m pip install lukuid-sdk
9
+ ```
10
+
11
+ Requires Python 3.11 or newer.
12
+
13
+ ## Quick start
14
+
15
+ ```python
16
+ from lukuid_sdk import LukuFile
17
+
18
+ result = LukuFile.parse("identity.luku")
19
+ print(result.verified)
20
+ ```
21
+
22
+ For fuller documentation, see [docs/python.md](../../docs/python.md).
@@ -0,0 +1,30 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from .luku import (
3
+ LUKU_MIMETYPE,
4
+ Criticality,
5
+ LukuArchive,
6
+ LukuBlock,
7
+ LukuDeviceIdentity,
8
+ LukuFile,
9
+ LukuItemResult,
10
+ LukuManifest,
11
+ LukuParseResult,
12
+ LukuSigner,
13
+ LukuVerifyOptions,
14
+ VerificationIssue,
15
+ )
16
+
17
+ __all__ = [
18
+ "Criticality",
19
+ "LUKU_MIMETYPE",
20
+ "LukuArchive",
21
+ "LukuBlock",
22
+ "LukuDeviceIdentity",
23
+ "LukuFile",
24
+ "LukuItemResult",
25
+ "LukuManifest",
26
+ "LukuParseResult",
27
+ "LukuSigner",
28
+ "LukuVerifyOptions",
29
+ "VerificationIssue",
30
+ ]
@@ -0,0 +1,277 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+
14
+ @dataclass(slots=True)
15
+ class DeviceAttestationInputs:
16
+ id: str
17
+ key: str
18
+ attestation_sig: str
19
+ certificate_chain: str | None = None
20
+ created: int | None = None
21
+ attestation_alg: str | None = None
22
+ attestation_payload_version: int | None = None
23
+ trust_profile: str = os.environ.get("LUKUID_TRUST_PROFILE", "prod")
24
+
25
+
26
+ @dataclass(slots=True)
27
+ class VerificationResult:
28
+ ok: bool
29
+ reason: str | None = None
30
+
31
+
32
+ # Mirrors the current Rust/Android shortcut: strict verification requires a
33
+ # configured trusted root to exist, but does not yet perform full PQC root
34
+ # signature validation in-process.
35
+ TRUSTED_ROOT_CERTS_PEM = ["configured-root-present"]
36
+
37
+ _CERT_PATTERN = re.compile(
38
+ r"-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----"
39
+ )
40
+ _ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
41
+
42
+
43
+ def verify_device_attestation(inputs: DeviceAttestationInputs) -> VerificationResult:
44
+ if not inputs.attestation_sig:
45
+ return VerificationResult(False, "attestationSig missing")
46
+
47
+ try:
48
+ signature_bytes = base64.b64decode(inputs.attestation_sig, validate=True)
49
+ except Exception:
50
+ return VerificationResult(False, "attestationSig is not valid base64")
51
+
52
+ payload = f"{inputs.id}:{inputs.key}".encode("utf-8")
53
+ leaf_public_key_pem: str | None = None
54
+
55
+ if inputs.certificate_chain:
56
+ certs = _CERT_PATTERN.findall(inputs.certificate_chain)
57
+ if not certs:
58
+ return VerificationResult(False, "Invalid certificate chain PEM")
59
+
60
+ try:
61
+ leaf_meta = _certificate_metadata(certs[0])
62
+ leaf_public_key_pem = leaf_meta["public_key_pem"]
63
+ except Exception as exc:
64
+ return VerificationResult(False, f"Chain processing error: {exc}")
65
+
66
+ required_ou = {
67
+ "dev": "lukuid-dev",
68
+ "test": "lukuid-test",
69
+ "prod": "lukuid-production",
70
+ }.get(inputs.trust_profile, "lukuid-production")
71
+
72
+ has_valid_profile = False
73
+ try:
74
+ for cert_pem in certs[1:]:
75
+ subject = _certificate_metadata(cert_pem)["subject"]
76
+ if required_ou in subject:
77
+ has_valid_profile = True
78
+ break
79
+ except Exception as exc:
80
+ return VerificationResult(False, f"Chain processing error: {exc}")
81
+
82
+ if not has_valid_profile:
83
+ return VerificationResult(
84
+ False,
85
+ f"Certificate chain does not match the requested trust profile: {inputs.trust_profile}",
86
+ )
87
+
88
+ if not TRUSTED_ROOT_CERTS_PEM:
89
+ return VerificationResult(False, "Certificate chain not trusted by any root")
90
+
91
+ if inputs.created is not None:
92
+ try:
93
+ for cert_pem in certs:
94
+ meta = _certificate_metadata(cert_pem)
95
+ valid_from = meta["not_before"]
96
+ valid_to = meta["not_after"]
97
+ if inputs.created < valid_from or inputs.created > valid_to:
98
+ return VerificationResult(
99
+ False,
100
+ f"Temporal birth check failed: created ({inputs.created}) is outside cert window [{valid_from} - {valid_to}]",
101
+ )
102
+ except Exception as exc:
103
+ return VerificationResult(False, f"Chain processing error: {exc}")
104
+
105
+ if leaf_public_key_pem is not None:
106
+ if _verify_signature_with_pem(leaf_public_key_pem, payload, signature_bytes):
107
+ return VerificationResult(True)
108
+ return VerificationResult(False, "Attestation verification failed")
109
+
110
+ for _root in TRUSTED_ROOT_CERTS_PEM:
111
+ return VerificationResult(False, "Attestation verification failed")
112
+
113
+ return VerificationResult(False, "Attestation verification failed")
114
+
115
+
116
+ def verify_detached_signature(public_key_base64: str, payload: bytes, signature_base64: str) -> bool:
117
+ try:
118
+ raw_public_key = base64.b64decode(public_key_base64, validate=True)
119
+ signature = base64.b64decode(signature_base64, validate=True)
120
+ except Exception:
121
+ return False
122
+
123
+ if len(raw_public_key) < 32:
124
+ return False
125
+
126
+ public_key_pem = _ed25519_public_key_pem(raw_public_key[:32])
127
+ return _verify_signature_with_pem(public_key_pem, payload, signature)
128
+
129
+
130
+ def sign_detached(private_key_pem: str, payload: bytes) -> str:
131
+ with tempfile.TemporaryDirectory() as tmpdir:
132
+ key_path = Path(tmpdir) / "key.pem"
133
+ payload_path = Path(tmpdir) / "payload.bin"
134
+ sig_path = Path(tmpdir) / "sig.bin"
135
+ key_path.write_text(private_key_pem, encoding="utf-8")
136
+ payload_path.write_bytes(payload)
137
+ _run(
138
+ [
139
+ "openssl",
140
+ "pkeyutl",
141
+ "-sign",
142
+ "-inkey",
143
+ str(key_path),
144
+ "-rawin",
145
+ "-in",
146
+ str(payload_path),
147
+ "-out",
148
+ str(sig_path),
149
+ ]
150
+ )
151
+ return base64.b64encode(sig_path.read_bytes()).decode("ascii")
152
+
153
+
154
+ def public_key_base64_from_private_key_pem(private_key_pem: str) -> str:
155
+ with tempfile.TemporaryDirectory() as tmpdir:
156
+ key_path = Path(tmpdir) / "key.pem"
157
+ pub_der_path = Path(tmpdir) / "pub.der"
158
+ key_path.write_text(private_key_pem, encoding="utf-8")
159
+ _run(
160
+ [
161
+ "openssl",
162
+ "pkey",
163
+ "-in",
164
+ str(key_path),
165
+ "-pubout",
166
+ "-outform",
167
+ "DER",
168
+ "-out",
169
+ str(pub_der_path),
170
+ ]
171
+ )
172
+ pub_der = pub_der_path.read_bytes()
173
+ if not pub_der.startswith(_ED25519_SPKI_PREFIX):
174
+ raise ValueError("Unexpected Ed25519 public key encoding")
175
+ return base64.b64encode(pub_der[len(_ED25519_SPKI_PREFIX):]).decode("ascii")
176
+
177
+
178
+ def generate_signer() -> tuple[str, str]:
179
+ with tempfile.TemporaryDirectory() as tmpdir:
180
+ key_path = Path(tmpdir) / "key.pem"
181
+ _run(["openssl", "genpkey", "-algorithm", "ED25519", "-out", str(key_path)])
182
+ private_key_pem = key_path.read_text(encoding="utf-8")
183
+ public_key_base64 = public_key_base64_from_private_key_pem(private_key_pem)
184
+ return private_key_pem, public_key_base64
185
+
186
+
187
+ def pem_from_der_string(value: str | None) -> str | None:
188
+ if not value:
189
+ return None
190
+ try:
191
+ der_bytes = base64.b64decode(value, validate=True)
192
+ except Exception:
193
+ return None
194
+ body = base64.encodebytes(der_bytes).decode("ascii").replace("\n", "")
195
+ lines = [body[index:index + 64] for index in range(0, len(body), 64)]
196
+ return "-----BEGIN CERTIFICATE-----\n" + "\n".join(lines) + "\n-----END CERTIFICATE-----\n"
197
+
198
+
199
+ def _verify_signature_with_pem(public_key_pem: str, payload: bytes, signature: bytes) -> bool:
200
+ with tempfile.TemporaryDirectory() as tmpdir:
201
+ pub_path = Path(tmpdir) / "pub.pem"
202
+ payload_path = Path(tmpdir) / "payload.bin"
203
+ sig_path = Path(tmpdir) / "sig.bin"
204
+ pub_path.write_text(public_key_pem, encoding="utf-8")
205
+ payload_path.write_bytes(payload)
206
+ sig_path.write_bytes(signature)
207
+ result = subprocess.run(
208
+ [
209
+ "openssl",
210
+ "pkeyutl",
211
+ "-verify",
212
+ "-pubin",
213
+ "-inkey",
214
+ str(pub_path),
215
+ "-rawin",
216
+ "-in",
217
+ str(payload_path),
218
+ "-sigfile",
219
+ str(sig_path),
220
+ ],
221
+ capture_output=True,
222
+ text=True,
223
+ )
224
+ return result.returncode == 0
225
+
226
+
227
+ def _certificate_metadata(cert_pem: str) -> dict[str, str | int]:
228
+ with tempfile.TemporaryDirectory() as tmpdir:
229
+ cert_path = Path(tmpdir) / "cert.pem"
230
+ cert_path.write_text(cert_pem, encoding="utf-8")
231
+ result = _run(
232
+ [
233
+ "openssl",
234
+ "x509",
235
+ "-in",
236
+ str(cert_path),
237
+ "-noout",
238
+ "-subject",
239
+ "-dates",
240
+ "-pubkey",
241
+ "-nameopt",
242
+ "RFC2253",
243
+ ]
244
+ )
245
+
246
+ lines = [line.strip() for line in result.splitlines() if line.strip()]
247
+ subject_line = next(line for line in lines if line.startswith("subject="))
248
+ not_before_line = next(line for line in lines if line.startswith("notBefore="))
249
+ not_after_line = next(line for line in lines if line.startswith("notAfter="))
250
+ pub_start = lines.index("-----BEGIN PUBLIC KEY-----")
251
+ public_key_pem = "\n".join(lines[pub_start:]) + "\n"
252
+
253
+ return {
254
+ "subject": subject_line.split("=", 1)[1],
255
+ "not_before": _parse_openssl_time(not_before_line.split("=", 1)[1]),
256
+ "not_after": _parse_openssl_time(not_after_line.split("=", 1)[1]),
257
+ "public_key_pem": public_key_pem,
258
+ }
259
+
260
+
261
+ def _parse_openssl_time(value: str) -> int:
262
+ parsed = datetime.strptime(value, "%b %d %H:%M:%S %Y %Z")
263
+ return int(parsed.replace(tzinfo=timezone.utc).timestamp())
264
+
265
+
266
+ def _ed25519_public_key_pem(raw_public_key: bytes) -> str:
267
+ der = _ED25519_SPKI_PREFIX + raw_public_key
268
+ body = base64.encodebytes(der).decode("ascii").replace("\n", "")
269
+ lines = [body[index:index + 64] for index in range(0, len(body), 64)]
270
+ return "-----BEGIN PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END PUBLIC KEY-----\n"
271
+
272
+
273
+ def _run(cmd: list[str]) -> str:
274
+ result = subprocess.run(cmd, capture_output=True, text=True)
275
+ if result.returncode != 0:
276
+ raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "openssl command failed")
277
+ return result.stdout