Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1 | # coding=utf-8 |
| 2 | """Representation of the ISO7816-4 filesystem model. |
| 3 | |
| 4 | The File (and its derived classes) represent the structure / hierarchy |
| 5 | of the ISO7816-4 smart card file system with the MF, DF, EF and ADF |
| 6 | entries, further sub-divided into the EF sub-types Transparent, Linear Fixed, etc. |
| 7 | |
| 8 | The classes are intended to represent the *specification* of the filesystem, |
| 9 | not the actual contents / runtime state of interacting with a given smart card. |
| 10 | |
| 11 | (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 12 | |
| 13 | This program is free software: you can redistribute it and/or modify |
| 14 | it under the terms of the GNU General Public License as published by |
| 15 | the Free Software Foundation, either version 2 of the License, or |
| 16 | (at your option) any later version. |
| 17 | |
| 18 | This program is distributed in the hope that it will be useful, |
| 19 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 20 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 21 | GNU General Public License for more details. |
| 22 | |
| 23 | You should have received a copy of the GNU General Public License |
| 24 | along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 25 | """ |
| 26 | |
| 27 | import code |
| 28 | import json |
| 29 | |
| 30 | import cmd2 |
| 31 | from cmd2 import CommandSet, with_default_category, with_argparser |
| 32 | import argparse |
| 33 | |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 34 | from pySim.utils import sw_match, h2b, b2h, is_hex |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 35 | from pySim.exceptions import * |
| 36 | |
| 37 | class CardFile(object): |
| 38 | """Base class for all objects in the smart card filesystem. |
| 39 | Serve as a common ancestor to all other file types; rarely used directly. |
| 40 | """ |
| 41 | RESERVED_NAMES = ['..', '.', '/', 'MF'] |
| 42 | RESERVED_FIDS = ['3f00'] |
| 43 | |
| 44 | def __init__(self, fid=None, sfid=None, name=None, desc=None, parent=None): |
| 45 | if not isinstance(self, CardADF) and fid == None: |
| 46 | raise ValueError("fid is mandatory") |
| 47 | if fid: |
| 48 | fid = fid.lower() |
| 49 | self.fid = fid # file identifier |
| 50 | self.sfid = sfid # short file identifier |
| 51 | self.name = name # human readable name |
| 52 | self.desc = desc # human readable description |
| 53 | self.parent = parent |
| 54 | if self.parent and self.parent != self and self.fid: |
| 55 | self.parent.add_file(self) |
| 56 | self.shell_commands = [] |
| 57 | |
Philipp Maier | 6606158 | 2021-03-09 21:57:57 +0100 | [diff] [blame] | 58 | # Note: the basic properties (fid, name, ect.) are verified when |
| 59 | # the file is attached to a parent file. See method add_file() in |
| 60 | # class Card DF |
| 61 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 62 | def __str__(self): |
| 63 | if self.name: |
| 64 | return self.name |
| 65 | else: |
| 66 | return self.fid |
| 67 | |
| 68 | def _path_element(self, prefer_name): |
| 69 | if prefer_name and self.name: |
| 70 | return self.name |
| 71 | else: |
| 72 | return self.fid |
| 73 | |
| 74 | def fully_qualified_path(self, prefer_name=True): |
| 75 | """Return fully qualified path to file as list of FID or name strings.""" |
| 76 | if self.parent != self: |
| 77 | ret = self.parent.fully_qualified_path(prefer_name) |
| 78 | else: |
| 79 | ret = [] |
| 80 | ret.append(self._path_element(prefer_name)) |
| 81 | return ret |
| 82 | |
| 83 | def get_mf(self): |
| 84 | """Return the MF (root) of the file system.""" |
| 85 | if self.parent == None: |
| 86 | return None |
| 87 | # iterate towards the top. MF has parent == self |
| 88 | node = self |
| 89 | while node.parent != node: |
| 90 | node = node.parent |
| 91 | return node |
| 92 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 93 | def _get_self_selectables(self, alias=None, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 94 | """Return a dict of {'identifier': self} tuples""" |
| 95 | sels = {} |
| 96 | if alias: |
| 97 | sels.update({alias: self}) |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 98 | if self.fid and (flags == [] or 'FIDS' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 99 | sels.update({self.fid: self}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 100 | if self.name and (flags == [] or 'FNAMES' in flags): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 101 | sels.update({self.name: self}) |
| 102 | return sels |
| 103 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 104 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 105 | """Return a dict of {'identifier': File} that is selectable from the current file.""" |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 106 | sels = {} |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 107 | # we can always select ourself |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 108 | if flags == [] or 'SELF' in flags: |
| 109 | sels = self._get_self_selectables('.', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 110 | # we can always select our parent |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 111 | if flags == [] or 'PARENT' in flags: |
| 112 | sels = self.parent._get_self_selectables('..', flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 113 | # if we have a MF, we can always select its applications |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 114 | if flags == [] or 'MF' in flags: |
| 115 | mf = self.get_mf() |
| 116 | if mf: |
| 117 | sels.update(mf._get_self_selectables(flags = flags)) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 118 | sels.update(mf.get_app_selectables(flags = flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 119 | return sels |
| 120 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 121 | def get_selectable_names(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 122 | """Return a list of strings for all identifiers that are selectable from the current file.""" |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 123 | sels = self.get_selectables(flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 124 | return sels.keys() |
| 125 | |
| 126 | def decode_select_response(self, data_hex): |
| 127 | """Decode the response to a SELECT command.""" |
| 128 | return self.parent.decode_select_response(data_hex) |
| 129 | |
| 130 | |
| 131 | class CardDF(CardFile): |
| 132 | """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] | 133 | |
| 134 | @with_default_category('DF/ADF Commands') |
| 135 | class ShellCommands(CommandSet): |
| 136 | def __init__(self): |
| 137 | super().__init__() |
| 138 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 139 | def __init__(self, **kwargs): |
| 140 | if not isinstance(self, CardADF): |
| 141 | if not 'fid' in kwargs: |
| 142 | raise TypeError('fid is mandatory for all DF') |
| 143 | super().__init__(**kwargs) |
| 144 | self.children = dict() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 145 | self.shell_commands = [self.ShellCommands()] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 146 | |
| 147 | def __str__(self): |
| 148 | return "DF(%s)" % (super().__str__()) |
| 149 | |
| 150 | def add_file(self, child, ignore_existing=False): |
| 151 | """Add a child (DF/EF) to this DF""" |
| 152 | if not isinstance(child, CardFile): |
| 153 | raise TypeError("Expected a File instance") |
Philipp Maier | 3aec871 | 2021-03-09 21:49:01 +0100 | [diff] [blame] | 154 | if not is_hex(child.fid, minlen = 4, maxlen = 4): |
| 155 | raise ValueError("File name %s is not a valid fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 156 | if child.name in CardFile.RESERVED_NAMES: |
| 157 | raise ValueError("File name %s is a reserved name" % (child.name)) |
| 158 | if child.fid in CardFile.RESERVED_FIDS: |
Philipp Maier | e8bc1b4 | 2021-03-09 20:33:41 +0100 | [diff] [blame] | 159 | raise ValueError("File fid %s is a reserved fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 160 | if child.fid in self.children: |
| 161 | if ignore_existing: |
| 162 | return |
| 163 | raise ValueError("File with given fid %s already exists" % (child.fid)) |
| 164 | if self.lookup_file_by_sfid(child.sfid): |
| 165 | raise ValueError("File with given sfid %s already exists" % (child.sfid)) |
| 166 | if self.lookup_file_by_name(child.name): |
| 167 | if ignore_existing: |
| 168 | return |
| 169 | raise ValueError("File with given name %s already exists" % (child.name)) |
| 170 | self.children[child.fid] = child |
| 171 | child.parent = self |
| 172 | |
| 173 | def add_files(self, children, ignore_existing=False): |
| 174 | """Add a list of child (DF/EF) to this DF""" |
| 175 | for child in children: |
| 176 | self.add_file(child, ignore_existing) |
| 177 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 178 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 179 | """Get selectable (DF/EF names) from current DF""" |
| 180 | # global selectables + our children |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 181 | sels = super().get_selectables(flags) |
| 182 | if flags == [] or 'FIDS' in flags: |
| 183 | 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] | 184 | if flags == [] or 'FNAMES' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 185 | 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] | 186 | return sels |
| 187 | |
| 188 | def lookup_file_by_name(self, name): |
| 189 | if name == None: |
| 190 | return None |
| 191 | for i in self.children.values(): |
| 192 | if i.name and i.name == name: |
| 193 | return i |
| 194 | return None |
| 195 | |
| 196 | def lookup_file_by_sfid(self, sfid): |
| 197 | if sfid == None: |
| 198 | return None |
| 199 | for i in self.children.values(): |
| 200 | if i.sfid == int(sfid): |
| 201 | return i |
| 202 | return None |
| 203 | |
| 204 | def lookup_file_by_fid(self, fid): |
| 205 | if fid in self.children: |
| 206 | return self.children[fid] |
| 207 | return None |
| 208 | |
| 209 | |
| 210 | class CardMF(CardDF): |
| 211 | """MF (Master File) in the smart card filesystem""" |
| 212 | def __init__(self, **kwargs): |
| 213 | # can be overridden; use setdefault |
| 214 | kwargs.setdefault('fid', '3f00') |
| 215 | kwargs.setdefault('name', 'MF') |
| 216 | kwargs.setdefault('desc', 'Master File (directory root)') |
| 217 | # cannot be overridden; use assignment |
| 218 | kwargs['parent'] = self |
| 219 | super().__init__(**kwargs) |
| 220 | self.applications = dict() |
| 221 | |
| 222 | def __str__(self): |
| 223 | return "MF(%s)" % (self.fid) |
| 224 | |
| 225 | def add_application(self, app): |
| 226 | """Add an ADF (Application Dedicated File) to the MF""" |
| 227 | if not isinstance(app, CardADF): |
| 228 | raise TypeError("Expected an ADF instance") |
| 229 | if app.aid in self.applications: |
| 230 | raise ValueError("AID %s already exists" % (app.aid)) |
| 231 | self.applications[app.aid] = app |
| 232 | app.parent=self |
| 233 | |
| 234 | def get_app_names(self): |
| 235 | """Get list of completions (AID names)""" |
| 236 | return [x.name for x in self.applications] |
| 237 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 238 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 239 | """Get list of completions (DF/EF/ADF names) from current DF""" |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 240 | sels = super().get_selectables(flags) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 241 | sels.update(self.get_app_selectables(flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 242 | return sels |
| 243 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 244 | def get_app_selectables(self, flags = []): |
| 245 | """Get applications by AID + name""" |
| 246 | sels = {} |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 247 | if flags == [] or 'AIDS' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 248 | sels.update({x.aid: x for x in self.applications.values()}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 249 | if flags == [] or 'ANAMES' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 250 | 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] | 251 | return sels |
| 252 | |
| 253 | def decode_select_response(self, data_hex): |
| 254 | """Decode the response to a SELECT command.""" |
| 255 | return data_hex |
| 256 | |
| 257 | |
| 258 | |
| 259 | class CardADF(CardDF): |
| 260 | """ADF (Application Dedicated File) in the smart card filesystem""" |
| 261 | def __init__(self, aid, **kwargs): |
| 262 | super().__init__(**kwargs) |
| 263 | self.aid = aid # Application Identifier |
| 264 | if self.parent: |
| 265 | self.parent.add_application(self) |
| 266 | |
| 267 | def __str__(self): |
| 268 | return "ADF(%s)" % (self.aid) |
| 269 | |
| 270 | def _path_element(self, prefer_name): |
| 271 | if self.name and prefer_name: |
| 272 | return self.name |
| 273 | else: |
| 274 | return self.aid |
| 275 | |
| 276 | |
| 277 | class CardEF(CardFile): |
| 278 | """EF (Entry File) in the smart card filesystem""" |
| 279 | def __init__(self, *, fid, **kwargs): |
| 280 | kwargs['fid'] = fid |
| 281 | super().__init__(**kwargs) |
| 282 | |
| 283 | def __str__(self): |
| 284 | return "EF(%s)" % (super().__str__()) |
| 285 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 286 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 287 | """Get list of completions (EF names) from current DF""" |
| 288 | #global selectable names + those of the parent DF |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 289 | sels = super().get_selectables(flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 290 | sels.update({x.name:x for x in self.parent.children.values() if x != self}) |
| 291 | return sels |
| 292 | |
| 293 | |
| 294 | class TransparentEF(CardEF): |
| 295 | """Transparent EF (Entry File) in the smart card filesystem""" |
| 296 | |
| 297 | @with_default_category('Transparent EF Commands') |
| 298 | class ShellCommands(CommandSet): |
| 299 | def __init__(self): |
| 300 | super().__init__() |
| 301 | |
| 302 | read_bin_parser = argparse.ArgumentParser() |
| 303 | read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 304 | read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read') |
| 305 | @cmd2.with_argparser(read_bin_parser) |
| 306 | def do_read_binary(self, opts): |
| 307 | """Read binary data from a transparent EF""" |
| 308 | (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset) |
| 309 | self._cmd.poutput(data) |
| 310 | |
| 311 | def do_read_binary_decoded(self, opts): |
| 312 | """Read + decode data from a transparent EF""" |
| 313 | (data, sw) = self._cmd.rs.read_binary_dec() |
| 314 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 315 | |
| 316 | upd_bin_parser = argparse.ArgumentParser() |
| 317 | upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 318 | upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 319 | @cmd2.with_argparser(upd_bin_parser) |
| 320 | def do_update_binary(self, opts): |
| 321 | """Update (Write) data of a transparent EF""" |
| 322 | (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 323 | if data: |
| 324 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 325 | |
| 326 | upd_bin_dec_parser = argparse.ArgumentParser() |
| 327 | upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write') |
| 328 | @cmd2.with_argparser(upd_bin_dec_parser) |
| 329 | def do_update_binary_decoded(self, opts): |
| 330 | """Encode + Update (Write) data of a transparent EF""" |
| 331 | data_json = json.loads(opts.data) |
| 332 | (data, sw) = self._cmd.rs.update_binary_dec(data_json) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 333 | if data: |
| 334 | self._cmd.poutput(json.dumps(data, indent=4)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 335 | |
| 336 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, size={1,None}): |
| 337 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 338 | self.size = size |
| 339 | self.shell_commands = [self.ShellCommands()] |
| 340 | |
| 341 | def decode_bin(self, raw_bin_data): |
| 342 | """Decode raw (binary) data into abstract representation. Overloaded by specific classes.""" |
| 343 | method = getattr(self, '_decode_bin', None) |
| 344 | if callable(method): |
| 345 | return method(raw_bin_data) |
| 346 | method = getattr(self, '_decode_hex', None) |
| 347 | if callable(method): |
| 348 | return method(b2h(raw_bin_data)) |
| 349 | return {'raw': raw_bin_data.hex()} |
| 350 | |
| 351 | def decode_hex(self, raw_hex_data): |
| 352 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 353 | method = getattr(self, '_decode_hex', None) |
| 354 | if callable(method): |
| 355 | return method(raw_hex_data) |
| 356 | raw_bin_data = h2b(raw_hex_data) |
| 357 | method = getattr(self, '_decode_bin', None) |
| 358 | if callable(method): |
| 359 | return method(raw_bin_data) |
| 360 | return {'raw': raw_bin_data.hex()} |
| 361 | |
| 362 | def encode_bin(self, abstract_data): |
| 363 | """Encode abstract representation into raw (binary) data. Overloaded by specific classes.""" |
| 364 | method = getattr(self, '_encode_bin', None) |
| 365 | if callable(method): |
| 366 | return method(abstract_data) |
| 367 | method = getattr(self, '_encode_hex', None) |
| 368 | if callable(method): |
| 369 | return h2b(method(abstract_data)) |
| 370 | raise NotImplementedError |
| 371 | |
| 372 | def encode_hex(self, abstract_data): |
| 373 | """Encode abstract representation into raw (hex string) data. Overloaded by specific classes.""" |
| 374 | method = getattr(self, '_encode_hex', None) |
| 375 | if callable(method): |
| 376 | return method(abstract_data) |
| 377 | method = getattr(self, '_encode_bin', None) |
| 378 | if callable(method): |
| 379 | raw_bin_data = method(abstract_data) |
| 380 | return b2h(raw_bin_data) |
| 381 | raise NotImplementedError |
| 382 | |
| 383 | |
| 384 | class LinFixedEF(CardEF): |
| 385 | """Linear Fixed EF (Entry File) in the smart card filesystem""" |
| 386 | |
| 387 | @with_default_category('Linear Fixed EF Commands') |
| 388 | class ShellCommands(CommandSet): |
| 389 | def __init__(self): |
| 390 | super().__init__() |
| 391 | |
| 392 | read_rec_parser = argparse.ArgumentParser() |
| 393 | 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] | 394 | 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] | 395 | @cmd2.with_argparser(read_rec_parser) |
| 396 | def do_read_record(self, opts): |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 397 | """Read one or multiple records from a record-oriented EF""" |
| 398 | for r in range(opts.count): |
| 399 | recnr = opts.record_nr + r |
| 400 | (data, sw) = self._cmd.rs.read_record(recnr) |
| 401 | if (len(data) > 0): |
| 402 | recstr = str(data) |
| 403 | else: |
| 404 | recstr = "(empty)" |
| 405 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 406 | |
| 407 | read_rec_dec_parser = argparse.ArgumentParser() |
| 408 | read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 409 | @cmd2.with_argparser(read_rec_dec_parser) |
| 410 | def do_read_record_decoded(self, opts): |
| 411 | """Read + decode a record from a record-oriented EF""" |
| 412 | (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr) |
| 413 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 414 | |
| 415 | upd_rec_parser = argparse.ArgumentParser() |
| 416 | upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 417 | upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 418 | @cmd2.with_argparser(upd_rec_parser) |
| 419 | def do_update_record(self, opts): |
| 420 | """Update (write) data to a record-oriented EF""" |
| 421 | (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 422 | if data: |
| 423 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 424 | |
| 425 | upd_rec_dec_parser = argparse.ArgumentParser() |
| 426 | upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 427 | upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 428 | @cmd2.with_argparser(upd_rec_dec_parser) |
| 429 | def do_update_record_decoded(self, opts): |
| 430 | """Encode + Update (write) data to a record-oriented EF""" |
| 431 | (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data) |
Philipp Maier | e6bc4f9 | 2021-03-11 17:13:46 +0100 | [diff] [blame] | 432 | if data: |
| 433 | self._cmd.poutput(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 434 | |
| 435 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}): |
| 436 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 437 | self.rec_len = rec_len |
| 438 | self.shell_commands = [self.ShellCommands()] |
| 439 | |
| 440 | def decode_record_hex(self, raw_hex_data): |
| 441 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 442 | method = getattr(self, '_decode_record_hex', None) |
| 443 | if callable(method): |
| 444 | return method(raw_hex_data) |
| 445 | raw_bin_data = h2b(raw_hex_data) |
| 446 | method = getattr(self, '_decode_record_bin', None) |
| 447 | if callable(method): |
| 448 | return method(raw_bin_data) |
| 449 | return {'raw': raw_bin_data.hex()} |
| 450 | |
| 451 | def decode_record_bin(self, raw_bin_data): |
| 452 | """Decode raw (binary) data into abstract representation. Overloaded by specific classes.""" |
| 453 | method = getattr(self, '_decode_record_bin', None) |
| 454 | if callable(method): |
| 455 | return method(raw_bin_data) |
| 456 | raw_hex_data = b2h(raw_bin_data) |
| 457 | method = getattr(self, '_decode_record_hex', None) |
| 458 | if callable(method): |
| 459 | return method(raw_hex_data) |
| 460 | return {'raw': raw_hex_data} |
| 461 | |
| 462 | def encode_record_hex(self, abstract_data): |
| 463 | """Encode abstract representation into raw (hex string) data. Overloaded by specific classes.""" |
| 464 | method = getattr(self, '_encode_record_hex', None) |
| 465 | if callable(method): |
| 466 | return method(abstract_data) |
| 467 | method = getattr(self, '_encode_record_bin', None) |
| 468 | if callable(method): |
| 469 | raw_bin_data = method(abstract_data) |
| 470 | return b2h(raww_bin_data) |
| 471 | raise NotImplementedError |
| 472 | |
| 473 | def encode_record_bin(self, abstract_data): |
| 474 | """Encode abstract representation into raw (binary) data. Overloaded by specific classes.""" |
| 475 | method = getattr(self, '_encode_record_bin', None) |
| 476 | if callable(method): |
| 477 | return method(abstract_data) |
| 478 | method = getattr(self, '_encode_record_hex', None) |
| 479 | if callable(method): |
| 480 | return b2h(method(abstract_data)) |
| 481 | raise NotImplementedError |
| 482 | |
| 483 | class CyclicEF(LinFixedEF): |
| 484 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 485 | # we don't really have any special support for those; just recycling LinFixedEF here |
| 486 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}): |
| 487 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len) |
| 488 | |
| 489 | class TransRecEF(TransparentEF): |
| 490 | """Transparent EF (Entry File) containing fixed-size records. |
| 491 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 492 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 493 | inside. |
| 494 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 495 | for a record, while this class takes care of split / merge of records. |
| 496 | """ |
| 497 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len=None, size={1,None}): |
| 498 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size) |
| 499 | self.rec_len = rec_len |
| 500 | |
| 501 | def decode_record_hex(self, raw_hex_data): |
| 502 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 503 | method = getattr(self, '_decode_record_hex', None) |
| 504 | if callable(method): |
| 505 | return method(raw_hex_data) |
| 506 | method = getattr(self, '_decode_record_bin', None) |
| 507 | if callable(method): |
| 508 | raw_bin_data = h2b(raw_hex_data) |
| 509 | return method(raw_bin_data) |
| 510 | return {'raw': raw_hex_data} |
| 511 | |
| 512 | def decode_record_bin(self, raw_bin_data): |
| 513 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 514 | method = getattr(self, '_decode_record_bin', None) |
| 515 | if callable(method): |
| 516 | return method(raw_bin_data) |
| 517 | raw_hex_data = b2h(raw_bin_data) |
| 518 | method = getattr(self, '_decode_record_hex', None) |
| 519 | if callable(method): |
| 520 | return method(raw_hex_data) |
| 521 | return {'raw': raw_hex_data} |
| 522 | |
| 523 | def encode_record_hex(self, abstract_data): |
| 524 | """Encode abstract representation into raw (hex string) data. Overloaded by specific classes.""" |
| 525 | method = getattr(self, '_encode_record_hex', None) |
| 526 | if callable(method): |
| 527 | return method(abstract_data) |
| 528 | method = getattr(self, '_encode_record_bin', None) |
| 529 | if callable(method): |
| 530 | return h2b(method(abstract_data)) |
| 531 | raise NotImplementedError |
| 532 | |
| 533 | def encode_record_bin(self, abstract_data): |
| 534 | """Encode abstract representation into raw (binary) data. Overloaded by specific classes.""" |
| 535 | method = getattr(self, '_encode_record_bin', None) |
| 536 | if callable(method): |
| 537 | return method(abstract_data) |
| 538 | method = getattr(self, '_encode_record_hex', None) |
| 539 | if callable(method): |
| 540 | return h2b(method(abstract_data)) |
| 541 | raise NotImplementedError |
| 542 | |
| 543 | def _decode_bin(self, raw_bin_data): |
| 544 | chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)] |
| 545 | return [self.decode_record_bin(x) for x in chunks] |
| 546 | |
| 547 | def _encode_bin(self, abstract_data): |
| 548 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 549 | # FIXME: pad to file size |
| 550 | return b''.join(chunks) |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | class RuntimeState(object): |
| 557 | """Represent the runtime state of a session with a card.""" |
| 558 | def __init__(self, card, profile): |
| 559 | self.mf = CardMF() |
| 560 | self.card = card |
| 561 | self.selected_file = self.mf |
| 562 | self.profile = profile |
| 563 | # add applications + MF-files from profile |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 564 | apps = self._match_applications() |
| 565 | for a in apps: |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 566 | self.mf.add_application(a) |
| 567 | for f in self.profile.files_in_mf: |
| 568 | self.mf.add_file(f) |
| 569 | |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 570 | def _match_applications(self): |
| 571 | """match the applications from the profile with applications on the card""" |
| 572 | apps_profile = self.profile.applications |
| 573 | aids_card = self.card.read_aids() |
| 574 | apps_taken = [] |
| 575 | if aids_card: |
| 576 | aids_taken = [] |
| 577 | print("AIDs on card:") |
| 578 | for a in aids_card: |
| 579 | for f in apps_profile: |
| 580 | if f.aid in a: |
| 581 | print(" %s: %s" % (f.name, a)) |
| 582 | aids_taken.append(a) |
| 583 | apps_taken.append(f) |
| 584 | aids_unknown = set(aids_card) - set(aids_taken) |
| 585 | for a in aids_unknown: |
| 586 | print(" unknown: %s" % a) |
| 587 | else: |
| 588 | print("error: could not determine card applications") |
| 589 | return apps_taken |
| 590 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 591 | def get_cwd(self): |
| 592 | """Obtain the current working directory.""" |
| 593 | if isinstance(self.selected_file, CardDF): |
| 594 | return self.selected_file |
| 595 | else: |
| 596 | return self.selected_file.parent |
| 597 | |
| 598 | def get_application(self): |
| 599 | """Obtain the currently selected application (if any).""" |
| 600 | # iterate upwards from selected file; check if any is an ADF |
| 601 | node = self.selected_file |
| 602 | while node.parent != node: |
| 603 | if isinstance(node, CardADF): |
| 604 | return node |
| 605 | node = node.parent |
| 606 | return None |
| 607 | |
| 608 | def interpret_sw(self, sw): |
| 609 | """Interpret the given SW relative to the currently selected Application |
| 610 | or the underlying profile.""" |
| 611 | app = self.get_application() |
| 612 | if app: |
| 613 | # The application either comes with its own interpret_sw |
| 614 | # method or we will use the interpret_sw method from the |
| 615 | # card profile. |
| 616 | if hasattr(app, "interpret_sw"): |
| 617 | return app.interpret_sw(sw) |
| 618 | else: |
| 619 | return self.profile.interpret_sw(sw) |
| 620 | return app.interpret_sw(sw) |
| 621 | else: |
| 622 | return self.profile.interpret_sw(sw) |
| 623 | |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 624 | def probe_file(self, fid, cmd_app=None): |
| 625 | """ |
| 626 | blindly try to select a file and automatically add a matching file |
| 627 | object if the file actually exists |
| 628 | """ |
| 629 | if not is_hex(fid, 4, 4): |
| 630 | raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid) |
| 631 | |
| 632 | try: |
| 633 | (data, sw) = self.card._scc.select_file(fid) |
| 634 | except SwMatchError as swm: |
| 635 | k = self.interpret_sw(swm.sw_actual) |
| 636 | if not k: |
| 637 | raise(swm) |
| 638 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
| 639 | |
| 640 | select_resp = self.selected_file.decode_select_response(data) |
| 641 | if (select_resp['file_descriptor']['file_type'] == 'df'): |
| 642 | f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime") |
| 643 | else: |
| 644 | if (select_resp['file_descriptor']['structure'] == 'transparent'): |
| 645 | f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime") |
| 646 | else: |
| 647 | f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime") |
| 648 | |
| 649 | self.selected_file.add_files([f]) |
| 650 | self.selected_file = f |
| 651 | return select_resp |
| 652 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 653 | def select(self, name, cmd_app=None): |
| 654 | """Change current directory""" |
| 655 | sels = self.selected_file.get_selectables() |
Philipp Maier | 7744b6e | 2021-03-11 14:29:37 +0100 | [diff] [blame] | 656 | if is_hex(name): |
| 657 | name = name.lower() |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 658 | |
| 659 | # unregister commands of old file |
| 660 | if cmd_app and self.selected_file.shell_commands: |
| 661 | for c in self.selected_file.shell_commands: |
| 662 | cmd_app.unregister_command_set(c) |
| 663 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 664 | if name in sels: |
| 665 | f = sels[name] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 666 | try: |
| 667 | if isinstance(f, CardADF): |
Philipp Maier | cba6dbc | 2021-03-11 13:03:18 +0100 | [diff] [blame^] | 668 | (data, sw) = self.card.select_adf_by_aid(f.aid) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 669 | else: |
| 670 | (data, sw) = self.card._scc.select_file(f.fid) |
| 671 | self.selected_file = f |
| 672 | except SwMatchError as swm: |
| 673 | k = self.interpret_sw(swm.sw_actual) |
| 674 | if not k: |
| 675 | raise(swm) |
| 676 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 677 | select_resp = f.decode_select_response(data) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 678 | else: |
Philipp Maier | 63f572d | 2021-03-09 22:42:47 +0100 | [diff] [blame] | 679 | select_resp = self.probe_file(name, cmd_app) |
| 680 | |
| 681 | # register commands of new file |
| 682 | if cmd_app and self.selected_file.shell_commands: |
| 683 | for c in self.selected_file.shell_commands: |
| 684 | cmd_app.register_command_set(c) |
| 685 | |
| 686 | return select_resp |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 687 | |
| 688 | def read_binary(self, length=None, offset=0): |
| 689 | if not isinstance(self.selected_file, TransparentEF): |
| 690 | raise TypeError("Only works with TransparentEF") |
| 691 | return self.card._scc.read_binary(self.selected_file.fid, length, offset) |
| 692 | |
| 693 | def read_binary_dec(self): |
| 694 | (data, sw) = self.read_binary() |
| 695 | dec_data = self.selected_file.decode_hex(data) |
| 696 | print("%s: %s -> %s" % (sw, data, dec_data)) |
| 697 | return (dec_data, sw) |
| 698 | |
| 699 | def update_binary(self, data_hex, offset=0): |
| 700 | if not isinstance(self.selected_file, TransparentEF): |
| 701 | raise TypeError("Only works with TransparentEF") |
| 702 | return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset) |
| 703 | |
| 704 | def update_binary_dec(self, data): |
| 705 | data_hex = self.selected_file.encode_hex(data) |
| 706 | print("%s -> %s" % (data, data_hex)) |
| 707 | return self.update_binary(data_hex) |
| 708 | |
| 709 | def read_record(self, rec_nr=0): |
| 710 | if not isinstance(self.selected_file, LinFixedEF): |
| 711 | raise TypeError("Only works with Linear Fixed EF") |
| 712 | # returns a string of hex nibbles |
| 713 | return self.card._scc.read_record(self.selected_file.fid, rec_nr) |
| 714 | |
| 715 | def read_record_dec(self, rec_nr=0): |
| 716 | (data, sw) = self.read_record(rec_nr) |
| 717 | return (self.selected_file.decode_record_hex(data), sw) |
| 718 | |
| 719 | def update_record(self, rec_nr, data_hex): |
| 720 | if not isinstance(self.selected_file, LinFixedEF): |
| 721 | raise TypeError("Only works with Linear Fixed EF") |
| 722 | return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex) |
| 723 | |
| 724 | def update_record_dec(self, rec_nr, data): |
| 725 | hex_data = self.selected_file.encode_record_hex(data) |
| 726 | return self.update_record(self, rec_nr, data_hex) |
| 727 | |
| 728 | |
| 729 | |
| 730 | class FileData(object): |
| 731 | """Represent the runtime, on-card data.""" |
| 732 | def __init__(self, fdesc): |
| 733 | self.desc = fdesc |
| 734 | self.fcp = None |
| 735 | |
| 736 | |
| 737 | def interpret_sw(sw_data, sw): |
| 738 | """Interpret a given status word within the profile. Returns tuple of |
| 739 | two strings""" |
| 740 | for class_str, swdict in sw_data.items(): |
| 741 | # first try direct match |
| 742 | if sw in swdict: |
| 743 | return (class_str, swdict[sw]) |
| 744 | # next try wildcard matches |
| 745 | for pattern, descr in swdict.items(): |
| 746 | if sw_match(sw, pattern): |
| 747 | return (class_str, descr) |
| 748 | return None |
| 749 | |
| 750 | class CardApplication(object): |
| 751 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 752 | some SW definitions.""" |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 753 | def __init__(self, name, adf=None, sw=None): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 754 | self.name = name |
| 755 | self.adf = adf |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 756 | self.sw = sw or dict() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 757 | |
| 758 | def __str__(self): |
| 759 | return "APP(%s)" % (self.name) |
| 760 | |
| 761 | def interpret_sw(self, sw): |
| 762 | """Interpret a given status word within the application. Returns tuple of |
| 763 | two strings""" |
| 764 | return interpret_sw(self.sw, sw) |
| 765 | |
| 766 | class CardProfile(object): |
| 767 | """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of |
| 768 | applications as well as profile-specific SW and shell commands. Every card has |
| 769 | one card profile, but there may be multiple applications within that profile.""" |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 770 | def __init__(self, name, **kw): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 771 | self.name = name |
Vadim Yanitskiy | 98f872b | 2021-03-27 01:25:46 +0100 | [diff] [blame] | 772 | self.desc = kw.get("desc", None) |
| 773 | self.files_in_mf = kw.get("files_in_mf", []) |
| 774 | self.sw = kw.get("sw", []) |
| 775 | self.applications = kw.get("applications", []) |
| 776 | self.shell_cmdsets = kw.get("shell_cmdsets", []) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 777 | |
| 778 | def __str__(self): |
| 779 | return self.name |
| 780 | |
| 781 | def add_application(self, app): |
Philipp Maier | eb72fa4 | 2021-03-26 21:29:57 +0100 | [diff] [blame] | 782 | self.applications.append(app) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 783 | |
| 784 | def interpret_sw(self, sw): |
| 785 | """Interpret a given status word within the profile. Returns tuple of |
| 786 | two strings""" |
| 787 | return interpret_sw(self.sw, sw) |