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