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