| 1 |
# Copyright 2021-2024 Nitrokey Developers |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or |
| 4 |
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or |
| 5 |
# http://opensource.org/licenses/MIT>, at your option. This file may not be |
| 6 |
# copied, modified, or distributed except according to those terms. |
| 7 |
|
| 8 |
import enum |
| 9 |
import logging |
| 10 |
import platform |
| 11 |
import sys |
| 12 |
from abc import abstractmethod |
| 13 |
from enum import Enum |
| 14 |
from typing import List, Optional, Sequence, TypeVar, Union |
| 15 |
|
| 16 |
from fido2.hid import CtapHidDevice, list_descriptors, open_device |
| 17 |
|
| 18 |
from nitrokey._smartcard import ExclusiveConnectCardConnection, ExclusiveTransmitCardConnection |
| 19 |
|
| 20 |
from ._base import TrussedBase |
| 21 |
from ._utils import Fido2Certs, Iso7816Apdu, Uuid |
| 22 |
|
| 23 |
T = TypeVar("T", bound="TrussedDevice") |
| 24 |
|
| 25 |
logger = logging.getLogger(__name__) |
| 26 |
|
| 27 |
|
| 28 |
class PcscError(Exception): |
| 29 |
def __init__(self, sw1: int, sw2: int) -> None: |
| 30 |
self.sw1 = sw1 |
| 31 |
self.sw2 = sw2 |
| 32 |
super().__init__(f"Got error code {bytes([sw1, sw2]).hex()}") |
| 33 |
|
| 34 |
|
| 35 |
@enum.unique |
| 36 |
class App(Enum): |
| 37 |
"""Vendor-specific CTAPHID commands for Trussed apps.""" |
| 38 |
|
| 39 |
SECRETS = 0x70 |
| 40 |
PROVISIONER = 0x71 |
| 41 |
ADMIN = 0x72 |
| 42 |
|
| 43 |
def aid(self) -> bytes: |
| 44 |
if self == App.SECRETS: |
| 45 |
return bytes.fromhex("A000000527 2101") |
| 46 |
elif self == App.ADMIN: |
| 47 |
return bytes.fromhex("A00000084700000001") |
| 48 |
elif self == App.PROVISIONER: |
| 49 |
return bytes.fromhex("A00000084700000001") |
| 50 |
else: |
| 51 |
# TODO: use typing.assert_never |
| 52 |
raise ValueError(self) |
| 53 |
|
| 54 |
|
| 55 |
class TrussedDevice(TrussedBase): |
| 56 |
def __init__( |
| 57 |
self, |
| 58 |
device: CtapHidDevice | ExclusiveTransmitCardConnection | ExclusiveConnectCardConnection, |
| 59 |
fido2_certs: Sequence[Fido2Certs], |
| 60 |
) -> None: |
| 61 |
self._path = None |
| 62 |
if isinstance(device, CtapHidDevice): |
| 63 |
self._validate_vid_pid(device.descriptor.vid, device.descriptor.pid) |
| 64 |
self._path = _device_path_to_str(device.descriptor.path) |
| 65 |
self._logger = logger.getChild(self._path) |
| 66 |
else: |
| 67 |
self._logger = logger.getChild(str(device.getReader())) |
| 68 |
|
| 69 |
self.device = device |
| 70 |
self.fido2_certs = fido2_certs |
| 71 |
|
| 72 |
from .admin_app import AdminApp |
| 73 |
|
| 74 |
self.admin = AdminApp(self) |
| 75 |
self.admin.status() |
| 76 |
|
| 77 |
@property |
| 78 |
def path(self) -> Optional[str]: |
| 79 |
return self._path |
| 80 |
|
| 81 |
def close(self) -> None: |
| 82 |
if isinstance(self.device, CtapHidDevice): |
| 83 |
self.device.close() |
| 84 |
else: |
| 85 |
self.device.disconnect() |
| 86 |
self.device.release() |
| 87 |
|
| 88 |
def reboot(self) -> bool: |
| 89 |
from .admin_app import BootMode |
| 90 |
|
| 91 |
return self.admin.reboot(BootMode.FIRMWARE) |
| 92 |
|
| 93 |
def uuid(self) -> Optional[Uuid]: |
| 94 |
return self.admin.uuid() |
| 95 |
|
| 96 |
def wink(self) -> None: |
| 97 |
if isinstance(self.device, CtapHidDevice): |
| 98 |
self.device.wink() |
| 99 |
|
| 100 |
def _call_admin_legacy( |
| 101 |
self, command: int, command_name: str, response_len: Optional[int] = None, data: bytes = b"" |
| 102 |
) -> bytes: |
| 103 |
response: bytes = bytes() |
| 104 |
if isinstance(self.device, CtapHidDevice): |
| 105 |
response = self.device.call(command, data=data) |
| 106 |
else: |
| 107 |
response = self._call_admin_ccid_legacy(command, data) |
| 108 |
|
| 109 |
if response_len is not None and response_len != len(response): |
| 110 |
raise ValueError( |
| 111 |
f"The response for the CTAPHID {command_name} command has an unexpected length " |
| 112 |
f"(expected: {response_len}, actual: {len(response)})" |
| 113 |
) |
| 114 |
return response |
| 115 |
|
| 116 |
def _call_admin_ccid_legacy( |
| 117 |
self, command: int, data: bytes, response_len: Optional[int] = None |
| 118 |
) -> bytes: |
| 119 |
assert not isinstance(self.device, CtapHidDevice) |
| 120 |
app = App.ADMIN |
| 121 |
select = bytes([0x00, 0xA4, 0x04, 0x00, len(app.aid())]) + app.aid() |
| 122 |
_, sw1, sw2 = self.device.transmit(list(select)) |
| 123 |
while True: |
| 124 |
if sw1 == 0x61: |
| 125 |
_, sw1, sw2 = self.device.transmit( |
| 126 |
list(Iso7816Apdu(0x00, 0xC0, 0, 0, None, sw2).to_bytes()) |
| 127 |
) |
| 128 |
continue |
| 129 |
break |
| 130 |
if sw1 != 0x90 or sw2 != 0x00: |
| 131 |
raise PcscError(sw1, sw2) |
| 132 |
p1 = 0 |
| 133 |
if len(data) >= 1: |
| 134 |
p1 = data[0] |
| 135 |
apdu = Iso7816Apdu(0x00, command, 0, p1, data, le=response_len) |
| 136 |
data, sw1, sw2 = self.device.transmit(list(apdu.to_bytes())) |
| 137 |
accumulator = bytes(data) |
| 138 |
while True: |
| 139 |
if sw1 == 0x61: |
| 140 |
data, sw1, sw2 = self.device.transmit( |
| 141 |
list(Iso7816Apdu(0x00, 0xC0, 0, 0, None, sw2).to_bytes()) |
| 142 |
) |
| 143 |
accumulator += bytes(data) |
| 144 |
continue |
| 145 |
break |
| 146 |
if sw1 != 0x90 or sw2 != 0x00: |
| 147 |
raise PcscError(sw1, sw2) |
| 148 |
|
| 149 |
return accumulator |
| 150 |
|
| 151 |
def _call_ccid(self, app: App, response_len: Optional[int] = None, data: bytes = b"") -> bytes: |
| 152 |
assert not isinstance(self.device, CtapHidDevice) |
| 153 |
select = bytes([0x00, 0xA4, 0x04, 0x00, len(app.aid())]) + app.aid() |
| 154 |
tmpbytes, sw1, sw2 = self.device.transmit(list(select)) |
| 155 |
while True: |
| 156 |
if sw1 == 0x61: |
| 157 |
_, sw1, sw2 = self.device.transmit( |
| 158 |
list(Iso7816Apdu(0x00, 0xC0, 0, 0, None, sw2).to_bytes()) |
| 159 |
) |
| 160 |
continue |
| 161 |
break |
| 162 |
if sw1 != 0x90 or sw2 != 0x00: |
| 163 |
raise PcscError(sw1, sw2) |
| 164 |
|
| 165 |
command = None |
| 166 |
if app == App.ADMIN or app == App.PROVISIONER: |
| 167 |
command = list(Iso7816Apdu(0x00, data[0], 0, 0, data[1:], le=response_len).to_bytes()) |
| 168 |
elif app == App.SECRETS: |
| 169 |
command = list(data) |
| 170 |
|
| 171 |
data, sw1, sw2 = self.device.transmit(command) |
| 172 |
accumulator = bytes(data) |
| 173 |
while True: |
| 174 |
if sw1 == 0x61: |
| 175 |
data, sw1, sw2 = self.device.transmit( |
| 176 |
list(Iso7816Apdu(0x00, 0xC0, 0, 0, None, sw2).to_bytes()) |
| 177 |
) |
| 178 |
accumulator += bytes(data) |
| 179 |
continue |
| 180 |
break |
| 181 |
|
| 182 |
if app == App.SECRETS: |
| 183 |
accumulator = bytes([sw1, sw2]) + accumulator |
| 184 |
# Let the secret app handle the error |
| 185 |
return accumulator |
| 186 |
|
| 187 |
if sw1 != 0x90 or sw2 != 0x00: |
| 188 |
raise PcscError(sw1, sw2) |
| 189 |
|
| 190 |
return accumulator |
| 191 |
|
| 192 |
def _call_app(self, app: App, response_len: Optional[int] = None, data: bytes = b"") -> bytes: |
| 193 |
response: bytes = bytes() |
| 194 |
if isinstance(self.device, CtapHidDevice): |
| 195 |
response = self.device.call(app.value, data=data) |
| 196 |
else: |
| 197 |
response = self._call_ccid(app, response_len, data) |
| 198 |
|
| 199 |
if response_len is not None and response_len != len(response): |
| 200 |
raise ValueError( |
| 201 |
f"The response for the CTAPHID {app.name} command has an unexpected length " |
| 202 |
f"(expected: {response_len}, actual: {len(response)})" |
| 203 |
) |
| 204 |
return response |
| 205 |
|
| 206 |
@classmethod |
| 207 |
@abstractmethod |
| 208 |
def from_device( |
| 209 |
cls: type[T], |
| 210 |
device: CtapHidDevice | ExclusiveTransmitCardConnection | ExclusiveConnectCardConnection, |
| 211 |
) -> T: ... |
| 212 |
|
| 213 |
@classmethod |
| 214 |
def open(cls: type[T], path: str) -> Optional[T]: |
| 215 |
try: |
| 216 |
if platform.system() == "Windows": |
| 217 |
device = open_device(bytes(path, "utf-8")) |
| 218 |
else: |
| 219 |
device = open_device(path) |
| 220 |
except Exception: |
| 221 |
logger.warning(f"No CTAPHID device at path {path}", exc_info=sys.exc_info()) |
| 222 |
return None |
| 223 |
try: |
| 224 |
return cls.from_device(device) |
| 225 |
except ValueError: |
| 226 |
logger.warning(f"No Nitrokey device at path {path}", exc_info=sys.exc_info()) |
| 227 |
return None |
| 228 |
|
| 229 |
@classmethod |
| 230 |
@abstractmethod |
| 231 |
def list_ccid(cls: type[T]) -> List[T]: ... |
| 232 |
|
| 233 |
@classmethod |
| 234 |
@abstractmethod |
| 235 |
def list_ctaphid(cls: type[T]) -> List[T]: ... |
| 236 |
|
| 237 |
@classmethod |
| 238 |
def _list_vid_pid(cls: type[T], vid: int, pid: int) -> List[T]: |
| 239 |
descriptors = [ |
| 240 |
desc |
| 241 |
for desc in list_descriptors() # type: ignore |
| 242 |
if desc.vid == vid and desc.pid == pid |
| 243 |
] |
| 244 |
return [cls.from_device(open_device(desc.path)) for desc in descriptors] |
| 245 |
|
| 246 |
@classmethod |
| 247 |
def _list_pcsc_atr(cls: type[T], atr: List[int], exclusive: bool) -> List[T]: |
| 248 |
try: |
| 249 |
from smartcard.Exceptions import CardConnectionException, NoCardException |
| 250 |
from smartcard.ExclusiveTransmitCardConnection import ExclusiveTransmitCardConnection |
| 251 |
from smartcard.System import readers |
| 252 |
|
| 253 |
devices = [] |
| 254 |
for r in readers(): |
| 255 |
raw_connection = r.createConnection() |
| 256 |
connection: Union[ExclusiveConnectCardConnection, ExclusiveTransmitCardConnection] |
| 257 |
if exclusive: |
| 258 |
connection = ExclusiveConnectCardConnection(raw_connection) |
| 259 |
else: |
| 260 |
connection = ExclusiveTransmitCardConnection(raw_connection) |
| 261 |
|
| 262 |
try: |
| 263 |
connection.connect() |
| 264 |
except NoCardException: |
| 265 |
continue |
| 266 |
except CardConnectionException: |
| 267 |
continue |
| 268 |
if atr != connection.getATR(): |
| 269 |
connection.disconnect() |
| 270 |
connection.release() |
| 271 |
continue |
| 272 |
devices.append(cls.from_device(connection)) |
| 273 |
|
| 274 |
return devices |
| 275 |
except ImportError: |
| 276 |
return [] |
| 277 |
|
| 278 |
|
| 279 |
def _device_path_to_str(path: Union[bytes, str]) -> str: |
| 280 |
""" |
| 281 |
Converts a device path as returned by the fido2 library to a string. |
| 282 |
|
| 283 |
Typically, the path already is a string. Only on Windows, a bytes object |
| 284 |
using an ANSI encoding is used instead. We use the ISO 8859-1 encoding to |
| 285 |
decode the string which should work for all systems. |
| 286 |
""" |
| 287 |
if isinstance(path, bytes): |
| 288 |
return path.decode("iso-8859-1", errors="ignore") |
| 289 |
else: |
| 290 |
return path |