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