Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1 | # coding=utf-8 |
| 2 | """Representation of the ISO7816-4 filesystem model. |
| 3 | |
| 4 | The File (and its derived classes) represent the structure / hierarchy |
| 5 | of the ISO7816-4 smart card file system with the MF, DF, EF and ADF |
| 6 | entries, further sub-divided into the EF sub-types Transparent, Linear Fixed, etc. |
| 7 | |
| 8 | The classes are intended to represent the *specification* of the filesystem, |
| 9 | not the actual contents / runtime state of interacting with a given smart card. |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 10 | """ |
| 11 | |
Harald Welte | 5a4fd52 | 2021-04-02 16:05:26 +0200 | [diff] [blame] | 12 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 13 | # |
| 14 | # This program is free software: you can redistribute it and/or modify |
| 15 | # it under the terms of the GNU General Public License as published by |
| 16 | # the Free Software Foundation, either version 2 of the License, or |
| 17 | # (at your option) any later version. |
| 18 | # |
| 19 | # This program is distributed in the hope that it will be useful, |
| 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 | # GNU General Public License for more details. |
| 23 | # |
| 24 | # You should have received a copy of the GNU General Public License |
| 25 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 26 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 27 | import code |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 28 | import tempfile |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 29 | import json |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 30 | import abc |
| 31 | import inspect |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 32 | |
| 33 | import cmd2 |
| 34 | from cmd2 import CommandSet, with_default_category, with_argparser |
| 35 | import argparse |
| 36 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 37 | from typing import cast, Optional, Iterable, List, Dict, Tuple, Union |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 38 | |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 39 | from smartcard.util import toBytes |
| 40 | |
Harald Welte | daf2b39 | 2021-05-03 23:17:29 +0200 | [diff] [blame] | 41 | from pySim.utils import sw_match, h2b, b2h, i2h, is_hex, auto_int, bertlv_parse_one, Hexstr |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 42 | from pySim.construct import filter_dict, parse_construct |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 43 | from pySim.exceptions import * |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 44 | from pySim.jsonpath import js_path_find, js_path_modify |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 45 | from pySim.commands import SimCardCommands |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 46 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 47 | # int: a single service is associated with this file |
| 48 | # list: any of the listed services requires this file |
| 49 | # tuple: logical-and of the listed services requires this file |
| 50 | CardFileService = Union[int, List[int], Tuple[int, ...]] |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 51 | |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 52 | Size = Tuple[int, Optional[int]] |
| 53 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 54 | class CardFile: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 55 | """Base class for all objects in the smart card filesystem. |
| 56 | Serve as a common ancestor to all other file types; rarely used directly. |
| 57 | """ |
| 58 | RESERVED_NAMES = ['..', '.', '/', 'MF'] |
| 59 | RESERVED_FIDS = ['3f00'] |
| 60 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 61 | 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] | 62 | parent: Optional['CardDF'] = None, profile: Optional['CardProfile'] = None, |
| 63 | service: Optional[CardFileService] = None): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 64 | """ |
| 65 | Args: |
| 66 | fid : File Identifier (4 hex digits) |
| 67 | sfid : Short File Identifier (2 hex digits, optional) |
| 68 | name : Brief name of the file, lik EF_ICCID |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 69 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 70 | parent : Parent CardFile object within filesystem hierarchy |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 71 | profile : Card profile that this file should be part of |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 72 | service : Service (SST/UST/IST) associated with the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 73 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 74 | if not isinstance(self, CardADF) and fid == None: |
| 75 | raise ValueError("fid is mandatory") |
| 76 | if fid: |
| 77 | fid = fid.lower() |
| 78 | self.fid = fid # file identifier |
| 79 | self.sfid = sfid # short file identifier |
| 80 | self.name = name # human readable name |
| 81 | self.desc = desc # human readable description |
| 82 | self.parent = parent |
| 83 | if self.parent and self.parent != self and self.fid: |
| 84 | self.parent.add_file(self) |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 85 | self.profile = profile |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 86 | self.service = service |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 87 | self.shell_commands = [] # type: List[CommandSet] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 88 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 89 | # Note: the basic properties (fid, name, ect.) are verified when |
| 90 | # the file is attached to a parent file. See method add_file() in |
| 91 | # class Card DF |
Philipp Maier | 6606158 | 2021-03-09 21:57:57 +0100 | [diff] [blame] | 92 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 93 | def __str__(self): |
| 94 | if self.name: |
| 95 | return self.name |
| 96 | else: |
| 97 | return self.fid |
| 98 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 99 | def _path_element(self, prefer_name: bool) -> Optional[str]: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 100 | if prefer_name and self.name: |
| 101 | return self.name |
| 102 | else: |
| 103 | return self.fid |
| 104 | |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 105 | def fully_qualified_path_str(self, prefer_name: bool = True) -> str: |
| 106 | """Return fully qualified path to file as string. |
| 107 | |
| 108 | Args: |
| 109 | prefer_name : Preferably build path of names; fall-back to FIDs as required |
| 110 | """ |
| 111 | return '/'.join(self.fully_qualified_path(prefer_name)) |
| 112 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 113 | def fully_qualified_path(self, prefer_name: bool = True) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 114 | """Return fully qualified path to file as list of FID or name strings. |
| 115 | |
| 116 | Args: |
| 117 | prefer_name : Preferably build path of names; fall-back to FIDs as required |
| 118 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 119 | if self.parent and self.parent != self: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 120 | ret = self.parent.fully_qualified_path(prefer_name) |
| 121 | else: |
| 122 | ret = [] |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 123 | elem = self._path_element(prefer_name) |
| 124 | if elem: |
| 125 | ret.append(elem) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 126 | return ret |
| 127 | |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 128 | def fully_qualified_path_fobj(self) -> List['CardFile']: |
| 129 | """Return fully qualified path to file as list of CardFile instance references.""" |
| 130 | if self.parent and self.parent != self: |
| 131 | ret = self.parent.fully_qualified_path_fobj() |
| 132 | else: |
| 133 | ret = [] |
| 134 | if self: |
| 135 | ret.append(self) |
| 136 | return ret |
| 137 | |
| 138 | def build_select_path_to(self, target: 'CardFile') -> Optional[List['CardFile']]: |
| 139 | """Build the relative sequence of files we need to traverse to get from us to 'target'.""" |
Harald Welte | 02a7f74 | 2023-07-11 09:21:52 +0200 | [diff] [blame] | 140 | # special-case handling for selecting MF while we MF is selected |
| 141 | if target == target.get_mf(): |
| 142 | return [target] |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 143 | cur_fqpath = self.fully_qualified_path_fobj() |
| 144 | target_fqpath = target.fully_qualified_path_fobj() |
| 145 | inter_path = [] |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 146 | cur_fqpath.reverse() |
| 147 | for ce in cur_fqpath: |
| 148 | inter_path.append(ce) |
| 149 | for i in range(0, len(target_fqpath)-1): |
| 150 | te = target_fqpath[i] |
| 151 | if te == ce: |
| 152 | for te2 in target_fqpath[i+1:]: |
| 153 | inter_path.append(te2) |
| 154 | # we found our common ancestor |
Philipp Maier | a24755e | 2023-10-31 16:04:29 +0100 | [diff] [blame] | 155 | return inter_path[1:] |
Harald Welte | aceb2a5 | 2022-02-12 21:41:59 +0100 | [diff] [blame] | 156 | return None |
| 157 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 158 | def get_mf(self) -> Optional['CardMF']: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 159 | """Return the MF (root) of the file system.""" |
| 160 | if self.parent == None: |
| 161 | return None |
| 162 | # iterate towards the top. MF has parent == self |
| 163 | node = self |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 164 | while node.parent and node.parent != node: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 165 | node = node.parent |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 166 | return cast(CardMF, node) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 167 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 168 | def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 169 | """Return a dict of {'identifier': self} tuples. |
| 170 | |
| 171 | Args: |
| 172 | alias : Add an alias with given name to 'self' |
| 173 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 174 | If not specified, all selectables will be returned. |
| 175 | Returns: |
| 176 | dict containing reference to 'self' for all identifiers. |
| 177 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 178 | sels = {} |
| 179 | if alias: |
| 180 | sels.update({alias: self}) |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 181 | if self.fid and (flags == [] or 'FIDS' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 182 | sels.update({self.fid: self}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 183 | if self.name and (flags == [] or 'FNAMES' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 184 | sels.update({self.name: self}) |
| 185 | return sels |
| 186 | |
Harald Welte | f5ff1b8 | 2022-07-24 12:19:57 +0200 | [diff] [blame] | 187 | def _get_parent_selectables(self, alias: Optional[str] = None, flags=[]) -> Dict[str, 'CardFile']: |
| 188 | sels = {} |
| 189 | if not self.parent or self.parent == self: |
| 190 | return sels |
| 191 | # add our immediate parent |
| 192 | if alias: |
| 193 | sels.update({alias: self.parent}) |
| 194 | if self.parent.fid and (flags == [] or 'FIDS' in flags): |
| 195 | sels.update({self.parent.fid: self.parent}) |
| 196 | if self.parent.name and (flags == [] or 'FNAMES' in flags): |
| 197 | sels.update({self.parent.name: self.parent}) |
| 198 | # recurse to parents of our parent, but without any alias |
| 199 | sels.update(self.parent._get_parent_selectables(None, flags)) |
| 200 | return sels |
| 201 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 202 | def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 203 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 204 | |
| 205 | Args: |
| 206 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 207 | If not specified, all selectables will be returned. |
| 208 | Returns: |
| 209 | dict containing all selectable items. Key is identifier (string), value |
| 210 | a reference to a CardFile (or derived class) instance. |
| 211 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 212 | sels = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 213 | # we can always select ourself |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 214 | if flags == [] or 'SELF' in flags: |
| 215 | sels = self._get_self_selectables('.', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 216 | # we can always select our parent |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 217 | if flags == [] or 'PARENT' in flags: |
Harald Welte | f5ff1b8 | 2022-07-24 12:19:57 +0200 | [diff] [blame] | 218 | sels.update(self._get_parent_selectables('..', flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 219 | # if we have a MF, we can always select its applications |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 220 | if flags == [] or 'MF' in flags: |
| 221 | mf = self.get_mf() |
| 222 | if mf: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 223 | sels.update(mf._get_self_selectables(flags=flags)) |
| 224 | sels.update(mf.get_app_selectables(flags=flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 225 | return sels |
| 226 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 227 | def get_selectable_names(self, flags=[]) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 228 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 229 | |
| 230 | Args: |
| 231 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 232 | If not specified, all selectables will be returned. |
| 233 | Returns: |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 234 | list containing all selectable names. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 235 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 236 | sels = self.get_selectables(flags) |
Harald Welte | b3d68c0 | 2022-01-21 15:31:29 +0100 | [diff] [blame] | 237 | sel_keys = list(sels.keys()) |
| 238 | sel_keys.sort() |
| 239 | return sel_keys |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 240 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 241 | def decode_select_response(self, data_hex: str): |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 242 | """Decode the response to a SELECT command. |
| 243 | |
| 244 | Args: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 245 | data_hex: Hex string of the select response |
| 246 | """ |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 247 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 248 | # When the current file does not implement a custom select response decoder, |
| 249 | # we just ask the parent file to decode the select response. If this method |
| 250 | # is not overloaded by the current file we will again ask the parent file. |
| 251 | # This way we recursively travel up the file system tree until we hit a file |
| 252 | # that does implement a concrete decoder. |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 253 | if self.parent: |
| 254 | return self.parent.decode_select_response(data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 255 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 256 | def get_profile(self): |
| 257 | """Get the profile associated with this file. If this file does not have any |
| 258 | profile assigned, try to find a file above (usually the MF) in the filesystem |
| 259 | hirarchy that has a profile assigned |
| 260 | """ |
| 261 | |
| 262 | # If we have a profile set, return it |
| 263 | if self.profile: |
| 264 | return self.profile |
| 265 | |
| 266 | # Walk up recursively until we hit a parent that has a profile set |
| 267 | if self.parent: |
| 268 | return self.parent.get_profile() |
| 269 | return None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 270 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 271 | def should_exist_for_services(self, services: List[int]): |
| 272 | """Assuming the provided list of activated services, should this file exist and be activated?.""" |
| 273 | if self.service is None: |
| 274 | return None |
| 275 | elif isinstance(self.service, int): |
| 276 | # a single service determines the result |
| 277 | return self.service in services |
| 278 | elif isinstance(self.service, list): |
| 279 | # any of the services active -> true |
| 280 | for s in self.service: |
| 281 | if s in services: |
| 282 | return True |
| 283 | return False |
| 284 | elif isinstance(self.service, tuple): |
| 285 | # all of the services active -> true |
| 286 | for s in self.service: |
| 287 | if not s in services: |
| 288 | return False |
| 289 | return True |
| 290 | else: |
| 291 | raise ValueError("self.service must be either int or list or tuple") |
| 292 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 293 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 294 | class CardDF(CardFile): |
| 295 | """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] | 296 | |
| 297 | @with_default_category('DF/ADF Commands') |
| 298 | class ShellCommands(CommandSet): |
| 299 | def __init__(self): |
| 300 | super().__init__() |
| 301 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 302 | def __init__(self, **kwargs): |
| 303 | if not isinstance(self, CardADF): |
| 304 | if not 'fid' in kwargs: |
| 305 | raise TypeError('fid is mandatory for all DF') |
| 306 | super().__init__(**kwargs) |
| 307 | self.children = dict() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 308 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 309 | # dict of CardFile affected by service(int), indexed by service |
| 310 | self.files_by_service = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 311 | |
| 312 | def __str__(self): |
| 313 | return "DF(%s)" % (super().__str__()) |
| 314 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 315 | def _add_file_services(self, child): |
| 316 | """Add a child (DF/EF) to the files_by_services of the parent.""" |
| 317 | if not child.service: |
| 318 | return |
| 319 | if isinstance(child.service, int): |
| 320 | self.files_by_service.setdefault(child.service, []).append(child) |
| 321 | elif isinstance(child.service, list): |
| 322 | for service in child.service: |
| 323 | self.files_by_service.setdefault(service, []).append(child) |
| 324 | elif isinstance(child.service, tuple): |
| 325 | for service in child.service: |
| 326 | self.files_by_service.setdefault(service, []).append(child) |
| 327 | else: |
| 328 | raise ValueError |
| 329 | |
Harald Welte | d56f45d | 2022-07-16 11:46:59 +0200 | [diff] [blame] | 330 | def _has_service(self): |
| 331 | if self.service: |
| 332 | return True |
| 333 | for c in self.children.values(): |
| 334 | if isinstance(c, CardDF): |
| 335 | if c._has_service(): |
| 336 | return True |
| 337 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 338 | def add_file(self, child: CardFile, ignore_existing: bool = False): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 339 | """Add a child (DF/EF) to this DF. |
| 340 | Args: |
| 341 | child: The new DF/EF to be added |
| 342 | ignore_existing: Ignore, if file with given FID already exists. Old one will be kept. |
| 343 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 344 | if not isinstance(child, CardFile): |
| 345 | raise TypeError("Expected a File instance") |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 346 | if not is_hex(child.fid, minlen=4, maxlen=4): |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 347 | raise ValueError("File name %s is not a valid fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 348 | if child.name in CardFile.RESERVED_NAMES: |
| 349 | raise ValueError("File name %s is a reserved name" % (child.name)) |
| 350 | if child.fid in CardFile.RESERVED_FIDS: |
Philipp Maier | e8bc1b4 | 2021-03-09 20:33:41 +0100 | [diff] [blame] | 351 | raise ValueError("File fid %s is a reserved fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 352 | if child.fid in self.children: |
| 353 | if ignore_existing: |
| 354 | return |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 355 | raise ValueError( |
| 356 | "File with given fid %s already exists in %s" % (child.fid, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 357 | if self.lookup_file_by_sfid(child.sfid): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 358 | raise ValueError( |
| 359 | "File with given sfid %s already exists in %s" % (child.sfid, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 360 | if self.lookup_file_by_name(child.name): |
| 361 | if ignore_existing: |
| 362 | return |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 363 | raise ValueError( |
| 364 | "File with given name %s already exists in %s" % (child.name, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 365 | self.children[child.fid] = child |
| 366 | child.parent = self |
Harald Welte | 419bb49 | 2022-02-12 21:39:35 +0100 | [diff] [blame] | 367 | # update the service -> file relationship table |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 368 | self._add_file_services(child) |
Harald Welte | 419bb49 | 2022-02-12 21:39:35 +0100 | [diff] [blame] | 369 | if isinstance(child, CardDF): |
| 370 | for c in child.children.values(): |
| 371 | self._add_file_services(c) |
| 372 | if isinstance(c, CardDF): |
Harald Welte | d56f45d | 2022-07-16 11:46:59 +0200 | [diff] [blame] | 373 | for gc in c.children.values(): |
| 374 | if isinstance(gc, CardDF): |
| 375 | if gc._has_service(): |
| 376 | raise ValueError('TODO: implement recursive service -> file mapping') |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 377 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 378 | def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 379 | """Add a list of child (DF/EF) to this DF |
| 380 | |
| 381 | Args: |
| 382 | children: List of new DF/EFs to be added |
| 383 | ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept. |
| 384 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 385 | for child in children: |
| 386 | self.add_file(child, ignore_existing) |
| 387 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 388 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 389 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 390 | |
| 391 | Args: |
| 392 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 393 | If not specified, all selectables will be returned. |
| 394 | Returns: |
| 395 | dict containing all selectable items. Key is identifier (string), value |
| 396 | a reference to a CardFile (or derived class) instance. |
| 397 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 398 | # global selectables + our children |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 399 | sels = super().get_selectables(flags) |
| 400 | if flags == [] or 'FIDS' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 401 | 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] | 402 | if flags == [] or 'FNAMES' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 403 | 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] | 404 | return sels |
| 405 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 406 | def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 407 | """Find a file with given name within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 408 | if name == None: |
| 409 | return None |
| 410 | for i in self.children.values(): |
| 411 | if i.name and i.name == name: |
| 412 | return i |
| 413 | return None |
| 414 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 415 | def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 416 | """Find a file with given short file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 417 | if sfid == None: |
| 418 | return None |
| 419 | for i in self.children.values(): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 420 | if i.sfid == int(str(sfid)): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 421 | return i |
| 422 | return None |
| 423 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 424 | def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 425 | """Find a file with given file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 426 | if fid in self.children: |
| 427 | return self.children[fid] |
| 428 | return None |
| 429 | |
| 430 | |
| 431 | class CardMF(CardDF): |
| 432 | """MF (Master File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 433 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 434 | def __init__(self, **kwargs): |
| 435 | # can be overridden; use setdefault |
| 436 | kwargs.setdefault('fid', '3f00') |
| 437 | kwargs.setdefault('name', 'MF') |
| 438 | kwargs.setdefault('desc', 'Master File (directory root)') |
| 439 | # cannot be overridden; use assignment |
| 440 | kwargs['parent'] = self |
| 441 | super().__init__(**kwargs) |
| 442 | self.applications = dict() |
| 443 | |
| 444 | def __str__(self): |
| 445 | return "MF(%s)" % (self.fid) |
| 446 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 447 | def add_application_df(self, app: 'CardADF'): |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 448 | """Add an Application to the MF""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 449 | if not isinstance(app, CardADF): |
| 450 | raise TypeError("Expected an ADF instance") |
| 451 | if app.aid in self.applications: |
| 452 | raise ValueError("AID %s already exists" % (app.aid)) |
| 453 | self.applications[app.aid] = app |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 454 | app.parent = self |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 455 | |
| 456 | def get_app_names(self): |
| 457 | """Get list of completions (AID names)""" |
Harald Welte | d53918c | 2022-02-12 18:20:49 +0100 | [diff] [blame] | 458 | return list(self.applications.values()) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 459 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 460 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 461 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 462 | |
| 463 | Args: |
| 464 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 465 | If not specified, all selectables will be returned. |
| 466 | Returns: |
| 467 | dict containing all selectable items. Key is identifier (string), value |
| 468 | a reference to a CardFile (or derived class) instance. |
| 469 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 470 | sels = super().get_selectables(flags) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 471 | sels.update(self.get_app_selectables(flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 472 | return sels |
| 473 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 474 | def get_app_selectables(self, flags=[]) -> dict: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 475 | """Get applications by AID + name""" |
| 476 | sels = {} |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 477 | if flags == [] or 'AIDS' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 478 | sels.update({x.aid: x for x in self.applications.values()}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 479 | if flags == [] or 'ANAMES' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 480 | sels.update( |
| 481 | {x.name: x for x in self.applications.values() if x.name}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 482 | return sels |
| 483 | |
Harald Welte | c975251 | 2022-02-11 16:31:15 +0100 | [diff] [blame] | 484 | def decode_select_response(self, data_hex: Optional[str]) -> object: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 485 | """Decode the response to a SELECT command. |
| 486 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 487 | This is the fall-back method which automatically defers to the standard decoding |
| 488 | 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] | 489 | performed. Specific derived classes (usually ADF) can overload this method to |
| 490 | install specific decoding. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 491 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 492 | |
Harald Welte | c975251 | 2022-02-11 16:31:15 +0100 | [diff] [blame] | 493 | if not data_hex: |
| 494 | return data_hex |
| 495 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 496 | profile = self.get_profile() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 497 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 498 | if profile: |
| 499 | return profile.decode_select_response(data_hex) |
| 500 | else: |
| 501 | return data_hex |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 502 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 503 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 504 | class CardADF(CardDF): |
| 505 | """ADF (Application Dedicated File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 506 | |
Philipp Maier | a1850ae | 2023-10-25 18:05:09 +0200 | [diff] [blame] | 507 | def __init__(self, aid: str, has_fs: bool=False, **kwargs): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 508 | super().__init__(**kwargs) |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 509 | # reference to CardApplication may be set from CardApplication constructor |
Harald Welte | fe8a744 | 2021-04-10 11:51:54 +0200 | [diff] [blame] | 510 | self.application = None # type: Optional[CardApplication] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 511 | self.aid = aid # Application Identifier |
Philipp Maier | a1850ae | 2023-10-25 18:05:09 +0200 | [diff] [blame] | 512 | self.has_fs = has_fs # Flag to tell whether the ADF supports a filesystem or not |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 513 | mf = self.get_mf() |
| 514 | if mf: |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 515 | mf.add_application_df(self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 516 | |
| 517 | def __str__(self): |
Harald Welte | 4b00365 | 2022-07-16 11:55:07 +0200 | [diff] [blame] | 518 | return "ADF(%s)" % (self.name if self.name else self.aid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 519 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 520 | def _path_element(self, prefer_name: bool): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 521 | if self.name and prefer_name: |
| 522 | return self.name |
| 523 | else: |
| 524 | return self.aid |
| 525 | |
| 526 | |
| 527 | class CardEF(CardFile): |
| 528 | """EF (Entry File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 529 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 530 | def __init__(self, *, fid, **kwargs): |
| 531 | kwargs['fid'] = fid |
| 532 | super().__init__(**kwargs) |
| 533 | |
| 534 | def __str__(self): |
| 535 | return "EF(%s)" % (super().__str__()) |
| 536 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 537 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 538 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 539 | |
| 540 | Args: |
| 541 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 542 | If not specified, all selectables will be returned. |
| 543 | Returns: |
| 544 | dict containing all selectable items. Key is identifier (string), value |
| 545 | a reference to a CardFile (or derived class) instance. |
| 546 | """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 547 | # global selectable names + those of the parent DF |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 548 | sels = super().get_selectables(flags) |
Harald Welte | d2c177b | 2022-07-24 11:35:53 +0200 | [diff] [blame] | 549 | if flags == [] or 'FIDS' in flags: |
| 550 | sels.update({x.fid: x for x in self.parent.children.values() if x.fid and x != self}) |
| 551 | if flags == [] or 'FNAMES' in flags: |
| 552 | sels.update({x.name: x for x in self.parent.children.values() if x.name and x != self}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 553 | return sels |
| 554 | |
| 555 | |
| 556 | class TransparentEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 557 | """Transparent EF (Entry File) in the smart card filesystem. |
| 558 | |
| 559 | A Transparent EF is a binary file with no formal structure. This is contrary to |
| 560 | 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] | 561 | |
| 562 | @with_default_category('Transparent EF Commands') |
| 563 | class ShellCommands(CommandSet): |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 564 | """Shell commands specific for transparent EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 565 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 566 | def __init__(self): |
| 567 | super().__init__() |
| 568 | |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 569 | dec_hex_parser = argparse.ArgumentParser() |
| 570 | dec_hex_parser.add_argument('--oneline', action='store_true', |
| 571 | help='No JSON pretty-printing, dump as a single line') |
| 572 | dec_hex_parser.add_argument('HEXSTR', help='Hex-string of encoded data to decode') |
| 573 | |
| 574 | @cmd2.with_argparser(dec_hex_parser) |
| 575 | def do_decode_hex(self, opts): |
| 576 | """Decode command-line provided hex-string as if it was read from the file.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 577 | data = self._cmd.lchan.selected_file.decode_hex(opts.HEXSTR) |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 578 | self._cmd.poutput_json(data, opts.oneline) |
| 579 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 580 | read_bin_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 581 | read_bin_parser.add_argument( |
| 582 | '--offset', type=int, default=0, help='Byte offset for start of read') |
| 583 | read_bin_parser.add_argument( |
| 584 | '--length', type=int, help='Number of bytes to read') |
| 585 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 586 | @cmd2.with_argparser(read_bin_parser) |
| 587 | def do_read_binary(self, opts): |
| 588 | """Read binary data from a transparent EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 589 | (data, sw) = self._cmd.lchan.read_binary(opts.length, opts.offset) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 590 | self._cmd.poutput(data) |
| 591 | |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame] | 592 | read_bin_dec_parser = argparse.ArgumentParser() |
| 593 | read_bin_dec_parser.add_argument('--oneline', action='store_true', |
| 594 | help='No JSON pretty-printing, dump as a single line') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 595 | |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame] | 596 | @cmd2.with_argparser(read_bin_dec_parser) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 597 | def do_read_binary_decoded(self, opts): |
| 598 | """Read + decode data from a transparent EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 599 | (data, sw) = self._cmd.lchan.read_binary_dec() |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 600 | self._cmd.poutput_json(data, opts.oneline) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 601 | |
| 602 | upd_bin_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 603 | upd_bin_parser.add_argument( |
| 604 | '--offset', type=int, default=0, help='Byte offset for start of read') |
| 605 | upd_bin_parser.add_argument( |
| 606 | 'data', help='Data bytes (hex format) to write') |
| 607 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 608 | @cmd2.with_argparser(upd_bin_parser) |
| 609 | def do_update_binary(self, opts): |
| 610 | """Update (Write) data of a transparent EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 611 | (data, sw) = self._cmd.lchan.update_binary(opts.data, opts.offset) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 612 | if data: |
| 613 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 614 | |
| 615 | upd_bin_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 616 | upd_bin_dec_parser.add_argument( |
| 617 | 'data', help='Abstract data (JSON format) to write') |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 618 | upd_bin_dec_parser.add_argument('--json-path', type=str, |
| 619 | help='JSON path to modify specific element of file only') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 620 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 621 | @cmd2.with_argparser(upd_bin_dec_parser) |
| 622 | def do_update_binary_decoded(self, opts): |
| 623 | """Encode + Update (Write) data of a transparent EF""" |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 624 | if opts.json_path: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 625 | (data_json, sw) = self._cmd.lchan.read_binary_dec() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 626 | js_path_modify(data_json, opts.json_path, |
| 627 | json.loads(opts.data)) |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 628 | else: |
| 629 | data_json = json.loads(opts.data) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 630 | (data, sw) = self._cmd.lchan.update_binary_dec(data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 631 | if data: |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 632 | self._cmd.poutput_json(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 633 | |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 634 | def do_edit_binary_decoded(self, opts): |
| 635 | """Edit the JSON representation of the EF contents in an editor.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 636 | (orig_json, sw) = self._cmd.lchan.read_binary_dec() |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 637 | with tempfile.TemporaryDirectory(prefix='pysim_') as dirname: |
| 638 | filename = '%s/file' % dirname |
| 639 | # write existing data as JSON to file |
| 640 | with open(filename, 'w') as text_file: |
| 641 | json.dump(orig_json, text_file, indent=4) |
| 642 | # run a text editor |
Harald Welte | e126872 | 2023-06-24 07:57:08 +0200 | [diff] [blame] | 643 | self._cmd.run_editor(filename) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 644 | with open(filename, 'r') as text_file: |
| 645 | edited_json = json.load(text_file) |
| 646 | if edited_json == orig_json: |
| 647 | self._cmd.poutput("Data not modified, skipping write") |
| 648 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 649 | (data, sw) = self._cmd.lchan.update_binary_dec(edited_json) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 650 | if data: |
| 651 | self._cmd.poutput_json(data) |
| 652 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 653 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 654 | size: Size = (1, None), **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 655 | """ |
| 656 | Args: |
| 657 | fid : File Identifier (4 hex digits) |
| 658 | sfid : Short File Identifier (2 hex digits, optional) |
| 659 | name : Brief name of the file, lik EF_ICCID |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 660 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 661 | parent : Parent CardFile object within filesystem hierarchy |
| 662 | size : tuple of (minimum_size, recommended_size) |
| 663 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 664 | 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] | 665 | self._construct = None |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 666 | self._tlv = None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 667 | self.size = size |
| 668 | self.shell_commands = [self.ShellCommands()] |
| 669 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 670 | def decode_bin(self, raw_bin_data: bytearray) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 671 | """Decode raw (binary) data into abstract representation. |
| 672 | |
| 673 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 674 | for implementing this specifically for the given file. This function checks which |
| 675 | of the method exists, add calls them (with conversion, as needed). |
| 676 | |
| 677 | Args: |
| 678 | raw_bin_data : binary encoded data |
| 679 | Returns: |
| 680 | abstract_data; dict representing the decoded data |
| 681 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 682 | method = getattr(self, '_decode_bin', None) |
| 683 | if callable(method): |
| 684 | return method(raw_bin_data) |
| 685 | method = getattr(self, '_decode_hex', None) |
| 686 | if callable(method): |
| 687 | return method(b2h(raw_bin_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 688 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 689 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 690 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 691 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 692 | t.from_tlv(raw_bin_data) |
| 693 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 694 | return {'raw': raw_bin_data.hex()} |
| 695 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 696 | def decode_hex(self, raw_hex_data: str) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 697 | """Decode raw (hex string) data into abstract representation. |
| 698 | |
| 699 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 700 | for implementing this specifically for the given file. This function checks which |
| 701 | of the method exists, add calls them (with conversion, as needed). |
| 702 | |
| 703 | Args: |
| 704 | raw_hex_data : hex-encoded data |
| 705 | Returns: |
| 706 | abstract_data; dict representing the decoded data |
| 707 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 708 | method = getattr(self, '_decode_hex', None) |
| 709 | if callable(method): |
| 710 | return method(raw_hex_data) |
| 711 | raw_bin_data = h2b(raw_hex_data) |
| 712 | method = getattr(self, '_decode_bin', None) |
| 713 | if callable(method): |
| 714 | return method(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 715 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 716 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 717 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 718 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 719 | t.from_tlv(raw_bin_data) |
| 720 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 721 | return {'raw': raw_bin_data.hex()} |
| 722 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 723 | def encode_bin(self, abstract_data: dict) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 724 | """Encode abstract representation into raw (binary) data. |
| 725 | |
| 726 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 727 | for implementing this specifically for the given file. This function checks which |
| 728 | of the method exists, add calls them (with conversion, as needed). |
| 729 | |
| 730 | Args: |
| 731 | abstract_data : dict representing the decoded data |
| 732 | Returns: |
| 733 | binary encoded data |
| 734 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 735 | method = getattr(self, '_encode_bin', None) |
| 736 | if callable(method): |
| 737 | return method(abstract_data) |
| 738 | method = getattr(self, '_encode_hex', None) |
| 739 | if callable(method): |
| 740 | return h2b(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 741 | if self._construct: |
| 742 | return self._construct.build(abstract_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 743 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 744 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 745 | t.from_dict(abstract_data) |
| 746 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 747 | raise NotImplementedError( |
| 748 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 749 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 750 | def encode_hex(self, abstract_data: dict) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 751 | """Encode abstract representation into raw (hex string) data. |
| 752 | |
| 753 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 754 | for implementing this specifically for the given file. This function checks which |
| 755 | of the method exists, add calls them (with conversion, as needed). |
| 756 | |
| 757 | Args: |
| 758 | abstract_data : dict representing the decoded data |
| 759 | Returns: |
| 760 | hex string encoded data |
| 761 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 762 | method = getattr(self, '_encode_hex', None) |
| 763 | if callable(method): |
| 764 | return method(abstract_data) |
| 765 | method = getattr(self, '_encode_bin', None) |
| 766 | if callable(method): |
| 767 | raw_bin_data = method(abstract_data) |
| 768 | return b2h(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 769 | if self._construct: |
| 770 | return b2h(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 771 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 772 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 773 | t.from_dict(abstract_data) |
| 774 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 775 | raise NotImplementedError( |
| 776 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 777 | |
| 778 | |
| 779 | class LinFixedEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 780 | """Linear Fixed EF (Entry File) in the smart card filesystem. |
| 781 | |
| 782 | Linear Fixed EFs are record oriented files. They consist of a number of fixed-size |
| 783 | records. The records can be individually read/updated.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 784 | |
| 785 | @with_default_category('Linear Fixed EF Commands') |
| 786 | class ShellCommands(CommandSet): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 787 | """Shell commands specific for Linear Fixed EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 788 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 789 | def __init__(self, **kwargs): |
| 790 | super().__init__(**kwargs) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 791 | |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 792 | dec_hex_parser = argparse.ArgumentParser() |
| 793 | dec_hex_parser.add_argument('--oneline', action='store_true', |
| 794 | help='No JSON pretty-printing, dump as a single line') |
| 795 | dec_hex_parser.add_argument('HEXSTR', help='Hex-string of encoded data to decode') |
| 796 | |
| 797 | @cmd2.with_argparser(dec_hex_parser) |
| 798 | def do_decode_hex(self, opts): |
| 799 | """Decode command-line provided hex-string as if it was read from the file.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 800 | data = self._cmd.lchan.selected_file.decode_record_hex(opts.HEXSTR) |
Harald Welte | aefd064 | 2022-02-25 15:26:37 +0100 | [diff] [blame] | 801 | self._cmd.poutput_json(data, opts.oneline) |
| 802 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 803 | read_rec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 804 | read_rec_parser.add_argument( |
| 805 | 'record_nr', type=int, help='Number of record to be read') |
| 806 | read_rec_parser.add_argument( |
| 807 | '--count', type=int, default=1, help='Number of records to be read, beginning at record_nr') |
| 808 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 809 | @cmd2.with_argparser(read_rec_parser) |
| 810 | def do_read_record(self, opts): |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 811 | """Read one or multiple records from a record-oriented EF""" |
| 812 | for r in range(opts.count): |
| 813 | recnr = opts.record_nr + r |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 814 | (data, sw) = self._cmd.lchan.read_record(recnr) |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 815 | if (len(data) > 0): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 816 | recstr = str(data) |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 817 | else: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 818 | recstr = "(empty)" |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 819 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 820 | |
| 821 | read_rec_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 822 | read_rec_dec_parser.add_argument( |
| 823 | 'record_nr', type=int, help='Number of record to be read') |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame] | 824 | read_rec_dec_parser.add_argument('--oneline', action='store_true', |
| 825 | help='No JSON pretty-printing, dump as a single line') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 826 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 827 | @cmd2.with_argparser(read_rec_dec_parser) |
| 828 | def do_read_record_decoded(self, opts): |
| 829 | """Read + decode a record from a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 830 | (data, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 831 | self._cmd.poutput_json(data, opts.oneline) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 832 | |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 833 | read_recs_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 834 | |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 835 | @cmd2.with_argparser(read_recs_parser) |
| 836 | def do_read_records(self, opts): |
| 837 | """Read all records from a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 838 | num_of_rec = self._cmd.lchan.selected_file_num_of_rec() |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 839 | for recnr in range(1, 1 + num_of_rec): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 840 | (data, sw) = self._cmd.lchan.read_record(recnr) |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 841 | if (len(data) > 0): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 842 | recstr = str(data) |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 843 | else: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 844 | recstr = "(empty)" |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 845 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
| 846 | |
| 847 | read_recs_dec_parser = argparse.ArgumentParser() |
| 848 | read_recs_dec_parser.add_argument('--oneline', action='store_true', |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 849 | help='No JSON pretty-printing, dump as a single line') |
| 850 | |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 851 | @cmd2.with_argparser(read_recs_dec_parser) |
| 852 | def do_read_records_decoded(self, opts): |
| 853 | """Read + decode all records from a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 854 | num_of_rec = self._cmd.lchan.selected_file_num_of_rec() |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 855 | # collect all results in list so they are rendered as JSON list when printing |
| 856 | data_list = [] |
| 857 | for recnr in range(1, 1 + num_of_rec): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 858 | (data, sw) = self._cmd.lchan.read_record_dec(recnr) |
Harald Welte | 850b72a | 2021-04-07 09:33:03 +0200 | [diff] [blame] | 859 | data_list.append(data) |
| 860 | self._cmd.poutput_json(data_list, opts.oneline) |
| 861 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 862 | upd_rec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 863 | upd_rec_parser.add_argument( |
| 864 | 'record_nr', type=int, help='Number of record to be read') |
| 865 | upd_rec_parser.add_argument( |
| 866 | 'data', help='Data bytes (hex format) to write') |
| 867 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 868 | @cmd2.with_argparser(upd_rec_parser) |
| 869 | def do_update_record(self, opts): |
| 870 | """Update (write) data to a record-oriented EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 871 | (data, sw) = self._cmd.lchan.update_record(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 872 | if data: |
| 873 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 874 | |
| 875 | upd_rec_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 876 | upd_rec_dec_parser.add_argument( |
| 877 | 'record_nr', type=int, help='Number of record to be read') |
| 878 | upd_rec_dec_parser.add_argument( |
| 879 | 'data', help='Abstract data (JSON format) to write') |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 880 | upd_rec_dec_parser.add_argument('--json-path', type=str, |
| 881 | help='JSON path to modify specific element of record only') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 882 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 883 | @cmd2.with_argparser(upd_rec_dec_parser) |
| 884 | def do_update_record_decoded(self, opts): |
| 885 | """Encode + Update (write) data to a record-oriented EF""" |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 886 | if opts.json_path: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 887 | (data_json, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 888 | js_path_modify(data_json, opts.json_path, |
| 889 | json.loads(opts.data)) |
Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame] | 890 | else: |
| 891 | data_json = json.loads(opts.data) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 892 | (data, sw) = self._cmd.lchan.update_record_dec( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 893 | opts.record_nr, data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 894 | if data: |
| 895 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 896 | |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 897 | edit_rec_dec_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 898 | edit_rec_dec_parser.add_argument( |
| 899 | 'record_nr', type=int, help='Number of record to be edited') |
| 900 | |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 901 | @cmd2.with_argparser(edit_rec_dec_parser) |
| 902 | def do_edit_record_decoded(self, opts): |
| 903 | """Edit the JSON representation of one record in an editor.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 904 | (orig_json, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
Vadim Yanitskiy | 895fa6f | 2021-05-02 02:36:44 +0200 | [diff] [blame] | 905 | with tempfile.TemporaryDirectory(prefix='pysim_') as dirname: |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 906 | filename = '%s/file' % dirname |
| 907 | # write existing data as JSON to file |
| 908 | with open(filename, 'w') as text_file: |
| 909 | json.dump(orig_json, text_file, indent=4) |
| 910 | # run a text editor |
Harald Welte | e126872 | 2023-06-24 07:57:08 +0200 | [diff] [blame] | 911 | self._cmd.run_editor(filename) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 912 | with open(filename, 'r') as text_file: |
| 913 | edited_json = json.load(text_file) |
| 914 | if edited_json == orig_json: |
| 915 | self._cmd.poutput("Data not modified, skipping write") |
| 916 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 917 | (data, sw) = self._cmd.lchan.update_record_dec( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 918 | opts.record_nr, edited_json) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 919 | if data: |
| 920 | self._cmd.poutput_json(data) |
Harald Welte | 4145d3c | 2021-04-08 20:34:13 +0200 | [diff] [blame] | 921 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 922 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, |
Philipp Maier | 37e57e0 | 2023-09-07 12:43:12 +0200 | [diff] [blame] | 923 | parent: Optional[CardDF] = None, rec_len: Size = (1, None), leftpad: bool = False, **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 924 | """ |
| 925 | Args: |
| 926 | fid : File Identifier (4 hex digits) |
| 927 | sfid : Short File Identifier (2 hex digits, optional) |
| 928 | name : Brief name of the file, lik EF_ICCID |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 929 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 930 | parent : Parent CardFile object within filesystem hierarchy |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 931 | rec_len : Tuple of (minimum_length, recommended_length) |
Philipp Maier | 37e57e0 | 2023-09-07 12:43:12 +0200 | [diff] [blame] | 932 | leftpad: On write, data must be padded from the left to fit pysical record length |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 933 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 934 | 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] | 935 | self.rec_len = rec_len |
Philipp Maier | 37e57e0 | 2023-09-07 12:43:12 +0200 | [diff] [blame] | 936 | self.leftpad = leftpad |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 937 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 938 | self._construct = None |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 939 | self._tlv = None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 940 | |
Harald Welte | caa94b5 | 2023-01-31 16:43:34 +0100 | [diff] [blame] | 941 | def decode_record_hex(self, raw_hex_data: str, record_nr: int = 1) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 942 | """Decode raw (hex string) data into abstract representation. |
| 943 | |
| 944 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 945 | method for implementing this specifically for the given file. This function checks which |
| 946 | of the method exists, add calls them (with conversion, as needed). |
| 947 | |
| 948 | Args: |
| 949 | raw_hex_data : hex-encoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 950 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 951 | Returns: |
| 952 | abstract_data; dict representing the decoded data |
| 953 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 954 | method = getattr(self, '_decode_record_hex', None) |
| 955 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 956 | return method(raw_hex_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 957 | raw_bin_data = h2b(raw_hex_data) |
| 958 | method = getattr(self, '_decode_record_bin', None) |
| 959 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 960 | return method(raw_bin_data, record_nr=record_nr) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 961 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 962 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 963 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 964 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 965 | t.from_tlv(raw_bin_data) |
| 966 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 967 | return {'raw': raw_bin_data.hex()} |
| 968 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 969 | def decode_record_bin(self, raw_bin_data: bytearray, record_nr: int) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 970 | """Decode raw (binary) data into abstract representation. |
| 971 | |
| 972 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 973 | method for implementing this specifically for the given file. This function checks which |
| 974 | of the method exists, add calls them (with conversion, as needed). |
| 975 | |
| 976 | Args: |
| 977 | raw_bin_data : binary encoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 978 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 979 | Returns: |
| 980 | abstract_data; dict representing the decoded data |
| 981 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 982 | method = getattr(self, '_decode_record_bin', None) |
| 983 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 984 | return method(raw_bin_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 985 | raw_hex_data = b2h(raw_bin_data) |
| 986 | method = getattr(self, '_decode_record_hex', None) |
| 987 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 988 | return method(raw_hex_data, record_nr=record_nr) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 989 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 990 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 991 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 992 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 993 | t.from_tlv(raw_bin_data) |
| 994 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 995 | return {'raw': raw_hex_data} |
| 996 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 997 | def encode_record_hex(self, abstract_data: dict, record_nr: int) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 998 | """Encode abstract representation into raw (hex string) data. |
| 999 | |
| 1000 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1001 | method for implementing this specifically for the given file. This function checks which |
| 1002 | of the method exists, add calls them (with conversion, as needed). |
| 1003 | |
| 1004 | Args: |
| 1005 | abstract_data : dict representing the decoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1006 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1007 | Returns: |
| 1008 | hex string encoded data |
| 1009 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1010 | method = getattr(self, '_encode_record_hex', None) |
| 1011 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1012 | return method(abstract_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1013 | method = getattr(self, '_encode_record_bin', None) |
| 1014 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1015 | raw_bin_data = method(abstract_data, record_nr=record_nr) |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1016 | return b2h(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1017 | if self._construct: |
| 1018 | return b2h(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1019 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1020 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1021 | t.from_dict(abstract_data) |
| 1022 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1023 | raise NotImplementedError( |
| 1024 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1025 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1026 | def encode_record_bin(self, abstract_data: dict, record_nr : int) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1027 | """Encode abstract representation into raw (binary) data. |
| 1028 | |
| 1029 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1030 | method for implementing this specifically for the given file. This function checks which |
| 1031 | of the method exists, add calls them (with conversion, as needed). |
| 1032 | |
| 1033 | Args: |
| 1034 | abstract_data : dict representing the decoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1035 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1036 | Returns: |
| 1037 | binary encoded data |
| 1038 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1039 | method = getattr(self, '_encode_record_bin', None) |
| 1040 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1041 | return method(abstract_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1042 | method = getattr(self, '_encode_record_hex', None) |
| 1043 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1044 | return h2b(method(abstract_data, record_nr=record_nr)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1045 | if self._construct: |
| 1046 | return self._construct.build(abstract_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1047 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1048 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1049 | t.from_dict(abstract_data) |
| 1050 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1051 | raise NotImplementedError( |
| 1052 | "%s encoder not yet implemented. Patches welcome." % self) |
| 1053 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1054 | |
| 1055 | class CyclicEF(LinFixedEF): |
| 1056 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 1057 | # 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] | 1058 | |
| 1059 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None, |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 1060 | rec_len: Size = (1, None), **kwargs): |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1061 | 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] | 1062 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1063 | |
| 1064 | class TransRecEF(TransparentEF): |
| 1065 | """Transparent EF (Entry File) containing fixed-size records. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1066 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1067 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 1068 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 1069 | inside. |
| 1070 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 1071 | for a record, while this class takes care of split / merge of records. |
| 1072 | """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1073 | |
| 1074 | def __init__(self, fid: str, rec_len: int, sfid: str = None, name: str = None, desc: str = None, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 1075 | parent: Optional[CardDF] = None, size: Size = (1, None), **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1076 | """ |
| 1077 | Args: |
| 1078 | fid : File Identifier (4 hex digits) |
| 1079 | sfid : Short File Identifier (2 hex digits, optional) |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1080 | name : Brief name of the file, like EF_ICCID |
| 1081 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1082 | parent : Parent CardFile object within filesystem hierarchy |
| 1083 | rec_len : Length of the fixed-length records within transparent EF |
| 1084 | size : tuple of (minimum_size, recommended_size) |
| 1085 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1086 | 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] | 1087 | self.rec_len = rec_len |
| 1088 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1089 | def decode_record_hex(self, raw_hex_data: str) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1090 | """Decode raw (hex string) data into abstract representation. |
| 1091 | |
| 1092 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 1093 | method for implementing this specifically for the given file. This function checks which |
| 1094 | of the method exists, add calls them (with conversion, as needed). |
| 1095 | |
| 1096 | Args: |
| 1097 | raw_hex_data : hex-encoded data |
| 1098 | Returns: |
| 1099 | abstract_data; dict representing the decoded data |
| 1100 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1101 | method = getattr(self, '_decode_record_hex', None) |
| 1102 | if callable(method): |
| 1103 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1104 | raw_bin_data = h2b(raw_hex_data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1105 | method = getattr(self, '_decode_record_bin', None) |
| 1106 | if callable(method): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1107 | return method(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1108 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 1109 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1110 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1111 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1112 | t.from_tlv(raw_bin_data) |
| 1113 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1114 | return {'raw': raw_hex_data} |
| 1115 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1116 | def decode_record_bin(self, raw_bin_data: bytearray) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1117 | """Decode raw (binary) data into abstract representation. |
| 1118 | |
| 1119 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 1120 | method for implementing this specifically for the given file. This function checks which |
| 1121 | of the method exists, add calls them (with conversion, as needed). |
| 1122 | |
| 1123 | Args: |
| 1124 | raw_bin_data : binary encoded data |
| 1125 | Returns: |
| 1126 | abstract_data; dict representing the decoded data |
| 1127 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1128 | method = getattr(self, '_decode_record_bin', None) |
| 1129 | if callable(method): |
| 1130 | return method(raw_bin_data) |
| 1131 | raw_hex_data = b2h(raw_bin_data) |
| 1132 | method = getattr(self, '_decode_record_hex', None) |
| 1133 | if callable(method): |
| 1134 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1135 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 1136 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1137 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1138 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1139 | t.from_tlv(raw_bin_data) |
| 1140 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1141 | return {'raw': raw_hex_data} |
| 1142 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1143 | def encode_record_hex(self, abstract_data: dict) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1144 | """Encode abstract representation into raw (hex string) data. |
| 1145 | |
| 1146 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1147 | method for implementing this specifically for the given file. This function checks which |
| 1148 | of the method exists, add calls them (with conversion, as needed). |
| 1149 | |
| 1150 | Args: |
| 1151 | abstract_data : dict representing the decoded data |
| 1152 | Returns: |
| 1153 | hex string encoded data |
| 1154 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1155 | method = getattr(self, '_encode_record_hex', None) |
| 1156 | if callable(method): |
| 1157 | return method(abstract_data) |
| 1158 | method = getattr(self, '_encode_record_bin', None) |
| 1159 | if callable(method): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1160 | return b2h(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1161 | if self._construct: |
| 1162 | return b2h(filter_dict(self._construct.build(abstract_data))) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1163 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1164 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1165 | t.from_dict(abstract_data) |
| 1166 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1167 | raise NotImplementedError( |
| 1168 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1169 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1170 | def encode_record_bin(self, abstract_data: dict) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1171 | """Encode abstract representation into raw (binary) data. |
| 1172 | |
| 1173 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1174 | method for implementing this specifically for the given file. This function checks which |
| 1175 | of the method exists, add calls them (with conversion, as needed). |
| 1176 | |
| 1177 | Args: |
| 1178 | abstract_data : dict representing the decoded data |
| 1179 | Returns: |
| 1180 | binary encoded data |
| 1181 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1182 | method = getattr(self, '_encode_record_bin', None) |
| 1183 | if callable(method): |
| 1184 | return method(abstract_data) |
| 1185 | method = getattr(self, '_encode_record_hex', None) |
| 1186 | if callable(method): |
| 1187 | return h2b(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1188 | if self._construct: |
| 1189 | return filter_dict(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1190 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1191 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1192 | t.from_dict(abstract_data) |
| 1193 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1194 | raise NotImplementedError( |
| 1195 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1196 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1197 | def _decode_bin(self, raw_bin_data: bytearray): |
| 1198 | chunks = [raw_bin_data[i:i+self.rec_len] |
| 1199 | for i in range(0, len(raw_bin_data), self.rec_len)] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1200 | return [self.decode_record_bin(x) for x in chunks] |
| 1201 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1202 | def _encode_bin(self, abstract_data) -> bytes: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1203 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 1204 | # FIXME: pad to file size |
| 1205 | return b''.join(chunks) |
| 1206 | |
| 1207 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1208 | class BerTlvEF(CardEF): |
Harald Welte | 2788162 | 2021-04-21 11:16:31 +0200 | [diff] [blame] | 1209 | """BER-TLV EF (Entry File) in the smart card filesystem. |
| 1210 | 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] | 1211 | |
Harald Welte | 2788162 | 2021-04-21 11:16:31 +0200 | [diff] [blame] | 1212 | NOTE: We currently don't really support those, this class is simply a wrapper |
| 1213 | around TransparentEF as a place-holder, so we can already define EFs of BER-TLV |
| 1214 | type without fully supporting them.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1215 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1216 | @with_default_category('BER-TLV EF Commands') |
| 1217 | class ShellCommands(CommandSet): |
| 1218 | """Shell commands specific for BER-TLV EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1219 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1220 | def __init__(self): |
| 1221 | super().__init__() |
| 1222 | |
| 1223 | retrieve_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1224 | retrieve_data_parser.add_argument( |
| 1225 | 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve') |
| 1226 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1227 | @cmd2.with_argparser(retrieve_data_parser) |
| 1228 | def do_retrieve_data(self, opts): |
| 1229 | """Retrieve (Read) data from a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1230 | (data, sw) = self._cmd.lchan.retrieve_data(opts.tag) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1231 | self._cmd.poutput(data) |
| 1232 | |
| 1233 | def do_retrieve_tags(self, opts): |
| 1234 | """List tags available in a given BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1235 | tags = self._cmd.lchan.retrieve_tags() |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1236 | self._cmd.poutput(tags) |
| 1237 | |
| 1238 | set_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1239 | set_data_parser.add_argument( |
| 1240 | 'tag', type=auto_int, help='BER-TLV Tag of value to set') |
| 1241 | set_data_parser.add_argument( |
| 1242 | 'data', help='Data bytes (hex format) to write') |
| 1243 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1244 | @cmd2.with_argparser(set_data_parser) |
| 1245 | def do_set_data(self, opts): |
| 1246 | """Set (Write) data for a given tag in a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1247 | (data, sw) = self._cmd.lchan.set_data(opts.tag, opts.data) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1248 | if data: |
| 1249 | self._cmd.poutput(data) |
| 1250 | |
| 1251 | del_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1252 | del_data_parser.add_argument( |
| 1253 | 'tag', type=auto_int, help='BER-TLV Tag of value to set') |
| 1254 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1255 | @cmd2.with_argparser(del_data_parser) |
| 1256 | def do_delete_data(self, opts): |
| 1257 | """Delete data for a given tag in a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1258 | (data, sw) = self._cmd.lchan.set_data(opts.tag, None) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1259 | if data: |
| 1260 | self._cmd.poutput(data) |
| 1261 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1262 | def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 1263 | size: Size = (1, None), **kwargs): |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1264 | """ |
| 1265 | Args: |
| 1266 | fid : File Identifier (4 hex digits) |
| 1267 | sfid : Short File Identifier (2 hex digits, optional) |
| 1268 | name : Brief name of the file, lik EF_ICCID |
| 1269 | desc : Description of the file |
| 1270 | parent : Parent CardFile object within filesystem hierarchy |
| 1271 | size : tuple of (minimum_size, recommended_size) |
| 1272 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1273 | 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] | 1274 | self._construct = None |
| 1275 | self.size = size |
| 1276 | self.shell_commands = [self.ShellCommands()] |
| 1277 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1278 | def interpret_sw(sw_data: dict, sw: str): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1279 | """Interpret a given status word. |
| 1280 | |
| 1281 | Args: |
| 1282 | sw_data : Hierarchical dict of status word matches |
| 1283 | sw : status word to match (string of 4 hex digits) |
| 1284 | Returns: |
| 1285 | tuple of two strings (class_string, description) |
| 1286 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1287 | for class_str, swdict in sw_data.items(): |
| 1288 | # first try direct match |
| 1289 | if sw in swdict: |
| 1290 | return (class_str, swdict[sw]) |
| 1291 | # next try wildcard matches |
| 1292 | for pattern, descr in swdict.items(): |
| 1293 | if sw_match(sw, pattern): |
| 1294 | return (class_str, descr) |
| 1295 | return None |
| 1296 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1297 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 1298 | class CardApplication: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1299 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 1300 | some SW definitions.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1301 | |
| 1302 | 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] | 1303 | """ |
| 1304 | Args: |
| 1305 | adf : ADF name |
| 1306 | sw : Dict of status word conversions |
| 1307 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1308 | self.name = name |
| 1309 | self.adf = adf |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1310 | self.sw = sw or dict() |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1311 | # back-reference from ADF to Applicaiton |
| 1312 | if self.adf: |
| 1313 | self.aid = aid or self.adf.aid |
| 1314 | self.adf.application = self |
| 1315 | else: |
| 1316 | self.aid = aid |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1317 | |
| 1318 | def __str__(self): |
| 1319 | return "APP(%s)" % (self.name) |
| 1320 | |
| 1321 | def interpret_sw(self, sw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1322 | """Interpret a given status word within the application. |
| 1323 | |
| 1324 | Args: |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1325 | sw : Status word as string of 4 hex digits |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1326 | |
| 1327 | Returns: |
| 1328 | Tuple of two strings |
| 1329 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1330 | return interpret_sw(self.sw, sw) |
| 1331 | |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1332 | |
| 1333 | class CardModel(abc.ABC): |
Harald Welte | 4c1dca0 | 2021-10-14 17:48:25 +0200 | [diff] [blame] | 1334 | """A specific card model, typically having some additional vendor-specific files. All |
| 1335 | you need to do is to define a sub-class with a list of ATRs or an overridden match |
| 1336 | method.""" |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1337 | _atrs = [] |
| 1338 | |
| 1339 | @classmethod |
| 1340 | @abc.abstractmethod |
Harald Welte | 531894d | 2023-07-11 19:11:11 +0200 | [diff] [blame] | 1341 | def add_files(cls, rs: 'RuntimeState'): |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1342 | """Add model specific files to given RuntimeState.""" |
| 1343 | |
| 1344 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1345 | def match(cls, scc: SimCardCommands) -> bool: |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1346 | """Test if given card matches this model.""" |
| 1347 | card_atr = scc.get_atr() |
| 1348 | for atr in cls._atrs: |
| 1349 | atr_bin = toBytes(atr) |
| 1350 | if atr_bin == card_atr: |
| 1351 | print("Detected CardModel:", cls.__name__) |
| 1352 | return True |
| 1353 | return False |
| 1354 | |
| 1355 | @staticmethod |
Harald Welte | 531894d | 2023-07-11 19:11:11 +0200 | [diff] [blame] | 1356 | def apply_matching_models(scc: SimCardCommands, rs: 'RuntimeState'): |
Harald Welte | 4c1dca0 | 2021-10-14 17:48:25 +0200 | [diff] [blame] | 1357 | """Check if any of the CardModel sub-classes 'match' the currently inserted card |
| 1358 | (by ATR or overriding the 'match' method). If so, call their 'add_files' |
| 1359 | method.""" |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1360 | for m in CardModel.__subclasses__(): |
| 1361 | if m.match(scc): |
| 1362 | m.add_files(rs) |