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