Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1 | # coding=utf-8 |
| 2 | """Representation of the ISO7816-4 filesystem model. |
| 3 | |
| 4 | The File (and its derived classes) represent the structure / hierarchy |
| 5 | of the ISO7816-4 smart card file system with the MF, DF, EF and ADF |
| 6 | entries, further sub-divided into the EF sub-types Transparent, Linear Fixed, etc. |
| 7 | |
| 8 | The classes are intended to represent the *specification* of the filesystem, |
| 9 | not the actual contents / runtime state of interacting with a given smart card. |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 10 | """ |
| 11 | |
Harald Welte | 5a4fd52 | 2021-04-02 16:05:26 +0200 | [diff] [blame] | 12 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 13 | # |
| 14 | # This program is free software: you can redistribute it and/or modify |
| 15 | # it under the terms of the GNU General Public License as published by |
| 16 | # the Free Software Foundation, either version 2 of the License, or |
| 17 | # (at your option) any later version. |
| 18 | # |
| 19 | # This program is distributed in the hope that it will be useful, |
| 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 | # GNU General Public License for more details. |
| 23 | # |
| 24 | # You should have received a copy of the GNU General Public License |
| 25 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 26 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 27 | import code |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 28 | import tempfile |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 29 | import json |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 30 | import abc |
| 31 | import inspect |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 32 | |
| 33 | import cmd2 |
| 34 | from cmd2 import CommandSet, with_default_category, with_argparser |
| 35 | import argparse |
| 36 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 37 | from typing import cast, Optional, Iterable, List, Dict, Tuple, Union |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 38 | |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 39 | from smartcard.util import toBytes |
| 40 | |
Harald Welte | daf2b39 | 2021-05-03 23:17:29 +0200 | [diff] [blame] | 41 | from pySim.utils import sw_match, h2b, b2h, i2h, is_hex, auto_int, bertlv_parse_one, Hexstr |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 42 | from pySim.construct import filter_dict, parse_construct |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 43 | from pySim.exceptions import * |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 44 | from pySim.jsonpath import js_path_find, js_path_modify |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 45 | from pySim.commands import SimCardCommands |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 46 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 47 | # int: a single service is associated with this file |
| 48 | # list: any of the listed services requires this file |
| 49 | # tuple: logical-and of the listed services requires this file |
| 50 | CardFileService = Union[int, List[int], Tuple[int, ...]] |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 51 | |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 52 | Size = Tuple[int, Optional[int]] |
| 53 | |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 54 | def lchan_nr_from_cla(cla: int) -> int: |
| 55 | """Resolve the logical channel number from the CLA byte.""" |
| 56 | # TS 102 221 10.1.1 Coding of Class Byte |
| 57 | if cla >> 4 in [0x0, 0xA, 0x8]: |
| 58 | # Table 10.3 |
| 59 | return cla & 0x03 |
| 60 | elif cla & 0xD0 in [0x40, 0xC0]: |
| 61 | # Table 10.4a |
| 62 | return 4 + (cla & 0x0F) |
| 63 | else: |
| 64 | raise ValueError('Could not determine logical channel for CLA=%2X' % cla) |
| 65 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 66 | class CardFile: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 67 | """Base class for all objects in the smart card filesystem. |
| 68 | Serve as a common ancestor to all other file types; rarely used directly. |
| 69 | """ |
| 70 | RESERVED_NAMES = ['..', '.', '/', 'MF'] |
| 71 | RESERVED_FIDS = ['3f00'] |
| 72 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 73 | def __init__(self, fid: str = None, sfid: str = None, name: str = None, desc: str = None, |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 74 | parent: Optional['CardDF'] = None, profile: Optional['CardProfile'] = None, |
| 75 | service: Optional[CardFileService] = None): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 76 | """ |
| 77 | Args: |
| 78 | fid : File Identifier (4 hex digits) |
| 79 | sfid : Short File Identifier (2 hex digits, optional) |
| 80 | name : Brief name of the file, lik EF_ICCID |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 81 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 82 | parent : Parent CardFile object within filesystem hierarchy |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 83 | profile : Card profile that this file should be part of |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 84 | service : Service (SST/UST/IST) associated with the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 85 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 86 | if not isinstance(self, CardADF) and fid == None: |
| 87 | raise ValueError("fid is mandatory") |
| 88 | if fid: |
| 89 | fid = fid.lower() |
| 90 | self.fid = fid # file identifier |
| 91 | self.sfid = sfid # short file identifier |
| 92 | self.name = name # human readable name |
| 93 | self.desc = desc # human readable description |
| 94 | self.parent = parent |
| 95 | if self.parent and self.parent != self and self.fid: |
| 96 | self.parent.add_file(self) |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 97 | self.profile = profile |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 98 | self.service = service |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 99 | self.shell_commands = [] # type: List[CommandSet] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 100 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 101 | # Note: the basic properties (fid, name, ect.) are verified when |
| 102 | # the file is attached to a parent file. See method add_file() in |
| 103 | # class Card DF |
Philipp Maier | 6606158 | 2021-03-09 21:57:57 +0100 | [diff] [blame] | 104 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 105 | def __str__(self): |
| 106 | if self.name: |
| 107 | return self.name |
| 108 | else: |
| 109 | return self.fid |
| 110 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 111 | def _path_element(self, prefer_name: bool) -> Optional[str]: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 112 | if prefer_name and self.name: |
| 113 | return self.name |
| 114 | else: |
| 115 | return self.fid |
| 116 | |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 117 | def fully_qualified_path_str(self, prefer_name: bool = True) -> str: |
| 118 | """Return fully qualified path to file as string. |
| 119 | |
| 120 | Args: |
| 121 | prefer_name : Preferably build path of names; fall-back to FIDs as required |
| 122 | """ |
| 123 | return '/'.join(self.fully_qualified_path(prefer_name)) |
| 124 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 125 | def fully_qualified_path(self, prefer_name: bool = True) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 126 | """Return fully qualified path to file as list of FID or name strings. |
| 127 | |
| 128 | Args: |
| 129 | prefer_name : Preferably build path of names; fall-back to FIDs as required |
| 130 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 131 | if self.parent and self.parent != self: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 132 | ret = self.parent.fully_qualified_path(prefer_name) |
| 133 | else: |
| 134 | ret = [] |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 135 | elem = self._path_element(prefer_name) |
| 136 | if elem: |
| 137 | ret.append(elem) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 138 | return ret |
| 139 | |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 140 | def fully_qualified_path_fobj(self) -> List['CardFile']: |
| 141 | """Return fully qualified path to file as list of CardFile instance references.""" |
| 142 | if self.parent and self.parent != self: |
| 143 | ret = self.parent.fully_qualified_path_fobj() |
| 144 | else: |
| 145 | ret = [] |
| 146 | if self: |
| 147 | ret.append(self) |
| 148 | return ret |
| 149 | |
| 150 | def build_select_path_to(self, target: 'CardFile') -> Optional[List['CardFile']]: |
| 151 | """Build the relative sequence of files we need to traverse to get from us to 'target'.""" |
| 152 | cur_fqpath = self.fully_qualified_path_fobj() |
| 153 | target_fqpath = target.fully_qualified_path_fobj() |
| 154 | inter_path = [] |
| 155 | cur_fqpath.pop() # drop last element (currently selected file, doesn't need re-selection |
| 156 | cur_fqpath.reverse() |
| 157 | for ce in cur_fqpath: |
| 158 | inter_path.append(ce) |
| 159 | for i in range(0, len(target_fqpath)-1): |
| 160 | te = target_fqpath[i] |
| 161 | if te == ce: |
| 162 | for te2 in target_fqpath[i+1:]: |
| 163 | inter_path.append(te2) |
| 164 | # we found our common ancestor |
| 165 | return inter_path |
| 166 | return None |
| 167 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 168 | def get_mf(self) -> Optional['CardMF']: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 169 | """Return the MF (root) of the file system.""" |
| 170 | if self.parent == None: |
| 171 | return None |
| 172 | # iterate towards the top. MF has parent == self |
| 173 | node = self |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 174 | while node.parent and node.parent != node: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 175 | node = node.parent |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 176 | return cast(CardMF, node) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 177 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 178 | def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 179 | """Return a dict of {'identifier': self} tuples. |
| 180 | |
| 181 | Args: |
| 182 | alias : Add an alias with given name to 'self' |
| 183 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 184 | If not specified, all selectables will be returned. |
| 185 | Returns: |
| 186 | dict containing reference to 'self' for all identifiers. |
| 187 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 188 | sels = {} |
| 189 | if alias: |
| 190 | sels.update({alias: self}) |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 191 | if self.fid and (flags == [] or 'FIDS' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 192 | sels.update({self.fid: self}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 193 | if self.name and (flags == [] or 'FNAMES' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 194 | sels.update({self.name: self}) |
| 195 | return sels |
| 196 | |
Harald Welte | f5ff1b8 | 2022-07-24 12:19:57 +0200 | [diff] [blame] | 197 | def _get_parent_selectables(self, alias: Optional[str] = None, flags=[]) -> Dict[str, 'CardFile']: |
| 198 | sels = {} |
| 199 | if not self.parent or self.parent == self: |
| 200 | return sels |
| 201 | # add our immediate parent |
| 202 | if alias: |
| 203 | sels.update({alias: self.parent}) |
| 204 | if self.parent.fid and (flags == [] or 'FIDS' in flags): |
| 205 | sels.update({self.parent.fid: self.parent}) |
| 206 | if self.parent.name and (flags == [] or 'FNAMES' in flags): |
| 207 | sels.update({self.parent.name: self.parent}) |
| 208 | # recurse to parents of our parent, but without any alias |
| 209 | sels.update(self.parent._get_parent_selectables(None, flags)) |
| 210 | return sels |
| 211 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 212 | def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 213 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 214 | |
| 215 | Args: |
| 216 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 217 | If not specified, all selectables will be returned. |
| 218 | Returns: |
| 219 | dict containing all selectable items. Key is identifier (string), value |
| 220 | a reference to a CardFile (or derived class) instance. |
| 221 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 222 | sels = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 223 | # we can always select ourself |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 224 | if flags == [] or 'SELF' in flags: |
| 225 | sels = self._get_self_selectables('.', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 226 | # we can always select our parent |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 227 | if flags == [] or 'PARENT' in flags: |
Harald Welte | f5ff1b8 | 2022-07-24 12:19:57 +0200 | [diff] [blame] | 228 | sels.update(self._get_parent_selectables('..', flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 229 | # if we have a MF, we can always select its applications |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 230 | if flags == [] or 'MF' in flags: |
| 231 | mf = self.get_mf() |
| 232 | if mf: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 233 | sels.update(mf._get_self_selectables(flags=flags)) |
| 234 | sels.update(mf.get_app_selectables(flags=flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 235 | return sels |
| 236 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 237 | def get_selectable_names(self, flags=[]) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 238 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 239 | |
| 240 | Args: |
| 241 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 242 | If not specified, all selectables will be returned. |
| 243 | Returns: |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 244 | list containing all selectable names. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 245 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 246 | sels = self.get_selectables(flags) |
Harald Welte | b3d68c0 | 2022-01-21 15:31:29 +0100 | [diff] [blame] | 247 | sel_keys = list(sels.keys()) |
| 248 | sel_keys.sort() |
| 249 | return sel_keys |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 250 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 251 | def decode_select_response(self, data_hex: str): |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 252 | """Decode the response to a SELECT command. |
| 253 | |
| 254 | Args: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 255 | data_hex: Hex string of the select response |
| 256 | """ |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 257 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 258 | # When the current file does not implement a custom select response decoder, |
| 259 | # we just ask the parent file to decode the select response. If this method |
| 260 | # is not overloaded by the current file we will again ask the parent file. |
| 261 | # This way we recursively travel up the file system tree until we hit a file |
| 262 | # that does implement a concrete decoder. |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 263 | if self.parent: |
| 264 | return self.parent.decode_select_response(data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 265 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 266 | def get_profile(self): |
| 267 | """Get the profile associated with this file. If this file does not have any |
| 268 | profile assigned, try to find a file above (usually the MF) in the filesystem |
| 269 | hirarchy that has a profile assigned |
| 270 | """ |
| 271 | |
| 272 | # If we have a profile set, return it |
| 273 | if self.profile: |
| 274 | return self.profile |
| 275 | |
| 276 | # Walk up recursively until we hit a parent that has a profile set |
| 277 | if self.parent: |
| 278 | return self.parent.get_profile() |
| 279 | return None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 280 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 281 | def should_exist_for_services(self, services: List[int]): |
| 282 | """Assuming the provided list of activated services, should this file exist and be activated?.""" |
| 283 | if self.service is None: |
| 284 | return None |
| 285 | elif isinstance(self.service, int): |
| 286 | # a single service determines the result |
| 287 | return self.service in services |
| 288 | elif isinstance(self.service, list): |
| 289 | # any of the services active -> true |
| 290 | for s in self.service: |
| 291 | if s in services: |
| 292 | return True |
| 293 | return False |
| 294 | elif isinstance(self.service, tuple): |
| 295 | # all of the services active -> true |
| 296 | for s in self.service: |
| 297 | if not s in services: |
| 298 | return False |
| 299 | return True |
| 300 | else: |
| 301 | raise ValueError("self.service must be either int or list or tuple") |
| 302 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 303 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 304 | class CardDF(CardFile): |
| 305 | """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories.""" |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 306 | |
| 307 | @with_default_category('DF/ADF Commands') |
| 308 | class ShellCommands(CommandSet): |
| 309 | def __init__(self): |
| 310 | super().__init__() |
| 311 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 312 | def __init__(self, **kwargs): |
| 313 | if not isinstance(self, CardADF): |
| 314 | if not 'fid' in kwargs: |
| 315 | raise TypeError('fid is mandatory for all DF') |
| 316 | super().__init__(**kwargs) |
| 317 | self.children = dict() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 318 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 319 | # dict of CardFile affected by service(int), indexed by service |
| 320 | self.files_by_service = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 321 | |
| 322 | def __str__(self): |
| 323 | return "DF(%s)" % (super().__str__()) |
| 324 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 325 | def _add_file_services(self, child): |
| 326 | """Add a child (DF/EF) to the files_by_services of the parent.""" |
| 327 | if not child.service: |
| 328 | return |
| 329 | if isinstance(child.service, int): |
| 330 | self.files_by_service.setdefault(child.service, []).append(child) |
| 331 | elif isinstance(child.service, list): |
| 332 | for service in child.service: |
| 333 | self.files_by_service.setdefault(service, []).append(child) |
| 334 | elif isinstance(child.service, tuple): |
| 335 | for service in child.service: |
| 336 | self.files_by_service.setdefault(service, []).append(child) |
| 337 | else: |
| 338 | raise ValueError |
| 339 | |
Harald Welte | d56f45d | 2022-07-16 11:46:59 +0200 | [diff] [blame] | 340 | def _has_service(self): |
| 341 | if self.service: |
| 342 | return True |
| 343 | for c in self.children.values(): |
| 344 | if isinstance(c, CardDF): |
| 345 | if c._has_service(): |
| 346 | return True |
| 347 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 348 | def add_file(self, child: CardFile, ignore_existing: bool = False): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 349 | """Add a child (DF/EF) to this DF. |
| 350 | Args: |
| 351 | child: The new DF/EF to be added |
| 352 | ignore_existing: Ignore, if file with given FID already exists. Old one will be kept. |
| 353 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 354 | if not isinstance(child, CardFile): |
| 355 | raise TypeError("Expected a File instance") |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 356 | if not is_hex(child.fid, minlen=4, maxlen=4): |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 357 | raise ValueError("File name %s is not a valid fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 358 | if child.name in CardFile.RESERVED_NAMES: |
| 359 | raise ValueError("File name %s is a reserved name" % (child.name)) |
| 360 | if child.fid in CardFile.RESERVED_FIDS: |
Philipp Maier | e8bc1b4 | 2021-03-09 20:33:41 +0100 | [diff] [blame] | 361 | raise ValueError("File fid %s is a reserved fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 362 | if child.fid in self.children: |
| 363 | if ignore_existing: |
| 364 | return |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 365 | raise ValueError( |
| 366 | "File with given fid %s already exists in %s" % (child.fid, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 367 | if self.lookup_file_by_sfid(child.sfid): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 368 | raise ValueError( |
| 369 | "File with given sfid %s already exists in %s" % (child.sfid, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 370 | if self.lookup_file_by_name(child.name): |
| 371 | if ignore_existing: |
| 372 | return |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 373 | raise ValueError( |
| 374 | "File with given name %s already exists in %s" % (child.name, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 375 | self.children[child.fid] = child |
| 376 | child.parent = self |
Harald Welte | 419bb49 | 2022-02-12 21:39:35 +0100 | [diff] [blame] | 377 | # update the service -> file relationship table |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 378 | self._add_file_services(child) |
Harald Welte | 419bb49 | 2022-02-12 21:39:35 +0100 | [diff] [blame] | 379 | if isinstance(child, CardDF): |
| 380 | for c in child.children.values(): |
| 381 | self._add_file_services(c) |
| 382 | if isinstance(c, CardDF): |
Harald Welte | d56f45d | 2022-07-16 11:46:59 +0200 | [diff] [blame] | 383 | for gc in c.children.values(): |
| 384 | if isinstance(gc, CardDF): |
| 385 | if gc._has_service(): |
| 386 | raise ValueError('TODO: implement recursive service -> file mapping') |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 387 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 388 | def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 389 | """Add a list of child (DF/EF) to this DF |
| 390 | |
| 391 | Args: |
| 392 | children: List of new DF/EFs to be added |
| 393 | ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept. |
| 394 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 395 | for child in children: |
| 396 | self.add_file(child, ignore_existing) |
| 397 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 398 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 399 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 400 | |
| 401 | Args: |
| 402 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 403 | If not specified, all selectables will be returned. |
| 404 | Returns: |
| 405 | dict containing all selectable items. Key is identifier (string), value |
| 406 | a reference to a CardFile (or derived class) instance. |
| 407 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 408 | # global selectables + our children |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 409 | sels = super().get_selectables(flags) |
| 410 | if flags == [] or 'FIDS' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 411 | sels.update({x.fid: x for x in self.children.values() if x.fid}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 412 | if flags == [] or 'FNAMES' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 413 | sels.update({x.name: x for x in self.children.values() if x.name}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 414 | return sels |
| 415 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 416 | def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 417 | """Find a file with given name within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 418 | if name == None: |
| 419 | return None |
| 420 | for i in self.children.values(): |
| 421 | if i.name and i.name == name: |
| 422 | return i |
| 423 | return None |
| 424 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 425 | def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 426 | """Find a file with given short file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 427 | if sfid == None: |
| 428 | return None |
| 429 | for i in self.children.values(): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 430 | if i.sfid == int(str(sfid)): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 431 | return i |
| 432 | return None |
| 433 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 434 | def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 435 | """Find a file with given file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 436 | if fid in self.children: |
| 437 | return self.children[fid] |
| 438 | return None |
| 439 | |
| 440 | |
| 441 | class CardMF(CardDF): |
| 442 | """MF (Master File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 443 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 444 | def __init__(self, **kwargs): |
| 445 | # can be overridden; use setdefault |
| 446 | kwargs.setdefault('fid', '3f00') |
| 447 | kwargs.setdefault('name', 'MF') |
| 448 | kwargs.setdefault('desc', 'Master File (directory root)') |
| 449 | # cannot be overridden; use assignment |
| 450 | kwargs['parent'] = self |
| 451 | super().__init__(**kwargs) |
| 452 | self.applications = dict() |
| 453 | |
| 454 | def __str__(self): |
| 455 | return "MF(%s)" % (self.fid) |
| 456 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 457 | def add_application_df(self, app: 'CardADF'): |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 458 | """Add an Application to the MF""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 459 | if not isinstance(app, CardADF): |
| 460 | raise TypeError("Expected an ADF instance") |
| 461 | if app.aid in self.applications: |
| 462 | raise ValueError("AID %s already exists" % (app.aid)) |
| 463 | self.applications[app.aid] = app |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 464 | app.parent = self |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 465 | |
| 466 | def get_app_names(self): |
| 467 | """Get list of completions (AID names)""" |
Harald Welte | d53918c | 2022-02-12 18:20:49 +0100 | [diff] [blame] | 468 | return list(self.applications.values()) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 469 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 470 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 471 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 472 | |
| 473 | Args: |
| 474 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 475 | If not specified, all selectables will be returned. |
| 476 | Returns: |
| 477 | dict containing all selectable items. Key is identifier (string), value |
| 478 | a reference to a CardFile (or derived class) instance. |
| 479 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 480 | sels = super().get_selectables(flags) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 481 | sels.update(self.get_app_selectables(flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 482 | return sels |
| 483 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 484 | def get_app_selectables(self, flags=[]) -> dict: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 485 | """Get applications by AID + name""" |
| 486 | sels = {} |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 487 | if flags == [] or 'AIDS' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 488 | sels.update({x.aid: x for x in self.applications.values()}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 489 | if flags == [] or 'ANAMES' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 490 | sels.update( |
| 491 | {x.name: x for x in self.applications.values() if x.name}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 492 | return sels |
| 493 | |
Harald Welte | c975251 | 2022-02-11 16:31:15 +0100 | [diff] [blame] | 494 | def decode_select_response(self, data_hex: Optional[str]) -> object: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 495 | """Decode the response to a SELECT command. |
| 496 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 497 | This is the fall-back method which automatically defers to the standard decoding |
| 498 | method defined by the card profile. When no profile is set, then no decoding is |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 499 | performed. Specific derived classes (usually ADF) can overload this method to |
| 500 | install specific decoding. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 501 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 502 | |
Harald Welte | c975251 | 2022-02-11 16:31:15 +0100 | [diff] [blame] | 503 | if not data_hex: |
| 504 | return data_hex |
| 505 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 506 | profile = self.get_profile() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 507 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 508 | if profile: |
| 509 | return profile.decode_select_response(data_hex) |
| 510 | else: |
| 511 | return data_hex |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 512 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 513 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 514 | class CardADF(CardDF): |
| 515 | """ADF (Application Dedicated File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 516 | |
| 517 | def __init__(self, aid: str, **kwargs): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 518 | super().__init__(**kwargs) |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 519 | # reference to CardApplication may be set from CardApplication constructor |
Harald Welte | fe8a744 | 2021-04-10 11:51:54 +0200 | [diff] [blame] | 520 | self.application = None # type: Optional[CardApplication] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 521 | self.aid = aid # Application Identifier |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 522 | mf = self.get_mf() |
| 523 | if mf: |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 524 | mf.add_application_df(self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 525 | |
| 526 | def __str__(self): |
Harald Welte | 4b00365 | 2022-07-16 11:55:07 +0200 | [diff] [blame] | 527 | return "ADF(%s)" % (self.name if self.name else self.aid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 528 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 529 | def _path_element(self, prefer_name: bool): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 530 | if self.name and prefer_name: |
| 531 | return self.name |
| 532 | else: |
| 533 | return self.aid |
| 534 | |
| 535 | |
| 536 | class CardEF(CardFile): |
| 537 | """EF (Entry File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 538 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 539 | def __init__(self, *, fid, **kwargs): |
| 540 | kwargs['fid'] = fid |
| 541 | super().__init__(**kwargs) |
| 542 | |
| 543 | def __str__(self): |
| 544 | return "EF(%s)" % (super().__str__()) |
| 545 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 546 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 547 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 548 | |
| 549 | Args: |
| 550 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 551 | If not specified, all selectables will be returned. |
| 552 | Returns: |
| 553 | dict containing all selectable items. Key is identifier (string), value |
| 554 | a reference to a CardFile (or derived class) instance. |
| 555 | """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 556 | # global selectable names + those of the parent DF |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 557 | sels = super().get_selectables(flags) |
Harald Welte | d2c177b | 2022-07-24 11:35:53 +0200 | [diff] [blame] | 558 | if flags == [] or 'FIDS' in flags: |
| 559 | sels.update({x.fid: x for x in self.parent.children.values() if x.fid and x != self}) |
| 560 | if flags == [] or 'FNAMES' in flags: |
| 561 | sels.update({x.name: x for x in self.parent.children.values() if x.name and x != self}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 562 | return sels |
| 563 | |
| 564 | |
| 565 | class TransparentEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 566 | """Transparent EF (Entry File) in the smart card filesystem. |
| 567 | |
| 568 | A Transparent EF is a binary file with no formal structure. This is contrary to |
| 569 | Record based EFs which have [fixed size] records that can be individually read/updated.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 570 | |
| 571 | @with_default_category('Transparent EF Commands') |
| 572 | class ShellCommands(CommandSet): |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 573 | """Shell commands specific for transparent EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 574 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 575 | def __init__(self): |
| 576 | super().__init__() |
| 577 | |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 578 | dec_hex_parser = argparse.ArgumentParser() |
| 579 | dec_hex_parser.add_argument('--oneline', action='store_true', |
| 580 | help='No JSON pretty-printing, dump as a single line') |
| 581 | dec_hex_parser.add_argument('HEXSTR', help='Hex-string of encoded data to decode') |
| 582 | |
| 583 | @cmd2.with_argparser(dec_hex_parser) |
| 584 | def do_decode_hex(self, opts): |
| 585 | """Decode command-line provided hex-string as if it was read from the file.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 586 | data = self._cmd.lchan.selected_file.decode_hex(opts.HEXSTR) |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 587 | self._cmd.poutput_json(data, opts.oneline) |
| 588 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 589 | read_bin_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 590 | read_bin_parser.add_argument( |
| 591 | '--offset', type=int, default=0, help='Byte offset for start of read') |
| 592 | read_bin_parser.add_argument( |
| 593 | '--length', type=int, help='Number of bytes to read') |
| 594 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 595 | @cmd2.with_argparser(read_bin_parser) |
| 596 | def do_read_binary(self, opts): |
| 597 | """Read binary data from a transparent EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 598 | (data, sw) = self._cmd.lchan.read_binary(opts.length, opts.offset) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 599 | self._cmd.poutput(data) |
| 600 | |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame] | 601 | read_bin_dec_parser = argparse.ArgumentParser() |
| 602 | read_bin_dec_parser.add_argument('--oneline', action='store_true', |
| 603 | help='No JSON pretty-printing, dump as a single line') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 604 | |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame] | 605 | @cmd2.with_argparser(read_bin_dec_parser) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 606 | def do_read_binary_decoded(self, opts): |
| 607 | """Read + decode data from a transparent EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 608 | (data, sw) = self._cmd.lchan.read_binary_dec() |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 609 | self._cmd.poutput_json(data, opts.oneline) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 610 | |
| 611 | upd_bin_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 612 | upd_bin_parser.add_argument( |
| 613 | '--offset', type=int, default=0, help='Byte offset for start of read') |
| 614 | upd_bin_parser.add_argument( |
| 615 | 'data', help='Data bytes (hex format) to write') |
| 616 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 617 | @cmd2.with_argparser(upd_bin_parser) |
| 618 | def do_update_binary(self, opts): |
| 619 | """Update (Write) data of a transparent EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 620 | (data, sw) = self._cmd.lchan.update_binary(opts.data, opts.offset) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 621 | if data: |
| 622 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 623 | |
| 624 | upd_bin_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 625 | upd_bin_dec_parser.add_argument( |
| 626 | 'data', help='Abstract data (JSON format) to write') |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 627 | upd_bin_dec_parser.add_argument('--json-path', type=str, |
| 628 | help='JSON path to modify specific element of file only') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 629 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 630 | @cmd2.with_argparser(upd_bin_dec_parser) |
| 631 | def do_update_binary_decoded(self, opts): |
| 632 | """Encode + Update (Write) data of a transparent EF""" |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 633 | if opts.json_path: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 634 | (data_json, sw) = self._cmd.lchan.read_binary_dec() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 635 | js_path_modify(data_json, opts.json_path, |
| 636 | json.loads(opts.data)) |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 637 | else: |
| 638 | data_json = json.loads(opts.data) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 639 | (data, sw) = self._cmd.lchan.update_binary_dec(data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 640 | if data: |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 641 | self._cmd.poutput_json(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 642 | |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 643 | def do_edit_binary_decoded(self, opts): |
| 644 | """Edit the JSON representation of the EF contents in an editor.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 645 | (orig_json, sw) = self._cmd.lchan.read_binary_dec() |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 646 | with tempfile.TemporaryDirectory(prefix='pysim_') as dirname: |
| 647 | filename = '%s/file' % dirname |
| 648 | # write existing data as JSON to file |
| 649 | with open(filename, 'w') as text_file: |
| 650 | json.dump(orig_json, text_file, indent=4) |
| 651 | # run a text editor |
| 652 | self._cmd._run_editor(filename) |
| 653 | with open(filename, 'r') as text_file: |
| 654 | edited_json = json.load(text_file) |
| 655 | if edited_json == orig_json: |
| 656 | self._cmd.poutput("Data not modified, skipping write") |
| 657 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 658 | (data, sw) = self._cmd.lchan.update_binary_dec(edited_json) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 659 | if data: |
| 660 | self._cmd.poutput_json(data) |
| 661 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 662 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 663 | size: Size = (1, None), **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 664 | """ |
| 665 | Args: |
| 666 | fid : File Identifier (4 hex digits) |
| 667 | sfid : Short File Identifier (2 hex digits, optional) |
| 668 | name : Brief name of the file, lik EF_ICCID |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 669 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 670 | parent : Parent CardFile object within filesystem hierarchy |
| 671 | size : tuple of (minimum_size, recommended_size) |
| 672 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 673 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 674 | self._construct = None |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 675 | self._tlv = None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 676 | self.size = size |
| 677 | self.shell_commands = [self.ShellCommands()] |
| 678 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 679 | def decode_bin(self, raw_bin_data: bytearray) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 680 | """Decode raw (binary) data into abstract representation. |
| 681 | |
| 682 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 683 | for implementing this specifically for the given file. This function checks which |
| 684 | of the method exists, add calls them (with conversion, as needed). |
| 685 | |
| 686 | Args: |
| 687 | raw_bin_data : binary encoded data |
| 688 | Returns: |
| 689 | abstract_data; dict representing the decoded data |
| 690 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 691 | method = getattr(self, '_decode_bin', None) |
| 692 | if callable(method): |
| 693 | return method(raw_bin_data) |
| 694 | method = getattr(self, '_decode_hex', None) |
| 695 | if callable(method): |
| 696 | return method(b2h(raw_bin_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 697 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 698 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 699 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 700 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 701 | t.from_tlv(raw_bin_data) |
| 702 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 703 | return {'raw': raw_bin_data.hex()} |
| 704 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 705 | def decode_hex(self, raw_hex_data: str) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 706 | """Decode raw (hex string) data into abstract representation. |
| 707 | |
| 708 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 709 | for implementing this specifically for the given file. This function checks which |
| 710 | of the method exists, add calls them (with conversion, as needed). |
| 711 | |
| 712 | Args: |
| 713 | raw_hex_data : hex-encoded data |
| 714 | Returns: |
| 715 | abstract_data; dict representing the decoded data |
| 716 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 717 | method = getattr(self, '_decode_hex', None) |
| 718 | if callable(method): |
| 719 | return method(raw_hex_data) |
| 720 | raw_bin_data = h2b(raw_hex_data) |
| 721 | method = getattr(self, '_decode_bin', None) |
| 722 | if callable(method): |
| 723 | return method(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 724 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 725 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 726 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 727 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 728 | t.from_tlv(raw_bin_data) |
| 729 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 730 | return {'raw': raw_bin_data.hex()} |
| 731 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 732 | def encode_bin(self, abstract_data: dict) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 733 | """Encode abstract representation into raw (binary) data. |
| 734 | |
| 735 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 736 | for implementing this specifically for the given file. This function checks which |
| 737 | of the method exists, add calls them (with conversion, as needed). |
| 738 | |
| 739 | Args: |
| 740 | abstract_data : dict representing the decoded data |
| 741 | Returns: |
| 742 | binary encoded data |
| 743 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 744 | method = getattr(self, '_encode_bin', None) |
| 745 | if callable(method): |
| 746 | return method(abstract_data) |
| 747 | method = getattr(self, '_encode_hex', None) |
| 748 | if callable(method): |
| 749 | return h2b(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 750 | if self._construct: |
| 751 | return self._construct.build(abstract_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 752 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 753 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 754 | t.from_dict(abstract_data) |
| 755 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 756 | raise NotImplementedError( |
| 757 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 758 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 759 | def encode_hex(self, abstract_data: dict) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 760 | """Encode abstract representation into raw (hex string) data. |
| 761 | |
| 762 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 763 | for implementing this specifically for the given file. This function checks which |
| 764 | of the method exists, add calls them (with conversion, as needed). |
| 765 | |
| 766 | Args: |
| 767 | abstract_data : dict representing the decoded data |
| 768 | Returns: |
| 769 | hex string encoded data |
| 770 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 771 | method = getattr(self, '_encode_hex', None) |
| 772 | if callable(method): |
| 773 | return method(abstract_data) |
| 774 | method = getattr(self, '_encode_bin', None) |
| 775 | if callable(method): |
| 776 | raw_bin_data = method(abstract_data) |
| 777 | return b2h(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 778 | if self._construct: |
| 779 | return b2h(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 780 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 781 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 782 | t.from_dict(abstract_data) |
| 783 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 784 | raise NotImplementedError( |
| 785 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 786 | |
| 787 | |
| 788 | class LinFixedEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 789 | """Linear Fixed EF (Entry File) in the smart card filesystem. |
| 790 | |
| 791 | Linear Fixed EFs are record oriented files. They consist of a number of fixed-size |
| 792 | records. The records can be individually read/updated.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 793 | |
| 794 | @with_default_category('Linear Fixed EF Commands') |
| 795 | class ShellCommands(CommandSet): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 796 | """Shell commands specific for Linear Fixed EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 797 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 798 | def __init__(self, **kwargs): |
| 799 | super().__init__(**kwargs) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 800 | |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 801 | dec_hex_parser = argparse.ArgumentParser() |
| 802 | dec_hex_parser.add_argument('--oneline', action='store_true', |
| 803 | help='No JSON pretty-printing, dump as a single line') |
| 804 | dec_hex_parser.add_argument('HEXSTR', help='Hex-string of encoded data to decode') |
| 805 | |
| 806 | @cmd2.with_argparser(dec_hex_parser) |
| 807 | def do_decode_hex(self, opts): |
| 808 | """Decode command-line provided hex-string as if it was read from the file.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 809 | data = self._cmd.lchan.selected_file.decode_record_hex(opts.HEXSTR) |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 810 | self._cmd.poutput_json(data, opts.oneline) |
| 811 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 812 | read_rec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 813 | read_rec_parser.add_argument( |
| 814 | 'record_nr', type=int, help='Number of record to be read') |
| 815 | read_rec_parser.add_argument( |
| 816 | '--count', type=int, default=1, help='Number of records to be read, beginning at record_nr') |
| 817 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 818 | @cmd2.with_argparser(read_rec_parser) |
| 819 | def do_read_record(self, opts): |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 820 | """Read one or multiple records from a record-oriented EF""" |
| 821 | for r in range(opts.count): |
| 822 | recnr = opts.record_nr + r |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 823 | (data, sw) = self._cmd.lchan.read_record(recnr) |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 824 | if (len(data) > 0): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 825 | recstr = str(data) |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 826 | else: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 827 | recstr = "(empty)" |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 828 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 829 | |
| 830 | read_rec_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 831 | read_rec_dec_parser.add_argument( |
| 832 | 'record_nr', type=int, help='Number of record to be read') |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame] | 833 | read_rec_dec_parser.add_argument('--oneline', action='store_true', |
| 834 | help='No JSON pretty-printing, dump as a single line') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 835 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 836 | @cmd2.with_argparser(read_rec_dec_parser) |
| 837 | def do_read_record_decoded(self, opts): |
| 838 | """Read + decode a record from a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 839 | (data, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 840 | self._cmd.poutput_json(data, opts.oneline) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 841 | |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 842 | read_recs_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 843 | |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 844 | @cmd2.with_argparser(read_recs_parser) |
| 845 | def do_read_records(self, opts): |
| 846 | """Read all records from a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 847 | num_of_rec = self._cmd.lchan.selected_file_num_of_rec() |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 848 | for recnr in range(1, 1 + num_of_rec): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 849 | (data, sw) = self._cmd.lchan.read_record(recnr) |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 850 | if (len(data) > 0): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 851 | recstr = str(data) |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 852 | else: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 853 | recstr = "(empty)" |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 854 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
| 855 | |
| 856 | read_recs_dec_parser = argparse.ArgumentParser() |
| 857 | read_recs_dec_parser.add_argument('--oneline', action='store_true', |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 858 | help='No JSON pretty-printing, dump as a single line') |
| 859 | |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 860 | @cmd2.with_argparser(read_recs_dec_parser) |
| 861 | def do_read_records_decoded(self, opts): |
| 862 | """Read + decode all records from a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 863 | num_of_rec = self._cmd.lchan.selected_file_num_of_rec() |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 864 | # collect all results in list so they are rendered as JSON list when printing |
| 865 | data_list = [] |
| 866 | for recnr in range(1, 1 + num_of_rec): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 867 | (data, sw) = self._cmd.lchan.read_record_dec(recnr) |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 868 | data_list.append(data) |
| 869 | self._cmd.poutput_json(data_list, opts.oneline) |
| 870 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 871 | upd_rec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 872 | upd_rec_parser.add_argument( |
| 873 | 'record_nr', type=int, help='Number of record to be read') |
| 874 | upd_rec_parser.add_argument( |
| 875 | 'data', help='Data bytes (hex format) to write') |
| 876 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 877 | @cmd2.with_argparser(upd_rec_parser) |
| 878 | def do_update_record(self, opts): |
| 879 | """Update (write) data to a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 880 | (data, sw) = self._cmd.lchan.update_record(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 881 | if data: |
| 882 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 883 | |
| 884 | upd_rec_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 885 | upd_rec_dec_parser.add_argument( |
| 886 | 'record_nr', type=int, help='Number of record to be read') |
| 887 | upd_rec_dec_parser.add_argument( |
| 888 | 'data', help='Abstract data (JSON format) to write') |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 889 | upd_rec_dec_parser.add_argument('--json-path', type=str, |
| 890 | help='JSON path to modify specific element of record only') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 891 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 892 | @cmd2.with_argparser(upd_rec_dec_parser) |
| 893 | def do_update_record_decoded(self, opts): |
| 894 | """Encode + Update (write) data to a record-oriented EF""" |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 895 | if opts.json_path: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 896 | (data_json, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 897 | js_path_modify(data_json, opts.json_path, |
| 898 | json.loads(opts.data)) |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 899 | else: |
| 900 | data_json = json.loads(opts.data) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 901 | (data, sw) = self._cmd.lchan.update_record_dec( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 902 | opts.record_nr, data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 903 | if data: |
| 904 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 905 | |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 906 | edit_rec_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 907 | edit_rec_dec_parser.add_argument( |
| 908 | 'record_nr', type=int, help='Number of record to be edited') |
| 909 | |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 910 | @cmd2.with_argparser(edit_rec_dec_parser) |
| 911 | def do_edit_record_decoded(self, opts): |
| 912 | """Edit the JSON representation of one record in an editor.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 913 | (orig_json, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
Vadim Yanitskiy | 895fa6f | 2021-05-02 02:36:44 +0200 | [diff] [blame] | 914 | with tempfile.TemporaryDirectory(prefix='pysim_') as dirname: |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 915 | filename = '%s/file' % dirname |
| 916 | # write existing data as JSON to file |
| 917 | with open(filename, 'w') as text_file: |
| 918 | json.dump(orig_json, text_file, indent=4) |
| 919 | # run a text editor |
| 920 | self._cmd._run_editor(filename) |
| 921 | with open(filename, 'r') as text_file: |
| 922 | edited_json = json.load(text_file) |
| 923 | if edited_json == orig_json: |
| 924 | self._cmd.poutput("Data not modified, skipping write") |
| 925 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 926 | (data, sw) = self._cmd.lchan.update_record_dec( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 927 | opts.record_nr, edited_json) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 928 | if data: |
| 929 | self._cmd.poutput_json(data) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 930 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 931 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 932 | parent: Optional[CardDF] = None, rec_len: Size = (1, None), **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 933 | """ |
| 934 | Args: |
| 935 | fid : File Identifier (4 hex digits) |
| 936 | sfid : Short File Identifier (2 hex digits, optional) |
| 937 | name : Brief name of the file, lik EF_ICCID |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 938 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 939 | parent : Parent CardFile object within filesystem hierarchy |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 940 | rec_len : Tuple of (minimum_length, recommended_length) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 941 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 942 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 943 | self.rec_len = rec_len |
| 944 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 945 | self._construct = None |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 946 | self._tlv = None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 947 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 948 | def decode_record_hex(self, raw_hex_data: str) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 949 | """Decode raw (hex string) data into abstract representation. |
| 950 | |
| 951 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 952 | method for implementing this specifically for the given file. This function checks which |
| 953 | of the method exists, add calls them (with conversion, as needed). |
| 954 | |
| 955 | Args: |
| 956 | raw_hex_data : hex-encoded data |
| 957 | Returns: |
| 958 | abstract_data; dict representing the decoded data |
| 959 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 960 | method = getattr(self, '_decode_record_hex', None) |
| 961 | if callable(method): |
| 962 | return method(raw_hex_data) |
| 963 | raw_bin_data = h2b(raw_hex_data) |
| 964 | method = getattr(self, '_decode_record_bin', None) |
| 965 | if callable(method): |
| 966 | return method(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 967 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 968 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 969 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 970 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 971 | t.from_tlv(raw_bin_data) |
| 972 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 973 | return {'raw': raw_bin_data.hex()} |
| 974 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 975 | def decode_record_bin(self, raw_bin_data: bytearray) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 976 | """Decode raw (binary) data into abstract representation. |
| 977 | |
| 978 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 979 | method for implementing this specifically for the given file. This function checks which |
| 980 | of the method exists, add calls them (with conversion, as needed). |
| 981 | |
| 982 | Args: |
| 983 | raw_bin_data : binary encoded data |
| 984 | Returns: |
| 985 | abstract_data; dict representing the decoded data |
| 986 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 987 | method = getattr(self, '_decode_record_bin', None) |
| 988 | if callable(method): |
| 989 | return method(raw_bin_data) |
| 990 | raw_hex_data = b2h(raw_bin_data) |
| 991 | method = getattr(self, '_decode_record_hex', None) |
| 992 | if callable(method): |
| 993 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 994 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 995 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 996 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 997 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 998 | t.from_tlv(raw_bin_data) |
| 999 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1000 | return {'raw': raw_hex_data} |
| 1001 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1002 | def encode_record_hex(self, abstract_data: dict) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1003 | """Encode abstract representation into raw (hex string) data. |
| 1004 | |
| 1005 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1006 | method for implementing this specifically for the given file. This function checks which |
| 1007 | of the method exists, add calls them (with conversion, as needed). |
| 1008 | |
| 1009 | Args: |
| 1010 | abstract_data : dict representing the decoded data |
| 1011 | Returns: |
| 1012 | hex string encoded data |
| 1013 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1014 | method = getattr(self, '_encode_record_hex', None) |
| 1015 | if callable(method): |
| 1016 | return method(abstract_data) |
| 1017 | method = getattr(self, '_encode_record_bin', None) |
| 1018 | if callable(method): |
| 1019 | raw_bin_data = method(abstract_data) |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1020 | return b2h(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1021 | if self._construct: |
| 1022 | return b2h(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1023 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1024 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1025 | t.from_dict(abstract_data) |
| 1026 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1027 | raise NotImplementedError( |
| 1028 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1029 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1030 | def encode_record_bin(self, abstract_data: dict) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1031 | """Encode abstract representation into raw (binary) data. |
| 1032 | |
| 1033 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1034 | method for implementing this specifically for the given file. This function checks which |
| 1035 | of the method exists, add calls them (with conversion, as needed). |
| 1036 | |
| 1037 | Args: |
| 1038 | abstract_data : dict representing the decoded data |
| 1039 | Returns: |
| 1040 | binary encoded data |
| 1041 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1042 | method = getattr(self, '_encode_record_bin', None) |
| 1043 | if callable(method): |
| 1044 | return method(abstract_data) |
| 1045 | method = getattr(self, '_encode_record_hex', None) |
| 1046 | if callable(method): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1047 | return h2b(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1048 | if self._construct: |
| 1049 | return self._construct.build(abstract_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1050 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1051 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1052 | t.from_dict(abstract_data) |
| 1053 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1054 | raise NotImplementedError( |
| 1055 | "%s encoder not yet implemented. Patches welcome." % self) |
| 1056 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1057 | |
| 1058 | class CyclicEF(LinFixedEF): |
| 1059 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 1060 | # we don't really have any special support for those; just recycling LinFixedEF here |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1061 | |
| 1062 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None, |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 1063 | rec_len: Size = (1, None), **kwargs): |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1064 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len, **kwargs) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1065 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1066 | |
| 1067 | class TransRecEF(TransparentEF): |
| 1068 | """Transparent EF (Entry File) containing fixed-size records. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1069 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1070 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 1071 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 1072 | inside. |
| 1073 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 1074 | for a record, while this class takes care of split / merge of records. |
| 1075 | """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1076 | |
| 1077 | def __init__(self, fid: str, rec_len: int, sfid: str = None, name: str = None, desc: str = None, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 1078 | parent: Optional[CardDF] = None, size: Size = (1, None), **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1079 | """ |
| 1080 | Args: |
| 1081 | fid : File Identifier (4 hex digits) |
| 1082 | sfid : Short File Identifier (2 hex digits, optional) |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1083 | name : Brief name of the file, like EF_ICCID |
| 1084 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1085 | parent : Parent CardFile object within filesystem hierarchy |
| 1086 | rec_len : Length of the fixed-length records within transparent EF |
| 1087 | size : tuple of (minimum_size, recommended_size) |
| 1088 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1089 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size, **kwargs) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1090 | self.rec_len = rec_len |
| 1091 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1092 | def decode_record_hex(self, raw_hex_data: str) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1093 | """Decode raw (hex string) data into abstract representation. |
| 1094 | |
| 1095 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 1096 | method for implementing this specifically for the given file. This function checks which |
| 1097 | of the method exists, add calls them (with conversion, as needed). |
| 1098 | |
| 1099 | Args: |
| 1100 | raw_hex_data : hex-encoded data |
| 1101 | Returns: |
| 1102 | abstract_data; dict representing the decoded data |
| 1103 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1104 | method = getattr(self, '_decode_record_hex', None) |
| 1105 | if callable(method): |
| 1106 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1107 | raw_bin_data = h2b(raw_hex_data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1108 | method = getattr(self, '_decode_record_bin', None) |
| 1109 | if callable(method): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1110 | return method(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1111 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 1112 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1113 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1114 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1115 | t.from_tlv(raw_bin_data) |
| 1116 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1117 | return {'raw': raw_hex_data} |
| 1118 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1119 | def decode_record_bin(self, raw_bin_data: bytearray) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1120 | """Decode raw (binary) data into abstract representation. |
| 1121 | |
| 1122 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 1123 | method for implementing this specifically for the given file. This function checks which |
| 1124 | of the method exists, add calls them (with conversion, as needed). |
| 1125 | |
| 1126 | Args: |
| 1127 | raw_bin_data : binary encoded data |
| 1128 | Returns: |
| 1129 | abstract_data; dict representing the decoded data |
| 1130 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1131 | method = getattr(self, '_decode_record_bin', None) |
| 1132 | if callable(method): |
| 1133 | return method(raw_bin_data) |
| 1134 | raw_hex_data = b2h(raw_bin_data) |
| 1135 | method = getattr(self, '_decode_record_hex', None) |
| 1136 | if callable(method): |
| 1137 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1138 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 1139 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1140 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1141 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1142 | t.from_tlv(raw_bin_data) |
| 1143 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1144 | return {'raw': raw_hex_data} |
| 1145 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1146 | def encode_record_hex(self, abstract_data: dict) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1147 | """Encode abstract representation into raw (hex string) data. |
| 1148 | |
| 1149 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1150 | method for implementing this specifically for the given file. This function checks which |
| 1151 | of the method exists, add calls them (with conversion, as needed). |
| 1152 | |
| 1153 | Args: |
| 1154 | abstract_data : dict representing the decoded data |
| 1155 | Returns: |
| 1156 | hex string encoded data |
| 1157 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1158 | method = getattr(self, '_encode_record_hex', None) |
| 1159 | if callable(method): |
| 1160 | return method(abstract_data) |
| 1161 | method = getattr(self, '_encode_record_bin', None) |
| 1162 | if callable(method): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1163 | return b2h(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1164 | if self._construct: |
| 1165 | return b2h(filter_dict(self._construct.build(abstract_data))) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1166 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1167 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1168 | t.from_dict(abstract_data) |
| 1169 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1170 | raise NotImplementedError( |
| 1171 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1172 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1173 | def encode_record_bin(self, abstract_data: dict) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1174 | """Encode abstract representation into raw (binary) data. |
| 1175 | |
| 1176 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1177 | method for implementing this specifically for the given file. This function checks which |
| 1178 | of the method exists, add calls them (with conversion, as needed). |
| 1179 | |
| 1180 | Args: |
| 1181 | abstract_data : dict representing the decoded data |
| 1182 | Returns: |
| 1183 | binary encoded data |
| 1184 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1185 | method = getattr(self, '_encode_record_bin', None) |
| 1186 | if callable(method): |
| 1187 | return method(abstract_data) |
| 1188 | method = getattr(self, '_encode_record_hex', None) |
| 1189 | if callable(method): |
| 1190 | return h2b(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1191 | if self._construct: |
| 1192 | return filter_dict(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1193 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1194 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1195 | t.from_dict(abstract_data) |
| 1196 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1197 | raise NotImplementedError( |
| 1198 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1199 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1200 | def _decode_bin(self, raw_bin_data: bytearray): |
| 1201 | chunks = [raw_bin_data[i:i+self.rec_len] |
| 1202 | for i in range(0, len(raw_bin_data), self.rec_len)] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1203 | return [self.decode_record_bin(x) for x in chunks] |
| 1204 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1205 | def _encode_bin(self, abstract_data) -> bytes: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1206 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 1207 | # FIXME: pad to file size |
| 1208 | return b''.join(chunks) |
| 1209 | |
| 1210 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1211 | class BerTlvEF(CardEF): |
Harald Welte | 2788162 | 2021-04-21 11:16:31 +0200 | [diff] [blame] | 1212 | """BER-TLV EF (Entry File) in the smart card filesystem. |
| 1213 | A BER-TLV EF is a binary file with a BER (Basic Encoding Rules) TLV structure |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1214 | |
Harald Welte | 2788162 | 2021-04-21 11:16:31 +0200 | [diff] [blame] | 1215 | NOTE: We currently don't really support those, this class is simply a wrapper |
| 1216 | around TransparentEF as a place-holder, so we can already define EFs of BER-TLV |
| 1217 | type without fully supporting them.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1218 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1219 | @with_default_category('BER-TLV EF Commands') |
| 1220 | class ShellCommands(CommandSet): |
| 1221 | """Shell commands specific for BER-TLV EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1222 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1223 | def __init__(self): |
| 1224 | super().__init__() |
| 1225 | |
| 1226 | retrieve_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1227 | retrieve_data_parser.add_argument( |
| 1228 | 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve') |
| 1229 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1230 | @cmd2.with_argparser(retrieve_data_parser) |
| 1231 | def do_retrieve_data(self, opts): |
| 1232 | """Retrieve (Read) data from a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1233 | (data, sw) = self._cmd.lchan.retrieve_data(opts.tag) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1234 | self._cmd.poutput(data) |
| 1235 | |
| 1236 | def do_retrieve_tags(self, opts): |
| 1237 | """List tags available in a given BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1238 | tags = self._cmd.lchan.retrieve_tags() |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1239 | self._cmd.poutput(tags) |
| 1240 | |
| 1241 | set_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1242 | set_data_parser.add_argument( |
| 1243 | 'tag', type=auto_int, help='BER-TLV Tag of value to set') |
| 1244 | set_data_parser.add_argument( |
| 1245 | 'data', help='Data bytes (hex format) to write') |
| 1246 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1247 | @cmd2.with_argparser(set_data_parser) |
| 1248 | def do_set_data(self, opts): |
| 1249 | """Set (Write) data for a given tag in a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1250 | (data, sw) = self._cmd.lchan.set_data(opts.tag, opts.data) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1251 | if data: |
| 1252 | self._cmd.poutput(data) |
| 1253 | |
| 1254 | del_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1255 | del_data_parser.add_argument( |
| 1256 | 'tag', type=auto_int, help='BER-TLV Tag of value to set') |
| 1257 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1258 | @cmd2.with_argparser(del_data_parser) |
| 1259 | def do_delete_data(self, opts): |
| 1260 | """Delete data for a given tag in a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1261 | (data, sw) = self._cmd.lchan.set_data(opts.tag, None) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1262 | if data: |
| 1263 | self._cmd.poutput(data) |
| 1264 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1265 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 1266 | size: Size = (1, None), **kwargs): |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1267 | """ |
| 1268 | Args: |
| 1269 | fid : File Identifier (4 hex digits) |
| 1270 | sfid : Short File Identifier (2 hex digits, optional) |
| 1271 | name : Brief name of the file, lik EF_ICCID |
| 1272 | desc : Description of the file |
| 1273 | parent : Parent CardFile object within filesystem hierarchy |
| 1274 | size : tuple of (minimum_size, recommended_size) |
| 1275 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1276 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1277 | self._construct = None |
| 1278 | self.size = size |
| 1279 | self.shell_commands = [self.ShellCommands()] |
| 1280 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1281 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 1282 | class RuntimeState: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1283 | """Represent the runtime state of a session with a card.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1284 | |
| 1285 | def __init__(self, card, profile: 'CardProfile'): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1286 | """ |
| 1287 | Args: |
| 1288 | card : pysim.cards.Card instance |
| 1289 | profile : CardProfile instance |
| 1290 | """ |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 1291 | self.mf = CardMF(profile=profile) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1292 | self.card = card |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1293 | self.profile = profile |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1294 | self.lchan = {} |
| 1295 | # the basic logical channel always exists |
| 1296 | self.lchan[0] = RuntimeLchan(0, self) |
Philipp Maier | 51cad0d | 2021-11-08 15:45:10 +0100 | [diff] [blame] | 1297 | |
| 1298 | # make sure the class and selection control bytes, which are specified |
| 1299 | # by the card profile are used |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1300 | self.card.set_apdu_parameter( |
| 1301 | cla=self.profile.cla, sel_ctrl=self.profile.sel_ctrl) |
Philipp Maier | 51cad0d | 2021-11-08 15:45:10 +0100 | [diff] [blame] | 1302 | |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1303 | # add application ADFs + MF-files from profile |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 1304 | apps = self._match_applications() |
| 1305 | for a in apps: |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1306 | if a.adf: |
| 1307 | self.mf.add_application_df(a.adf) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1308 | for f in self.profile.files_in_mf: |
| 1309 | self.mf.add_file(f) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 1310 | self.conserve_write = True |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1311 | |
Philipp Maier | 4e2e1d9 | 2021-11-08 15:36:01 +0100 | [diff] [blame] | 1312 | # make sure that when the runtime state is created, the card is also |
| 1313 | # in a defined state. |
| 1314 | self.reset() |
| 1315 | |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 1316 | def _match_applications(self): |
| 1317 | """match the applications from the profile with applications on the card""" |
| 1318 | apps_profile = self.profile.applications |
Philipp Maier | d454fe7 | 2021-11-08 15:32:23 +0100 | [diff] [blame] | 1319 | |
| 1320 | # When the profile does not feature any applications, then we are done already |
| 1321 | if not apps_profile: |
| 1322 | return [] |
| 1323 | |
| 1324 | # Read AIDs from card and match them against the applications defined by the |
| 1325 | # card profile |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 1326 | aids_card = self.card.read_aids() |
| 1327 | apps_taken = [] |
| 1328 | if aids_card: |
| 1329 | aids_taken = [] |
| 1330 | print("AIDs on card:") |
| 1331 | for a in aids_card: |
| 1332 | for f in apps_profile: |
| 1333 | if f.aid in a: |
Philipp Maier | 8d8bdef | 2021-12-01 11:48:27 +0100 | [diff] [blame] | 1334 | print(" %s: %s (EF.DIR)" % (f.name, a)) |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 1335 | aids_taken.append(a) |
| 1336 | apps_taken.append(f) |
| 1337 | aids_unknown = set(aids_card) - set(aids_taken) |
| 1338 | for a in aids_unknown: |
Philipp Maier | 8d8bdef | 2021-12-01 11:48:27 +0100 | [diff] [blame] | 1339 | print(" unknown: %s (EF.DIR)" % a) |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 1340 | else: |
Philipp Maier | 8d8bdef | 2021-12-01 11:48:27 +0100 | [diff] [blame] | 1341 | print("warning: EF.DIR seems to be empty!") |
| 1342 | |
| 1343 | # Some card applications may not be registered in EF.DIR, we will actively |
| 1344 | # probe for those applications |
| 1345 | for f in set(apps_profile) - set(apps_taken): |
Bjoern Riemer | da57ef1 | 2022-01-18 15:38:14 +0100 | [diff] [blame] | 1346 | try: |
| 1347 | data, sw = self.card.select_adf_by_aid(f.aid) |
| 1348 | if sw == "9000": |
| 1349 | print(" %s: %s" % (f.name, f.aid)) |
| 1350 | apps_taken.append(f) |
| 1351 | except SwMatchError: |
| 1352 | pass |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 1353 | return apps_taken |
| 1354 | |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1355 | def reset(self, cmd_app=None) -> Hexstr: |
| 1356 | """Perform physical card reset and obtain ATR. |
| 1357 | Args: |
| 1358 | cmd_app : Command Application State (for unregistering old file commands) |
| 1359 | """ |
| 1360 | # delete all lchan != 0 (basic lchan) |
| 1361 | for lchan_nr in self.lchan.keys(): |
| 1362 | if lchan_nr == 0: |
| 1363 | continue |
| 1364 | del self.lchan[lchan_nr] |
| 1365 | atr = i2h(self.card.reset()) |
| 1366 | # select MF to reset internal state and to verify card really works |
| 1367 | self.lchan[0].select('MF', cmd_app) |
| 1368 | self.lchan[0].selected_adf = None |
| 1369 | return atr |
| 1370 | |
| 1371 | def add_lchan(self, lchan_nr: int) -> 'RuntimeLchan': |
| 1372 | """Add a logical channel to the runtime state. You shouldn't call this |
| 1373 | directly but always go through RuntimeLchan.add_lchan().""" |
| 1374 | if lchan_nr in self.lchan.keys(): |
| 1375 | raise ValueError('Cannot create already-existing lchan %d' % lchan_nr) |
| 1376 | self.lchan[lchan_nr] = RuntimeLchan(lchan_nr, self) |
| 1377 | return self.lchan[lchan_nr] |
| 1378 | |
| 1379 | def del_lchan(self, lchan_nr: int): |
| 1380 | if lchan_nr in self.lchan.keys(): |
| 1381 | del self.lchan[lchan_nr] |
| 1382 | return True |
| 1383 | else: |
| 1384 | return False |
| 1385 | |
| 1386 | def get_lchan_by_cla(self, cla) -> Optional['RuntimeLchan']: |
| 1387 | lchan_nr = lchan_nr_from_cla(cla) |
| 1388 | if lchan_nr in self.lchan.keys(): |
| 1389 | return self.lchan[lchan_nr] |
| 1390 | else: |
| 1391 | return None |
| 1392 | |
| 1393 | |
| 1394 | class RuntimeLchan: |
| 1395 | """Represent the runtime state of a logical channel with a card.""" |
| 1396 | |
| 1397 | def __init__(self, lchan_nr: int, rs: RuntimeState): |
| 1398 | self.lchan_nr = lchan_nr |
| 1399 | self.rs = rs |
| 1400 | self.selected_file = self.rs.mf |
| 1401 | self.selected_adf = None |
| 1402 | self.selected_file_fcp = None |
| 1403 | self.selected_file_fcp_hex = None |
| 1404 | |
| 1405 | def add_lchan(self, lchan_nr: int) -> 'RuntimeLchan': |
| 1406 | """Add a new logical channel from the current logical channel. Just affects |
| 1407 | internal state, doesn't actually open a channel with the UICC.""" |
| 1408 | new_lchan = self.rs.add_lchan(lchan_nr) |
| 1409 | # See TS 102 221 Table 8.3 |
| 1410 | if self.lchan_nr != 0: |
| 1411 | new_lchan.selected_file = self.get_cwd() |
| 1412 | new_lchan.selected_adf = self.selected_adf |
| 1413 | return new_lchan |
| 1414 | |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 1415 | def selected_file_descriptor_byte(self) -> dict: |
| 1416 | return self.selected_file_fcp['file_descriptor']['file_descriptor_byte'] |
| 1417 | |
| 1418 | def selected_file_shareable(self) -> bool: |
| 1419 | return self.selected_file_descriptor_byte()['shareable'] |
| 1420 | |
| 1421 | def selected_file_structure(self) -> str: |
| 1422 | return self.selected_file_descriptor_byte()['structure'] |
| 1423 | |
| 1424 | def selected_file_type(self) -> str: |
| 1425 | return self.selected_file_descriptor_byte()['file_type'] |
| 1426 | |
| 1427 | def selected_file_num_of_rec(self) -> Optional[int]: |
| 1428 | return self.selected_file_fcp['file_descriptor'].get('num_of_rec') |
| 1429 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1430 | def get_cwd(self) -> CardDF: |
| 1431 | """Obtain the current working directory. |
| 1432 | |
| 1433 | Returns: |
| 1434 | CardDF instance |
| 1435 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1436 | if isinstance(self.selected_file, CardDF): |
| 1437 | return self.selected_file |
| 1438 | else: |
| 1439 | return self.selected_file.parent |
| 1440 | |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1441 | def get_application_df(self) -> Optional[CardADF]: |
| 1442 | """Obtain the currently selected application DF (if any). |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1443 | |
| 1444 | Returns: |
| 1445 | CardADF() instance or None""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1446 | # iterate upwards from selected file; check if any is an ADF |
| 1447 | node = self.selected_file |
| 1448 | while node.parent != node: |
| 1449 | if isinstance(node, CardADF): |
| 1450 | return node |
| 1451 | node = node.parent |
| 1452 | return None |
| 1453 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1454 | def interpret_sw(self, sw: str): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1455 | """Interpret a given status word relative to the currently selected application |
| 1456 | or the underlying card profile. |
| 1457 | |
| 1458 | Args: |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1459 | sw : Status word as string of 4 hex digits |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1460 | |
| 1461 | Returns: |
| 1462 | Tuple of two strings |
| 1463 | """ |
Harald Welte | 86fbd39 | 2021-04-02 22:13:09 +0200 | [diff] [blame] | 1464 | res = None |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1465 | adf = self.get_application_df() |
| 1466 | if adf: |
| 1467 | app = adf.application |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1468 | # The application either comes with its own interpret_sw |
| 1469 | # method or we will use the interpret_sw method from the |
| 1470 | # card profile. |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1471 | if app and hasattr(app, "interpret_sw"): |
Harald Welte | 86fbd39 | 2021-04-02 22:13:09 +0200 | [diff] [blame] | 1472 | res = app.interpret_sw(sw) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1473 | return res or self.rs.profile.interpret_sw(sw) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1474 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1475 | def probe_file(self, fid: str, cmd_app=None): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1476 | """Blindly try to select a file and automatically add a matching file |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1477 | object if the file actually exists.""" |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1478 | if not is_hex(fid, 4, 4): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1479 | raise ValueError( |
| 1480 | "Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1481 | |
| 1482 | try: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1483 | (data, sw) = self.rs.card._scc.select_file(fid) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1484 | except SwMatchError as swm: |
| 1485 | k = self.interpret_sw(swm.sw_actual) |
| 1486 | if not k: |
| 1487 | raise(swm) |
| 1488 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
| 1489 | |
| 1490 | select_resp = self.selected_file.decode_select_response(data) |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 1491 | if (select_resp['file_descriptor']['file_descriptor_byte']['file_type'] == 'df'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1492 | f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), |
| 1493 | desc="dedicated file, manually added at runtime") |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1494 | else: |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 1495 | if (select_resp['file_descriptor']['file_descriptor_byte']['structure'] == 'transparent'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1496 | f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), |
| 1497 | desc="elementary file, manually added at runtime") |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1498 | else: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1499 | f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), |
| 1500 | desc="elementary file, manually added at runtime") |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1501 | |
| 1502 | self.selected_file.add_files([f]) |
| 1503 | self.selected_file = f |
Philipp Maier | 6b8eedc | 2022-06-01 18:10:04 +0200 | [diff] [blame] | 1504 | return select_resp, data |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1505 | |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 1506 | def _select_pre(self, cmd_app): |
| 1507 | # unregister commands of old file |
| 1508 | if cmd_app and self.selected_file.shell_commands: |
| 1509 | for c in self.selected_file.shell_commands: |
| 1510 | cmd_app.unregister_command_set(c) |
| 1511 | |
| 1512 | def _select_post(self, cmd_app): |
| 1513 | # register commands of new file |
| 1514 | if cmd_app and self.selected_file.shell_commands: |
| 1515 | for c in self.selected_file.shell_commands: |
| 1516 | cmd_app.register_command_set(c) |
| 1517 | |
| 1518 | def select_file(self, file: CardFile, cmd_app=None): |
| 1519 | """Select a file (EF, DF, ADF, MF, ...). |
| 1520 | |
| 1521 | Args: |
| 1522 | file : CardFile [or derived class] instance |
| 1523 | cmd_app : Command Application State (for unregistering old file commands) |
| 1524 | """ |
| 1525 | # we need to find a path from our self.selected_file to the destination |
| 1526 | inter_path = self.selected_file.build_select_path_to(file) |
| 1527 | if not inter_path: |
| 1528 | raise RuntimeError('Cannot determine path from %s to %s' % (self.selected_file, file)) |
| 1529 | |
| 1530 | self._select_pre(cmd_app) |
| 1531 | |
| 1532 | for p in inter_path: |
| 1533 | try: |
| 1534 | if isinstance(p, CardADF): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1535 | (data, sw) = self.rs.card.select_adf_by_aid(p.aid) |
Harald Welte | 46a7a3f | 2022-07-16 11:47:47 +0200 | [diff] [blame] | 1536 | self.selected_adf = p |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 1537 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1538 | (data, sw) = self.rs.card._scc.select_file(p.fid) |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 1539 | self.selected_file = p |
| 1540 | except SwMatchError as swm: |
| 1541 | self._select_post(cmd_app) |
| 1542 | raise(swm) |
| 1543 | |
| 1544 | self._select_post(cmd_app) |
| 1545 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1546 | def select(self, name: str, cmd_app=None): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1547 | """Select a file (EF, DF, ADF, MF, ...). |
| 1548 | |
| 1549 | Args: |
| 1550 | name : Name of file to select |
| 1551 | cmd_app : Command Application State (for unregistering old file commands) |
| 1552 | """ |
Harald Welte | ee670bc | 2022-02-13 15:10:15 +0100 | [diff] [blame] | 1553 | # handling of entire paths with multiple directories/elements |
| 1554 | if '/' in name: |
| 1555 | prev_sel_file = self.selected_file |
| 1556 | pathlist = name.split('/') |
| 1557 | # treat /DF.GSM/foo like MF/DF.GSM/foo |
| 1558 | if pathlist[0] == '': |
| 1559 | pathlist[0] = 'MF' |
| 1560 | try: |
| 1561 | for p in pathlist: |
| 1562 | self.select(p, cmd_app) |
| 1563 | return |
| 1564 | except Exception as e: |
| 1565 | # if any intermediate step fails, go back to where we were |
| 1566 | self.select_file(prev_sel_file, cmd_app) |
| 1567 | raise e |
| 1568 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1569 | sels = self.selected_file.get_selectables() |
Philipp Maier | 7744b6e | 2021-03-11 14:29:37 +0100 | [diff] [blame] | 1570 | if is_hex(name): |
| 1571 | name = name.lower() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1572 | |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 1573 | self._select_pre(cmd_app) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1574 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1575 | if name in sels: |
| 1576 | f = sels[name] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1577 | try: |
| 1578 | if isinstance(f, CardADF): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1579 | (data, sw) = self.rs.card.select_adf_by_aid(f.aid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1580 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1581 | (data, sw) = self.rs.card._scc.select_file(f.fid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1582 | self.selected_file = f |
| 1583 | except SwMatchError as swm: |
| 1584 | k = self.interpret_sw(swm.sw_actual) |
| 1585 | if not k: |
| 1586 | raise(swm) |
| 1587 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1588 | select_resp = f.decode_select_response(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1589 | else: |
Philipp Maier | 6b8eedc | 2022-06-01 18:10:04 +0200 | [diff] [blame] | 1590 | (select_resp, data) = self.probe_file(name, cmd_app) |
| 1591 | |
Harald Welte | 2bb17f3 | 2022-02-15 15:41:55 +0100 | [diff] [blame] | 1592 | # store the raw + decoded FCP for later reference |
| 1593 | self.selected_file_fcp_hex = data |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 1594 | self.selected_file_fcp = select_resp |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1595 | |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 1596 | self._select_post(cmd_app) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 1597 | return select_resp |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1598 | |
Harald Welte | 34b05d3 | 2021-05-25 22:03:13 +0200 | [diff] [blame] | 1599 | def status(self): |
| 1600 | """Request STATUS (current selected file FCP) from card.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1601 | (data, sw) = self.rs.card._scc.status() |
Harald Welte | 34b05d3 | 2021-05-25 22:03:13 +0200 | [diff] [blame] | 1602 | return self.selected_file.decode_select_response(data) |
| 1603 | |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 1604 | def get_file_for_selectable(self, name: str): |
| 1605 | sels = self.selected_file.get_selectables() |
| 1606 | return sels[name] |
| 1607 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1608 | def activate_file(self, name: str): |
Harald Welte | 485692b | 2021-05-25 22:21:44 +0200 | [diff] [blame] | 1609 | """Request ACTIVATE FILE of specified file.""" |
| 1610 | sels = self.selected_file.get_selectables() |
| 1611 | f = sels[name] |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1612 | data, sw = self.rs.card._scc.activate_file(f.fid) |
Harald Welte | 485692b | 2021-05-25 22:21:44 +0200 | [diff] [blame] | 1613 | return data, sw |
| 1614 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1615 | def read_binary(self, length: int = None, offset: int = 0): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1616 | """Read [part of] a transparent EF binary data. |
| 1617 | |
| 1618 | Args: |
| 1619 | length : Amount of data to read (None: as much as possible) |
| 1620 | offset : Offset into the file from which to read 'length' bytes |
| 1621 | Returns: |
| 1622 | binary data read from the file |
| 1623 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1624 | if not isinstance(self.selected_file, TransparentEF): |
| 1625 | raise TypeError("Only works with TransparentEF") |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1626 | return self.rs.card._scc.read_binary(self.selected_file.fid, length, offset) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1627 | |
Harald Welte | 2d4a64b | 2021-04-03 09:01:24 +0200 | [diff] [blame] | 1628 | def read_binary_dec(self) -> Tuple[dict, str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1629 | """Read [part of] a transparent EF binary data and decode it. |
| 1630 | |
| 1631 | Args: |
| 1632 | length : Amount of data to read (None: as much as possible) |
| 1633 | offset : Offset into the file from which to read 'length' bytes |
| 1634 | Returns: |
| 1635 | abstract decode data read from the file |
| 1636 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1637 | (data, sw) = self.read_binary() |
| 1638 | dec_data = self.selected_file.decode_hex(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1639 | return (dec_data, sw) |
| 1640 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1641 | def update_binary(self, data_hex: str, offset: int = 0): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1642 | """Update transparent EF binary data. |
| 1643 | |
| 1644 | Args: |
| 1645 | data_hex : hex string of data to be written |
| 1646 | offset : Offset into the file from which to write 'data_hex' |
| 1647 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1648 | if not isinstance(self.selected_file, TransparentEF): |
| 1649 | raise TypeError("Only works with TransparentEF") |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1650 | return self.rs.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.rs.conserve_write) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1651 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1652 | def update_binary_dec(self, data: dict): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1653 | """Update transparent EF from abstract data. Encodes the data to binary and |
| 1654 | then updates the EF with it. |
| 1655 | |
| 1656 | Args: |
| 1657 | data : abstract data which is to be encoded and written |
| 1658 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1659 | data_hex = self.selected_file.encode_hex(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1660 | return self.update_binary(data_hex) |
| 1661 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1662 | def read_record(self, rec_nr: int = 0): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1663 | """Read a record as binary data. |
| 1664 | |
| 1665 | Args: |
| 1666 | rec_nr : Record number to read |
| 1667 | Returns: |
| 1668 | hex string of binary data contained in record |
| 1669 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1670 | if not isinstance(self.selected_file, LinFixedEF): |
| 1671 | raise TypeError("Only works with Linear Fixed EF") |
| 1672 | # returns a string of hex nibbles |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1673 | return self.rs.card._scc.read_record(self.selected_file.fid, rec_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1674 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1675 | def read_record_dec(self, rec_nr: int = 0) -> Tuple[dict, str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1676 | """Read a record and decode it to abstract data. |
| 1677 | |
| 1678 | Args: |
| 1679 | rec_nr : Record number to read |
| 1680 | Returns: |
| 1681 | abstract data contained in record |
| 1682 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1683 | (data, sw) = self.read_record(rec_nr) |
| 1684 | return (self.selected_file.decode_record_hex(data), sw) |
| 1685 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1686 | def update_record(self, rec_nr: int, data_hex: str): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1687 | """Update a record with given binary data |
| 1688 | |
| 1689 | Args: |
| 1690 | rec_nr : Record number to read |
| 1691 | data_hex : Hex string binary data to be written |
| 1692 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1693 | if not isinstance(self.selected_file, LinFixedEF): |
| 1694 | raise TypeError("Only works with Linear Fixed EF") |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1695 | return self.rs.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex, conserve=self.rs.conserve_write) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1696 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1697 | def update_record_dec(self, rec_nr: int, data: dict): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1698 | """Update a record with given abstract data. Will encode abstract to binary data |
| 1699 | and then write it to the given record on the card. |
| 1700 | |
| 1701 | Args: |
| 1702 | rec_nr : Record number to read |
| 1703 | data_hex : Abstract data to be written |
| 1704 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1705 | data_hex = self.selected_file.encode_record_hex(data) |
| 1706 | return self.update_record(rec_nr, data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1707 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1708 | def retrieve_data(self, tag: int = 0): |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1709 | """Read a DO/TLV as binary data. |
| 1710 | |
| 1711 | Args: |
| 1712 | tag : Tag of TLV/DO to read |
| 1713 | Returns: |
| 1714 | hex string of full BER-TLV DO including Tag and Length |
| 1715 | """ |
| 1716 | if not isinstance(self.selected_file, BerTlvEF): |
| 1717 | raise TypeError("Only works with BER-TLV EF") |
| 1718 | # returns a string of hex nibbles |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1719 | return self.rs.card._scc.retrieve_data(self.selected_file.fid, tag) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1720 | |
| 1721 | def retrieve_tags(self): |
| 1722 | """Retrieve tags available on BER-TLV EF. |
| 1723 | |
| 1724 | Returns: |
| 1725 | list of integer tags contained in EF |
| 1726 | """ |
| 1727 | if not isinstance(self.selected_file, BerTlvEF): |
| 1728 | raise TypeError("Only works with BER-TLV EF") |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1729 | data, sw = self.rs.card._scc.retrieve_data(self.selected_file.fid, 0x5c) |
Harald Welte | c147530 | 2021-05-21 21:47:55 +0200 | [diff] [blame] | 1730 | tag, length, value, remainder = bertlv_parse_one(h2b(data)) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1731 | return list(value) |
| 1732 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1733 | def set_data(self, tag: int, data_hex: str): |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1734 | """Update a TLV/DO with given binary data |
| 1735 | |
| 1736 | Args: |
| 1737 | tag : Tag of TLV/DO to be written |
| 1738 | data_hex : Hex string binary data to be written (value portion) |
| 1739 | """ |
| 1740 | if not isinstance(self.selected_file, BerTlvEF): |
| 1741 | raise TypeError("Only works with BER-TLV EF") |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1742 | return self.rs.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.rs.conserve_write) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1743 | |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 1744 | def unregister_cmds(self, cmd_app=None): |
| 1745 | """Unregister all file specific commands.""" |
| 1746 | if cmd_app and self.selected_file.shell_commands: |
| 1747 | for c in self.selected_file.shell_commands: |
| 1748 | cmd_app.unregister_command_set(c) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1749 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1750 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 1751 | class FileData: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1752 | """Represent the runtime, on-card data.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1753 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1754 | def __init__(self, fdesc): |
| 1755 | self.desc = fdesc |
| 1756 | self.fcp = None |
| 1757 | |
| 1758 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1759 | def interpret_sw(sw_data: dict, sw: str): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1760 | """Interpret a given status word. |
| 1761 | |
| 1762 | Args: |
| 1763 | sw_data : Hierarchical dict of status word matches |
| 1764 | sw : status word to match (string of 4 hex digits) |
| 1765 | Returns: |
| 1766 | tuple of two strings (class_string, description) |
| 1767 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1768 | for class_str, swdict in sw_data.items(): |
| 1769 | # first try direct match |
| 1770 | if sw in swdict: |
| 1771 | return (class_str, swdict[sw]) |
| 1772 | # next try wildcard matches |
| 1773 | for pattern, descr in swdict.items(): |
| 1774 | if sw_match(sw, pattern): |
| 1775 | return (class_str, descr) |
| 1776 | return None |
| 1777 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1778 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 1779 | class CardApplication: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1780 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 1781 | some SW definitions.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1782 | |
| 1783 | def __init__(self, name, adf: Optional[CardADF] = None, aid: str = None, sw: dict = None): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1784 | """ |
| 1785 | Args: |
| 1786 | adf : ADF name |
| 1787 | sw : Dict of status word conversions |
| 1788 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1789 | self.name = name |
| 1790 | self.adf = adf |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1791 | self.sw = sw or dict() |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1792 | # back-reference from ADF to Applicaiton |
| 1793 | if self.adf: |
| 1794 | self.aid = aid or self.adf.aid |
| 1795 | self.adf.application = self |
| 1796 | else: |
| 1797 | self.aid = aid |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1798 | |
| 1799 | def __str__(self): |
| 1800 | return "APP(%s)" % (self.name) |
| 1801 | |
| 1802 | def interpret_sw(self, sw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1803 | """Interpret a given status word within the application. |
| 1804 | |
| 1805 | Args: |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1806 | sw : Status word as string of 4 hex digits |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1807 | |
| 1808 | Returns: |
| 1809 | Tuple of two strings |
| 1810 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1811 | return interpret_sw(self.sw, sw) |
| 1812 | |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1813 | |
| 1814 | class CardModel(abc.ABC): |
Harald Welte | 4c1dca0 | 2021-10-14 17:48:25 +0200 | [diff] [blame] | 1815 | """A specific card model, typically having some additional vendor-specific files. All |
| 1816 | you need to do is to define a sub-class with a list of ATRs or an overridden match |
| 1817 | method.""" |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1818 | _atrs = [] |
| 1819 | |
| 1820 | @classmethod |
| 1821 | @abc.abstractmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1822 | def add_files(cls, rs: RuntimeState): |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1823 | """Add model specific files to given RuntimeState.""" |
| 1824 | |
| 1825 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1826 | def match(cls, scc: SimCardCommands) -> bool: |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1827 | """Test if given card matches this model.""" |
| 1828 | card_atr = scc.get_atr() |
| 1829 | for atr in cls._atrs: |
| 1830 | atr_bin = toBytes(atr) |
| 1831 | if atr_bin == card_atr: |
| 1832 | print("Detected CardModel:", cls.__name__) |
| 1833 | return True |
| 1834 | return False |
| 1835 | |
| 1836 | @staticmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1837 | def apply_matching_models(scc: SimCardCommands, rs: RuntimeState): |
Harald Welte | 4c1dca0 | 2021-10-14 17:48:25 +0200 | [diff] [blame] | 1838 | """Check if any of the CardModel sub-classes 'match' the currently inserted card |
| 1839 | (by ATR or overriding the 'match' method). If so, call their 'add_files' |
| 1840 | method.""" |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1841 | for m in CardModel.__subclasses__(): |
| 1842 | if m.match(scc): |
| 1843 | m.add_files(rs) |