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