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/cli.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Command-line interface: ``pythonbeid`` or ``python -m pythonbeid``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .card_reader import CardReader, list_readers
|
|
15
|
+
from .exceptions import BeidError
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
|
|
20
|
+
__all__ = ["main"]
|
|
21
|
+
|
|
22
|
+
EXIT_OK = 0
|
|
23
|
+
EXIT_ERROR = 1
|
|
24
|
+
EXIT_INVALID = 3
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _reader_argument(value: str) -> int | str:
|
|
28
|
+
return int(value) if value.isdigit() else value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
32
|
+
parser = argparse.ArgumentParser(
|
|
33
|
+
prog="pythonbeid",
|
|
34
|
+
description="Read and verify Belgian eID cards through PC/SC.",
|
|
35
|
+
)
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--version", action="version", version=f"%(prog)s {__version__}"
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"-v",
|
|
41
|
+
"--verbose",
|
|
42
|
+
action="count",
|
|
43
|
+
default=0,
|
|
44
|
+
help="show progress (-v) or the APDU trace without card data (-vv)",
|
|
45
|
+
)
|
|
46
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
47
|
+
|
|
48
|
+
commands.add_parser("readers", help="list the connected readers")
|
|
49
|
+
|
|
50
|
+
card_options = argparse.ArgumentParser(add_help=False)
|
|
51
|
+
card_options.add_argument(
|
|
52
|
+
"-r",
|
|
53
|
+
"--reader",
|
|
54
|
+
type=_reader_argument,
|
|
55
|
+
help="reader index or name (default: first reader holding an eID card)",
|
|
56
|
+
)
|
|
57
|
+
card_options.add_argument(
|
|
58
|
+
"-t",
|
|
59
|
+
"--timeout",
|
|
60
|
+
type=float,
|
|
61
|
+
help="seconds to wait for a card to be inserted",
|
|
62
|
+
)
|
|
63
|
+
card_options.add_argument(
|
|
64
|
+
"--json", action="store_true", help="print JSON instead of text"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
commands.add_parser(
|
|
68
|
+
"info", parents=[card_options], help="show reader, ATR and chip information"
|
|
69
|
+
)
|
|
70
|
+
read = commands.add_parser(
|
|
71
|
+
"read", parents=[card_options], help="read identity and address"
|
|
72
|
+
)
|
|
73
|
+
read.add_argument(
|
|
74
|
+
"--photo", type=Path, metavar="FILE", help="also save the photo (JPEG)"
|
|
75
|
+
)
|
|
76
|
+
verify = commands.add_parser(
|
|
77
|
+
"verify",
|
|
78
|
+
parents=[card_options],
|
|
79
|
+
help="check signatures, certificates and chip (needs pythonbeid[verify])",
|
|
80
|
+
)
|
|
81
|
+
verify.add_argument(
|
|
82
|
+
"--no-chip",
|
|
83
|
+
action="store_true",
|
|
84
|
+
help="skip the chip challenge of applet 1.8 cards",
|
|
85
|
+
)
|
|
86
|
+
return parser
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _print_section(title: str, values: dict[str, Any]) -> None:
|
|
90
|
+
print(title)
|
|
91
|
+
width = max(len(key) for key in values)
|
|
92
|
+
for key, value in values.items():
|
|
93
|
+
if value in ("", None, []):
|
|
94
|
+
continue
|
|
95
|
+
print(f" {key.replace('_', ' '):<{width}} : {value}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _open(args: argparse.Namespace) -> CardReader:
|
|
99
|
+
return CardReader(args.reader, timeout=args.timeout)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _info(args: argparse.Namespace) -> int:
|
|
103
|
+
with _open(args) as reader:
|
|
104
|
+
data = {
|
|
105
|
+
"reader": reader.reader_name,
|
|
106
|
+
"atr": reader.atr.hex(" ").upper(),
|
|
107
|
+
**reader.card_info.to_dict(),
|
|
108
|
+
}
|
|
109
|
+
if args.json:
|
|
110
|
+
print(json.dumps(data, indent=2))
|
|
111
|
+
else:
|
|
112
|
+
_print_section("Card", data)
|
|
113
|
+
return EXIT_OK
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _read(args: argparse.Namespace) -> int:
|
|
117
|
+
with _open(args) as reader:
|
|
118
|
+
eid = reader.read(photo=args.photo is not None, integrity=False)
|
|
119
|
+
if args.photo is not None and eid.photo is not None:
|
|
120
|
+
args.photo.write_bytes(eid.photo)
|
|
121
|
+
if args.json:
|
|
122
|
+
# ASCII escapes keep the JSON lossless whatever the console encoding.
|
|
123
|
+
print(json.dumps(eid.to_dict(include_photo=False), indent=2))
|
|
124
|
+
else:
|
|
125
|
+
_print_section("Identity", eid.identity.to_dict())
|
|
126
|
+
_print_section("Address", eid.address.to_dict())
|
|
127
|
+
if args.photo is not None:
|
|
128
|
+
print(f"Photo saved to {args.photo}")
|
|
129
|
+
return EXIT_OK
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _verify(args: argparse.Namespace) -> int:
|
|
133
|
+
with _open(args) as reader:
|
|
134
|
+
report = reader.verify(authenticate_chip=not args.no_chip)
|
|
135
|
+
if args.json:
|
|
136
|
+
print(json.dumps(report.to_dict(), indent=2))
|
|
137
|
+
else:
|
|
138
|
+
checks = report.to_dict()
|
|
139
|
+
errors = checks.pop("errors")
|
|
140
|
+
valid = checks.pop("is_valid")
|
|
141
|
+
_print_section(
|
|
142
|
+
"Verification",
|
|
143
|
+
{key: _VERDICTS[value] for key, value in checks.items()},
|
|
144
|
+
)
|
|
145
|
+
for error in errors:
|
|
146
|
+
print(f" ! {error}")
|
|
147
|
+
print("Result: VALID" if valid else "Result: INVALID")
|
|
148
|
+
return EXIT_OK if report.is_valid else EXIT_INVALID
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
_VERDICTS = {True: "ok", False: "FAILED", None: "not applicable"}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _tolerate_console_encoding() -> None:
|
|
155
|
+
"""Avoid crashing on names a legacy console code page cannot encode."""
|
|
156
|
+
for stream in (sys.stdout, sys.stderr):
|
|
157
|
+
if isinstance(stream, io.TextIOWrapper):
|
|
158
|
+
stream.reconfigure(errors="replace")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
162
|
+
"""Run the command line and return the exit status."""
|
|
163
|
+
args = _build_parser().parse_args(argv)
|
|
164
|
+
_tolerate_console_encoding()
|
|
165
|
+
level = {0: logging.WARNING, 1: logging.INFO}.get(args.verbose, logging.DEBUG)
|
|
166
|
+
logging.basicConfig(level=level, format="%(levelname)s %(name)s: %(message)s")
|
|
167
|
+
try:
|
|
168
|
+
if args.command == "readers":
|
|
169
|
+
for index, name in enumerate(list_readers()):
|
|
170
|
+
print(f"{index}: {name}")
|
|
171
|
+
return EXIT_OK
|
|
172
|
+
handlers = {"info": _info, "read": _read, "verify": _verify}
|
|
173
|
+
return handlers[args.command](args)
|
|
174
|
+
except (BeidError, ImportError, OSError) as exc:
|
|
175
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
176
|
+
return EXIT_ERROR
|
pythonbeid/exceptions.py
CHANGED
|
@@ -1,30 +1,73 @@
|
|
|
1
|
-
"""
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
""
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
""
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
1
|
+
"""Exception hierarchy of pythonbeid.
|
|
2
|
+
|
|
3
|
+
Every exception raised by the library derives from :class:`BeidError`, so a
|
|
4
|
+
single ``except BeidError`` clause is enough to handle all library failures.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"APDUError",
|
|
11
|
+
"BeidError",
|
|
12
|
+
"CardCommunicationError",
|
|
13
|
+
"CardDataError",
|
|
14
|
+
"NoCardError",
|
|
15
|
+
"NoReaderError",
|
|
16
|
+
"PCSCServiceError",
|
|
17
|
+
"UnsupportedCardError",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class BeidError(RuntimeError):
|
|
22
|
+
"""Base class of all pythonbeid exceptions."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class NoReaderError(BeidError):
|
|
26
|
+
"""Raised when no usable smart card reader is available."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PCSCServiceError(NoReaderError):
|
|
30
|
+
"""Raised when the PC/SC service itself cannot be reached.
|
|
31
|
+
|
|
32
|
+
Typical causes: ``pcscd`` not running on Linux, or the *Smart Card*
|
|
33
|
+
service stopped on Windows.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class NoCardError(BeidError):
|
|
38
|
+
"""Raised when no card is present in the reader (or it was removed)."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class CardCommunicationError(BeidError):
|
|
42
|
+
"""Raised on a failure while talking to the card."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class APDUError(CardCommunicationError):
|
|
46
|
+
"""Raised when the card answers a command with an unexpected status word.
|
|
47
|
+
|
|
48
|
+
Attributes:
|
|
49
|
+
sw1: First status byte.
|
|
50
|
+
sw2: Second status byte.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, sw1: int, sw2: int, message: str = "") -> None:
|
|
54
|
+
self.sw1 = sw1
|
|
55
|
+
self.sw2 = sw2
|
|
56
|
+
super().__init__(message or f"Unexpected APDU status: SW={sw1:02X}{sw2:02X}")
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def sw(self) -> int:
|
|
60
|
+
"""Both status bytes combined into one integer (e.g. ``0x6A82``)."""
|
|
61
|
+
return (self.sw1 << 8) | self.sw2
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class UnsupportedCardError(CardCommunicationError):
|
|
65
|
+
"""Raised when the card does not support the requested operation.
|
|
66
|
+
|
|
67
|
+
For example, the basic-key chip authentication only exists on applet 1.8
|
|
68
|
+
cards.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class CardDataError(BeidError, ValueError):
|
|
73
|
+
"""Raised when data read from the card cannot be decoded."""
|