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 |
| 28 | import json |
| 29 | |
| 30 | import cmd2 |
| 31 | from cmd2 import CommandSet, with_default_category, with_argparser |
| 32 | import argparse |
| 33 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 34 | from typing import cast, Optional, Iterable, List, Any, Dict, Tuple |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 35 | |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 36 | from pySim.utils import sw_match, h2b, b2h, is_hex |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 37 | from pySim.exceptions import * |
| 38 | |
| 39 | class CardFile(object): |
| 40 | """Base class for all objects in the smart card filesystem. |
| 41 | Serve as a common ancestor to all other file types; rarely used directly. |
| 42 | """ |
| 43 | RESERVED_NAMES = ['..', '.', '/', 'MF'] |
| 44 | RESERVED_FIDS = ['3f00'] |
| 45 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 46 | def __init__(self, fid:str=None, sfid:str=None, name:str=None, desc:str=None, |
| 47 | parent:Optional['CardDF']=None): |
| 48 | """ |
| 49 | Args: |
| 50 | fid : File Identifier (4 hex digits) |
| 51 | sfid : Short File Identifier (2 hex digits, optional) |
| 52 | name : Brief name of the file, lik EF_ICCID |
| 53 | desc : Descriptoin of the file |
| 54 | parent : Parent CardFile object within filesystem hierarchy |
| 55 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 56 | if not isinstance(self, CardADF) and fid == None: |
| 57 | raise ValueError("fid is mandatory") |
| 58 | if fid: |
| 59 | fid = fid.lower() |
| 60 | self.fid = fid # file identifier |
| 61 | self.sfid = sfid # short file identifier |
| 62 | self.name = name # human readable name |
| 63 | self.desc = desc # human readable description |
| 64 | self.parent = parent |
| 65 | if self.parent and self.parent != self and self.fid: |
| 66 | self.parent.add_file(self) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 67 | self.shell_commands: List[CommandSet] = [] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 68 | |
Philipp Maier | 6606158 | 2021-03-09 21:57:57 +0100 | [diff] [blame] | 69 | # Note: the basic properties (fid, name, ect.) are verified when |
| 70 | # the file is attached to a parent file. See method add_file() in |
| 71 | # class Card DF |
| 72 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 73 | def __str__(self): |
| 74 | if self.name: |
| 75 | return self.name |
| 76 | else: |
| 77 | return self.fid |
| 78 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 79 | def _path_element(self, prefer_name:bool) -> Optional[str]: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 80 | if prefer_name and self.name: |
| 81 | return self.name |
| 82 | else: |
| 83 | return self.fid |
| 84 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 85 | def fully_qualified_path(self, prefer_name:bool=True) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 86 | """Return fully qualified path to file as list of FID or name strings. |
| 87 | |
| 88 | Args: |
| 89 | prefer_name : Preferably build path of names; fall-back to FIDs as required |
| 90 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 91 | if self.parent and self.parent != self: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 92 | ret = self.parent.fully_qualified_path(prefer_name) |
| 93 | else: |
| 94 | ret = [] |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 95 | elem = self._path_element(prefer_name) |
| 96 | if elem: |
| 97 | ret.append(elem) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 98 | return ret |
| 99 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 100 | def get_mf(self) -> Optional['CardMF']: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 101 | """Return the MF (root) of the file system.""" |
| 102 | if self.parent == None: |
| 103 | return None |
| 104 | # iterate towards the top. MF has parent == self |
| 105 | node = self |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 106 | while node.parent and node.parent != node: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 107 | node = node.parent |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 108 | return cast(CardMF, node) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 109 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 110 | def _get_self_selectables(self, alias:str=None, flags = []) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 111 | """Return a dict of {'identifier': self} tuples. |
| 112 | |
| 113 | Args: |
| 114 | alias : Add an alias with given name to 'self' |
| 115 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 116 | If not specified, all selectables will be returned. |
| 117 | Returns: |
| 118 | dict containing reference to 'self' for all identifiers. |
| 119 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 120 | sels = {} |
| 121 | if alias: |
| 122 | sels.update({alias: self}) |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 123 | if self.fid and (flags == [] or 'FIDS' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 124 | sels.update({self.fid: self}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 125 | if self.name and (flags == [] or 'FNAMES' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 126 | sels.update({self.name: self}) |
| 127 | return sels |
| 128 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 129 | def get_selectables(self, flags = []) -> Dict[str, 'CardFile']: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 130 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 131 | |
| 132 | Args: |
| 133 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 134 | If not specified, all selectables will be returned. |
| 135 | Returns: |
| 136 | dict containing all selectable items. Key is identifier (string), value |
| 137 | a reference to a CardFile (or derived class) instance. |
| 138 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 139 | sels = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 140 | # we can always select ourself |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 141 | if flags == [] or 'SELF' in flags: |
| 142 | sels = self._get_self_selectables('.', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 143 | # we can always select our parent |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 144 | if flags == [] or 'PARENT' in flags: |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 145 | if self.parent: |
| 146 | sels = self.parent._get_self_selectables('..', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 147 | # if we have a MF, we can always select its applications |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 148 | if flags == [] or 'MF' in flags: |
| 149 | mf = self.get_mf() |
| 150 | if mf: |
| 151 | sels.update(mf._get_self_selectables(flags = flags)) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 152 | sels.update(mf.get_app_selectables(flags = flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 153 | return sels |
| 154 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 155 | def get_selectable_names(self, flags = []) -> List[str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 156 | """Return a dict of {'identifier': File} that is selectable from the current file. |
| 157 | |
| 158 | Args: |
| 159 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 160 | If not specified, all selectables will be returned. |
| 161 | Returns: |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 162 | list containing all selectable names. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 163 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 164 | sels = self.get_selectables(flags) |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 165 | return list(sels.keys()) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 166 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 167 | def decode_select_response(self, data_hex:str): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 168 | """Decode the response to a SELECT command.""" |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 169 | if self.parent: |
| 170 | return self.parent.decode_select_response(data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 171 | |
| 172 | |
| 173 | class CardDF(CardFile): |
| 174 | """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] | 175 | |
| 176 | @with_default_category('DF/ADF Commands') |
| 177 | class ShellCommands(CommandSet): |
| 178 | def __init__(self): |
| 179 | super().__init__() |
| 180 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 181 | def __init__(self, **kwargs): |
| 182 | if not isinstance(self, CardADF): |
| 183 | if not 'fid' in kwargs: |
| 184 | raise TypeError('fid is mandatory for all DF') |
| 185 | super().__init__(**kwargs) |
| 186 | self.children = dict() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 187 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 188 | |
| 189 | def __str__(self): |
| 190 | return "DF(%s)" % (super().__str__()) |
| 191 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 192 | def add_file(self, child:CardFile, ignore_existing:bool=False): |
| 193 | """Add a child (DF/EF) to this DF. |
| 194 | Args: |
| 195 | child: The new DF/EF to be added |
| 196 | ignore_existing: Ignore, if file with given FID already exists. Old one will be kept. |
| 197 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 198 | if not isinstance(child, CardFile): |
| 199 | raise TypeError("Expected a File instance") |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 200 | if not is_hex(child.fid, minlen = 4, maxlen = 4): |
| 201 | raise ValueError("File name %s is not a valid fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 202 | if child.name in CardFile.RESERVED_NAMES: |
| 203 | raise ValueError("File name %s is a reserved name" % (child.name)) |
| 204 | if child.fid in CardFile.RESERVED_FIDS: |
Philipp Maier | e8bc1b4 | 2021-03-09 20:33:41 +0100 | [diff] [blame] | 205 | raise ValueError("File fid %s is a reserved fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 206 | if child.fid in self.children: |
| 207 | if ignore_existing: |
| 208 | return |
| 209 | raise ValueError("File with given fid %s already exists" % (child.fid)) |
| 210 | if self.lookup_file_by_sfid(child.sfid): |
| 211 | raise ValueError("File with given sfid %s already exists" % (child.sfid)) |
| 212 | if self.lookup_file_by_name(child.name): |
| 213 | if ignore_existing: |
| 214 | return |
| 215 | raise ValueError("File with given name %s already exists" % (child.name)) |
| 216 | self.children[child.fid] = child |
| 217 | child.parent = self |
| 218 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 219 | def add_files(self, children:Iterable[CardFile], ignore_existing:bool=False): |
| 220 | """Add a list of child (DF/EF) to this DF |
| 221 | |
| 222 | Args: |
| 223 | children: List of new DF/EFs to be added |
| 224 | ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept. |
| 225 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 226 | for child in children: |
| 227 | self.add_file(child, ignore_existing) |
| 228 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 229 | def get_selectables(self, flags = []) -> dict: |
| 230 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 231 | |
| 232 | Args: |
| 233 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 234 | If not specified, all selectables will be returned. |
| 235 | Returns: |
| 236 | dict containing all selectable items. Key is identifier (string), value |
| 237 | a reference to a CardFile (or derived class) instance. |
| 238 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 239 | # global selectables + our children |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 240 | sels = super().get_selectables(flags) |
| 241 | if flags == [] or 'FIDS' in flags: |
| 242 | 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] | 243 | if flags == [] or 'FNAMES' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 244 | 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] | 245 | return sels |
| 246 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 247 | def lookup_file_by_name(self, name:Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 248 | """Find a file with given name within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 249 | if name == None: |
| 250 | return None |
| 251 | for i in self.children.values(): |
| 252 | if i.name and i.name == name: |
| 253 | return i |
| 254 | return None |
| 255 | |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 256 | def lookup_file_by_sfid(self, sfid:Optional[str]) -> Optional[CardFile]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 257 | """Find a file with given short file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 258 | if sfid == None: |
| 259 | return None |
| 260 | for i in self.children.values(): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 261 | if i.sfid == int(str(sfid)): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 262 | return i |
| 263 | return None |
| 264 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 265 | def lookup_file_by_fid(self, fid:str) -> Optional[CardFile]: |
| 266 | """Find a file with given file ID within current DF.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 267 | if fid in self.children: |
| 268 | return self.children[fid] |
| 269 | return None |
| 270 | |
| 271 | |
| 272 | class CardMF(CardDF): |
| 273 | """MF (Master File) in the smart card filesystem""" |
| 274 | def __init__(self, **kwargs): |
| 275 | # can be overridden; use setdefault |
| 276 | kwargs.setdefault('fid', '3f00') |
| 277 | kwargs.setdefault('name', 'MF') |
| 278 | kwargs.setdefault('desc', 'Master File (directory root)') |
| 279 | # cannot be overridden; use assignment |
| 280 | kwargs['parent'] = self |
| 281 | super().__init__(**kwargs) |
| 282 | self.applications = dict() |
| 283 | |
| 284 | def __str__(self): |
| 285 | return "MF(%s)" % (self.fid) |
| 286 | |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 287 | def add_application_df(self, app:'CardADF'): |
| 288 | """Add an Application to the MF""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 289 | if not isinstance(app, CardADF): |
| 290 | raise TypeError("Expected an ADF instance") |
| 291 | if app.aid in self.applications: |
| 292 | raise ValueError("AID %s already exists" % (app.aid)) |
| 293 | self.applications[app.aid] = app |
| 294 | app.parent=self |
| 295 | |
| 296 | def get_app_names(self): |
| 297 | """Get list of completions (AID names)""" |
| 298 | return [x.name for x in self.applications] |
| 299 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 300 | def get_selectables(self, flags = []) -> dict: |
| 301 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 302 | |
| 303 | Args: |
| 304 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 305 | If not specified, all selectables will be returned. |
| 306 | Returns: |
| 307 | dict containing all selectable items. Key is identifier (string), value |
| 308 | a reference to a CardFile (or derived class) instance. |
| 309 | """ |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 310 | sels = super().get_selectables(flags) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 311 | sels.update(self.get_app_selectables(flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 312 | return sels |
| 313 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 314 | def get_app_selectables(self, flags = []) -> dict: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 315 | """Get applications by AID + name""" |
| 316 | sels = {} |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 317 | if flags == [] or 'AIDS' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 318 | sels.update({x.aid: x for x in self.applications.values()}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 319 | if flags == [] or 'ANAMES' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 320 | sels.update({x.name: x for x in self.applications.values() if x.name}) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 321 | return sels |
| 322 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 323 | def decode_select_response(self, data_hex:str) -> Any: |
| 324 | """Decode the response to a SELECT command. |
| 325 | |
| 326 | This is the fall-back method which doesn't perform any decoding. It mostly |
| 327 | exists so specific derived classes can overload it for actual decoding. |
| 328 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 329 | return data_hex |
| 330 | |
| 331 | |
| 332 | |
| 333 | class CardADF(CardDF): |
| 334 | """ADF (Application Dedicated File) in the smart card filesystem""" |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 335 | def __init__(self, aid:str, **kwargs): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 336 | super().__init__(**kwargs) |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 337 | # reference to CardApplication may be set from CardApplication constructor |
| 338 | self.application:Optional[CardApplication] = None |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 339 | self.aid = aid # Application Identifier |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 340 | mf = self.get_mf() |
| 341 | if mf: |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 342 | mf.add_application_df(self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 343 | |
| 344 | def __str__(self): |
| 345 | return "ADF(%s)" % (self.aid) |
| 346 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 347 | def _path_element(self, prefer_name:bool): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 348 | if self.name and prefer_name: |
| 349 | return self.name |
| 350 | else: |
| 351 | return self.aid |
| 352 | |
| 353 | |
| 354 | class CardEF(CardFile): |
| 355 | """EF (Entry File) in the smart card filesystem""" |
| 356 | def __init__(self, *, fid, **kwargs): |
| 357 | kwargs['fid'] = fid |
| 358 | super().__init__(**kwargs) |
| 359 | |
| 360 | def __str__(self): |
| 361 | return "EF(%s)" % (super().__str__()) |
| 362 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 363 | def get_selectables(self, flags = []) -> dict: |
| 364 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 365 | |
| 366 | Args: |
| 367 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 368 | If not specified, all selectables will be returned. |
| 369 | Returns: |
| 370 | dict containing all selectable items. Key is identifier (string), value |
| 371 | a reference to a CardFile (or derived class) instance. |
| 372 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 373 | #global selectable names + those of the parent DF |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 374 | sels = super().get_selectables(flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 375 | sels.update({x.name:x for x in self.parent.children.values() if x != self}) |
| 376 | return sels |
| 377 | |
| 378 | |
| 379 | class TransparentEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 380 | """Transparent EF (Entry File) in the smart card filesystem. |
| 381 | |
| 382 | A Transparent EF is a binary file with no formal structure. This is contrary to |
| 383 | 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] | 384 | |
| 385 | @with_default_category('Transparent EF Commands') |
| 386 | class ShellCommands(CommandSet): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 387 | """Shell commands specific for Trransparent EFs.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 388 | def __init__(self): |
| 389 | super().__init__() |
| 390 | |
| 391 | read_bin_parser = argparse.ArgumentParser() |
| 392 | read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 393 | read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read') |
| 394 | @cmd2.with_argparser(read_bin_parser) |
| 395 | def do_read_binary(self, opts): |
| 396 | """Read binary data from a transparent EF""" |
| 397 | (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset) |
| 398 | self._cmd.poutput(data) |
| 399 | |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame^] | 400 | read_bin_dec_parser = argparse.ArgumentParser() |
| 401 | read_bin_dec_parser.add_argument('--oneline', action='store_true', |
| 402 | help='No JSON pretty-printing, dump as a single line') |
| 403 | @cmd2.with_argparser(read_bin_dec_parser) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 404 | def do_read_binary_decoded(self, opts): |
| 405 | """Read + decode data from a transparent EF""" |
| 406 | (data, sw) = self._cmd.rs.read_binary_dec() |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame^] | 407 | if opts.oneline: |
| 408 | output = json.dumps(data) |
| 409 | else: |
| 410 | output = json.dumps(data, indent=4) |
| 411 | self._cmd.poutput(output) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 412 | |
| 413 | upd_bin_parser = argparse.ArgumentParser() |
| 414 | upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 415 | upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 416 | @cmd2.with_argparser(upd_bin_parser) |
| 417 | def do_update_binary(self, opts): |
| 418 | """Update (Write) data of a transparent EF""" |
| 419 | (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 420 | if data: |
| 421 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 422 | |
| 423 | upd_bin_dec_parser = argparse.ArgumentParser() |
| 424 | upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write') |
| 425 | @cmd2.with_argparser(upd_bin_dec_parser) |
| 426 | def do_update_binary_decoded(self, opts): |
| 427 | """Encode + Update (Write) data of a transparent EF""" |
| 428 | data_json = json.loads(opts.data) |
| 429 | (data, sw) = self._cmd.rs.update_binary_dec(data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 430 | if data: |
| 431 | self._cmd.poutput(json.dumps(data, indent=4)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 432 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 433 | def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None, |
| 434 | size={1,None}): |
| 435 | """ |
| 436 | Args: |
| 437 | fid : File Identifier (4 hex digits) |
| 438 | sfid : Short File Identifier (2 hex digits, optional) |
| 439 | name : Brief name of the file, lik EF_ICCID |
| 440 | desc : Descriptoin of the file |
| 441 | parent : Parent CardFile object within filesystem hierarchy |
| 442 | size : tuple of (minimum_size, recommended_size) |
| 443 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 444 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 445 | self.size = size |
| 446 | self.shell_commands = [self.ShellCommands()] |
| 447 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 448 | def decode_bin(self, raw_bin_data:bytearray) -> dict: |
| 449 | """Decode raw (binary) data into abstract representation. |
| 450 | |
| 451 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 452 | for implementing this specifically for the given file. This function checks which |
| 453 | of the method exists, add calls them (with conversion, as needed). |
| 454 | |
| 455 | Args: |
| 456 | raw_bin_data : binary encoded data |
| 457 | Returns: |
| 458 | abstract_data; dict representing the decoded data |
| 459 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 460 | method = getattr(self, '_decode_bin', None) |
| 461 | if callable(method): |
| 462 | return method(raw_bin_data) |
| 463 | method = getattr(self, '_decode_hex', None) |
| 464 | if callable(method): |
| 465 | return method(b2h(raw_bin_data)) |
| 466 | return {'raw': raw_bin_data.hex()} |
| 467 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 468 | def decode_hex(self, raw_hex_data:str) -> dict: |
| 469 | """Decode raw (hex string) data into abstract representation. |
| 470 | |
| 471 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 472 | for implementing this specifically for the given file. This function checks which |
| 473 | of the method exists, add calls them (with conversion, as needed). |
| 474 | |
| 475 | Args: |
| 476 | raw_hex_data : hex-encoded data |
| 477 | Returns: |
| 478 | abstract_data; dict representing the decoded data |
| 479 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 480 | method = getattr(self, '_decode_hex', None) |
| 481 | if callable(method): |
| 482 | return method(raw_hex_data) |
| 483 | raw_bin_data = h2b(raw_hex_data) |
| 484 | method = getattr(self, '_decode_bin', None) |
| 485 | if callable(method): |
| 486 | return method(raw_bin_data) |
| 487 | return {'raw': raw_bin_data.hex()} |
| 488 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 489 | def encode_bin(self, abstract_data:dict) -> bytearray: |
| 490 | """Encode abstract representation into raw (binary) data. |
| 491 | |
| 492 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 493 | for implementing this specifically for the given file. This function checks which |
| 494 | of the method exists, add calls them (with conversion, as needed). |
| 495 | |
| 496 | Args: |
| 497 | abstract_data : dict representing the decoded data |
| 498 | Returns: |
| 499 | binary encoded data |
| 500 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 501 | method = getattr(self, '_encode_bin', None) |
| 502 | if callable(method): |
| 503 | return method(abstract_data) |
| 504 | method = getattr(self, '_encode_hex', None) |
| 505 | if callable(method): |
| 506 | return h2b(method(abstract_data)) |
| 507 | raise NotImplementedError |
| 508 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 509 | def encode_hex(self, abstract_data:dict) -> str: |
| 510 | """Encode abstract representation into raw (hex string) data. |
| 511 | |
| 512 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 513 | for implementing this specifically for the given file. This function checks which |
| 514 | of the method exists, add calls them (with conversion, as needed). |
| 515 | |
| 516 | Args: |
| 517 | abstract_data : dict representing the decoded data |
| 518 | Returns: |
| 519 | hex string encoded data |
| 520 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 521 | method = getattr(self, '_encode_hex', None) |
| 522 | if callable(method): |
| 523 | return method(abstract_data) |
| 524 | method = getattr(self, '_encode_bin', None) |
| 525 | if callable(method): |
| 526 | raw_bin_data = method(abstract_data) |
| 527 | return b2h(raw_bin_data) |
| 528 | raise NotImplementedError |
| 529 | |
| 530 | |
| 531 | class LinFixedEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 532 | """Linear Fixed EF (Entry File) in the smart card filesystem. |
| 533 | |
| 534 | Linear Fixed EFs are record oriented files. They consist of a number of fixed-size |
| 535 | records. The records can be individually read/updated.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 536 | |
| 537 | @with_default_category('Linear Fixed EF Commands') |
| 538 | class ShellCommands(CommandSet): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 539 | """Shell commands specific for Linear Fixed EFs.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 540 | def __init__(self): |
| 541 | super().__init__() |
| 542 | |
| 543 | read_rec_parser = argparse.ArgumentParser() |
| 544 | read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 545 | read_rec_parser.add_argument('--count', type=int, default=1, help='Number of records to be read, beginning at record_nr') |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 546 | @cmd2.with_argparser(read_rec_parser) |
| 547 | def do_read_record(self, opts): |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 548 | """Read one or multiple records from a record-oriented EF""" |
| 549 | for r in range(opts.count): |
| 550 | recnr = opts.record_nr + r |
| 551 | (data, sw) = self._cmd.rs.read_record(recnr) |
| 552 | if (len(data) > 0): |
| 553 | recstr = str(data) |
| 554 | else: |
| 555 | recstr = "(empty)" |
| 556 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 557 | |
| 558 | read_rec_dec_parser = argparse.ArgumentParser() |
| 559 | read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame^] | 560 | read_rec_dec_parser.add_argument('--oneline', action='store_true', |
| 561 | help='No JSON pretty-printing, dump as a single line') |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 562 | @cmd2.with_argparser(read_rec_dec_parser) |
| 563 | def do_read_record_decoded(self, opts): |
| 564 | """Read + decode a record from a record-oriented EF""" |
| 565 | (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr) |
Harald Welte | bcad86c | 2021-04-06 20:08:39 +0200 | [diff] [blame^] | 566 | if opts.oneline: |
| 567 | output = json.dumps(data) |
| 568 | else: |
| 569 | output = json.dumps(data, indent=4) |
| 570 | self._cmd.poutput(output) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 571 | |
| 572 | upd_rec_parser = argparse.ArgumentParser() |
| 573 | upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 574 | upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 575 | @cmd2.with_argparser(upd_rec_parser) |
| 576 | def do_update_record(self, opts): |
| 577 | """Update (write) data to a record-oriented EF""" |
| 578 | (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 579 | if data: |
| 580 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 581 | |
| 582 | upd_rec_dec_parser = argparse.ArgumentParser() |
| 583 | upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 584 | upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 585 | @cmd2.with_argparser(upd_rec_dec_parser) |
| 586 | def do_update_record_decoded(self, opts): |
| 587 | """Encode + Update (write) data to a record-oriented EF""" |
| 588 | (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 589 | if data: |
| 590 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 591 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 592 | def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, |
| 593 | parent:Optional[CardDF]=None, rec_len={1,None}): |
| 594 | """ |
| 595 | Args: |
| 596 | fid : File Identifier (4 hex digits) |
| 597 | sfid : Short File Identifier (2 hex digits, optional) |
| 598 | name : Brief name of the file, lik EF_ICCID |
| 599 | desc : Descriptoin of the file |
| 600 | parent : Parent CardFile object within filesystem hierarchy |
| 601 | rec_len : tuple of (minimum_length, recommended_length) |
| 602 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 603 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 604 | self.rec_len = rec_len |
| 605 | self.shell_commands = [self.ShellCommands()] |
| 606 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 607 | def decode_record_hex(self, raw_hex_data:str) -> dict: |
| 608 | """Decode raw (hex string) data into abstract representation. |
| 609 | |
| 610 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 611 | method for implementing this specifically for the given file. This function checks which |
| 612 | of the method exists, add calls them (with conversion, as needed). |
| 613 | |
| 614 | Args: |
| 615 | raw_hex_data : hex-encoded data |
| 616 | Returns: |
| 617 | abstract_data; dict representing the decoded data |
| 618 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 619 | method = getattr(self, '_decode_record_hex', None) |
| 620 | if callable(method): |
| 621 | return method(raw_hex_data) |
| 622 | raw_bin_data = h2b(raw_hex_data) |
| 623 | method = getattr(self, '_decode_record_bin', None) |
| 624 | if callable(method): |
| 625 | return method(raw_bin_data) |
| 626 | return {'raw': raw_bin_data.hex()} |
| 627 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 628 | def decode_record_bin(self, raw_bin_data:bytearray) -> dict: |
| 629 | """Decode raw (binary) data into abstract representation. |
| 630 | |
| 631 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 632 | method for implementing this specifically for the given file. This function checks which |
| 633 | of the method exists, add calls them (with conversion, as needed). |
| 634 | |
| 635 | Args: |
| 636 | raw_bin_data : binary encoded data |
| 637 | Returns: |
| 638 | abstract_data; dict representing the decoded data |
| 639 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 640 | method = getattr(self, '_decode_record_bin', None) |
| 641 | if callable(method): |
| 642 | return method(raw_bin_data) |
| 643 | raw_hex_data = b2h(raw_bin_data) |
| 644 | method = getattr(self, '_decode_record_hex', None) |
| 645 | if callable(method): |
| 646 | return method(raw_hex_data) |
| 647 | return {'raw': raw_hex_data} |
| 648 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 649 | def encode_record_hex(self, abstract_data:dict) -> str: |
| 650 | """Encode abstract representation into raw (hex string) data. |
| 651 | |
| 652 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 653 | method for implementing this specifically for the given file. This function checks which |
| 654 | of the method exists, add calls them (with conversion, as needed). |
| 655 | |
| 656 | Args: |
| 657 | abstract_data : dict representing the decoded data |
| 658 | Returns: |
| 659 | hex string encoded data |
| 660 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 661 | method = getattr(self, '_encode_record_hex', None) |
| 662 | if callable(method): |
| 663 | return method(abstract_data) |
| 664 | method = getattr(self, '_encode_record_bin', None) |
| 665 | if callable(method): |
| 666 | raw_bin_data = method(abstract_data) |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 667 | return b2h(raw_bin_data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 668 | raise NotImplementedError |
| 669 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 670 | def encode_record_bin(self, abstract_data:dict) -> bytearray: |
| 671 | """Encode abstract representation into raw (binary) data. |
| 672 | |
| 673 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 674 | method for implementing this specifically for the given file. This function checks which |
| 675 | of the method exists, add calls them (with conversion, as needed). |
| 676 | |
| 677 | Args: |
| 678 | abstract_data : dict representing the decoded data |
| 679 | Returns: |
| 680 | binary encoded data |
| 681 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 682 | method = getattr(self, '_encode_record_bin', None) |
| 683 | if callable(method): |
| 684 | return method(abstract_data) |
| 685 | method = getattr(self, '_encode_record_hex', None) |
| 686 | if callable(method): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 687 | return h2b(method(abstract_data)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 688 | raise NotImplementedError |
| 689 | |
| 690 | class CyclicEF(LinFixedEF): |
| 691 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 692 | # we don't really have any special support for those; just recycling LinFixedEF here |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 693 | def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None, |
| 694 | rec_len={1,None}): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 695 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len) |
| 696 | |
| 697 | class TransRecEF(TransparentEF): |
| 698 | """Transparent EF (Entry File) containing fixed-size records. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 699 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 700 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 701 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 702 | inside. |
| 703 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 704 | for a record, while this class takes care of split / merge of records. |
| 705 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 706 | def __init__(self, fid:str, rec_len:int, sfid:str=None, name:str=None, desc:str=None, |
| 707 | parent:Optional[CardDF]=None, size={1,None}): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 708 | """ |
| 709 | Args: |
| 710 | fid : File Identifier (4 hex digits) |
| 711 | sfid : Short File Identifier (2 hex digits, optional) |
| 712 | name : Brief name of the file, lik EF_ICCID |
| 713 | desc : Descriptoin of the file |
| 714 | parent : Parent CardFile object within filesystem hierarchy |
| 715 | rec_len : Length of the fixed-length records within transparent EF |
| 716 | size : tuple of (minimum_size, recommended_size) |
| 717 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 718 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size) |
| 719 | self.rec_len = rec_len |
| 720 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 721 | def decode_record_hex(self, raw_hex_data:str) -> dict: |
| 722 | """Decode raw (hex string) data into abstract representation. |
| 723 | |
| 724 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 725 | method for implementing this specifically for the given file. This function checks which |
| 726 | of the method exists, add calls them (with conversion, as needed). |
| 727 | |
| 728 | Args: |
| 729 | raw_hex_data : hex-encoded data |
| 730 | Returns: |
| 731 | abstract_data; dict representing the decoded data |
| 732 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 733 | method = getattr(self, '_decode_record_hex', None) |
| 734 | if callable(method): |
| 735 | return method(raw_hex_data) |
| 736 | method = getattr(self, '_decode_record_bin', None) |
| 737 | if callable(method): |
| 738 | raw_bin_data = h2b(raw_hex_data) |
| 739 | return method(raw_bin_data) |
| 740 | return {'raw': raw_hex_data} |
| 741 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 742 | def decode_record_bin(self, raw_bin_data:bytearray) -> dict: |
| 743 | """Decode raw (binary) data into abstract representation. |
| 744 | |
| 745 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 746 | method for implementing this specifically for the given file. This function checks which |
| 747 | of the method exists, add calls them (with conversion, as needed). |
| 748 | |
| 749 | Args: |
| 750 | raw_bin_data : binary encoded data |
| 751 | Returns: |
| 752 | abstract_data; dict representing the decoded data |
| 753 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 754 | method = getattr(self, '_decode_record_bin', None) |
| 755 | if callable(method): |
| 756 | return method(raw_bin_data) |
| 757 | raw_hex_data = b2h(raw_bin_data) |
| 758 | method = getattr(self, '_decode_record_hex', None) |
| 759 | if callable(method): |
| 760 | return method(raw_hex_data) |
| 761 | return {'raw': raw_hex_data} |
| 762 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 763 | def encode_record_hex(self, abstract_data:dict) -> str: |
| 764 | """Encode abstract representation into raw (hex string) data. |
| 765 | |
| 766 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 767 | method for implementing this specifically for the given file. This function checks which |
| 768 | of the method exists, add calls them (with conversion, as needed). |
| 769 | |
| 770 | Args: |
| 771 | abstract_data : dict representing the decoded data |
| 772 | Returns: |
| 773 | hex string encoded data |
| 774 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 775 | method = getattr(self, '_encode_record_hex', None) |
| 776 | if callable(method): |
| 777 | return method(abstract_data) |
| 778 | method = getattr(self, '_encode_record_bin', None) |
| 779 | if callable(method): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 780 | return b2h(method(abstract_data)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 781 | raise NotImplementedError |
| 782 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 783 | def encode_record_bin(self, abstract_data:dict) -> bytearray: |
| 784 | """Encode abstract representation into raw (binary) data. |
| 785 | |
| 786 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 787 | method for implementing this specifically for the given file. This function checks which |
| 788 | of the method exists, add calls them (with conversion, as needed). |
| 789 | |
| 790 | Args: |
| 791 | abstract_data : dict representing the decoded data |
| 792 | Returns: |
| 793 | binary encoded data |
| 794 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 795 | method = getattr(self, '_encode_record_bin', None) |
| 796 | if callable(method): |
| 797 | return method(abstract_data) |
| 798 | method = getattr(self, '_encode_record_hex', None) |
| 799 | if callable(method): |
| 800 | return h2b(method(abstract_data)) |
| 801 | raise NotImplementedError |
| 802 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 803 | def _decode_bin(self, raw_bin_data:bytearray): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 804 | chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)] |
| 805 | return [self.decode_record_bin(x) for x in chunks] |
| 806 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 807 | def _encode_bin(self, abstract_data) -> bytes: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 808 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 809 | # FIXME: pad to file size |
| 810 | return b''.join(chunks) |
| 811 | |
| 812 | |
| 813 | |
| 814 | |
| 815 | |
| 816 | class RuntimeState(object): |
| 817 | """Represent the runtime state of a session with a card.""" |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 818 | def __init__(self, card, profile:'CardProfile'): |
| 819 | """ |
| 820 | Args: |
| 821 | card : pysim.cards.Card instance |
| 822 | profile : CardProfile instance |
| 823 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 824 | self.mf = CardMF() |
| 825 | self.card = card |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 826 | self.selected_file:CardDF = self.mf |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 827 | self.profile = profile |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 828 | # add application ADFs + MF-files from profile |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 829 | apps = self._match_applications() |
| 830 | for a in apps: |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 831 | if a.adf: |
| 832 | self.mf.add_application_df(a.adf) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 833 | for f in self.profile.files_in_mf: |
| 834 | self.mf.add_file(f) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 835 | self.conserve_write = True |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 836 | |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 837 | def _match_applications(self): |
| 838 | """match the applications from the profile with applications on the card""" |
| 839 | apps_profile = self.profile.applications |
| 840 | aids_card = self.card.read_aids() |
| 841 | apps_taken = [] |
| 842 | if aids_card: |
| 843 | aids_taken = [] |
| 844 | print("AIDs on card:") |
| 845 | for a in aids_card: |
| 846 | for f in apps_profile: |
| 847 | if f.aid in a: |
| 848 | print(" %s: %s" % (f.name, a)) |
| 849 | aids_taken.append(a) |
| 850 | apps_taken.append(f) |
| 851 | aids_unknown = set(aids_card) - set(aids_taken) |
| 852 | for a in aids_unknown: |
| 853 | print(" unknown: %s" % a) |
| 854 | else: |
| 855 | print("error: could not determine card applications") |
| 856 | return apps_taken |
| 857 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 858 | def get_cwd(self) -> CardDF: |
| 859 | """Obtain the current working directory. |
| 860 | |
| 861 | Returns: |
| 862 | CardDF instance |
| 863 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 864 | if isinstance(self.selected_file, CardDF): |
| 865 | return self.selected_file |
| 866 | else: |
| 867 | return self.selected_file.parent |
| 868 | |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 869 | def get_application_df(self) -> Optional[CardADF]: |
| 870 | """Obtain the currently selected application DF (if any). |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 871 | |
| 872 | Returns: |
| 873 | CardADF() instance or None""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 874 | # iterate upwards from selected file; check if any is an ADF |
| 875 | node = self.selected_file |
| 876 | while node.parent != node: |
| 877 | if isinstance(node, CardADF): |
| 878 | return node |
| 879 | node = node.parent |
| 880 | return None |
| 881 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 882 | def interpret_sw(self, sw:str): |
| 883 | """Interpret a given status word relative to the currently selected application |
| 884 | or the underlying card profile. |
| 885 | |
| 886 | Args: |
| 887 | sw : Status word as string of 4 hexd digits |
| 888 | |
| 889 | Returns: |
| 890 | Tuple of two strings |
| 891 | """ |
Harald Welte | 86fbd39 | 2021-04-02 22:13:09 +0200 | [diff] [blame] | 892 | res = None |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 893 | adf = self.get_application_df() |
| 894 | if adf: |
| 895 | app = adf.application |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 896 | # The application either comes with its own interpret_sw |
| 897 | # method or we will use the interpret_sw method from the |
| 898 | # card profile. |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 899 | if app and hasattr(app, "interpret_sw"): |
Harald Welte | 86fbd39 | 2021-04-02 22:13:09 +0200 | [diff] [blame] | 900 | res = app.interpret_sw(sw) |
| 901 | return res or self.profile.interpret_sw(sw) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 902 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 903 | def probe_file(self, fid:str, cmd_app=None): |
| 904 | """Blindly try to select a file and automatically add a matching file |
| 905 | object if the file actually exists.""" |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 906 | if not is_hex(fid, 4, 4): |
| 907 | raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid) |
| 908 | |
| 909 | try: |
| 910 | (data, sw) = self.card._scc.select_file(fid) |
| 911 | except SwMatchError as swm: |
| 912 | k = self.interpret_sw(swm.sw_actual) |
| 913 | if not k: |
| 914 | raise(swm) |
| 915 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
| 916 | |
| 917 | select_resp = self.selected_file.decode_select_response(data) |
| 918 | if (select_resp['file_descriptor']['file_type'] == 'df'): |
| 919 | f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime") |
| 920 | else: |
| 921 | if (select_resp['file_descriptor']['structure'] == 'transparent'): |
| 922 | f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime") |
| 923 | else: |
| 924 | f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime") |
| 925 | |
| 926 | self.selected_file.add_files([f]) |
| 927 | self.selected_file = f |
| 928 | return select_resp |
| 929 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 930 | def select(self, name:str, cmd_app=None): |
| 931 | """Select a file (EF, DF, ADF, MF, ...). |
| 932 | |
| 933 | Args: |
| 934 | name : Name of file to select |
| 935 | cmd_app : Command Application State (for unregistering old file commands) |
| 936 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 937 | sels = self.selected_file.get_selectables() |
Philipp Maier | 7744b6e | 2021-03-11 14:29:37 +0100 | [diff] [blame] | 938 | if is_hex(name): |
| 939 | name = name.lower() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 940 | |
| 941 | # unregister commands of old file |
| 942 | if cmd_app and self.selected_file.shell_commands: |
| 943 | for c in self.selected_file.shell_commands: |
| 944 | cmd_app.unregister_command_set(c) |
| 945 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 946 | if name in sels: |
| 947 | f = sels[name] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 948 | try: |
| 949 | if isinstance(f, CardADF): |
Philipp Maier | cba6dbc | 2021-03-11 13:03:18 +0100 | [diff] [blame] | 950 | (data, sw) = self.card.select_adf_by_aid(f.aid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 951 | else: |
| 952 | (data, sw) = self.card._scc.select_file(f.fid) |
| 953 | self.selected_file = f |
| 954 | except SwMatchError as swm: |
| 955 | k = self.interpret_sw(swm.sw_actual) |
| 956 | if not k: |
| 957 | raise(swm) |
| 958 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 959 | select_resp = f.decode_select_response(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 960 | else: |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 961 | select_resp = self.probe_file(name, cmd_app) |
| 962 | |
| 963 | # register commands of new file |
| 964 | if cmd_app and self.selected_file.shell_commands: |
| 965 | for c in self.selected_file.shell_commands: |
| 966 | cmd_app.register_command_set(c) |
| 967 | |
| 968 | return select_resp |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 969 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 970 | def read_binary(self, length:int=None, offset:int=0): |
| 971 | """Read [part of] a transparent EF binary data. |
| 972 | |
| 973 | Args: |
| 974 | length : Amount of data to read (None: as much as possible) |
| 975 | offset : Offset into the file from which to read 'length' bytes |
| 976 | Returns: |
| 977 | binary data read from the file |
| 978 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 979 | if not isinstance(self.selected_file, TransparentEF): |
| 980 | raise TypeError("Only works with TransparentEF") |
| 981 | return self.card._scc.read_binary(self.selected_file.fid, length, offset) |
| 982 | |
Harald Welte | 2d4a64b | 2021-04-03 09:01:24 +0200 | [diff] [blame] | 983 | def read_binary_dec(self) -> Tuple[dict, str]: |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 984 | """Read [part of] a transparent EF binary data and decode it. |
| 985 | |
| 986 | Args: |
| 987 | length : Amount of data to read (None: as much as possible) |
| 988 | offset : Offset into the file from which to read 'length' bytes |
| 989 | Returns: |
| 990 | abstract decode data read from the file |
| 991 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 992 | (data, sw) = self.read_binary() |
| 993 | dec_data = self.selected_file.decode_hex(data) |
| 994 | print("%s: %s -> %s" % (sw, data, dec_data)) |
| 995 | return (dec_data, sw) |
| 996 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 997 | def update_binary(self, data_hex:str, offset:int=0): |
| 998 | """Update transparent EF binary data. |
| 999 | |
| 1000 | Args: |
| 1001 | data_hex : hex string of data to be written |
| 1002 | offset : Offset into the file from which to write 'data_hex' |
| 1003 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1004 | if not isinstance(self.selected_file, TransparentEF): |
| 1005 | raise TypeError("Only works with TransparentEF") |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 1006 | 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] | 1007 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1008 | def update_binary_dec(self, data:dict): |
| 1009 | """Update transparent EF from abstract data. Encodes the data to binary and |
| 1010 | then updates the EF with it. |
| 1011 | |
| 1012 | Args: |
| 1013 | data : abstract data which is to be encoded and written |
| 1014 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1015 | data_hex = self.selected_file.encode_hex(data) |
| 1016 | print("%s -> %s" % (data, data_hex)) |
| 1017 | return self.update_binary(data_hex) |
| 1018 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1019 | def read_record(self, rec_nr:int=0): |
| 1020 | """Read a record as binary data. |
| 1021 | |
| 1022 | Args: |
| 1023 | rec_nr : Record number to read |
| 1024 | Returns: |
| 1025 | hex string of binary data contained in record |
| 1026 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1027 | if not isinstance(self.selected_file, LinFixedEF): |
| 1028 | raise TypeError("Only works with Linear Fixed EF") |
| 1029 | # returns a string of hex nibbles |
| 1030 | return self.card._scc.read_record(self.selected_file.fid, rec_nr) |
| 1031 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1032 | def read_record_dec(self, rec_nr:int=0) -> Tuple[dict, str]: |
| 1033 | """Read a record and decode it to abstract data. |
| 1034 | |
| 1035 | Args: |
| 1036 | rec_nr : Record number to read |
| 1037 | Returns: |
| 1038 | abstract data contained in record |
| 1039 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1040 | (data, sw) = self.read_record(rec_nr) |
| 1041 | return (self.selected_file.decode_record_hex(data), sw) |
| 1042 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1043 | def update_record(self, rec_nr:int, data_hex:str): |
| 1044 | """Update a record with given binary data |
| 1045 | |
| 1046 | Args: |
| 1047 | rec_nr : Record number to read |
| 1048 | data_hex : Hex string binary data to be written |
| 1049 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1050 | if not isinstance(self.selected_file, LinFixedEF): |
| 1051 | raise TypeError("Only works with Linear Fixed EF") |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 1052 | 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] | 1053 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1054 | def update_record_dec(self, rec_nr:int, data:dict): |
| 1055 | """Update a record with given abstract data. Will encode abstract to binary data |
| 1056 | and then write it to the given record on the card. |
| 1057 | |
| 1058 | Args: |
| 1059 | rec_nr : Record number to read |
| 1060 | data_hex : Abstract data to be written |
| 1061 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame] | 1062 | data_hex = self.selected_file.encode_record_hex(data) |
| 1063 | return self.update_record(rec_nr, data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1064 | |
| 1065 | |
| 1066 | |
| 1067 | class FileData(object): |
| 1068 | """Represent the runtime, on-card data.""" |
| 1069 | def __init__(self, fdesc): |
| 1070 | self.desc = fdesc |
| 1071 | self.fcp = None |
| 1072 | |
| 1073 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1074 | def interpret_sw(sw_data:dict, sw:str): |
| 1075 | """Interpret a given status word. |
| 1076 | |
| 1077 | Args: |
| 1078 | sw_data : Hierarchical dict of status word matches |
| 1079 | sw : status word to match (string of 4 hex digits) |
| 1080 | Returns: |
| 1081 | tuple of two strings (class_string, description) |
| 1082 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1083 | for class_str, swdict in sw_data.items(): |
| 1084 | # first try direct match |
| 1085 | if sw in swdict: |
| 1086 | return (class_str, swdict[sw]) |
| 1087 | # next try wildcard matches |
| 1088 | for pattern, descr in swdict.items(): |
| 1089 | if sw_match(sw, pattern): |
| 1090 | return (class_str, descr) |
| 1091 | return None |
| 1092 | |
| 1093 | class CardApplication(object): |
| 1094 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 1095 | some SW definitions.""" |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1096 | 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] | 1097 | """ |
| 1098 | Args: |
| 1099 | adf : ADF name |
| 1100 | sw : Dict of status word conversions |
| 1101 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1102 | self.name = name |
| 1103 | self.adf = adf |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1104 | self.sw = sw or dict() |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 1105 | # back-reference from ADF to Applicaiton |
| 1106 | if self.adf: |
| 1107 | self.aid = aid or self.adf.aid |
| 1108 | self.adf.application = self |
| 1109 | else: |
| 1110 | self.aid = aid |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1111 | |
| 1112 | def __str__(self): |
| 1113 | return "APP(%s)" % (self.name) |
| 1114 | |
| 1115 | def interpret_sw(self, sw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1116 | """Interpret a given status word within the application. |
| 1117 | |
| 1118 | Args: |
| 1119 | sw : Status word as string of 4 hexd digits |
| 1120 | |
| 1121 | Returns: |
| 1122 | Tuple of two strings |
| 1123 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1124 | return interpret_sw(self.sw, sw) |
| 1125 | |
| 1126 | class CardProfile(object): |
| 1127 | """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of |
| 1128 | applications as well as profile-specific SW and shell commands. Every card has |
| 1129 | one card profile, but there may be multiple applications within that profile.""" |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1130 | def __init__(self, name, **kw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1131 | """ |
| 1132 | Args: |
| 1133 | desc (str) : Description |
| 1134 | files_in_mf : List of CardEF instances present in MF |
| 1135 | applications : List of CardApplications present on card |
| 1136 | sw : List of status word definitions |
| 1137 | shell_cmdsets : List of cmd2 shell command sets of profile-specific commands |
| 1138 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1139 | self.name = name |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1140 | self.desc = kw.get("desc", None) |
| 1141 | self.files_in_mf = kw.get("files_in_mf", []) |
| 1142 | self.sw = kw.get("sw", []) |
| 1143 | self.applications = kw.get("applications", []) |
| 1144 | self.shell_cmdsets = kw.get("shell_cmdsets", []) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1145 | |
| 1146 | def __str__(self): |
| 1147 | return self.name |
| 1148 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1149 | def add_application(self, app:CardApplication): |
| 1150 | """Add an application to a card profile. |
| 1151 | |
| 1152 | Args: |
| 1153 | app : CardApplication instance to be added to profile |
| 1154 | """ |
Philipp Maier | eb72fa4 | 2021-03-26 21:29:57 +0100 | [diff] [blame] | 1155 | self.applications.append(app) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1156 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1157 | def interpret_sw(self, sw:str): |
| 1158 | """Interpret a given status word within the profile. |
| 1159 | |
| 1160 | Args: |
| 1161 | sw : Status word as string of 4 hexd digits |
| 1162 | |
| 1163 | Returns: |
| 1164 | Tuple of two strings |
| 1165 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1166 | return interpret_sw(self.sw, sw) |