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 = [] |
| 146 | cur_fqpath.pop() # drop last element (currently selected file, doesn't need re-selection |
| 147 | cur_fqpath.reverse() |
| 148 | for ce in cur_fqpath: |
| 149 | inter_path.append(ce) |
| 150 | for i in range(0, len(target_fqpath)-1): |
| 151 | te = target_fqpath[i] |
| 152 | if te == ce: |
| 153 | for te2 in target_fqpath[i+1:]: |
| 154 | inter_path.append(te2) |
| 155 | # we found our common ancestor |
| 156 | return inter_path |
| 157 | return None |
| 158 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 159 | def get_mf(self) -> Optional['CardMF']: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 160 | """Return the MF (root) of the file system.""" |
| 161 | if self.parent == None: |
| 162 | return None |
| 163 | # iterate towards the top. MF has parent == self |
| 164 | node = self |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 165 | while node.parent and node.parent != node: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 166 | node = node.parent |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 167 | return cast(CardMF, node) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 168 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 169 | def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 170 | """Return a dict of {'identifier': self} tuples. |
| 171 | |
| 172 | Args: |
| 173 | alias : Add an alias with given name to 'self' |
| 174 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 175 | If not specified, all selectables will be returned. |
| 176 | Returns: |
| 177 | dict containing reference to 'self' for all identifiers. |
| 178 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 179 | sels = {} |
| 180 | if alias: |
| 181 | sels.update({alias: self}) |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 182 | if self.fid and (flags == [] or 'FIDS' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 183 | sels.update({self.fid: self}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 184 | if self.name and (flags == [] or 'FNAMES' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 185 | sels.update({self.name: self}) |
| 186 | return sels |
| 187 | |
Harald Welte | f5ff1b8 | 2022-07-24 12:19:57 +0200 | [diff] [blame] | 188 | def _get_parent_selectables(self, alias: Optional[str] = None, flags=[]) -> Dict[str, 'CardFile']: |
| 189 | sels = {} |
| 190 | if not self.parent or self.parent == self: |
| 191 | return sels |
| 192 | # add our immediate parent |
| 193 | if alias: |
| 194 | sels.update({alias: self.parent}) |
| 195 | if self.parent.fid and (flags == [] or 'FIDS' in flags): |
| 196 | sels.update({self.parent.fid: self.parent}) |
| 197 | if self.parent.name and (flags == [] or 'FNAMES' in flags): |
| 198 | sels.update({self.parent.name: self.parent}) |
| 199 | # recurse to parents of our parent, but without any alias |
| 200 | sels.update(self.parent._get_parent_selectables(None, flags)) |
| 201 | return sels |
| 202 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 203 | def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 204 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 205 | |
| 206 | Args: |
| 207 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 208 | If not specified, all selectables will be returned. |
| 209 | Returns: |
| 210 | dict containing all selectable items. Key is identifier (string), value |
| 211 | a reference to a CardFile (or derived class) instance. |
| 212 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 213 | sels = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 214 | # we can always select ourself |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 215 | if flags == [] or 'SELF' in flags: |
| 216 | sels = self._get_self_selectables('.', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 217 | # we can always select our parent |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 218 | if flags == [] or 'PARENT' in flags: |
Harald Welte | f5ff1b8 | 2022-07-24 12:19:57 +0200 | [diff] [blame] | 219 | sels.update(self._get_parent_selectables('..', flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 220 | # if we have a MF, we can always select its applications |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 221 | if flags == [] or 'MF' in flags: |
| 222 | mf = self.get_mf() |
| 223 | if mf: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 224 | sels.update(mf._get_self_selectables(flags=flags)) |
| 225 | sels.update(mf.get_app_selectables(flags=flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 226 | return sels |
| 227 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 228 | def get_selectable_names(self, flags=[]) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 229 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 230 | |
| 231 | Args: |
| 232 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 233 | If not specified, all selectables will be returned. |
| 234 | Returns: |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 235 | list containing all selectable names. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 236 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 237 | sels = self.get_selectables(flags) |
Harald Welte | b3d68c0 | 2022-01-21 15:31:29 +0100 | [diff] [blame] | 238 | sel_keys = list(sels.keys()) |
| 239 | sel_keys.sort() |
| 240 | return sel_keys |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 241 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 242 | def decode_select_response(self, data_hex: str): |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 243 | """Decode the response to a SELECT command. |
| 244 | |
| 245 | Args: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 246 | data_hex: Hex string of the select response |
| 247 | """ |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 248 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 249 | # When the current file does not implement a custom select response decoder, |
| 250 | # we just ask the parent file to decode the select response. If this method |
| 251 | # is not overloaded by the current file we will again ask the parent file. |
| 252 | # This way we recursively travel up the file system tree until we hit a file |
| 253 | # that does implement a concrete decoder. |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 254 | if self.parent: |
| 255 | return self.parent.decode_select_response(data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 256 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 257 | def get_profile(self): |
| 258 | """Get the profile associated with this file. If this file does not have any |
| 259 | profile assigned, try to find a file above (usually the MF) in the filesystem |
| 260 | hirarchy that has a profile assigned |
| 261 | """ |
| 262 | |
| 263 | # If we have a profile set, return it |
| 264 | if self.profile: |
| 265 | return self.profile |
| 266 | |
| 267 | # Walk up recursively until we hit a parent that has a profile set |
| 268 | if self.parent: |
| 269 | return self.parent.get_profile() |
| 270 | return None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 271 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 272 | def should_exist_for_services(self, services: List[int]): |
| 273 | """Assuming the provided list of activated services, should this file exist and be activated?.""" |
| 274 | if self.service is None: |
| 275 | return None |
| 276 | elif isinstance(self.service, int): |
| 277 | # a single service determines the result |
| 278 | return self.service in services |
| 279 | elif isinstance(self.service, list): |
| 280 | # any of the services active -> true |
| 281 | for s in self.service: |
| 282 | if s in services: |
| 283 | return True |
| 284 | return False |
| 285 | elif isinstance(self.service, tuple): |
| 286 | # all of the services active -> true |
| 287 | for s in self.service: |
| 288 | if not s in services: |
| 289 | return False |
| 290 | return True |
| 291 | else: |
| 292 | raise ValueError("self.service must be either int or list or tuple") |
| 293 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 294 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 295 | class CardDF(CardFile): |
| 296 | """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] | 297 | |
| 298 | @with_default_category('DF/ADF Commands') |
| 299 | class ShellCommands(CommandSet): |
| 300 | def __init__(self): |
| 301 | super().__init__() |
| 302 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 303 | def __init__(self, **kwargs): |
| 304 | if not isinstance(self, CardADF): |
| 305 | if not 'fid' in kwargs: |
| 306 | raise TypeError('fid is mandatory for all DF') |
| 307 | super().__init__(**kwargs) |
| 308 | self.children = dict() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 309 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 310 | # dict of CardFile affected by service(int), indexed by service |
| 311 | self.files_by_service = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 312 | |
| 313 | def __str__(self): |
| 314 | return "DF(%s)" % (super().__str__()) |
| 315 | |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 316 | def _add_file_services(self, child): |
| 317 | """Add a child (DF/EF) to the files_by_services of the parent.""" |
| 318 | if not child.service: |
| 319 | return |
| 320 | if isinstance(child.service, int): |
| 321 | self.files_by_service.setdefault(child.service, []).append(child) |
| 322 | elif isinstance(child.service, list): |
| 323 | for service in child.service: |
| 324 | self.files_by_service.setdefault(service, []).append(child) |
| 325 | elif isinstance(child.service, tuple): |
| 326 | for service in child.service: |
| 327 | self.files_by_service.setdefault(service, []).append(child) |
| 328 | else: |
| 329 | raise ValueError |
| 330 | |
Harald Welte | d56f45d | 2022-07-16 11:46:59 +0200 | [diff] [blame] | 331 | def _has_service(self): |
| 332 | if self.service: |
| 333 | return True |
| 334 | for c in self.children.values(): |
| 335 | if isinstance(c, CardDF): |
| 336 | if c._has_service(): |
| 337 | return True |
| 338 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 339 | def add_file(self, child: CardFile, ignore_existing: bool = False): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 340 | """Add a child (DF/EF) to this DF. |
| 341 | Args: |
| 342 | child: The new DF/EF to be added |
| 343 | ignore_existing: Ignore, if file with given FID already exists. Old one will be kept. |
| 344 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 345 | if not isinstance(child, CardFile): |
| 346 | raise TypeError("Expected a File instance") |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 347 | if not is_hex(child.fid, minlen=4, maxlen=4): |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 348 | raise ValueError("File name %s is not a valid fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 349 | if child.name in CardFile.RESERVED_NAMES: |
| 350 | raise ValueError("File name %s is a reserved name" % (child.name)) |
| 351 | if child.fid in CardFile.RESERVED_FIDS: |
Philipp Maier | e8bc1b4 | 2021-03-09 20:33:41 +0100 | [diff] [blame] | 352 | raise ValueError("File fid %s is a reserved fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 353 | if child.fid in self.children: |
| 354 | if ignore_existing: |
| 355 | return |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 356 | raise ValueError( |
| 357 | "File with given fid %s already exists in %s" % (child.fid, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 358 | if self.lookup_file_by_sfid(child.sfid): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 359 | raise ValueError( |
| 360 | "File with given sfid %s already exists in %s" % (child.sfid, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 361 | if self.lookup_file_by_name(child.name): |
| 362 | if ignore_existing: |
| 363 | return |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 364 | raise ValueError( |
| 365 | "File with given name %s already exists in %s" % (child.name, self)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 366 | self.children[child.fid] = child |
| 367 | child.parent = self |
Harald Welte | 419bb49 | 2022-02-12 21:39:35 +0100 | [diff] [blame] | 368 | # update the service -> file relationship table |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 369 | self._add_file_services(child) |
Harald Welte | 419bb49 | 2022-02-12 21:39:35 +0100 | [diff] [blame] | 370 | if isinstance(child, CardDF): |
| 371 | for c in child.children.values(): |
| 372 | self._add_file_services(c) |
| 373 | if isinstance(c, CardDF): |
Harald Welte | d56f45d | 2022-07-16 11:46:59 +0200 | [diff] [blame] | 374 | for gc in c.children.values(): |
| 375 | if isinstance(gc, CardDF): |
| 376 | if gc._has_service(): |
| 377 | raise ValueError('TODO: implement recursive service -> file mapping') |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 378 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 379 | def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 380 | """Add a list of child (DF/EF) to this DF |
| 381 | |
| 382 | Args: |
| 383 | children: List of new DF/EFs to be added |
| 384 | ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept. |
| 385 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 386 | for child in children: |
| 387 | self.add_file(child, ignore_existing) |
| 388 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 389 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 390 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 391 | |
| 392 | Args: |
| 393 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 394 | If not specified, all selectables will be returned. |
| 395 | Returns: |
| 396 | dict containing all selectable items. Key is identifier (string), value |
| 397 | a reference to a CardFile (or derived class) instance. |
| 398 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 399 | # global selectables + our children |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 400 | sels = super().get_selectables(flags) |
| 401 | if flags == [] or 'FIDS' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 402 | 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] | 403 | if flags == [] or 'FNAMES' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 404 | 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] | 405 | return sels |
| 406 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 407 | def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 408 | """Find a file with given name within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 409 | if name == None: |
| 410 | return None |
| 411 | for i in self.children.values(): |
| 412 | if i.name and i.name == name: |
| 413 | return i |
| 414 | return None |
| 415 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 416 | def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 417 | """Find a file with given short file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 418 | if sfid == None: |
| 419 | return None |
| 420 | for i in self.children.values(): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 421 | if i.sfid == int(str(sfid)): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 422 | return i |
| 423 | return None |
| 424 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 425 | def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 426 | """Find a file with given file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 427 | if fid in self.children: |
| 428 | return self.children[fid] |
| 429 | return None |
| 430 | |
| 431 | |
| 432 | class CardMF(CardDF): |
| 433 | """MF (Master File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 434 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 435 | def __init__(self, **kwargs): |
| 436 | # can be overridden; use setdefault |
| 437 | kwargs.setdefault('fid', '3f00') |
| 438 | kwargs.setdefault('name', 'MF') |
| 439 | kwargs.setdefault('desc', 'Master File (directory root)') |
| 440 | # cannot be overridden; use assignment |
| 441 | kwargs['parent'] = self |
| 442 | super().__init__(**kwargs) |
| 443 | self.applications = dict() |
| 444 | |
| 445 | def __str__(self): |
| 446 | return "MF(%s)" % (self.fid) |
| 447 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 448 | def add_application_df(self, app: 'CardADF'): |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 449 | """Add an Application to the MF""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 450 | if not isinstance(app, CardADF): |
| 451 | raise TypeError("Expected an ADF instance") |
| 452 | if app.aid in self.applications: |
| 453 | raise ValueError("AID %s already exists" % (app.aid)) |
| 454 | self.applications[app.aid] = app |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 455 | app.parent = self |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 456 | |
| 457 | def get_app_names(self): |
| 458 | """Get list of completions (AID names)""" |
Harald Welte | d53918c | 2022-02-12 18:20:49 +0100 | [diff] [blame] | 459 | return list(self.applications.values()) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 460 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 461 | def get_selectables(self, flags=[]) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 462 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 463 | |
| 464 | Args: |
| 465 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 466 | If not specified, all selectables will be returned. |
| 467 | Returns: |
| 468 | dict containing all selectable items. Key is identifier (string), value |
| 469 | a reference to a CardFile (or derived class) instance. |
| 470 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 471 | sels = super().get_selectables(flags) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 472 | sels.update(self.get_app_selectables(flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 473 | return sels |
| 474 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 475 | def get_app_selectables(self, flags=[]) -> dict: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 476 | """Get applications by AID + name""" |
| 477 | sels = {} |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 478 | if flags == [] or 'AIDS' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 479 | sels.update({x.aid: x for x in self.applications.values()}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 480 | if flags == [] or 'ANAMES' in flags: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 481 | sels.update( |
| 482 | {x.name: x for x in self.applications.values() if x.name}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 483 | return sels |
| 484 | |
Harald Welte | c975251 | 2022-02-11 16:31:15 +0100 | [diff] [blame] | 485 | def decode_select_response(self, data_hex: Optional[str]) -> object: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 486 | """Decode the response to a SELECT command. |
| 487 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 488 | This is the fall-back method which automatically defers to the standard decoding |
| 489 | 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] | 490 | performed. Specific derived classes (usually ADF) can overload this method to |
| 491 | install specific decoding. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 492 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 493 | |
Harald Welte | c975251 | 2022-02-11 16:31:15 +0100 | [diff] [blame] | 494 | if not data_hex: |
| 495 | return data_hex |
| 496 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 497 | profile = self.get_profile() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 498 | |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 499 | if profile: |
| 500 | return profile.decode_select_response(data_hex) |
| 501 | else: |
| 502 | return data_hex |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 503 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 504 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 505 | class CardADF(CardDF): |
| 506 | """ADF (Application Dedicated File) in the smart card filesystem""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 507 | |
| 508 | def __init__(self, aid: str, **kwargs): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 509 | super().__init__(**kwargs) |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 510 | # reference to CardApplication may be set from CardApplication constructor |
Harald Welte | fe8a744 | 2021-04-10 11:51:54 +0200 | [diff] [blame] | 511 | self.application = None # type: Optional[CardApplication] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 512 | self.aid = aid # Application Identifier |
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, |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 923 | parent: Optional[CardDF] = None, rec_len: Size = (1, None), **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) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 932 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 933 | 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] | 934 | self.rec_len = rec_len |
| 935 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 936 | self._construct = None |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 937 | self._tlv = None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 938 | |
Harald Welte | caa94b5 | 2023-01-31 16:43:34 +0100 | [diff] [blame] | 939 | 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] | 940 | """Decode raw (hex string) data into abstract representation. |
| 941 | |
| 942 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 943 | method for implementing this specifically for the given file. This function checks which |
| 944 | of the method exists, add calls them (with conversion, as needed). |
| 945 | |
| 946 | Args: |
| 947 | raw_hex_data : hex-encoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 948 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 949 | Returns: |
| 950 | abstract_data; dict representing the decoded data |
| 951 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 952 | method = getattr(self, '_decode_record_hex', None) |
| 953 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 954 | return method(raw_hex_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 955 | raw_bin_data = h2b(raw_hex_data) |
| 956 | method = getattr(self, '_decode_record_bin', None) |
| 957 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 958 | return method(raw_bin_data, record_nr=record_nr) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 959 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 960 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 961 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 962 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 963 | t.from_tlv(raw_bin_data) |
| 964 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 965 | return {'raw': raw_bin_data.hex()} |
| 966 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 967 | 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] | 968 | """Decode raw (binary) data into abstract representation. |
| 969 | |
| 970 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 971 | method for implementing this specifically for the given file. This function checks which |
| 972 | of the method exists, add calls them (with conversion, as needed). |
| 973 | |
| 974 | Args: |
| 975 | raw_bin_data : binary encoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 976 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 977 | Returns: |
| 978 | abstract_data; dict representing the decoded data |
| 979 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 980 | method = getattr(self, '_decode_record_bin', None) |
| 981 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 982 | return method(raw_bin_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 983 | raw_hex_data = b2h(raw_bin_data) |
| 984 | method = getattr(self, '_decode_record_hex', None) |
| 985 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 986 | return method(raw_hex_data, record_nr=record_nr) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 987 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 988 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 989 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 990 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 991 | t.from_tlv(raw_bin_data) |
| 992 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 993 | return {'raw': raw_hex_data} |
| 994 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 995 | def encode_record_hex(self, abstract_data: dict, record_nr: int) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 996 | """Encode abstract representation into raw (hex string) data. |
| 997 | |
| 998 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 999 | method for implementing this specifically for the given file. This function checks which |
| 1000 | of the method exists, add calls them (with conversion, as needed). |
| 1001 | |
| 1002 | Args: |
| 1003 | abstract_data : dict representing the decoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1004 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1005 | Returns: |
| 1006 | hex string encoded data |
| 1007 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1008 | method = getattr(self, '_encode_record_hex', None) |
| 1009 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1010 | return method(abstract_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1011 | method = getattr(self, '_encode_record_bin', None) |
| 1012 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1013 | raw_bin_data = method(abstract_data, record_nr=record_nr) |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1014 | return b2h(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1015 | if self._construct: |
| 1016 | return b2h(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1017 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1018 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1019 | t.from_dict(abstract_data) |
| 1020 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1021 | raise NotImplementedError( |
| 1022 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1023 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1024 | def encode_record_bin(self, abstract_data: dict, record_nr : int) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1025 | """Encode abstract representation into raw (binary) data. |
| 1026 | |
| 1027 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1028 | method for implementing this specifically for the given file. This function checks which |
| 1029 | of the method exists, add calls them (with conversion, as needed). |
| 1030 | |
| 1031 | Args: |
| 1032 | abstract_data : dict representing the decoded data |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1033 | record_nr : record number (1 for first record, ...) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1034 | Returns: |
| 1035 | binary encoded data |
| 1036 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1037 | method = getattr(self, '_encode_record_bin', None) |
| 1038 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1039 | return method(abstract_data, record_nr=record_nr) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1040 | method = getattr(self, '_encode_record_hex', None) |
| 1041 | if callable(method): |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 1042 | return h2b(method(abstract_data, record_nr=record_nr)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1043 | if self._construct: |
| 1044 | return self._construct.build(abstract_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1045 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1046 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1047 | t.from_dict(abstract_data) |
| 1048 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1049 | raise NotImplementedError( |
| 1050 | "%s encoder not yet implemented. Patches welcome." % self) |
| 1051 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1052 | |
| 1053 | class CyclicEF(LinFixedEF): |
| 1054 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 1055 | # 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] | 1056 | |
| 1057 | 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] | 1058 | rec_len: Size = (1, None), **kwargs): |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1059 | 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] | 1060 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1061 | |
| 1062 | class TransRecEF(TransparentEF): |
| 1063 | """Transparent EF (Entry File) containing fixed-size records. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1064 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1065 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 1066 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 1067 | inside. |
| 1068 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 1069 | for a record, while this class takes care of split / merge of records. |
| 1070 | """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1071 | |
| 1072 | 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] | 1073 | parent: Optional[CardDF] = None, size: Size = (1, None), **kwargs): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1074 | """ |
| 1075 | Args: |
| 1076 | fid : File Identifier (4 hex digits) |
| 1077 | sfid : Short File Identifier (2 hex digits, optional) |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1078 | name : Brief name of the file, like EF_ICCID |
| 1079 | desc : Description of the file |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1080 | parent : Parent CardFile object within filesystem hierarchy |
| 1081 | rec_len : Length of the fixed-length records within transparent EF |
| 1082 | size : tuple of (minimum_size, recommended_size) |
| 1083 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1084 | 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] | 1085 | self.rec_len = rec_len |
| 1086 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1087 | def decode_record_hex(self, raw_hex_data: str) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1088 | """Decode raw (hex string) data into abstract representation. |
| 1089 | |
| 1090 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 1091 | method for implementing this specifically for the given file. This function checks which |
| 1092 | of the method exists, add calls them (with conversion, as needed). |
| 1093 | |
| 1094 | Args: |
| 1095 | raw_hex_data : hex-encoded data |
| 1096 | Returns: |
| 1097 | abstract_data; dict representing the decoded data |
| 1098 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1099 | method = getattr(self, '_decode_record_hex', None) |
| 1100 | if callable(method): |
| 1101 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1102 | raw_bin_data = h2b(raw_hex_data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1103 | method = getattr(self, '_decode_record_bin', None) |
| 1104 | if callable(method): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1105 | return method(raw_bin_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1106 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 1107 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1108 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1109 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1110 | t.from_tlv(raw_bin_data) |
| 1111 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1112 | return {'raw': raw_hex_data} |
| 1113 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1114 | def decode_record_bin(self, raw_bin_data: bytearray) -> dict: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1115 | """Decode raw (binary) data into abstract representation. |
| 1116 | |
| 1117 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 1118 | method for implementing this specifically for the given file. This function checks which |
| 1119 | of the method exists, add calls them (with conversion, as needed). |
| 1120 | |
| 1121 | Args: |
| 1122 | raw_bin_data : binary encoded data |
| 1123 | Returns: |
| 1124 | abstract_data; dict representing the decoded data |
| 1125 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1126 | method = getattr(self, '_decode_record_bin', None) |
| 1127 | if callable(method): |
| 1128 | return method(raw_bin_data) |
| 1129 | raw_hex_data = b2h(raw_bin_data) |
| 1130 | method = getattr(self, '_decode_record_hex', None) |
| 1131 | if callable(method): |
| 1132 | return method(raw_hex_data) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1133 | if self._construct: |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 1134 | return parse_construct(self._construct, raw_bin_data) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1135 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1136 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1137 | t.from_tlv(raw_bin_data) |
| 1138 | return t.to_dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1139 | return {'raw': raw_hex_data} |
| 1140 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1141 | def encode_record_hex(self, abstract_data: dict) -> str: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1142 | """Encode abstract representation into raw (hex string) data. |
| 1143 | |
| 1144 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1145 | method for implementing this specifically for the given file. This function checks which |
| 1146 | of the method exists, add calls them (with conversion, as needed). |
| 1147 | |
| 1148 | Args: |
| 1149 | abstract_data : dict representing the decoded data |
| 1150 | Returns: |
| 1151 | hex string encoded data |
| 1152 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1153 | method = getattr(self, '_encode_record_hex', None) |
| 1154 | if callable(method): |
| 1155 | return method(abstract_data) |
| 1156 | method = getattr(self, '_encode_record_bin', None) |
| 1157 | if callable(method): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1158 | return b2h(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1159 | if self._construct: |
| 1160 | return b2h(filter_dict(self._construct.build(abstract_data))) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1161 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1162 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1163 | t.from_dict(abstract_data) |
| 1164 | return b2h(t.to_tlv()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1165 | raise NotImplementedError( |
| 1166 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1167 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1168 | def encode_record_bin(self, abstract_data: dict) -> bytearray: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1169 | """Encode abstract representation into raw (binary) data. |
| 1170 | |
| 1171 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 1172 | method for implementing this specifically for the given file. This function checks which |
| 1173 | of the method exists, add calls them (with conversion, as needed). |
| 1174 | |
| 1175 | Args: |
| 1176 | abstract_data : dict representing the decoded data |
| 1177 | Returns: |
| 1178 | binary encoded data |
| 1179 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1180 | method = getattr(self, '_encode_record_bin', None) |
| 1181 | if callable(method): |
| 1182 | return method(abstract_data) |
| 1183 | method = getattr(self, '_encode_record_hex', None) |
| 1184 | if callable(method): |
| 1185 | return h2b(method(abstract_data)) |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 1186 | if self._construct: |
| 1187 | return filter_dict(self._construct.build(abstract_data)) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 1188 | elif self._tlv: |
Harald Welte | ca60ac2 | 2022-02-10 18:01:02 +0100 | [diff] [blame] | 1189 | t = self._tlv() if inspect.isclass(self._tlv) else self._tlv |
Harald Welte | 944cd2f | 2022-01-21 16:01:29 +0100 | [diff] [blame] | 1190 | t.from_dict(abstract_data) |
| 1191 | return t.to_tlv() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1192 | raise NotImplementedError( |
| 1193 | "%s encoder not yet implemented. Patches welcome." % self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1194 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1195 | def _decode_bin(self, raw_bin_data: bytearray): |
| 1196 | chunks = [raw_bin_data[i:i+self.rec_len] |
| 1197 | for i in range(0, len(raw_bin_data), self.rec_len)] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1198 | return [self.decode_record_bin(x) for x in chunks] |
| 1199 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1200 | def _encode_bin(self, abstract_data) -> bytes: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1201 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 1202 | # FIXME: pad to file size |
| 1203 | return b''.join(chunks) |
| 1204 | |
| 1205 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1206 | class BerTlvEF(CardEF): |
Harald Welte | 2788162 | 2021-04-21 11:16:31 +0200 | [diff] [blame] | 1207 | """BER-TLV EF (Entry File) in the smart card filesystem. |
| 1208 | 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] | 1209 | |
Harald Welte | 2788162 | 2021-04-21 11:16:31 +0200 | [diff] [blame] | 1210 | NOTE: We currently don't really support those, this class is simply a wrapper |
| 1211 | around TransparentEF as a place-holder, so we can already define EFs of BER-TLV |
| 1212 | type without fully supporting them.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1213 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1214 | @with_default_category('BER-TLV EF Commands') |
| 1215 | class ShellCommands(CommandSet): |
| 1216 | """Shell commands specific for BER-TLV EFs.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1217 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1218 | def __init__(self): |
| 1219 | super().__init__() |
| 1220 | |
| 1221 | retrieve_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1222 | retrieve_data_parser.add_argument( |
| 1223 | 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve') |
| 1224 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1225 | @cmd2.with_argparser(retrieve_data_parser) |
| 1226 | def do_retrieve_data(self, opts): |
| 1227 | """Retrieve (Read) data from a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1228 | (data, sw) = self._cmd.lchan.retrieve_data(opts.tag) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1229 | self._cmd.poutput(data) |
| 1230 | |
| 1231 | def do_retrieve_tags(self, opts): |
| 1232 | """List tags available in a given BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1233 | tags = self._cmd.lchan.retrieve_tags() |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1234 | self._cmd.poutput(tags) |
| 1235 | |
| 1236 | set_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1237 | set_data_parser.add_argument( |
| 1238 | 'tag', type=auto_int, help='BER-TLV Tag of value to set') |
| 1239 | set_data_parser.add_argument( |
| 1240 | 'data', help='Data bytes (hex format) to write') |
| 1241 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1242 | @cmd2.with_argparser(set_data_parser) |
| 1243 | def do_set_data(self, opts): |
| 1244 | """Set (Write) data for a given tag in a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1245 | (data, sw) = self._cmd.lchan.set_data(opts.tag, opts.data) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1246 | if data: |
| 1247 | self._cmd.poutput(data) |
| 1248 | |
| 1249 | del_data_parser = argparse.ArgumentParser() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1250 | del_data_parser.add_argument( |
| 1251 | 'tag', type=auto_int, help='BER-TLV Tag of value to set') |
| 1252 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1253 | @cmd2.with_argparser(del_data_parser) |
| 1254 | def do_delete_data(self, opts): |
| 1255 | """Delete data for a given tag in a BER-TLV EF""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 1256 | (data, sw) = self._cmd.lchan.set_data(opts.tag, None) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1257 | if data: |
| 1258 | self._cmd.poutput(data) |
| 1259 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1260 | 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] | 1261 | size: Size = (1, None), **kwargs): |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 1262 | """ |
| 1263 | Args: |
| 1264 | fid : File Identifier (4 hex digits) |
| 1265 | sfid : Short File Identifier (2 hex digits, optional) |
| 1266 | name : Brief name of the file, lik EF_ICCID |
| 1267 | desc : Description of the file |
| 1268 | parent : Parent CardFile object within filesystem hierarchy |
| 1269 | size : tuple of (minimum_size, recommended_size) |
| 1270 | """ |
Harald Welte | 9170fbf | 2022-02-11 21:54:37 +0100 | [diff] [blame] | 1271 | 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] | 1272 | self._construct = None |
| 1273 | self.size = size |
| 1274 | self.shell_commands = [self.ShellCommands()] |
| 1275 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1276 | def interpret_sw(sw_data: dict, sw: str): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1277 | """Interpret a given status word. |
| 1278 | |
| 1279 | Args: |
| 1280 | sw_data : Hierarchical dict of status word matches |
| 1281 | sw : status word to match (string of 4 hex digits) |
| 1282 | Returns: |
| 1283 | tuple of two strings (class_string, description) |
| 1284 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1285 | for class_str, swdict in sw_data.items(): |
| 1286 | # first try direct match |
| 1287 | if sw in swdict: |
| 1288 | return (class_str, swdict[sw]) |
| 1289 | # next try wildcard matches |
| 1290 | for pattern, descr in swdict.items(): |
| 1291 | if sw_match(sw, pattern): |
| 1292 | return (class_str, descr) |
| 1293 | return None |
| 1294 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1295 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 1296 | class CardApplication: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1297 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 1298 | some SW definitions.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1299 | |
| 1300 | 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] | 1301 | """ |
| 1302 | Args: |
| 1303 | adf : ADF name |
| 1304 | sw : Dict of status word conversions |
| 1305 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1306 | self.name = name |
| 1307 | self.adf = adf |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1308 | self.sw = sw or dict() |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1309 | # back-reference from ADF to Applicaiton |
| 1310 | if self.adf: |
| 1311 | self.aid = aid or self.adf.aid |
| 1312 | self.adf.application = self |
| 1313 | else: |
| 1314 | self.aid = aid |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1315 | |
| 1316 | def __str__(self): |
| 1317 | return "APP(%s)" % (self.name) |
| 1318 | |
| 1319 | def interpret_sw(self, sw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1320 | """Interpret a given status word within the application. |
| 1321 | |
| 1322 | Args: |
Harald Welte | c9cdce3 | 2021-04-11 10:28:28 +0200 | [diff] [blame] | 1323 | sw : Status word as string of 4 hex digits |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1324 | |
| 1325 | Returns: |
| 1326 | Tuple of two strings |
| 1327 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1328 | return interpret_sw(self.sw, sw) |
| 1329 | |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1330 | |
| 1331 | class CardModel(abc.ABC): |
Harald Welte | 4c1dca0 | 2021-10-14 17:48:25 +0200 | [diff] [blame] | 1332 | """A specific card model, typically having some additional vendor-specific files. All |
| 1333 | you need to do is to define a sub-class with a list of ATRs or an overridden match |
| 1334 | method.""" |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1335 | _atrs = [] |
| 1336 | |
| 1337 | @classmethod |
| 1338 | @abc.abstractmethod |
Harald Welte | 531894d | 2023-07-11 19:11:11 +0200 | [diff] [blame] | 1339 | def add_files(cls, rs: 'RuntimeState'): |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1340 | """Add model specific files to given RuntimeState.""" |
| 1341 | |
| 1342 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1343 | def match(cls, scc: SimCardCommands) -> bool: |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1344 | """Test if given card matches this model.""" |
| 1345 | card_atr = scc.get_atr() |
| 1346 | for atr in cls._atrs: |
| 1347 | atr_bin = toBytes(atr) |
| 1348 | if atr_bin == card_atr: |
| 1349 | print("Detected CardModel:", cls.__name__) |
| 1350 | return True |
| 1351 | return False |
| 1352 | |
| 1353 | @staticmethod |
Harald Welte | 531894d | 2023-07-11 19:11:11 +0200 | [diff] [blame] | 1354 | def apply_matching_models(scc: SimCardCommands, rs: 'RuntimeState'): |
Harald Welte | 4c1dca0 | 2021-10-14 17:48:25 +0200 | [diff] [blame] | 1355 | """Check if any of the CardModel sub-classes 'match' the currently inserted card |
| 1356 | (by ATR or overriding the 'match' method). If so, call their 'add_files' |
| 1357 | method.""" |
Harald Welte | f44256c | 2021-10-14 15:53:39 +0200 | [diff] [blame] | 1358 | for m in CardModel.__subclasses__(): |
| 1359 | if m.match(scc): |
| 1360 | m.add_files(rs) |