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 | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 287 | def add_application(self, app:'CardADF'): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 288 | """Add an ADF (Application Dedicated File) to the MF""" |
| 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) |
| 337 | self.aid = aid # Application Identifier |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame^] | 338 | mf = self.get_mf() |
| 339 | if mf: |
| 340 | mf.add_application(self) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 341 | |
| 342 | def __str__(self): |
| 343 | return "ADF(%s)" % (self.aid) |
| 344 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 345 | def _path_element(self, prefer_name:bool): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 346 | if self.name and prefer_name: |
| 347 | return self.name |
| 348 | else: |
| 349 | return self.aid |
| 350 | |
| 351 | |
| 352 | class CardEF(CardFile): |
| 353 | """EF (Entry File) in the smart card filesystem""" |
| 354 | def __init__(self, *, fid, **kwargs): |
| 355 | kwargs['fid'] = fid |
| 356 | super().__init__(**kwargs) |
| 357 | |
| 358 | def __str__(self): |
| 359 | return "EF(%s)" % (super().__str__()) |
| 360 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 361 | def get_selectables(self, flags = []) -> dict: |
| 362 | """Return a dict of {'identifier': File} that is selectable from the current DF. |
| 363 | |
| 364 | Args: |
| 365 | flags : Specify which selectables to return 'FIDS' and/or 'NAMES'; |
| 366 | If not specified, all selectables will be returned. |
| 367 | Returns: |
| 368 | dict containing all selectable items. Key is identifier (string), value |
| 369 | a reference to a CardFile (or derived class) instance. |
| 370 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 371 | #global selectable names + those of the parent DF |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 372 | sels = super().get_selectables(flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 373 | sels.update({x.name:x for x in self.parent.children.values() if x != self}) |
| 374 | return sels |
| 375 | |
| 376 | |
| 377 | class TransparentEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 378 | """Transparent EF (Entry File) in the smart card filesystem. |
| 379 | |
| 380 | A Transparent EF is a binary file with no formal structure. This is contrary to |
| 381 | 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] | 382 | |
| 383 | @with_default_category('Transparent EF Commands') |
| 384 | class ShellCommands(CommandSet): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 385 | """Shell commands specific for Trransparent EFs.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 386 | def __init__(self): |
| 387 | super().__init__() |
| 388 | |
| 389 | read_bin_parser = argparse.ArgumentParser() |
| 390 | read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 391 | read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read') |
| 392 | @cmd2.with_argparser(read_bin_parser) |
| 393 | def do_read_binary(self, opts): |
| 394 | """Read binary data from a transparent EF""" |
| 395 | (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset) |
| 396 | self._cmd.poutput(data) |
| 397 | |
| 398 | def do_read_binary_decoded(self, opts): |
| 399 | """Read + decode data from a transparent EF""" |
| 400 | (data, sw) = self._cmd.rs.read_binary_dec() |
| 401 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 402 | |
| 403 | upd_bin_parser = argparse.ArgumentParser() |
| 404 | upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 405 | upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 406 | @cmd2.with_argparser(upd_bin_parser) |
| 407 | def do_update_binary(self, opts): |
| 408 | """Update (Write) data of a transparent EF""" |
| 409 | (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 410 | if data: |
| 411 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 412 | |
| 413 | upd_bin_dec_parser = argparse.ArgumentParser() |
| 414 | upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write') |
| 415 | @cmd2.with_argparser(upd_bin_dec_parser) |
| 416 | def do_update_binary_decoded(self, opts): |
| 417 | """Encode + Update (Write) data of a transparent EF""" |
| 418 | data_json = json.loads(opts.data) |
| 419 | (data, sw) = self._cmd.rs.update_binary_dec(data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 420 | if data: |
| 421 | self._cmd.poutput(json.dumps(data, indent=4)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 422 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 423 | def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None, |
| 424 | size={1,None}): |
| 425 | """ |
| 426 | Args: |
| 427 | fid : File Identifier (4 hex digits) |
| 428 | sfid : Short File Identifier (2 hex digits, optional) |
| 429 | name : Brief name of the file, lik EF_ICCID |
| 430 | desc : Descriptoin of the file |
| 431 | parent : Parent CardFile object within filesystem hierarchy |
| 432 | size : tuple of (minimum_size, recommended_size) |
| 433 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 434 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 435 | self.size = size |
| 436 | self.shell_commands = [self.ShellCommands()] |
| 437 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 438 | def decode_bin(self, raw_bin_data:bytearray) -> dict: |
| 439 | """Decode raw (binary) data into abstract representation. |
| 440 | |
| 441 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 442 | for implementing this specifically for the given file. This function checks which |
| 443 | of the method exists, add calls them (with conversion, as needed). |
| 444 | |
| 445 | Args: |
| 446 | raw_bin_data : binary encoded data |
| 447 | Returns: |
| 448 | abstract_data; dict representing the decoded data |
| 449 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 450 | method = getattr(self, '_decode_bin', None) |
| 451 | if callable(method): |
| 452 | return method(raw_bin_data) |
| 453 | method = getattr(self, '_decode_hex', None) |
| 454 | if callable(method): |
| 455 | return method(b2h(raw_bin_data)) |
| 456 | return {'raw': raw_bin_data.hex()} |
| 457 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 458 | def decode_hex(self, raw_hex_data:str) -> dict: |
| 459 | """Decode raw (hex string) data into abstract representation. |
| 460 | |
| 461 | A derived class would typically provide a _decode_bin() or _decode_hex() method |
| 462 | for implementing this specifically for the given file. This function checks which |
| 463 | of the method exists, add calls them (with conversion, as needed). |
| 464 | |
| 465 | Args: |
| 466 | raw_hex_data : hex-encoded data |
| 467 | Returns: |
| 468 | abstract_data; dict representing the decoded data |
| 469 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 470 | method = getattr(self, '_decode_hex', None) |
| 471 | if callable(method): |
| 472 | return method(raw_hex_data) |
| 473 | raw_bin_data = h2b(raw_hex_data) |
| 474 | method = getattr(self, '_decode_bin', None) |
| 475 | if callable(method): |
| 476 | return method(raw_bin_data) |
| 477 | return {'raw': raw_bin_data.hex()} |
| 478 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 479 | def encode_bin(self, abstract_data:dict) -> bytearray: |
| 480 | """Encode abstract representation into raw (binary) data. |
| 481 | |
| 482 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 483 | for implementing this specifically for the given file. This function checks which |
| 484 | of the method exists, add calls them (with conversion, as needed). |
| 485 | |
| 486 | Args: |
| 487 | abstract_data : dict representing the decoded data |
| 488 | Returns: |
| 489 | binary encoded data |
| 490 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 491 | method = getattr(self, '_encode_bin', None) |
| 492 | if callable(method): |
| 493 | return method(abstract_data) |
| 494 | method = getattr(self, '_encode_hex', None) |
| 495 | if callable(method): |
| 496 | return h2b(method(abstract_data)) |
| 497 | raise NotImplementedError |
| 498 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 499 | def encode_hex(self, abstract_data:dict) -> str: |
| 500 | """Encode abstract representation into raw (hex string) data. |
| 501 | |
| 502 | A derived class would typically provide an _encode_bin() or _encode_hex() method |
| 503 | for implementing this specifically for the given file. This function checks which |
| 504 | of the method exists, add calls them (with conversion, as needed). |
| 505 | |
| 506 | Args: |
| 507 | abstract_data : dict representing the decoded data |
| 508 | Returns: |
| 509 | hex string encoded data |
| 510 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 511 | method = getattr(self, '_encode_hex', None) |
| 512 | if callable(method): |
| 513 | return method(abstract_data) |
| 514 | method = getattr(self, '_encode_bin', None) |
| 515 | if callable(method): |
| 516 | raw_bin_data = method(abstract_data) |
| 517 | return b2h(raw_bin_data) |
| 518 | raise NotImplementedError |
| 519 | |
| 520 | |
| 521 | class LinFixedEF(CardEF): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 522 | """Linear Fixed EF (Entry File) in the smart card filesystem. |
| 523 | |
| 524 | Linear Fixed EFs are record oriented files. They consist of a number of fixed-size |
| 525 | records. The records can be individually read/updated.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 526 | |
| 527 | @with_default_category('Linear Fixed EF Commands') |
| 528 | class ShellCommands(CommandSet): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 529 | """Shell commands specific for Linear Fixed EFs.""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 530 | def __init__(self): |
| 531 | super().__init__() |
| 532 | |
| 533 | read_rec_parser = argparse.ArgumentParser() |
| 534 | 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] | 535 | 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] | 536 | @cmd2.with_argparser(read_rec_parser) |
| 537 | def do_read_record(self, opts): |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 538 | """Read one or multiple records from a record-oriented EF""" |
| 539 | for r in range(opts.count): |
| 540 | recnr = opts.record_nr + r |
| 541 | (data, sw) = self._cmd.rs.read_record(recnr) |
| 542 | if (len(data) > 0): |
| 543 | recstr = str(data) |
| 544 | else: |
| 545 | recstr = "(empty)" |
| 546 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 547 | |
| 548 | read_rec_dec_parser = argparse.ArgumentParser() |
| 549 | read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 550 | @cmd2.with_argparser(read_rec_dec_parser) |
| 551 | def do_read_record_decoded(self, opts): |
| 552 | """Read + decode a record from a record-oriented EF""" |
| 553 | (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr) |
| 554 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 555 | |
| 556 | upd_rec_parser = argparse.ArgumentParser() |
| 557 | upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 558 | upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 559 | @cmd2.with_argparser(upd_rec_parser) |
| 560 | def do_update_record(self, opts): |
| 561 | """Update (write) data to a record-oriented EF""" |
| 562 | (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 563 | if data: |
| 564 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 565 | |
| 566 | upd_rec_dec_parser = argparse.ArgumentParser() |
| 567 | upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 568 | upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 569 | @cmd2.with_argparser(upd_rec_dec_parser) |
| 570 | def do_update_record_decoded(self, opts): |
| 571 | """Encode + Update (write) data to a record-oriented EF""" |
| 572 | (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] | 573 | if data: |
| 574 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 575 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 576 | def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, |
| 577 | parent:Optional[CardDF]=None, rec_len={1,None}): |
| 578 | """ |
| 579 | Args: |
| 580 | fid : File Identifier (4 hex digits) |
| 581 | sfid : Short File Identifier (2 hex digits, optional) |
| 582 | name : Brief name of the file, lik EF_ICCID |
| 583 | desc : Descriptoin of the file |
| 584 | parent : Parent CardFile object within filesystem hierarchy |
| 585 | rec_len : tuple of (minimum_length, recommended_length) |
| 586 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 587 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 588 | self.rec_len = rec_len |
| 589 | self.shell_commands = [self.ShellCommands()] |
| 590 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 591 | def decode_record_hex(self, raw_hex_data:str) -> dict: |
| 592 | """Decode raw (hex string) data into abstract representation. |
| 593 | |
| 594 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 595 | method for implementing this specifically for the given file. This function checks which |
| 596 | of the method exists, add calls them (with conversion, as needed). |
| 597 | |
| 598 | Args: |
| 599 | raw_hex_data : hex-encoded data |
| 600 | Returns: |
| 601 | abstract_data; dict representing the decoded data |
| 602 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 603 | method = getattr(self, '_decode_record_hex', None) |
| 604 | if callable(method): |
| 605 | return method(raw_hex_data) |
| 606 | raw_bin_data = h2b(raw_hex_data) |
| 607 | method = getattr(self, '_decode_record_bin', None) |
| 608 | if callable(method): |
| 609 | return method(raw_bin_data) |
| 610 | return {'raw': raw_bin_data.hex()} |
| 611 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 612 | def decode_record_bin(self, raw_bin_data:bytearray) -> dict: |
| 613 | """Decode raw (binary) data into abstract representation. |
| 614 | |
| 615 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 616 | method for implementing this specifically for the given file. This function checks which |
| 617 | of the method exists, add calls them (with conversion, as needed). |
| 618 | |
| 619 | Args: |
| 620 | raw_bin_data : binary encoded data |
| 621 | Returns: |
| 622 | abstract_data; dict representing the decoded data |
| 623 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 624 | method = getattr(self, '_decode_record_bin', None) |
| 625 | if callable(method): |
| 626 | return method(raw_bin_data) |
| 627 | raw_hex_data = b2h(raw_bin_data) |
| 628 | method = getattr(self, '_decode_record_hex', None) |
| 629 | if callable(method): |
| 630 | return method(raw_hex_data) |
| 631 | return {'raw': raw_hex_data} |
| 632 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 633 | def encode_record_hex(self, abstract_data:dict) -> str: |
| 634 | """Encode abstract representation into raw (hex string) data. |
| 635 | |
| 636 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 637 | method for implementing this specifically for the given file. This function checks which |
| 638 | of the method exists, add calls them (with conversion, as needed). |
| 639 | |
| 640 | Args: |
| 641 | abstract_data : dict representing the decoded data |
| 642 | Returns: |
| 643 | hex string encoded data |
| 644 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 645 | method = getattr(self, '_encode_record_hex', None) |
| 646 | if callable(method): |
| 647 | return method(abstract_data) |
| 648 | method = getattr(self, '_encode_record_bin', None) |
| 649 | if callable(method): |
| 650 | raw_bin_data = method(abstract_data) |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame^] | 651 | return b2h(raw_bin_data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 652 | raise NotImplementedError |
| 653 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 654 | def encode_record_bin(self, abstract_data:dict) -> bytearray: |
| 655 | """Encode abstract representation into raw (binary) data. |
| 656 | |
| 657 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 658 | method for implementing this specifically for the given file. This function checks which |
| 659 | of the method exists, add calls them (with conversion, as needed). |
| 660 | |
| 661 | Args: |
| 662 | abstract_data : dict representing the decoded data |
| 663 | Returns: |
| 664 | binary encoded data |
| 665 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 666 | method = getattr(self, '_encode_record_bin', None) |
| 667 | if callable(method): |
| 668 | return method(abstract_data) |
| 669 | method = getattr(self, '_encode_record_hex', None) |
| 670 | if callable(method): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 671 | return h2b(method(abstract_data)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 672 | raise NotImplementedError |
| 673 | |
| 674 | class CyclicEF(LinFixedEF): |
| 675 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 676 | # 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] | 677 | def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None, |
| 678 | rec_len={1,None}): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 679 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len) |
| 680 | |
| 681 | class TransRecEF(TransparentEF): |
| 682 | """Transparent EF (Entry File) containing fixed-size records. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 683 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 684 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 685 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 686 | inside. |
| 687 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 688 | for a record, while this class takes care of split / merge of records. |
| 689 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame^] | 690 | def __init__(self, fid:str, rec_len:int, sfid:str=None, name:str=None, desc:str=None, |
| 691 | parent:Optional[CardDF]=None, size={1,None}): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 692 | """ |
| 693 | Args: |
| 694 | fid : File Identifier (4 hex digits) |
| 695 | sfid : Short File Identifier (2 hex digits, optional) |
| 696 | name : Brief name of the file, lik EF_ICCID |
| 697 | desc : Descriptoin of the file |
| 698 | parent : Parent CardFile object within filesystem hierarchy |
| 699 | rec_len : Length of the fixed-length records within transparent EF |
| 700 | size : tuple of (minimum_size, recommended_size) |
| 701 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 702 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size) |
| 703 | self.rec_len = rec_len |
| 704 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 705 | def decode_record_hex(self, raw_hex_data:str) -> dict: |
| 706 | """Decode raw (hex string) data into abstract representation. |
| 707 | |
| 708 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 709 | method for implementing this specifically for the given file. This function checks which |
| 710 | of the method exists, add calls them (with conversion, as needed). |
| 711 | |
| 712 | Args: |
| 713 | raw_hex_data : hex-encoded data |
| 714 | Returns: |
| 715 | abstract_data; dict representing the decoded data |
| 716 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 717 | method = getattr(self, '_decode_record_hex', None) |
| 718 | if callable(method): |
| 719 | return method(raw_hex_data) |
| 720 | method = getattr(self, '_decode_record_bin', None) |
| 721 | if callable(method): |
| 722 | raw_bin_data = h2b(raw_hex_data) |
| 723 | return method(raw_bin_data) |
| 724 | return {'raw': raw_hex_data} |
| 725 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 726 | def decode_record_bin(self, raw_bin_data:bytearray) -> dict: |
| 727 | """Decode raw (binary) data into abstract representation. |
| 728 | |
| 729 | A derived class would typically provide a _decode_record_bin() or _decode_record_hex() |
| 730 | method for implementing this specifically for the given file. This function checks which |
| 731 | of the method exists, add calls them (with conversion, as needed). |
| 732 | |
| 733 | Args: |
| 734 | raw_bin_data : binary encoded data |
| 735 | Returns: |
| 736 | abstract_data; dict representing the decoded data |
| 737 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 738 | method = getattr(self, '_decode_record_bin', None) |
| 739 | if callable(method): |
| 740 | return method(raw_bin_data) |
| 741 | raw_hex_data = b2h(raw_bin_data) |
| 742 | method = getattr(self, '_decode_record_hex', None) |
| 743 | if callable(method): |
| 744 | return method(raw_hex_data) |
| 745 | return {'raw': raw_hex_data} |
| 746 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 747 | def encode_record_hex(self, abstract_data:dict) -> str: |
| 748 | """Encode abstract representation into raw (hex string) data. |
| 749 | |
| 750 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 751 | method for implementing this specifically for the given file. This function checks which |
| 752 | of the method exists, add calls them (with conversion, as needed). |
| 753 | |
| 754 | Args: |
| 755 | abstract_data : dict representing the decoded data |
| 756 | Returns: |
| 757 | hex string encoded data |
| 758 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 759 | method = getattr(self, '_encode_record_hex', None) |
| 760 | if callable(method): |
| 761 | return method(abstract_data) |
| 762 | method = getattr(self, '_encode_record_bin', None) |
| 763 | if callable(method): |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame^] | 764 | return b2h(method(abstract_data)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 765 | raise NotImplementedError |
| 766 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 767 | def encode_record_bin(self, abstract_data:dict) -> bytearray: |
| 768 | """Encode abstract representation into raw (binary) data. |
| 769 | |
| 770 | A derived class would typically provide an _encode_record_bin() or _encode_record_hex() |
| 771 | method for implementing this specifically for the given file. This function checks which |
| 772 | of the method exists, add calls them (with conversion, as needed). |
| 773 | |
| 774 | Args: |
| 775 | abstract_data : dict representing the decoded data |
| 776 | Returns: |
| 777 | binary encoded data |
| 778 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 779 | method = getattr(self, '_encode_record_bin', None) |
| 780 | if callable(method): |
| 781 | return method(abstract_data) |
| 782 | method = getattr(self, '_encode_record_hex', None) |
| 783 | if callable(method): |
| 784 | return h2b(method(abstract_data)) |
| 785 | raise NotImplementedError |
| 786 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 787 | def _decode_bin(self, raw_bin_data:bytearray): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 788 | chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)] |
| 789 | return [self.decode_record_bin(x) for x in chunks] |
| 790 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 791 | def _encode_bin(self, abstract_data) -> bytes: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 792 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 793 | # FIXME: pad to file size |
| 794 | return b''.join(chunks) |
| 795 | |
| 796 | |
| 797 | |
| 798 | |
| 799 | |
| 800 | class RuntimeState(object): |
| 801 | """Represent the runtime state of a session with a card.""" |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 802 | def __init__(self, card, profile:'CardProfile'): |
| 803 | """ |
| 804 | Args: |
| 805 | card : pysim.cards.Card instance |
| 806 | profile : CardProfile instance |
| 807 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 808 | self.mf = CardMF() |
| 809 | self.card = card |
| 810 | self.selected_file = self.mf |
| 811 | self.profile = profile |
| 812 | # add applications + MF-files from profile |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 813 | apps = self._match_applications() |
| 814 | for a in apps: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 815 | self.mf.add_application(a) |
| 816 | for f in self.profile.files_in_mf: |
| 817 | self.mf.add_file(f) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 818 | self.conserve_write = True |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 819 | |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 820 | def _match_applications(self): |
| 821 | """match the applications from the profile with applications on the card""" |
| 822 | apps_profile = self.profile.applications |
| 823 | aids_card = self.card.read_aids() |
| 824 | apps_taken = [] |
| 825 | if aids_card: |
| 826 | aids_taken = [] |
| 827 | print("AIDs on card:") |
| 828 | for a in aids_card: |
| 829 | for f in apps_profile: |
| 830 | if f.aid in a: |
| 831 | print(" %s: %s" % (f.name, a)) |
| 832 | aids_taken.append(a) |
| 833 | apps_taken.append(f) |
| 834 | aids_unknown = set(aids_card) - set(aids_taken) |
| 835 | for a in aids_unknown: |
| 836 | print(" unknown: %s" % a) |
| 837 | else: |
| 838 | print("error: could not determine card applications") |
| 839 | return apps_taken |
| 840 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 841 | def get_cwd(self) -> CardDF: |
| 842 | """Obtain the current working directory. |
| 843 | |
| 844 | Returns: |
| 845 | CardDF instance |
| 846 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 847 | if isinstance(self.selected_file, CardDF): |
| 848 | return self.selected_file |
| 849 | else: |
| 850 | return self.selected_file.parent |
| 851 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 852 | def get_application(self) -> Optional[CardADF]: |
| 853 | """Obtain the currently selected application (if any). |
| 854 | |
| 855 | Returns: |
| 856 | CardADF() instance or None""" |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 857 | # iterate upwards from selected file; check if any is an ADF |
| 858 | node = self.selected_file |
| 859 | while node.parent != node: |
| 860 | if isinstance(node, CardADF): |
| 861 | return node |
| 862 | node = node.parent |
| 863 | return None |
| 864 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 865 | def interpret_sw(self, sw:str): |
| 866 | """Interpret a given status word relative to the currently selected application |
| 867 | or the underlying card profile. |
| 868 | |
| 869 | Args: |
| 870 | sw : Status word as string of 4 hexd digits |
| 871 | |
| 872 | Returns: |
| 873 | Tuple of two strings |
| 874 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 875 | app = self.get_application() |
| 876 | if app: |
| 877 | # The application either comes with its own interpret_sw |
| 878 | # method or we will use the interpret_sw method from the |
| 879 | # card profile. |
| 880 | if hasattr(app, "interpret_sw"): |
| 881 | return app.interpret_sw(sw) |
| 882 | else: |
| 883 | return self.profile.interpret_sw(sw) |
| 884 | return app.interpret_sw(sw) |
| 885 | else: |
| 886 | return self.profile.interpret_sw(sw) |
| 887 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 888 | def probe_file(self, fid:str, cmd_app=None): |
| 889 | """Blindly try to select a file and automatically add a matching file |
| 890 | object if the file actually exists.""" |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 891 | if not is_hex(fid, 4, 4): |
| 892 | raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid) |
| 893 | |
| 894 | try: |
| 895 | (data, sw) = self.card._scc.select_file(fid) |
| 896 | except SwMatchError as swm: |
| 897 | k = self.interpret_sw(swm.sw_actual) |
| 898 | if not k: |
| 899 | raise(swm) |
| 900 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
| 901 | |
| 902 | select_resp = self.selected_file.decode_select_response(data) |
| 903 | if (select_resp['file_descriptor']['file_type'] == 'df'): |
| 904 | f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime") |
| 905 | else: |
| 906 | if (select_resp['file_descriptor']['structure'] == 'transparent'): |
| 907 | f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime") |
| 908 | else: |
| 909 | f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime") |
| 910 | |
| 911 | self.selected_file.add_files([f]) |
| 912 | self.selected_file = f |
| 913 | return select_resp |
| 914 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 915 | def select(self, name:str, cmd_app=None): |
| 916 | """Select a file (EF, DF, ADF, MF, ...). |
| 917 | |
| 918 | Args: |
| 919 | name : Name of file to select |
| 920 | cmd_app : Command Application State (for unregistering old file commands) |
| 921 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 922 | sels = self.selected_file.get_selectables() |
Philipp Maier | 7744b6e | 2021-03-11 14:29:37 +0100 | [diff] [blame] | 923 | if is_hex(name): |
| 924 | name = name.lower() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 925 | |
| 926 | # unregister commands of old file |
| 927 | if cmd_app and self.selected_file.shell_commands: |
| 928 | for c in self.selected_file.shell_commands: |
| 929 | cmd_app.unregister_command_set(c) |
| 930 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 931 | if name in sels: |
| 932 | f = sels[name] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 933 | try: |
| 934 | if isinstance(f, CardADF): |
Philipp Maier | cba6dbc | 2021-03-11 13:03:18 +0100 | [diff] [blame] | 935 | (data, sw) = self.card.select_adf_by_aid(f.aid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 936 | else: |
| 937 | (data, sw) = self.card._scc.select_file(f.fid) |
| 938 | self.selected_file = f |
| 939 | except SwMatchError as swm: |
| 940 | k = self.interpret_sw(swm.sw_actual) |
| 941 | if not k: |
| 942 | raise(swm) |
| 943 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 944 | select_resp = f.decode_select_response(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 945 | else: |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 946 | select_resp = self.probe_file(name, cmd_app) |
| 947 | |
| 948 | # register commands of new file |
| 949 | if cmd_app and self.selected_file.shell_commands: |
| 950 | for c in self.selected_file.shell_commands: |
| 951 | cmd_app.register_command_set(c) |
| 952 | |
| 953 | return select_resp |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 954 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 955 | def read_binary(self, length:int=None, offset:int=0): |
| 956 | """Read [part of] a transparent EF binary data. |
| 957 | |
| 958 | Args: |
| 959 | length : Amount of data to read (None: as much as possible) |
| 960 | offset : Offset into the file from which to read 'length' bytes |
| 961 | Returns: |
| 962 | binary data read from the file |
| 963 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 964 | if not isinstance(self.selected_file, TransparentEF): |
| 965 | raise TypeError("Only works with TransparentEF") |
| 966 | return self.card._scc.read_binary(self.selected_file.fid, length, offset) |
| 967 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 968 | def read_binary_dec(self) -> dict: |
| 969 | """Read [part of] a transparent EF binary data and decode it. |
| 970 | |
| 971 | Args: |
| 972 | length : Amount of data to read (None: as much as possible) |
| 973 | offset : Offset into the file from which to read 'length' bytes |
| 974 | Returns: |
| 975 | abstract decode data read from the file |
| 976 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 977 | (data, sw) = self.read_binary() |
| 978 | dec_data = self.selected_file.decode_hex(data) |
| 979 | print("%s: %s -> %s" % (sw, data, dec_data)) |
| 980 | return (dec_data, sw) |
| 981 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 982 | def update_binary(self, data_hex:str, offset:int=0): |
| 983 | """Update transparent EF binary data. |
| 984 | |
| 985 | Args: |
| 986 | data_hex : hex string of data to be written |
| 987 | offset : Offset into the file from which to write 'data_hex' |
| 988 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 989 | if not isinstance(self.selected_file, TransparentEF): |
| 990 | raise TypeError("Only works with TransparentEF") |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 991 | 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] | 992 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 993 | def update_binary_dec(self, data:dict): |
| 994 | """Update transparent EF from abstract data. Encodes the data to binary and |
| 995 | then updates the EF with it. |
| 996 | |
| 997 | Args: |
| 998 | data : abstract data which is to be encoded and written |
| 999 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1000 | data_hex = self.selected_file.encode_hex(data) |
| 1001 | print("%s -> %s" % (data, data_hex)) |
| 1002 | return self.update_binary(data_hex) |
| 1003 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1004 | def read_record(self, rec_nr:int=0): |
| 1005 | """Read a record as binary data. |
| 1006 | |
| 1007 | Args: |
| 1008 | rec_nr : Record number to read |
| 1009 | Returns: |
| 1010 | hex string of binary data contained in record |
| 1011 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1012 | if not isinstance(self.selected_file, LinFixedEF): |
| 1013 | raise TypeError("Only works with Linear Fixed EF") |
| 1014 | # returns a string of hex nibbles |
| 1015 | return self.card._scc.read_record(self.selected_file.fid, rec_nr) |
| 1016 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1017 | def read_record_dec(self, rec_nr:int=0) -> Tuple[dict, str]: |
| 1018 | """Read a record and decode it to abstract data. |
| 1019 | |
| 1020 | Args: |
| 1021 | rec_nr : Record number to read |
| 1022 | Returns: |
| 1023 | abstract data contained in record |
| 1024 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1025 | (data, sw) = self.read_record(rec_nr) |
| 1026 | return (self.selected_file.decode_record_hex(data), sw) |
| 1027 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1028 | def update_record(self, rec_nr:int, data_hex:str): |
| 1029 | """Update a record with given binary data |
| 1030 | |
| 1031 | Args: |
| 1032 | rec_nr : Record number to read |
| 1033 | data_hex : Hex string binary data to be written |
| 1034 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1035 | if not isinstance(self.selected_file, LinFixedEF): |
| 1036 | raise TypeError("Only works with Linear Fixed EF") |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 1037 | 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] | 1038 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1039 | def update_record_dec(self, rec_nr:int, data:dict): |
| 1040 | """Update a record with given abstract data. Will encode abstract to binary data |
| 1041 | and then write it to the given record on the card. |
| 1042 | |
| 1043 | Args: |
| 1044 | rec_nr : Record number to read |
| 1045 | data_hex : Abstract data to be written |
| 1046 | """ |
Harald Welte | 1e45657 | 2021-04-02 17:16:30 +0200 | [diff] [blame^] | 1047 | data_hex = self.selected_file.encode_record_hex(data) |
| 1048 | return self.update_record(rec_nr, data_hex) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1049 | |
| 1050 | |
| 1051 | |
| 1052 | class FileData(object): |
| 1053 | """Represent the runtime, on-card data.""" |
| 1054 | def __init__(self, fdesc): |
| 1055 | self.desc = fdesc |
| 1056 | self.fcp = None |
| 1057 | |
| 1058 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1059 | def interpret_sw(sw_data:dict, sw:str): |
| 1060 | """Interpret a given status word. |
| 1061 | |
| 1062 | Args: |
| 1063 | sw_data : Hierarchical dict of status word matches |
| 1064 | sw : status word to match (string of 4 hex digits) |
| 1065 | Returns: |
| 1066 | tuple of two strings (class_string, description) |
| 1067 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1068 | for class_str, swdict in sw_data.items(): |
| 1069 | # first try direct match |
| 1070 | if sw in swdict: |
| 1071 | return (class_str, swdict[sw]) |
| 1072 | # next try wildcard matches |
| 1073 | for pattern, descr in swdict.items(): |
| 1074 | if sw_match(sw, pattern): |
| 1075 | return (class_str, descr) |
| 1076 | return None |
| 1077 | |
| 1078 | class CardApplication(object): |
| 1079 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 1080 | some SW definitions.""" |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1081 | def __init__(self, name, adf:str=None, sw:dict=None): |
| 1082 | """ |
| 1083 | Args: |
| 1084 | adf : ADF name |
| 1085 | sw : Dict of status word conversions |
| 1086 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1087 | self.name = name |
| 1088 | self.adf = adf |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1089 | self.sw = sw or dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1090 | |
| 1091 | def __str__(self): |
| 1092 | return "APP(%s)" % (self.name) |
| 1093 | |
| 1094 | def interpret_sw(self, sw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1095 | """Interpret a given status word within the application. |
| 1096 | |
| 1097 | Args: |
| 1098 | sw : Status word as string of 4 hexd digits |
| 1099 | |
| 1100 | Returns: |
| 1101 | Tuple of two strings |
| 1102 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1103 | return interpret_sw(self.sw, sw) |
| 1104 | |
| 1105 | class CardProfile(object): |
| 1106 | """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of |
| 1107 | applications as well as profile-specific SW and shell commands. Every card has |
| 1108 | one card profile, but there may be multiple applications within that profile.""" |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1109 | def __init__(self, name, **kw): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1110 | """ |
| 1111 | Args: |
| 1112 | desc (str) : Description |
| 1113 | files_in_mf : List of CardEF instances present in MF |
| 1114 | applications : List of CardApplications present on card |
| 1115 | sw : List of status word definitions |
| 1116 | shell_cmdsets : List of cmd2 shell command sets of profile-specific commands |
| 1117 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1118 | self.name = name |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 1119 | self.desc = kw.get("desc", None) |
| 1120 | self.files_in_mf = kw.get("files_in_mf", []) |
| 1121 | self.sw = kw.get("sw", []) |
| 1122 | self.applications = kw.get("applications", []) |
| 1123 | self.shell_cmdsets = kw.get("shell_cmdsets", []) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1124 | |
| 1125 | def __str__(self): |
| 1126 | return self.name |
| 1127 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1128 | def add_application(self, app:CardApplication): |
| 1129 | """Add an application to a card profile. |
| 1130 | |
| 1131 | Args: |
| 1132 | app : CardApplication instance to be added to profile |
| 1133 | """ |
Philipp Maier | eb72fa4 | 2021-03-26 21:29:57 +0100 | [diff] [blame] | 1134 | self.applications.append(app) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1135 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 1136 | def interpret_sw(self, sw:str): |
| 1137 | """Interpret a given status word within the profile. |
| 1138 | |
| 1139 | Args: |
| 1140 | sw : Status word as string of 4 hexd digits |
| 1141 | |
| 1142 | Returns: |
| 1143 | Tuple of two strings |
| 1144 | """ |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1145 | return interpret_sw(self.sw, sw) |