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