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/__init__.py +77 -6
- pythonbeid/__main__.py +3 -0
- pythonbeid/card_reader.py +846 -256
- pythonbeid/cli.py +176 -0
- pythonbeid/exceptions.py +73 -30
- pythonbeid/integrity.py +455 -0
- pythonbeid/models.py +593 -0
- pythonbeid/parser.py +472 -89
- pythonbeid/py.typed +0 -0
- pythonbeid/trust/belgium_root_ca2.pem +22 -0
- pythonbeid/trust/belgium_root_ca3.pem +32 -0
- pythonbeid/trust/belgium_root_ca4.pem +32 -0
- pythonbeid/trust/belgium_root_ca6.pem +21 -0
- pythonbeid-1.0.0.dist-info/METADATA +293 -0
- pythonbeid-1.0.0.dist-info/RECORD +19 -0
- {pythonbeid-0.2.0.dist-info → pythonbeid-1.0.0.dist-info}/WHEEL +1 -1
- pythonbeid-1.0.0.dist-info/entry_points.txt +2 -0
- {pythonbeid-0.2.0.dist-info → pythonbeid-1.0.0.dist-info}/licenses/LICENSE +21 -21
- pythonbeid-0.2.0.dist-info/METADATA +0 -104
- pythonbeid-0.2.0.dist-info/RECORD +0 -9
- {pythonbeid-0.2.0.dist-info → pythonbeid-1.0.0.dist-info}/top_level.txt +0 -0
pythonbeid/card_reader.py
CHANGED
|
@@ -1,256 +1,846 @@
|
|
|
1
|
-
"""Belgian eID
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
from
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
self.
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
#
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|