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