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.
pythonbeid/card_reader.py CHANGED
@@ -1,258 +1,846 @@
1
- """Belgian eID card reader.
1
+ """PC/SC access to Belgian eID cards.
2
+
3
+ The transport follows what the official middleware (``Fedict/eid-mw``) does:
4
+
5
+ * files are selected by absolute path, with a fallback that selects the Belpic
6
+ applet when another application left the card in a different state;
7
+ * files are read in 252-byte blocks, ``6Cxx`` answers are re-sent with the
8
+ exact length, ``61xx`` answers are collected with GET RESPONSE and ``6B00``
9
+ past the first block marks the end of a file whose size is a multiple of
10
+ the block size;
11
+ * every multi-command operation runs inside a PC/SC transaction, so other
12
+ applications (browser, middleware, Windows certificate propagation) cannot
13
+ interleave their own commands;
14
+ * the card is left powered when the connection is closed.
15
+
16
+ No PIN is ever sent: everything this module reads is public card content.
17
+ """
2
18
 
3
- Reads personal data, address and optionally the photo from a Belgian
4
- electronic identity card via a PC/SC-compatible smart card reader.
19
+ from __future__ import annotations
5
20
 
6
- Dependencies: pyscard (python-smartcard)
21
+ import base64
22
+ import logging
23
+ import os
24
+ import time
25
+ import warnings
26
+ from contextlib import contextmanager
27
+ from dataclasses import replace
28
+ from datetime import date, datetime
29
+ from typing import TYPE_CHECKING, Any, NamedTuple, Self
30
+
31
+ from smartcard.CardConnectionDecorator import CardConnectionDecorator
32
+ from smartcard.CardRequest import CardRequest
33
+ from smartcard.Exceptions import (
34
+ CardConnectionException,
35
+ CardRequestTimeoutException,
36
+ NoCardException,
37
+ SmartcardException,
38
+ )
39
+ from smartcard.pcsc.PCSCExceptions import BaseSCardException
40
+ from smartcard.scard import (
41
+ SCARD_E_NO_SMARTCARD,
42
+ SCARD_LEAVE_CARD,
43
+ SCARD_S_SUCCESS,
44
+ SCARD_W_REMOVED_CARD,
45
+ SCARD_W_RESET_CARD,
46
+ SCardBeginTransaction,
47
+ SCardEndTransaction,
48
+ SCardGetErrorMessage,
49
+ )
50
+ from smartcard.System import readers as _pcsc_readers
51
+
52
+ from .exceptions import (
53
+ APDUError,
54
+ BeidError,
55
+ CardCommunicationError,
56
+ CardDataError,
57
+ NoCardError,
58
+ NoReaderError,
59
+ PCSCServiceError,
60
+ UnsupportedCardError,
61
+ )
62
+ from .models import CardFile, CardInfo, EidData
63
+ from .parser import _der_length, _text, parse_address, parse_card_data, parse_identity
64
+
65
+ if TYPE_CHECKING:
66
+ from collections.abc import Callable, Iterator, Sequence
67
+ from types import TracebackType
68
+
69
+ from .models import Address, Identity, VerificationReport
70
+
71
+ __all__ = ["CardReader", "list_readers"]
7
72
 
8
- Usage::
73
+ logger = logging.getLogger(__name__)
9
74
 
10
- from pythonbeid import CardReader
75
+ _BELPIC_AID = bytes.fromhex("A0 00 00 00 30 29 05 70 00 AD 13 10 01 01 FF")
76
+ _DEFAULT_CHUNK_SIZE = 252 # eid-mw MAX_APDU_READ_LEN
77
+ _MAX_OFFSET = 0x7FFF # READ BINARY with a 15-bit offset
78
+ _MAX_6C_RETRIES = 3
79
+ _MAX_GET_RESPONSE = 64
80
+ _CHALLENGE_SIZE = 48 # SHA-384 digest size, as eid-viewer does
81
+ _WAIT_STEP = 1.0 # seconds between two scans of the readers while waiting
11
82
 
12
- with CardReader() as cr:
13
- info = cr.read_informations(photo=False)
14
- print(info["last_name"])
15
- """
16
- import base64
17
- import logging
18
- from datetime import datetime
19
- from typing import Any
83
+ _SW_OK = 0x9000
84
+ _SW_EOF_WARNING = 0x6282 # end of file reached before reading Le bytes
85
+ _SW_WRONG_OFFSET = 0x6B00
86
+ _SW_NOT_FOUND = (0x6A82, 0x6A86)
87
+ _SW_MESSAGES = {
88
+ 0x6700: "wrong length",
89
+ 0x6982: "security status not satisfied",
90
+ 0x6986: "command not allowed",
91
+ 0x6A82: "file not found",
92
+ 0x6A86: "incorrect P1/P2",
93
+ 0x6B00: "offset outside the file",
94
+ 0x6D00: "instruction not supported",
95
+ 0x6E00: "class not supported",
96
+ }
20
97
 
21
- from smartcard.Exceptions import CardConnectionException, NoCardException
22
- from smartcard.System import readers
23
98
 
24
- from .exceptions import APDUError, CardCommunicationError, NoCardError, NoReaderError
25
- from .parser import parse_french_date, parse_tlv
99
+ # PC/SC codes are signed on Windows and unsigned elsewhere: compare them as
100
+ # unsigned 32-bit values on both sides.
101
+ _UINT32 = 0xFFFFFFFF
102
+ _CARD_ABSENT_CODES = frozenset(
103
+ code & _UINT32 for code in (SCARD_W_REMOVED_CARD, SCARD_E_NO_SMARTCARD)
104
+ )
105
+ _CARD_RESET_CODE = SCARD_W_RESET_CARD & _UINT32
26
106
 
27
- logger = logging.getLogger(__name__)
28
107
 
29
- # ── File identifiers (path on the card) ──────────────────────────────────────
30
- _FILE_ID = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x31] # personal identity data
31
- _FILE_ADDRESS = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x33] # address data
32
- _FILE_PHOTO = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x35] # photo data
108
+ class _Response(NamedTuple):
109
+ data: bytes
110
+ sw: int
111
+
112
+
113
+ class _CardResetError(Exception):
114
+ """Internal signal: another application reset the card."""
115
+
116
+
117
+ def _repeated_reset() -> CardCommunicationError:
118
+ return CardCommunicationError(
119
+ "The card was reset repeatedly by another application"
120
+ )
121
+
33
122
 
34
- # ISO 7816-4: Le=0x00 in a short APDU means "expect up to 256 bytes".
35
- _LE_MAX = 0x00
123
+ def _hresult(exc: BaseException) -> int:
124
+ """PC/SC return code of a pyscard exception, as an unsigned integer."""
125
+ return int(getattr(exc, "hresult", -1)) & _UINT32
36
126
 
37
- # ── Status words that are handled in-band ──────────────────────────────────
38
- _SW_OK = 0x90 # Normal completion
39
- _SW_MORE_DATA = 0x61 # More data available (GET RESPONSE with SW2 bytes)
40
- _SW_WRONG_LE = 0x6C # Wrong Le: use SW2 as exact length
127
+
128
+ def _naive_datetime(day: date) -> datetime:
129
+ """Midnight of *day* as a naive datetime, the 0.x date type."""
130
+ return datetime(day.year, day.month, day.day) # noqa: DTZ001 - 0.x compatibility
131
+
132
+
133
+ def _list_pcsc_readers() -> list[Any]:
134
+ try:
135
+ return list(_pcsc_readers())
136
+ except (BaseSCardException, SmartcardException) as exc:
137
+ msg = f"PC/SC service unavailable: {exc}"
138
+ raise PCSCServiceError(msg) from exc
41
139
 
42
140
 
43
141
  def list_readers() -> list[str]:
44
- """Return the names of all connected PC/SC smart card readers.
142
+ """Return the names of the connected PC/SC smart card readers.
143
+
144
+ The position of a name in the list is the index accepted by
145
+ :class:`CardReader`.
45
146
 
46
- Returns:
47
- A list of human-readable reader names, in PC/SC order (the index
48
- of a name matches the ``reader_index`` argument of
49
- :class:`CardReader`). Empty when no reader is connected.
147
+ Raises:
148
+ PCSCServiceError: If the PC/SC service cannot be reached.
50
149
  """
51
- return [str(reader) for reader in readers()]
150
+ return [str(reader) for reader in _list_pcsc_readers()]
52
151
 
53
152
 
54
- class CardReader:
55
- """Read information from a Belgian eID card.
153
+ class _TransactionalConnection(CardConnectionDecorator): # type: ignore[misc]
154
+ """pyscard connection able to hold PC/SC transactions.
56
155
 
57
- Args:
58
- reader_index: Index of the PC/SC reader to use when multiple readers
59
- are connected. Defaults to 0 (first available reader).
156
+ Unlike pyscard's ``ExclusiveTransmitCardConnection``, failures keep the
157
+ PC/SC return code in ``hresult``, which is needed to detect a card reset.
158
+ """
60
159
 
61
- Examples:
62
- Using as a context manager (recommended)::
160
+ def _hcard(self) -> Any:
161
+ component = self.component
162
+ while component is not None:
163
+ if hasattr(component, "hcard"):
164
+ return component.hcard
165
+ component = getattr(component, "component", None)
166
+ return None # pragma: no cover - pyscard always has a PCSC connection
63
167
 
64
- with CardReader() as cr:
65
- data = cr.read_informations()
168
+ def lock(self) -> None:
169
+ """Begin a PC/SC transaction (``SCardBeginTransaction``)."""
170
+ hresult = SCardBeginTransaction(self._hcard())
171
+ if hresult != SCARD_S_SUCCESS:
172
+ msg = f"SCardBeginTransaction failed: {SCardGetErrorMessage(hresult)}"
173
+ raise CardConnectionException(msg, hresult=hresult)
66
174
 
67
- Or manually::
175
+ def unlock(self) -> None:
176
+ """End the PC/SC transaction, leaving the card as it is."""
177
+ hresult = SCardEndTransaction(self._hcard(), SCARD_LEAVE_CARD)
178
+ if hresult != SCARD_S_SUCCESS:
179
+ msg = f"SCardEndTransaction failed: {SCardGetErrorMessage(hresult)}"
180
+ raise CardConnectionException(msg, hresult=hresult)
68
181
 
69
- cr = CardReader()
70
- try:
71
- data = cr.read_informations()
72
- finally:
73
- cr.close()
182
+
183
+ def _wrap_connection(connection: Any) -> Any:
184
+ """Decorate a pyscard connection so it can hold PC/SC transactions."""
185
+ return _TransactionalConnection(connection)
186
+
187
+
188
+ class CardReader:
189
+ """Connection to a Belgian eID card inserted in a PC/SC reader.
190
+
191
+ Args:
192
+ reader: Which reader to use: its index in :func:`list_readers`, its
193
+ name (exact, or a unique case-insensitive substring), or ``None``
194
+ (default) to pick the first reader holding a Belgian eID card.
195
+ timeout: Seconds to wait for a card to be inserted when none is
196
+ present. ``None`` (default) does not wait.
197
+ chunk_size: Number of bytes requested per READ BINARY command
198
+ (1-256). The default (252) is the value of the official
199
+ middleware; lower it only for readers that cannot transfer
200
+ larger blocks.
201
+ reader_index: Deprecated alias of *reader*.
202
+
203
+ Raises:
204
+ NoReaderError: If no reader matches.
205
+ PCSCServiceError: If the PC/SC service cannot be reached.
206
+ NoCardError: If no card is present (after *timeout*).
207
+ UnsupportedCardError: If the card is not a Belgian eID card.
208
+ CardCommunicationError: If the connection fails.
209
+
210
+ Examples:
211
+ >>> with CardReader() as reader: # doctest: +SKIP
212
+ ... eid = reader.read()
213
+ ... print(eid.identity.last_name)
74
214
  """
75
215
 
76
- def __init__(self, reader_index: int = 0) -> None:
77
- available = readers()
78
- if not available:
79
- raise NoReaderError("No smart card reader detected")
80
- if reader_index >= len(available):
81
- raise NoReaderError(
82
- f"Reader index {reader_index} out of range "
83
- f"({len(available)} reader(s) available)"
216
+ def __init__(
217
+ self,
218
+ reader: int | str | None = None,
219
+ *,
220
+ timeout: float | None = None,
221
+ chunk_size: int = _DEFAULT_CHUNK_SIZE,
222
+ reader_index: int | None = None,
223
+ ) -> None:
224
+ if reader_index is not None:
225
+ warnings.warn(
226
+ "'reader_index' is deprecated, pass the index as 'reader'",
227
+ DeprecationWarning,
228
+ stacklevel=2,
84
229
  )
85
- reader = available[reader_index]
86
- logger.debug("Using reader: %s", reader)
230
+ if reader is not None:
231
+ msg = "pass either 'reader' or 'reader_index', not both"
232
+ raise TypeError(msg)
233
+ reader = reader_index
234
+ if not 1 <= chunk_size <= 256:
235
+ msg = f"chunk_size must be between 1 and 256, got {chunk_size}"
236
+ raise ValueError(msg)
237
+ self._chunk_size = chunk_size
238
+ self._lock_depth = 0
239
+ self._retry_delay = 0.0
240
+ self._connection: Any = None
241
+ self._card_info: CardInfo | None = None
242
+
243
+ available = _list_pcsc_readers()
244
+ if not available:
245
+ msg = "No smart card reader detected"
246
+ raise NoReaderError(msg)
247
+ candidates = self._resolve_readers(available, reader)
248
+ self._open(candidates, explicit=reader is not None, timeout=timeout)
249
+
250
+ # ── Reader selection and connection ──────────────────────────────────
251
+
252
+ @staticmethod
253
+ def _resolve_readers(available: list[Any], reader: int | str | None) -> list[Any]:
254
+ if reader is None:
255
+ return available
256
+ if isinstance(reader, bool) or not isinstance(reader, int | str):
257
+ msg = f"reader must be an index or a name, got {type(reader).__name__}"
258
+ raise TypeError(msg)
259
+ if isinstance(reader, int):
260
+ if not 0 <= reader < len(available):
261
+ msg = (
262
+ f"Reader index {reader} out of range "
263
+ f"({len(available)} reader(s) available)"
264
+ )
265
+ raise NoReaderError(msg)
266
+ return [available[reader]]
267
+ names = [str(item) for item in available]
268
+ if reader in names:
269
+ return [available[names.index(reader)]]
270
+ matches = [
271
+ item for item, name in zip(available, names, strict=True)
272
+ if reader.casefold() in name.casefold()
273
+ ] # fmt: skip
274
+ if len(matches) == 1:
275
+ return matches
276
+ if not matches:
277
+ msg = f"No reader matches {reader!r} (available: {', '.join(names)})"
278
+ else:
279
+ found = ", ".join(str(item) for item in matches)
280
+ msg = f"Reader name {reader!r} is ambiguous ({found})"
281
+ raise NoReaderError(msg)
282
+
283
+ def _open(
284
+ self, candidates: list[Any], *, explicit: bool, timeout: float | None
285
+ ) -> None:
286
+ if self._try_candidates(candidates, explicit=explicit):
287
+ return
288
+ if timeout is None:
289
+ names = ", ".join(f"'{item}'" for item in candidates)
290
+ msg = f"No Belgian eID card in reader {names}"
291
+ raise NoCardError(msg)
292
+ deadline = time.monotonic() + timeout
293
+ while True:
294
+ remaining = deadline - time.monotonic()
295
+ if remaining <= 0:
296
+ msg = f"No Belgian eID card inserted within {timeout:g} s"
297
+ raise NoCardError(msg)
298
+ self._wait_for_insertion(candidates, min(remaining, _WAIT_STEP))
299
+ if self._try_candidates(candidates, explicit=explicit):
300
+ return
301
+
302
+ def _try_candidates(self, candidates: list[Any], *, explicit: bool) -> bool:
303
+ for candidate in candidates:
304
+ try:
305
+ self._connect(candidate)
306
+ except NoCardError:
307
+ continue
308
+ except BeidError:
309
+ if explicit:
310
+ raise
311
+ logger.debug("Skipping reader '%s'", candidate, exc_info=True)
312
+ continue
313
+ return True
314
+ return False
315
+
316
+ def _connect(self, reader: Any) -> None:
317
+ try:
318
+ connection = _wrap_connection(reader.createConnection())
319
+ connection.connect(disposition=SCARD_LEAVE_CARD)
320
+ except NoCardException as exc:
321
+ msg = f"No card in reader '{reader}'"
322
+ raise NoCardError(msg) from exc
323
+ except SmartcardException as exc:
324
+ if _hresult(exc) in _CARD_ABSENT_CODES:
325
+ msg = f"No card in reader '{reader}'"
326
+ raise NoCardError(msg) from exc
327
+ msg = f"Connection error on '{reader}': {exc}"
328
+ raise CardCommunicationError(msg) from exc
329
+ self._connection = connection
330
+ self._reader = reader
331
+ try:
332
+ self._card_info = self._read_card_info()
333
+ except APDUError as exc:
334
+ self.close()
335
+ msg = f"The card in '{reader}' is not a Belgian eID card ({exc})"
336
+ raise UnsupportedCardError(msg) from exc
337
+ except BeidError:
338
+ self.close()
339
+ raise
340
+ if self._card_info.global_os_version == 0x0001:
341
+ # eid-mw waits before re-sending a command answered with 6Cxx
342
+ # on cards with this global OS version.
343
+ self._retry_delay = 0.05
344
+ logger.debug(
345
+ "Connected to applet %s card via '%s'",
346
+ self._card_info.applet_version_string,
347
+ reader,
348
+ )
349
+
350
+ @staticmethod
351
+ def _wait_for_insertion(candidates: list[Any], seconds: float) -> None:
352
+ """Block until a card is inserted in one of *candidates*, or *seconds*.
353
+
354
+ Readers that already hold a card (e.g. a bank card) do not end the
355
+ wait: only new insertions do, and the caller then retries every
356
+ reader.
357
+ """
358
+ request = CardRequest(timeout=seconds, readers=candidates, newcardonly=True)
87
359
  try:
88
- self._cnx = reader.createConnection()
89
- self._cnx.connect()
90
- except NoCardException:
91
- raise NoCardError(f"No card in reader '{reader}'")
92
- except CardConnectionException as exc:
93
- raise CardCommunicationError(f"Connection error on '{reader}': {exc}") from exc
94
- logger.debug("Connected to card via '%s'", reader)
360
+ request.waitforcard()
361
+ except CardRequestTimeoutException:
362
+ return
363
+ except (BaseSCardException, SmartcardException) as exc:
364
+ msg = f"Error while waiting for a card: {exc}"
365
+ raise CardCommunicationError(msg) from exc
95
366
 
96
- # ── Context manager ───────────────────────────────────────────────────
367
+ # ── Context manager and properties ───────────────────────────────────
97
368
 
98
- def __enter__(self) -> "CardReader":
369
+ def __enter__(self) -> Self:
99
370
  return self
100
371
 
101
- def __exit__(self, *_: Any) -> None:
372
+ def __exit__(
373
+ self,
374
+ exc_type: type[BaseException] | None,
375
+ exc: BaseException | None,
376
+ traceback: TracebackType | None,
377
+ ) -> None:
102
378
  self.close()
103
379
 
380
+ def __repr__(self) -> str:
381
+ state = "open" if self._connection is not None else "closed"
382
+ return f"<CardReader reader='{getattr(self, '_reader', '?')}' {state}>"
383
+
104
384
  def close(self) -> None:
105
- """Disconnect from the card and release the reader."""
385
+ """Release the card, leaving it powered for other applications.
386
+
387
+ Calling it more than once is harmless.
388
+ """
389
+ connection, self._connection = self._connection, None
390
+ if connection is None:
391
+ return
106
392
  try:
107
- self._cnx.disconnect()
393
+ connection.disconnect()
394
+ except (BaseSCardException, SmartcardException) as exc:
395
+ logger.debug("Ignoring error while disconnecting: %s", exc)
396
+ else:
108
397
  logger.debug("Disconnected from card")
109
- except Exception:
110
- pass # Ignore errors on cleanup
111
398
 
112
- # ── Low-level APDU transport ──────────────────────────────────────────
399
+ @property
400
+ def reader_name(self) -> str:
401
+ """Name of the PC/SC reader in use."""
402
+ return str(self._reader)
403
+
404
+ @property
405
+ def atr(self) -> bytes:
406
+ """Answer To Reset of the card."""
407
+ atr: bytes = self._with_reset_retry(
408
+ lambda: bytes(self._call(self._live_connection().getATR))
409
+ )
410
+ return atr
411
+
412
+ @property
413
+ def card_info(self) -> CardInfo:
414
+ """Chip information (GET CARD DATA), read when connecting."""
415
+ if self._card_info is None: # pragma: no cover - set by the constructor
416
+ self._card_info = self._read_card_info()
417
+ return self._card_info
418
+
419
+ # ── Low-level transport ──────────────────────────────────────────────
420
+
421
+ def _live_connection(self) -> Any:
422
+ if self._connection is None:
423
+ msg = "The connection to the card is closed"
424
+ raise CardCommunicationError(msg)
425
+ return self._connection
426
+
427
+ def _call(self, func: Callable[..., Any], *args: Any) -> Any:
428
+ """Run a pyscard call and translate its exceptions."""
429
+ try:
430
+ return func(*args)
431
+ except NoCardException as exc:
432
+ msg = f"Card removed from reader '{self._reader}'"
433
+ raise NoCardError(msg) from exc
434
+ except SmartcardException as exc:
435
+ code = _hresult(exc)
436
+ if code in _CARD_ABSENT_CODES:
437
+ msg = f"Card removed from reader '{self._reader}'"
438
+ raise NoCardError(msg) from exc
439
+ if code == _CARD_RESET_CODE:
440
+ raise _CardResetError from exc
441
+ msg = f"Communication error with the card: {exc}"
442
+ raise CardCommunicationError(msg) from exc
443
+
444
+ def _transmit_once(self, apdu: bytes) -> _Response:
445
+ data, sw1, sw2 = self._call(self._live_connection().transmit, list(apdu))
446
+ response = _Response(bytes(data), (sw1 << 8) | sw2)
447
+ logger.debug(
448
+ "APDU %s (%d bytes) -> SW=%04X, %d bytes",
449
+ apdu[:4].hex(" ").upper(),
450
+ len(apdu),
451
+ response.sw,
452
+ len(response.data),
453
+ )
454
+ return response
455
+
456
+ def _transmit(self, apdu: bytes) -> _Response:
457
+ """Send one command, handling ``6Cxx`` and ``61xx`` transparently."""
458
+ response = self._transmit_once(apdu)
459
+ for _ in range(_MAX_6C_RETRIES):
460
+ if response.sw >> 8 != 0x6C or len(apdu) != 5:
461
+ break
462
+ if self._retry_delay:
463
+ time.sleep(self._retry_delay)
464
+ apdu = apdu[:4] + bytes([response.sw & 0xFF])
465
+ response = self._transmit_once(apdu)
466
+ data = response.data
467
+ for _ in range(_MAX_GET_RESPONSE):
468
+ if response.sw >> 8 != 0x61:
469
+ break
470
+ response = self._transmit_once(
471
+ bytes([0x00, 0xC0, 0x00, 0x00, response.sw & 0xFF])
472
+ )
473
+ data += response.data
474
+ else:
475
+ msg = "too many chained GET RESPONSE commands"
476
+ raise CardCommunicationError(msg)
477
+ return _Response(data, response.sw)
478
+
479
+ @staticmethod
480
+ def _check(response: _Response, action: str) -> bytes:
481
+ if response.sw != _SW_OK:
482
+ sw1, sw2 = response.sw >> 8, response.sw & 0xFF
483
+ reason = _SW_MESSAGES.get(response.sw, "unexpected status")
484
+ msg = f"{action} failed: SW={response.sw:04X} ({reason})"
485
+ raise APDUError(sw1, sw2, msg)
486
+ return response.data
487
+
488
+ @contextmanager
489
+ def _transaction(self) -> Iterator[None]:
490
+ """Hold a PC/SC transaction (re-entrant) around several commands."""
491
+ if self._lock_depth == 0:
492
+ try:
493
+ self._call(self._live_connection().lock)
494
+ except _CardResetError:
495
+ self._reconnect()
496
+ try:
497
+ self._call(self._live_connection().lock)
498
+ except _CardResetError as exc:
499
+ raise _repeated_reset() from exc
500
+ self._lock_depth += 1
501
+ try:
502
+ yield
503
+ finally:
504
+ self._lock_depth -= 1
505
+ if self._lock_depth == 0 and self._connection is not None:
506
+ try:
507
+ self._connection.unlock()
508
+ except (BaseSCardException, SmartcardException) as exc:
509
+ logger.debug("Ignoring error while ending transaction: %s", exc)
510
+
511
+ def _reconnect(self) -> None:
512
+ logger.debug("Card was reset by another application, reconnecting")
513
+ connection = self._live_connection()
514
+ try:
515
+ self._call(connection.reconnect, None, None, SCARD_LEAVE_CARD)
516
+ if self._lock_depth:
517
+ self._call(connection.lock)
518
+ except _CardResetError as exc:
519
+ self.close()
520
+ raise _repeated_reset() from exc
521
+ except BeidError:
522
+ # pyscard drops the card handle when reconnecting fails.
523
+ self.close()
524
+ raise
525
+
526
+ def _with_reset_retry(self, operation: Callable[[], Any]) -> Any:
527
+ try:
528
+ with self._transaction():
529
+ return operation()
530
+ except _CardResetError:
531
+ self._reconnect()
532
+ try:
533
+ with self._transaction():
534
+ return operation()
535
+ except _CardResetError as exc:
536
+ raise _repeated_reset() from exc
537
+
538
+ def _select(self, path: bytes) -> None:
539
+ command = bytes([0x00, 0xA4, 0x08, 0x0C, len(path)]) + path
540
+ response = self._transmit(command)
541
+ if response.sw in _SW_NOT_FOUND or response.sw >> 8 in (0x6D, 0x6E):
542
+ # Another application may have selected a different applet.
543
+ self._transmit(
544
+ bytes([0x00, 0xA4, 0x04, 0x0C, len(_BELPIC_AID)]) + _BELPIC_AID
545
+ )
546
+ response = self._transmit(command)
547
+ self._check(response, f"SELECT {path.hex().upper()}")
548
+
549
+ def _read_selected(self) -> bytes:
550
+ content = bytearray()
551
+ le = self._chunk_size & 0xFF # 256 is encoded as 0x00
552
+ while True:
553
+ offset = len(content)
554
+ if offset > _MAX_OFFSET:
555
+ msg = "file larger than the READ BINARY offset range"
556
+ raise CardDataError(msg)
557
+ response = self._transmit(
558
+ bytes([0x00, 0xB0, offset >> 8, offset & 0xFF, le])
559
+ )
560
+ if response.sw == _SW_WRONG_OFFSET and offset > 0:
561
+ break # the file size is a multiple of the block size
562
+ if response.sw == _SW_EOF_WARNING:
563
+ content += response.data
564
+ break
565
+ content += self._check(response, f"READ BINARY at offset {offset}")
566
+ if len(response.data) < self._chunk_size:
567
+ break
568
+ return bytes(content)
569
+
570
+ def _read_card_info(self) -> CardInfo:
571
+ def operation() -> CardInfo:
572
+ data = self._check(
573
+ self._transmit(bytes([0x80, 0xE4, 0x00, 0x00, 0x1C])), "GET CARD DATA"
574
+ )
575
+ extended = None
576
+ if len(data) > 21 and data[21] >= 0x18:
577
+ extended = self._check(
578
+ self._transmit(bytes([0x80, 0xE4, 0x00, 0x01, 0x1F])),
579
+ "GET CARD DATA (extended)",
580
+ )
581
+ return parse_card_data(data, extended)
582
+
583
+ result: CardInfo = self._with_reset_retry(operation)
584
+ return result
585
+
586
+ # ── Public API ───────────────────────────────────────────────────────
113
587
 
114
- def _send_apdu(self, apdu: list[int]) -> tuple[list[int], int, int]:
115
- """Transmit one APDU and return ``(data, SW1, SW2)``.
588
+ def read_file(self, file: CardFile | bytes | Sequence[int]) -> bytes:
589
+ """Read the complete raw content of a file.
590
+
591
+ Args:
592
+ file: A :class:`CardFile`, or an absolute path such as
593
+ ``bytes.fromhex("3F00DF014031")``.
594
+
595
+ Returns:
596
+ The file content, including any zero padding.
116
597
 
117
598
  Raises:
118
- APDUError: If the card returns an unexpected status word
119
- (i.e. not 0x90, 0x61, or 0x6C).
599
+ APDUError: If the file does not exist or cannot be read.
600
+ NoCardError: If the card was removed.
601
+ CardCommunicationError: On any other transport failure.
120
602
  """
121
- response, sw1, sw2 = self._cnx.transmit(apdu)
122
- logger.debug("APDU %s → SW=%02X%02X data(%d)=%s",
123
- [f"{b:02X}" for b in apdu], sw1, sw2, len(response),
124
- [f"{b:02X}" for b in response[:8]])
125
- if sw1 not in (_SW_OK, _SW_MORE_DATA, _SW_WRONG_LE):
126
- raise APDUError(sw1, sw2,
127
- f"Unexpected status SW={sw1:02X}{sw2:02X} "
128
- f"for APDU {[hex(b) for b in apdu[:4]]}")
129
- return response, sw1, sw2
130
-
131
- # ── File access helpers ───────────────────────────────────────────────
132
-
133
- def _select_file(self, file_id: list[int]) -> None:
134
- """Send a SELECT command for *file_id* (no response expected)."""
135
- cmd = [0x00, 0xA4, 0x08, 0x0C, len(file_id)] + file_id
136
- _, sw1, sw2 = self._send_apdu(cmd)
137
- if sw1 != _SW_OK:
138
- raise APDUError(sw1, sw2, f"SELECT failed for file {[hex(b) for b in file_id]}")
139
- logger.debug("Selected file %s", [f"{b:02X}" for b in file_id])
140
-
141
- def _read_binary(self, p1: int, p2: int, le: int) -> tuple[list[int], int, int]:
142
- """Send a READ BINARY command and handle Le mismatch (0x6C)."""
143
- cmd = [0x00, 0xB0, p1, p2, le]
144
- data, sw1, sw2 = self._send_apdu(cmd)
145
- if sw1 == _SW_WRONG_LE:
146
- # Card tells us the exact length: re-issue with SW2 as Le.
147
- logger.debug("RE-READ BINARY with Le=%d (was %d)", sw2, le)
148
- cmd[-1] = sw2
149
- data, sw1, sw2 = self._send_apdu(cmd)
150
- return data, sw1, sw2
151
-
152
- def _read_data(self, file_id: list[int]) -> list[int]:
153
- """Select *file_id* and read its content (up to 256 bytes)."""
154
- self._select_file(file_id)
155
- data, sw1, sw2 = self._read_binary(0x00, 0x00, _LE_MAX)
156
- logger.debug("Read %d bytes from file %s, SW=%02X%02X",
157
- len(data), [f"{b:02X}" for b in file_id], sw1, sw2)
158
- return data
159
-
160
- def _read_photo(self) -> bytearray:
161
- """Read the complete photo file in 256-byte chunks.
162
-
163
- The photo file is typically larger than 256 bytes so it must be
164
- read with successive READ BINARY commands using an incrementing
165
- offset (P1 = high byte, P2 = low byte of a 15-bit offset).
603
+ path = file.path if isinstance(file, CardFile) else bytes(file)
604
+
605
+ def operation() -> bytes:
606
+ self._select(path)
607
+ return self._read_selected()
608
+
609
+ content: bytes = self._with_reset_retry(operation)
610
+ logger.debug("Read %d bytes from %s", len(content), path.hex().upper())
611
+ return content
612
+
613
+ def read_certificate(self, file: CardFile) -> bytes:
614
+ """Read a certificate file and return the DER certificate it holds.
615
+
616
+ Certificate files are larger than their content and padded with zero
617
+ bytes; the padding is removed.
618
+
619
+ Raises:
620
+ ValueError: If *file* is not a certificate file.
166
621
  """
167
- self._select_file(_FILE_PHOTO)
168
- photo_bytes: list[int] = []
169
- # Offset advances by 256 bytes on each iteration.
170
- # P1 holds the high byte of the byte offset (offset >> 8),
171
- # P2 holds the low byte (offset & 0xFF).
172
- # Starting with P1=0, P2=0 and incrementing P1 by 1 each time
173
- # moves the window by 256 bytes per step.
174
- p1 = 0
175
- while True:
176
- data, sw1, sw2 = self._read_binary(p1, 0x00, _LE_MAX)
177
- if sw1 == _SW_OK:
178
- photo_bytes.extend(data)
179
- if len(data) < 256:
180
- # Received fewer bytes than requested → end of file.
181
- break
182
- p1 += 1
183
- elif sw1 == _SW_WRONG_LE:
184
- # _read_binary already retried with the correct Le,
185
- # so if we still get here something went wrong.
186
- logger.warning("Unexpected 0x6C after retry at p1=%d", p1)
187
- photo_bytes.extend(data)
188
- break
189
- else:
190
- # Any other status (e.g. 0x6282 end-of-file) ends the loop.
191
- logger.debug("Photo read ended at p1=%d, SW=%02X%02X", p1, sw1, sw2)
192
- break
193
- logger.debug("Photo: %d bytes total", len(photo_bytes))
194
- return bytearray(photo_bytes)
622
+ if not file.is_certificate:
623
+ msg = f"{file.name} is not a certificate file"
624
+ raise ValueError(msg)
625
+ content = self.read_file(file)
626
+ return content[: _der_length(content)]
195
627
 
196
- # ── Public API ────────────────────────────────────────────────────────
628
+ def read_card_info(self) -> CardInfo:
629
+ """Read the chip information (GET CARD DATA) again."""
630
+ self._card_info = self._read_card_info()
631
+ return self._card_info
197
632
 
198
- def read_informations(self, photo: bool = False) -> dict[str, Any]:
199
- """Read and return all information from the card.
633
+ def read_identity(self) -> Identity:
634
+ """Read and decode the identity file."""
635
+ return parse_identity(self.read_file(CardFile.IDENTITY))
636
+
637
+ def read_address(self) -> Address:
638
+ """Read and decode the address file."""
639
+ return parse_address(self.read_file(CardFile.ADDRESS))
640
+
641
+ def read_photo(self) -> bytes:
642
+ """Read the photo of the card holder (JPEG)."""
643
+ return self.read_file(CardFile.PHOTO)
644
+
645
+ def read(self, *, photo: bool = True, integrity: bool = True) -> EidData:
646
+ """Read the card content in a single PC/SC transaction.
200
647
 
201
648
  Args:
202
- photo: When ``True`` the card photo is read and included in the
203
- returned dictionary as a base-64 encoded string.
649
+ photo: Read the photo.
650
+ integrity: Also read the files needed by
651
+ :func:`pythonbeid.verify_eid`: the signatures, the RRN
652
+ certificate and, when the identity file references one, the
653
+ basic public key (applet 1.8).
204
654
 
205
655
  Returns:
206
- A dictionary with keys: ``card_number``, ``validity_start``,
207
- ``validity_end``, ``issuing_municipality``, ``national_number``,
208
- ``last_name``, ``first_names``, ``suffix``, ``nationality``,
209
- ``birth_place``, ``birth_date``, ``sex``, ``address``,
210
- ``postal_code``, ``city``, and optionally ``photo``.
656
+ The decoded content, with the raw files in :attr:`EidData.files`.
211
657
  """
212
- # ── Identity file ────────────────────────────────────────────────
213
- id_data = self._read_data(_FILE_ID)
214
- id_fields = parse_tlv(id_data, 13) # tags 1–13 (tag 2 / index 1 unused)
658
+ with self._transaction():
659
+ files = {CardFile.IDENTITY: self.read_file(CardFile.IDENTITY)}
660
+ identity = parse_identity(files[CardFile.IDENTITY])
661
+ wanted = [CardFile.ADDRESS]
662
+ if photo:
663
+ wanted.append(CardFile.PHOTO)
664
+ if integrity:
665
+ wanted += [
666
+ CardFile.IDENTITY_SIGNATURE,
667
+ CardFile.ADDRESS_SIGNATURE,
668
+ CardFile.RRN_CERTIFICATE,
669
+ ]
670
+ if identity.basic_key_hash is not None:
671
+ wanted.append(CardFile.BASIC_PUBLIC_KEY)
672
+ files.update((file, self.read_file(file)) for file in wanted)
673
+ return EidData(
674
+ identity=identity,
675
+ address=parse_address(files[CardFile.ADDRESS]),
676
+ card=self.card_info,
677
+ photo=files.get(CardFile.PHOTO),
678
+ files=files,
679
+ )
680
+
681
+ def challenge(self, nonce: bytes) -> bytes:
682
+ """Have the chip sign *nonce* with its basic private key.
683
+
684
+ This INTERNAL AUTHENTICATE command only exists on applet 1.8 cards
685
+ and needs no PIN. Prefer :meth:`authenticate_chip`, which also checks
686
+ the key and the answer.
215
687
 
216
- informations: dict[str, Any] = {
217
- "card_number": id_fields[0],
218
- # id_fields[1] is the chip serial number — not exposed in the API
219
- "validity_start": datetime.strptime(id_fields[2], "%d.%m.%Y"),
220
- "validity_end": datetime.strptime(id_fields[3], "%d.%m.%Y"),
221
- "issuing_municipality": id_fields[4],
222
- "national_number": id_fields[5],
223
- "last_name": id_fields[6],
224
- "first_names": id_fields[7],
225
- "suffix": id_fields[8],
226
- "nationality": id_fields[9],
227
- "birth_place": id_fields[10],
228
- "birth_date": parse_french_date(id_fields[11]),
229
- "sex": id_fields[12],
230
- }
688
+ Args:
689
+ nonce: Data to sign (the official viewer uses 48 random bytes).
231
690
 
232
- # ── Address file ─────────────────────────────────────────────────
233
- addr_data = self._read_data(_FILE_ADDRESS)
234
- addr_fields = parse_tlv(addr_data, 3)
691
+ Returns:
692
+ The raw ECDSA signature (``r || s``).
235
693
 
236
- informations["address"] = addr_fields[0]
237
- informations["postal_code"] = addr_fields[1]
238
- informations["city"] = addr_fields[2]
694
+ Raises:
695
+ APDUError: If the card refuses the command (applet 1.7 cards).
696
+ """
697
+ if not 1 <= len(nonce) <= 253:
698
+ msg = "nonce must be between 1 and 253 bytes"
699
+ raise ValueError(msg)
700
+ command = (
701
+ bytes([0x00, 0x88, 0x02, 0x81, len(nonce) + 2, 0x94, len(nonce)]) + nonce
702
+ )
703
+ response = self._with_reset_retry(lambda: self._transmit(command))
704
+ return self._check(response, "INTERNAL AUTHENTICATE")
705
+
706
+ def authenticate_chip(self, identity: Identity | None = None) -> bool:
707
+ """Prove that the chip is the genuine one (applet 1.8 cards).
708
+
709
+ The basic public key file is checked against its digest in the
710
+ identity file, then the chip must sign a random challenge with the
711
+ matching private key, which a copy of the card data cannot do.
239
712
 
240
- # ── Photo (optional) ─────────────────────────────────────────────
241
- if photo:
242
- photo_bytes = self._read_photo()
243
- informations["photo"] = base64.b64encode(photo_bytes).decode("ascii")
713
+ Args:
714
+ identity: The identity whose signed basic key digest is the
715
+ reference, typically one checked by :func:`verify_eid`
716
+ (:meth:`verify` does both). Read from the card when omitted;
717
+ it then proves the chip matches its own identity file, whose
718
+ signature must be checked separately.
244
719
 
245
- # Mirror every key as an instance attribute for convenience.
246
- for key, value in informations.items():
247
- setattr(self, key, value)
720
+ Returns:
721
+ Whether the key matches its digest and the chip signature is
722
+ valid.
248
723
 
249
- return informations
724
+ Raises:
725
+ UnsupportedCardError: If the identity file references no basic
726
+ key (applet 1.7 cards).
727
+ ImportError: If the ``cryptography`` package is not installed.
728
+ """
729
+ from .integrity import ( # noqa: PLC0415 - optional dependency
730
+ basic_key_matches,
731
+ verify_chip_signature,
732
+ )
733
+
734
+ with self._transaction():
735
+ if identity is None:
736
+ identity = self.read_identity()
737
+ if identity.basic_key_hash is None:
738
+ msg = "This card has no basic key (applet 1.8 or later required)"
739
+ raise UnsupportedCardError(msg)
740
+ key_file = self.read_file(CardFile.BASIC_PUBLIC_KEY)
741
+ if not basic_key_matches(key_file, identity.basic_key_hash):
742
+ logger.warning("The basic public key does not match its digest")
743
+ return False
744
+ nonce = os.urandom(_CHALLENGE_SIZE)
745
+ signature = self.challenge(nonce)
746
+ try:
747
+ return verify_chip_signature(key_file, nonce, signature)
748
+ except CardDataError:
749
+ return False
750
+
751
+ def verify(
752
+ self,
753
+ eid: EidData | None = None,
754
+ *,
755
+ authenticate_chip: bool = True,
756
+ trusted_roots: Sequence[bytes] | None = None,
757
+ ) -> VerificationReport:
758
+ """Check the integrity and authenticity of the card content.
759
+
760
+ Args:
761
+ eid: Data previously returned by :meth:`read` (with
762
+ ``integrity=True``); read from the card when omitted.
763
+ authenticate_chip: When the signed identity file references a
764
+ basic key (applet 1.8), also run the chip challenge
765
+ (:meth:`authenticate_chip`).
766
+ trusted_roots: Root certificates (DER or PEM) to trust instead of
767
+ the bundled Belgian roots.
250
768
 
769
+ Returns:
770
+ The outcome of every check.
251
771
 
252
- if __name__ == "__main__":
253
- import logging
254
- from pprint import pprint
772
+ Raises:
773
+ ImportError: If the ``cryptography`` package is not installed.
774
+ NoCardError: If the card is removed during the checks.
775
+ """
776
+ from .integrity import verify_eid # noqa: PLC0415 - optional dependency
255
777
 
256
- logging.basicConfig(level=logging.WARNING)
257
- with CardReader() as cr:
258
- pprint(cr.read_informations(photo=False))
778
+ if eid is None:
779
+ eid = self.read(photo=True, integrity=True)
780
+ report = verify_eid(eid, trusted_roots=trusted_roots)
781
+ try:
782
+ signed = parse_identity(eid.files[CardFile.IDENTITY])
783
+ except CardDataError:
784
+ return report # already reported as failed
785
+ if not authenticate_chip or signed.basic_key_hash is None:
786
+ return report
787
+ try:
788
+ authenticated = self.authenticate_chip(signed)
789
+ except (UnsupportedCardError, APDUError) as exc:
790
+ logger.warning("Chip challenge refused: %s", exc)
791
+ authenticated = False
792
+ errors = report.errors
793
+ if not authenticated:
794
+ errors = (*errors, "chip challenge failed: the chip is not genuine")
795
+ return replace(report, chip_authenticated=authenticated, errors=errors)
796
+
797
+ # ── Deprecated 0.x API ───────────────────────────────────────────────
798
+
799
+ def read_informations(
800
+ self, photo: bool = False # noqa: FBT001, FBT002 - 0.x signature
801
+ ) -> dict[str, Any]:
802
+ """Return the card content as a 0.x-style dictionary.
803
+
804
+ .. deprecated:: 1.0
805
+ Use :meth:`read`, which returns typed data. This method keeps the
806
+ 0.x keys and types: naive ``datetime`` dates, ``suffix`` for the
807
+ initial of the third given name, raw ``sex`` letter, photo as a
808
+ base-64 string. ``birth_date`` is ``None`` for incomplete dates.
809
+
810
+ Args:
811
+ photo: Include the photo, as a base-64 encoded string.
812
+ """
813
+ warnings.warn(
814
+ "read_informations() is deprecated, use read() instead",
815
+ DeprecationWarning,
816
+ stacklevel=2,
817
+ )
818
+ eid = self.read(photo=photo, integrity=False)
819
+ identity, address = eid.identity, eid.address
820
+ birth = identity.birth_date
821
+ informations: dict[str, Any] = {
822
+ "card_number": identity.card_number,
823
+ "validity_start": _naive_datetime(identity.validity_start),
824
+ "validity_end": _naive_datetime(identity.validity_end),
825
+ "issuing_municipality": identity.issuing_municipality,
826
+ "national_number": identity.national_number,
827
+ "last_name": identity.last_name,
828
+ "first_names": identity.first_names,
829
+ "suffix": identity.third_given_name_initial,
830
+ "nationality": identity.nationality,
831
+ "birth_place": identity.birth_place,
832
+ "birth_date": (
833
+ _naive_datetime(birth.to_date())
834
+ if birth is not None and birth.is_complete
835
+ else None
836
+ ),
837
+ "sex": _text(identity.raw.get(0x0D)),
838
+ "address": address.street,
839
+ "postal_code": address.postal_code,
840
+ "city": address.municipality,
841
+ }
842
+ if eid.photo is not None:
843
+ informations["photo"] = base64.b64encode(eid.photo).decode("ascii")
844
+ for key, value in informations.items():
845
+ setattr(self, key, value)
846
+ return informations