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