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