pythonbeid 0.3.0__py3-none-any.whl → 1.0.0__py3-none-any.whl

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,455 @@
1
+ """Integrity and authenticity checks of Belgian eID data.
2
+
3
+ The National Register (RRN) signs the identity file and the address file;
4
+ the identity file holds the digest of the photo and, on applet 1.8 cards, of
5
+ the chip's basic public key. Checking all of them proves the data was issued
6
+ by the Belgian state and was not altered. On applet 1.8 cards, the chip
7
+ challenge (:meth:`pythonbeid.CardReader.authenticate_chip`) additionally
8
+ proves the data comes from a genuine chip rather than a copy.
9
+
10
+ :func:`verify_photo` only needs the standard library. Every other function
11
+ needs the ``cryptography`` package::
12
+
13
+ pip install "pythonbeid[verify]"
14
+
15
+ Trusted roots: Belgium Root CA2, CA3, CA4 and CA6, downloaded from
16
+ ``certs.eid.belgium.be`` and ``crt.eidpki.belgium.be`` (SHA-256 fingerprints
17
+ are listed in the README).
18
+
19
+ The logic mirrors the official eID Viewer (``Fedict/eid-mw``,
20
+ ``plugins_tools/eid-viewer/certhelpers.c`` and ``verify.c``), with stricter
21
+ rules: every check is derived from the signed files, the RRN certificate
22
+ must be an end-entity signing certificate, and the presence of a basic key
23
+ is decided by the signed identity file rather than by the unsigned card
24
+ data.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import hashlib
31
+ import hmac
32
+ import logging
33
+ from importlib import resources
34
+ from typing import TYPE_CHECKING, Any
35
+
36
+ from .exceptions import CardDataError
37
+ from .models import CardFile, VerificationReport
38
+ from .parser import _der_length, parse_address, parse_identity
39
+
40
+ if TYPE_CHECKING:
41
+ from collections.abc import Iterable, Mapping, Sequence
42
+
43
+ from cryptography.x509 import Certificate
44
+
45
+ from .models import EidData, Identity
46
+
47
+ __all__ = [
48
+ "basic_key_matches",
49
+ "bundled_trusted_roots",
50
+ "verify_chip_signature",
51
+ "verify_eid",
52
+ "verify_photo",
53
+ ]
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ _PHOTO_HASHES = {20: "sha1", 32: "sha256", 48: "sha384"}
58
+ _REQUIRED_FILES = (
59
+ CardFile.IDENTITY,
60
+ CardFile.IDENTITY_SIGNATURE,
61
+ CardFile.ADDRESS,
62
+ CardFile.ADDRESS_SIGNATURE,
63
+ CardFile.RRN_CERTIFICATE,
64
+ )
65
+
66
+
67
+ def verify_photo(photo: bytes, photo_hash: bytes) -> bool:
68
+ """Check a photo against the digest stored in the identity file.
69
+
70
+ The algorithm is deduced from the digest length: SHA-1 (older applet 1.7
71
+ cards), SHA-256 (recent applet 1.7 cards) or SHA-384 (applet 1.8).
72
+
73
+ Raises:
74
+ CardDataError: If the digest length matches no known algorithm.
75
+ """
76
+ algorithm = _PHOTO_HASHES.get(len(photo_hash))
77
+ if algorithm is None:
78
+ msg = f"unexpected photo hash length: {len(photo_hash)} bytes"
79
+ raise CardDataError(msg)
80
+ return hmac.compare_digest(hashlib.new(algorithm, photo).digest(), photo_hash)
81
+
82
+
83
+ def _crypto() -> Any:
84
+ try:
85
+ import cryptography.x509
86
+ except ImportError as exc: # pragma: no cover - exercised without the extra
87
+ msg = (
88
+ "Signature verification needs the 'cryptography' package: "
89
+ "pip install 'pythonbeid[verify]'"
90
+ )
91
+ raise ImportError(msg) from exc
92
+ return cryptography.x509
93
+
94
+
95
+ def bundled_trusted_roots() -> list[bytes]:
96
+ """Return the bundled Belgian root certificates (PEM)."""
97
+ folder = resources.files("pythonbeid").joinpath("trust")
98
+ return [
99
+ item.read_bytes()
100
+ for item in sorted(folder.iterdir(), key=lambda entry: entry.name)
101
+ if item.name.endswith(".pem")
102
+ ]
103
+
104
+
105
+ def _load_certificates(data: bytes) -> list[Certificate]:
106
+ """Load one DER certificate, or every certificate of a PEM bundle."""
107
+ x509 = _crypto()
108
+ if data.lstrip().startswith(b"-----BEGIN"):
109
+ certificates: list[Certificate] = x509.load_pem_x509_certificates(data)
110
+ return certificates
111
+ return [x509.load_der_x509_certificate(data[: _der_length(data)])]
112
+
113
+
114
+ def _hash(name: str) -> Any:
115
+ from cryptography.hazmat.primitives import hashes
116
+
117
+ return {
118
+ "sha1": hashes.SHA1(), # noqa: S303 - mandated by applet 1.7 cards
119
+ "sha256": hashes.SHA256(),
120
+ "sha384": hashes.SHA384(),
121
+ "sha512": hashes.SHA512(),
122
+ }[name]
123
+
124
+
125
+ def _verify_signature(
126
+ certificate: Certificate, data: bytes, signature: bytes, hash_hint: str | None
127
+ ) -> bool:
128
+ """Verify a data signature made with the key of *certificate*.
129
+
130
+ RSA signatures (applet 1.7) use PKCS#1 v1.5. Some re-signed cards mix a
131
+ SHA-1 photo digest with SHA-256 signatures, so every usual digest is
132
+ tried (safe: the DigestInfo inside the signature binds the algorithm).
133
+ EC signatures (applet 1.8 and re-keyed 1.7 cards) always use SHA-384 and
134
+ are DER-encoded in a zero-padded file.
135
+ """
136
+ from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
137
+ from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
138
+
139
+ try:
140
+ key = certificate.public_key()
141
+ except (ValueError, UnsupportedAlgorithm):
142
+ return False
143
+ if isinstance(key, ec.EllipticCurvePublicKey):
144
+ try:
145
+ key.verify(
146
+ signature[: _der_length(signature)], data, ec.ECDSA(_hash("sha384"))
147
+ )
148
+ except (InvalidSignature, CardDataError):
149
+ return False
150
+ return True
151
+ if not isinstance(key, rsa.RSAPublicKey):
152
+ logger.warning("Unsupported RRN key type: %s", type(key).__name__)
153
+ return False
154
+ names = dict.fromkeys(
155
+ name for name in (hash_hint, "sha256", "sha1", "sha384", "sha512") if name
156
+ )
157
+ for name in names:
158
+ try:
159
+ key.verify(signature, data, padding.PKCS1v15(), _hash(name))
160
+ except InvalidSignature:
161
+ continue
162
+ return True
163
+ return False
164
+
165
+
166
+ def _issued_by(certificate: Certificate, issuer: Certificate) -> bool:
167
+ from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
168
+ from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
169
+
170
+ if certificate.issuer != issuer.subject:
171
+ return False
172
+ try:
173
+ key = issuer.public_key()
174
+ parameters = certificate.signature_algorithm_parameters
175
+ digest = certificate.signature_hash_algorithm
176
+ signature, tbs = certificate.signature, certificate.tbs_certificate_bytes
177
+ if (
178
+ isinstance(key, rsa.RSAPublicKey)
179
+ and isinstance(parameters, padding.PKCS1v15 | padding.PSS)
180
+ and digest is not None
181
+ ):
182
+ key.verify(signature, tbs, parameters, digest)
183
+ elif isinstance(key, ec.EllipticCurvePublicKey) and isinstance(
184
+ parameters, ec.ECDSA
185
+ ):
186
+ key.verify(signature, tbs, parameters)
187
+ else:
188
+ # A root with the right name but another key type is simply not
189
+ # the issuer.
190
+ return False
191
+ except (InvalidSignature, UnsupportedAlgorithm, ValueError):
192
+ return False
193
+ return True
194
+
195
+
196
+ def _trusted(certificate: Certificate, roots: Iterable[Certificate]) -> bool:
197
+ return any(_issued_by(certificate, root) for root in roots)
198
+
199
+
200
+ def _is_data_signer(certificate: Certificate) -> bool:
201
+ """Whether *certificate* is an end-entity certificate allowed to sign.
202
+
203
+ The RRN certificate is not a CA (unlike the Citizen and Foreigner CA
204
+ certificates issued by the same roots) and has the digital signature or
205
+ non-repudiation key usage.
206
+ """
207
+ x509 = _crypto()
208
+ extensions = certificate.extensions
209
+ with contextlib.suppress(x509.ExtensionNotFound):
210
+ if extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
211
+ return False
212
+ try:
213
+ usage = extensions.get_extension_for_class(x509.KeyUsage).value
214
+ except x509.ExtensionNotFound:
215
+ return True
216
+ return bool(usage.digital_signature or usage.content_commitment)
217
+
218
+
219
+ def basic_key_matches(basic_public_key: bytes, basic_key_hash: bytes) -> bool:
220
+ """Check the basic public key file against its signed SHA-384 digest.
221
+
222
+ Args:
223
+ basic_public_key: Content of the basic public key file, possibly
224
+ zero-padded.
225
+ basic_key_hash: :attr:`Identity.basic_key_hash` (tag ``0x1A``).
226
+ """
227
+ candidates = [basic_public_key]
228
+ with contextlib.suppress(CardDataError):
229
+ candidates.append(basic_public_key[: _der_length(basic_public_key)])
230
+ return any(
231
+ hmac.compare_digest(hashlib.sha384(item).digest(), basic_key_hash)
232
+ for item in candidates
233
+ )
234
+
235
+
236
+ def verify_chip_signature(
237
+ basic_public_key: bytes, nonce: bytes, signature: bytes
238
+ ) -> bool:
239
+ """Check the answer of the chip to a basic-key challenge (applet 1.8).
240
+
241
+ This only checks the signature against *basic_public_key*: the key must
242
+ itself be checked against its signed digest (:func:`basic_key_matches`),
243
+ as :meth:`pythonbeid.CardReader.authenticate_chip` does.
244
+
245
+ Args:
246
+ basic_public_key: Content of the basic public key file
247
+ (SubjectPublicKeyInfo DER, possibly zero-padded).
248
+ nonce: The 48-byte challenge sent to the chip.
249
+ signature: The raw ``r || s`` ECDSA signature returned by the chip.
250
+
251
+ Raises:
252
+ ValueError: If the nonce is not 48 bytes long.
253
+ CardDataError: If the public key is not a valid EC key.
254
+ """
255
+ from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
256
+ from cryptography.hazmat.primitives.asymmetric import ec
257
+ from cryptography.hazmat.primitives.asymmetric.utils import (
258
+ Prehashed,
259
+ encode_dss_signature,
260
+ )
261
+ from cryptography.hazmat.primitives.serialization import load_der_public_key
262
+
263
+ if len(nonce) != 48:
264
+ msg = "the nonce must be 48 bytes long (SHA-384 digest size)"
265
+ raise ValueError(msg)
266
+ try:
267
+ key = load_der_public_key(basic_public_key[: _der_length(basic_public_key)])
268
+ except (ValueError, UnsupportedAlgorithm) as exc:
269
+ msg = "invalid basic public key"
270
+ raise CardDataError(msg) from exc
271
+ if not isinstance(key, ec.EllipticCurvePublicKey):
272
+ msg = "the basic public key is not an EC key"
273
+ raise CardDataError(msg)
274
+ if not signature or len(signature) % 2:
275
+ return False
276
+ half = len(signature) // 2
277
+ der_signature = encode_dss_signature(
278
+ int.from_bytes(signature[:half], "big"), int.from_bytes(signature[half:], "big")
279
+ )
280
+ try:
281
+ key.verify(der_signature, nonce, ec.ECDSA(Prehashed(_hash("sha384"))))
282
+ except InvalidSignature:
283
+ return False
284
+ return True
285
+
286
+
287
+ def _basic_key_valid(
288
+ identity: Identity | None, files: Mapping[CardFile, bytes], errors: list[str]
289
+ ) -> bool | None:
290
+ # Decided by the signed identity file, never by the unsigned card data,
291
+ # so a card claiming an older applet cannot escape the check.
292
+ if identity is None or identity.basic_key_hash is None:
293
+ return None
294
+ key_file = files.get(CardFile.BASIC_PUBLIC_KEY)
295
+ if key_file is None:
296
+ errors.append("the basic public key was not read, although it is signed")
297
+ return False
298
+ if basic_key_matches(key_file, identity.basic_key_hash):
299
+ return True
300
+ errors.append("the basic public key does not match its signed digest")
301
+ return False
302
+
303
+
304
+ def _decode_signed(
305
+ files: Mapping[CardFile, bytes], errors: list[str]
306
+ ) -> tuple[Identity | None, Any]:
307
+ try:
308
+ return parse_identity(files[CardFile.IDENTITY]), parse_address(
309
+ files[CardFile.ADDRESS]
310
+ )
311
+ except CardDataError:
312
+ errors.append("the signed files cannot be decoded")
313
+ return None, None
314
+
315
+
316
+ def _load_rrn(files: Mapping[CardFile, bytes], errors: list[str]) -> Certificate | None:
317
+ from cryptography.exceptions import UnsupportedAlgorithm
318
+
319
+ try:
320
+ return _load_certificates(files[CardFile.RRN_CERTIFICATE])[0]
321
+ except (ValueError, UnsupportedAlgorithm): # CardDataError is a ValueError
322
+ errors.append("the RRN certificate cannot be decoded")
323
+ return None
324
+
325
+
326
+ def _photo_valid(
327
+ photo: bytes | None, identity: Identity | None, errors: list[str]
328
+ ) -> bool | None:
329
+ if photo is None:
330
+ return None
331
+ if identity is None:
332
+ return False
333
+ try:
334
+ valid = verify_photo(photo, identity.photo_hash)
335
+ except CardDataError as exc:
336
+ errors.append(str(exc))
337
+ return False
338
+ if not valid:
339
+ errors.append("the photo does not match its signed digest")
340
+ return valid
341
+
342
+
343
+ def _rrn_checks(
344
+ rrn: Certificate | None,
345
+ roots: Iterable[Certificate],
346
+ identity: Identity | None,
347
+ errors: list[str],
348
+ ) -> tuple[bool, bool]:
349
+ """Return whether the RRN certificate is trusted and in period."""
350
+ if rrn is None:
351
+ return False, False
352
+ trusted = False
353
+ if not _trusted(rrn, roots):
354
+ errors.append("the RRN certificate is not issued by a trusted Belgian root")
355
+ elif not _is_data_signer(rrn):
356
+ errors.append("the RRN certificate is not a data signing certificate")
357
+ else:
358
+ trusted = True
359
+ if identity is None:
360
+ return trusted, False
361
+ in_period = (
362
+ rrn.not_valid_before_utc.date() <= identity.validity_end
363
+ and rrn.not_valid_after_utc.date() >= identity.validity_start
364
+ )
365
+ if not in_period:
366
+ errors.append("the RRN certificate was not valid during the card validity")
367
+ return trusted, in_period
368
+
369
+
370
+ def verify_eid(
371
+ eid: EidData, *, trusted_roots: Sequence[bytes] | None = None
372
+ ) -> VerificationReport:
373
+ """Check the integrity and authenticity of data read from a card.
374
+
375
+ Every check is made on the raw files (:attr:`EidData.files`), and the
376
+ decoded fields of *eid* must match them (``content_matches_files``), so
377
+ data received from an untrusted source (e.g. uploaded to a server) can be
378
+ checked safely. Build such data with :meth:`EidData.from_files`.
379
+
380
+ This offline check does not include the live chip challenge, see
381
+ :meth:`pythonbeid.CardReader.verify`. Card content never makes it raise:
382
+ malformed data gives failed checks.
383
+
384
+ Args:
385
+ eid: The data to check.
386
+ trusted_roots: Root certificates (PEM, PEM bundles or DER) to trust
387
+ instead of the bundled Belgian roots.
388
+
389
+ Returns:
390
+ The outcome of every check; see :attr:`VerificationReport.is_valid`.
391
+
392
+ Raises:
393
+ ValueError: If *eid* lacks files needed for the checks (it was read
394
+ with ``integrity=False``), or a trusted root cannot be loaded.
395
+ ImportError: If the ``cryptography`` package is not installed.
396
+ """
397
+ missing = [file.name for file in _REQUIRED_FILES if file not in eid.files]
398
+ if missing:
399
+ msg = (
400
+ f"missing files for verification: {', '.join(missing)} "
401
+ "(read the card with integrity=True)"
402
+ )
403
+ raise ValueError(msg)
404
+ roots = [
405
+ certificate
406
+ for root in (
407
+ bundled_trusted_roots() if trusted_roots is None else trusted_roots
408
+ )
409
+ for certificate in _load_certificates(root)
410
+ ]
411
+ errors: list[str] = []
412
+ files = eid.files
413
+
414
+ identity, address = _decode_signed(files, errors)
415
+ photo = files.get(CardFile.PHOTO, eid.photo)
416
+ content_ok = (
417
+ identity is not None
418
+ and eid.identity == identity
419
+ and eid.address == address
420
+ and (eid.photo is None or eid.photo == photo)
421
+ )
422
+ if identity is not None and not content_ok:
423
+ errors.append("the decoded content does not match the signed files")
424
+
425
+ photo_valid = _photo_valid(photo, identity, errors)
426
+ rrn = _load_rrn(files, errors)
427
+ hint = _PHOTO_HASHES.get(len(identity.photo_hash)) if identity else None
428
+ identity_signature = files[CardFile.IDENTITY_SIGNATURE]
429
+ identity_valid = rrn is not None and _verify_signature(
430
+ rrn, files[CardFile.IDENTITY], identity_signature, hint
431
+ )
432
+ if rrn is not None and not identity_valid:
433
+ errors.append("the identity signature is invalid")
434
+
435
+ # The address signature covers the address file without its trailing
436
+ # zero padding, followed by the complete identity signature file.
437
+ signed_address = files[CardFile.ADDRESS].rstrip(b"\x00") + identity_signature
438
+ address_valid = rrn is not None and _verify_signature(
439
+ rrn, signed_address, files[CardFile.ADDRESS_SIGNATURE], hint
440
+ )
441
+ if rrn is not None and not address_valid:
442
+ errors.append("the address signature is invalid")
443
+
444
+ rrn_trusted, period_valid = _rrn_checks(rrn, roots, identity, errors)
445
+
446
+ return VerificationReport(
447
+ photo_hash_valid=photo_valid,
448
+ identity_signature_valid=identity_valid,
449
+ address_signature_valid=address_valid,
450
+ rrn_certificate_trusted=rrn_trusted,
451
+ rrn_certificate_period_valid=period_valid,
452
+ content_matches_files=content_ok,
453
+ basic_key_valid=_basic_key_valid(identity, files, errors),
454
+ errors=tuple(errors),
455
+ )