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