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