pythonbeid 0.2.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,256 +1,846 @@
1
- """Belgian eID card reader.
2
-
3
- Reads personal data, address and optionally the photo from a Belgian
4
- electronic identity card via a PC/SC-compatible smart card reader.
5
-
6
- Dependencies: pyscard (python-smartcard)
7
-
8
- Usage::
9
-
10
- from pythonbeid import CardReader
11
-
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
20
-
21
- from smartcard.Exceptions import CardConnectionException, NoCardException
22
- from smartcard.System import readers
23
-
24
- from .exceptions import APDUError, CardCommunicationError, NoCardError, NoReaderError
25
- from .parser import parse_french_date, parse_tlv
26
-
27
- logger = logging.getLogger(__name__)
28
-
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
33
-
34
- # ISO 7816-4: Le=0x00 in a short APDU means "expect up to 256 bytes".
35
- _LE_MAX = 0x00
36
-
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
41
-
42
-
43
- class CardReader:
44
- """Read information from a Belgian eID card.
45
-
46
- Parameters
47
- ----------
48
- reader_index:
49
- Index of the PC/SC reader to use when multiple readers are connected.
50
- Defaults to 0 (first available reader).
51
-
52
- Examples
53
- --------
54
- Using as a context manager (recommended)::
55
-
56
- with CardReader() as cr:
57
- data = cr.read_informations()
58
-
59
- Or manually::
60
-
61
- cr = CardReader()
62
- try:
63
- data = cr.read_informations()
64
- finally:
65
- cr.close()
66
- """
67
-
68
- def __init__(self, reader_index: int = 0) -> None:
69
- available = readers()
70
- if not available:
71
- raise NoReaderError("No smart card reader detected")
72
- if reader_index >= len(available):
73
- raise NoReaderError(
74
- f"Reader index {reader_index} out of range "
75
- f"({len(available)} reader(s) available)"
76
- )
77
- reader = available[reader_index]
78
- logger.debug("Using reader: %s", reader)
79
- try:
80
- self._cnx = reader.createConnection()
81
- self._cnx.connect()
82
- except NoCardException:
83
- raise NoCardError(f"No card in reader '{reader}'")
84
- except CardConnectionException as exc:
85
- raise CardCommunicationError(f"Connection error on '{reader}': {exc}") from exc
86
- logger.debug("Connected to card via '%s'", reader)
87
-
88
- # ── Context manager ───────────────────────────────────────────────────
89
-
90
- def __enter__(self) -> "CardReader":
91
- return self
92
-
93
- def __exit__(self, *_: Any) -> None:
94
- self.close()
95
-
96
- def close(self) -> None:
97
- """Disconnect from the card and release the reader."""
98
- try:
99
- self._cnx.disconnect()
100
- logger.debug("Disconnected from card")
101
- except Exception:
102
- pass # Ignore errors on cleanup
103
-
104
- # ── Low-level APDU transport ──────────────────────────────────────────
105
-
106
- def _send_apdu(self, apdu: list[int]) -> tuple[list[int], int, int]:
107
- """Transmit one APDU and return ``(data, SW1, SW2)``.
108
-
109
- Raises
110
- ------
111
- APDUError
112
- If the card returns an unexpected status word (i.e. not 0x90,
113
- 0x61, or 0x6C).
114
- """
115
- response, sw1, sw2 = self._cnx.transmit(apdu)
116
- logger.debug("APDU %s → SW=%02X%02X data(%d)=%s",
117
- [f"{b:02X}" for b in apdu], sw1, sw2, len(response),
118
- [f"{b:02X}" for b in response[:8]])
119
- if sw1 not in (_SW_OK, _SW_MORE_DATA, _SW_WRONG_LE):
120
- raise APDUError(sw1, sw2,
121
- f"Unexpected status SW={sw1:02X}{sw2:02X} "
122
- f"for APDU {[hex(b) for b in apdu[:4]]}")
123
- return response, sw1, sw2
124
-
125
- # ── File access helpers ───────────────────────────────────────────────
126
-
127
- def _select_file(self, file_id: list[int]) -> None:
128
- """Send a SELECT command for *file_id* (no response expected)."""
129
- cmd = [0x00, 0xA4, 0x08, 0x0C, len(file_id)] + file_id
130
- _, sw1, sw2 = self._send_apdu(cmd)
131
- if sw1 != _SW_OK:
132
- raise APDUError(sw1, sw2, f"SELECT failed for file {[hex(b) for b in file_id]}")
133
- logger.debug("Selected file %s", [f"{b:02X}" for b in file_id])
134
-
135
- def _read_binary(self, p1: int, p2: int, le: int) -> tuple[list[int], int, int]:
136
- """Send a READ BINARY command and handle Le mismatch (0x6C)."""
137
- cmd = [0x00, 0xB0, p1, p2, le]
138
- data, sw1, sw2 = self._send_apdu(cmd)
139
- if sw1 == _SW_WRONG_LE:
140
- # Card tells us the exact length: re-issue with SW2 as Le.
141
- logger.debug("RE-READ BINARY with Le=%d (was %d)", sw2, le)
142
- cmd[-1] = sw2
143
- data, sw1, sw2 = self._send_apdu(cmd)
144
- return data, sw1, sw2
145
-
146
- def _read_data(self, file_id: list[int]) -> list[int]:
147
- """Select *file_id* and read its content (up to 256 bytes)."""
148
- self._select_file(file_id)
149
- data, sw1, sw2 = self._read_binary(0x00, 0x00, _LE_MAX)
150
- logger.debug("Read %d bytes from file %s, SW=%02X%02X",
151
- len(data), [f"{b:02X}" for b in file_id], sw1, sw2)
152
- return data
153
-
154
- def _read_photo(self) -> bytearray:
155
- """Read the complete photo file in 256-byte chunks.
156
-
157
- The photo file is typically larger than 256 bytes so it must be
158
- read with successive READ BINARY commands using an incrementing
159
- offset (P1 = high byte, P2 = low byte of a 15-bit offset).
160
- """
161
- self._select_file(_FILE_PHOTO)
162
- photo_bytes: list[int] = []
163
- # Offset advances by 256 bytes on each iteration.
164
- # P1 holds the high byte of the byte offset (offset >> 8),
165
- # P2 holds the low byte (offset & 0xFF).
166
- # Starting with P1=0, P2=0 and incrementing P1 by 1 each time
167
- # moves the window by 256 bytes per step.
168
- p1 = 0
169
- while True:
170
- data, sw1, sw2 = self._read_binary(p1, 0x00, _LE_MAX)
171
- if sw1 == _SW_OK:
172
- photo_bytes.extend(data)
173
- if len(data) < 256:
174
- # Received fewer bytes than requested → end of file.
175
- break
176
- p1 += 1
177
- elif sw1 == _SW_WRONG_LE:
178
- # _read_binary already retried with the correct Le,
179
- # so if we still get here something went wrong.
180
- logger.warning("Unexpected 0x6C after retry at p1=%d", p1)
181
- photo_bytes.extend(data)
182
- break
183
- else:
184
- # Any other status (e.g. 0x6282 end-of-file) ends the loop.
185
- logger.debug("Photo read ended at p1=%d, SW=%02X%02X", p1, sw1, sw2)
186
- break
187
- logger.debug("Photo: %d bytes total", len(photo_bytes))
188
- return bytearray(photo_bytes)
189
-
190
- # ── Public API ────────────────────────────────────────────────────────
191
-
192
- def read_informations(self, photo: bool = False) -> dict[str, Any]:
193
- """Read and return all information from the card.
194
-
195
- Parameters
196
- ----------
197
- photo:
198
- When ``True`` the card photo is read and included in the
199
- returned dictionary as a base-64 encoded string.
200
-
201
- Returns
202
- -------
203
- dict
204
- Keys: ``card_number``, ``validity_start``, ``validity_end``,
205
- ``issuing_municipality``, ``national_number``, ``last_name``,
206
- ``first_names``, ``suffix``, ``nationality``, ``birth_place``,
207
- ``birth_date``, ``sex``, ``address``, ``postal_code``,
208
- ``city``, and optionally ``photo``.
209
- """
210
- # ── Identity file ────────────────────────────────────────────────
211
- id_data = self._read_data(_FILE_ID)
212
- id_fields = parse_tlv(id_data, 13) # tags 1–13 (tag 2 / index 1 unused)
213
-
214
- informations: dict[str, Any] = {
215
- "card_number": id_fields[0],
216
- # id_fields[1] is the chip serial number — not exposed in the API
217
- "validity_start": datetime.strptime(id_fields[2], "%d.%m.%Y"),
218
- "validity_end": datetime.strptime(id_fields[3], "%d.%m.%Y"),
219
- "issuing_municipality": id_fields[4],
220
- "national_number": id_fields[5],
221
- "last_name": id_fields[6],
222
- "first_names": id_fields[7],
223
- "suffix": id_fields[8],
224
- "nationality": id_fields[9],
225
- "birth_place": id_fields[10],
226
- "birth_date": parse_french_date(id_fields[11]),
227
- "sex": id_fields[12],
228
- }
229
-
230
- # ── Address file ─────────────────────────────────────────────────
231
- addr_data = self._read_data(_FILE_ADDRESS)
232
- addr_fields = parse_tlv(addr_data, 3)
233
-
234
- informations["address"] = addr_fields[0]
235
- informations["postal_code"] = addr_fields[1]
236
- informations["city"] = addr_fields[2]
237
-
238
- # ── Photo (optional) ─────────────────────────────────────────────
239
- if photo:
240
- photo_bytes = self._read_photo()
241
- informations["photo"] = base64.b64encode(photo_bytes).decode("ascii")
242
-
243
- # Mirror every key as an instance attribute for convenience.
244
- for key, value in informations.items():
245
- setattr(self, key, value)
246
-
247
- return informations
248
-
249
-
250
- if __name__ == "__main__":
251
- import logging
252
- from pprint import pprint
253
-
254
- logging.basicConfig(level=logging.WARNING)
255
- with CardReader() as cr:
256
- pprint(cr.read_informations(photo=False))
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
+ """
18
+
19
+ from __future__ import annotations
20
+
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"]
72
+
73
+ logger = logging.getLogger(__name__)
74
+
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
82
+
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
+ }
97
+
98
+
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
106
+
107
+
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
+
122
+
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
126
+
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
139
+
140
+
141
+ def list_readers() -> list[str]:
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`.
146
+
147
+ Raises:
148
+ PCSCServiceError: If the PC/SC service cannot be reached.
149
+ """
150
+ return [str(reader) for reader in _list_pcsc_readers()]
151
+
152
+
153
+ class _TransactionalConnection(CardConnectionDecorator): # type: ignore[misc]
154
+ """pyscard connection able to hold PC/SC transactions.
155
+
156
+ Unlike pyscard's ``ExclusiveTransmitCardConnection``, failures keep the
157
+ PC/SC return code in ``hresult``, which is needed to detect a card reset.
158
+ """
159
+
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
167
+
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)
174
+
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)
181
+
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)
214
+ """
215
+
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,
229
+ )
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)
359
+ try:
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
366
+
367
+ # ── Context manager and properties ───────────────────────────────────
368
+
369
+ def __enter__(self) -> Self:
370
+ return self
371
+
372
+ def __exit__(
373
+ self,
374
+ exc_type: type[BaseException] | None,
375
+ exc: BaseException | None,
376
+ traceback: TracebackType | None,
377
+ ) -> None:
378
+ self.close()
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
+
384
+ def close(self) -> None:
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
392
+ try:
393
+ connection.disconnect()
394
+ except (BaseSCardException, SmartcardException) as exc:
395
+ logger.debug("Ignoring error while disconnecting: %s", exc)
396
+ else:
397
+ logger.debug("Disconnected from card")
398
+
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 ───────────────────────────────────────────────────────
587
+
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.
597
+
598
+ Raises:
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.
602
+ """
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.
621
+ """
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)]
627
+
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
632
+
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.
647
+
648
+ Args:
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).
654
+
655
+ Returns:
656
+ The decoded content, with the raw files in :attr:`EidData.files`.
657
+ """
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.
687
+
688
+ Args:
689
+ nonce: Data to sign (the official viewer uses 48 random bytes).
690
+
691
+ Returns:
692
+ The raw ECDSA signature (``r || s``).
693
+
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.
712
+
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.
719
+
720
+ Returns:
721
+ Whether the key matches its digest and the chip signature is
722
+ valid.
723
+
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.
768
+
769
+ Returns:
770
+ The outcome of every check.
771
+
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
777
+
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