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