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