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 | |
| 34 | from pySim.utils import sw_match, h2b, b2h |
| 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.""" |
| 133 | def __init__(self, **kwargs): |
| 134 | if not isinstance(self, CardADF): |
| 135 | if not 'fid' in kwargs: |
| 136 | raise TypeError('fid is mandatory for all DF') |
| 137 | super().__init__(**kwargs) |
| 138 | self.children = dict() |
| 139 | |
| 140 | def __str__(self): |
| 141 | return "DF(%s)" % (super().__str__()) |
| 142 | |
| 143 | def add_file(self, child, ignore_existing=False): |
| 144 | """Add a child (DF/EF) to this DF""" |
| 145 | if not isinstance(child, CardFile): |
| 146 | raise TypeError("Expected a File instance") |
| 147 | if child.name in CardFile.RESERVED_NAMES: |
| 148 | raise ValueError("File name %s is a reserved name" % (child.name)) |
| 149 | if child.fid in CardFile.RESERVED_FIDS: |
Philipp Maier | e8bc1b4 | 2021-03-09 20:33:41 +0100 | [diff] [blame] | 150 | raise ValueError("File fid %s is a reserved fid" % (child.fid)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 151 | if child.fid in self.children: |
| 152 | if ignore_existing: |
| 153 | return |
| 154 | raise ValueError("File with given fid %s already exists" % (child.fid)) |
| 155 | if self.lookup_file_by_sfid(child.sfid): |
| 156 | raise ValueError("File with given sfid %s already exists" % (child.sfid)) |
| 157 | if self.lookup_file_by_name(child.name): |
| 158 | if ignore_existing: |
| 159 | return |
| 160 | raise ValueError("File with given name %s already exists" % (child.name)) |
| 161 | self.children[child.fid] = child |
| 162 | child.parent = self |
| 163 | |
| 164 | def add_files(self, children, ignore_existing=False): |
| 165 | """Add a list of child (DF/EF) to this DF""" |
| 166 | for child in children: |
| 167 | self.add_file(child, ignore_existing) |
| 168 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 169 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 170 | """Get selectable (DF/EF names) from current DF""" |
| 171 | # global selectables + our children |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 172 | sels = super().get_selectables(flags) |
| 173 | if flags == [] or 'FIDS' in flags: |
| 174 | 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] | 175 | if flags == [] or 'FNAMES' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 176 | 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] | 177 | return sels |
| 178 | |
| 179 | def lookup_file_by_name(self, name): |
| 180 | if name == None: |
| 181 | return None |
| 182 | for i in self.children.values(): |
| 183 | if i.name and i.name == name: |
| 184 | return i |
| 185 | return None |
| 186 | |
| 187 | def lookup_file_by_sfid(self, sfid): |
| 188 | if sfid == None: |
| 189 | return None |
| 190 | for i in self.children.values(): |
| 191 | if i.sfid == int(sfid): |
| 192 | return i |
| 193 | return None |
| 194 | |
| 195 | def lookup_file_by_fid(self, fid): |
| 196 | if fid in self.children: |
| 197 | return self.children[fid] |
| 198 | return None |
| 199 | |
| 200 | |
| 201 | class CardMF(CardDF): |
| 202 | """MF (Master File) in the smart card filesystem""" |
| 203 | def __init__(self, **kwargs): |
| 204 | # can be overridden; use setdefault |
| 205 | kwargs.setdefault('fid', '3f00') |
| 206 | kwargs.setdefault('name', 'MF') |
| 207 | kwargs.setdefault('desc', 'Master File (directory root)') |
| 208 | # cannot be overridden; use assignment |
| 209 | kwargs['parent'] = self |
| 210 | super().__init__(**kwargs) |
| 211 | self.applications = dict() |
| 212 | |
| 213 | def __str__(self): |
| 214 | return "MF(%s)" % (self.fid) |
| 215 | |
| 216 | def add_application(self, app): |
| 217 | """Add an ADF (Application Dedicated File) to the MF""" |
| 218 | if not isinstance(app, CardADF): |
| 219 | raise TypeError("Expected an ADF instance") |
| 220 | if app.aid in self.applications: |
| 221 | raise ValueError("AID %s already exists" % (app.aid)) |
| 222 | self.applications[app.aid] = app |
| 223 | app.parent=self |
| 224 | |
| 225 | def get_app_names(self): |
| 226 | """Get list of completions (AID names)""" |
| 227 | return [x.name for x in self.applications] |
| 228 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 229 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 230 | """Get list of completions (DF/EF/ADF names) from current DF""" |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 231 | sels = super().get_selectables(flags) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 232 | sels.update(self.get_app_selectables(flags)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 233 | return sels |
| 234 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 235 | def get_app_selectables(self, flags = []): |
| 236 | """Get applications by AID + name""" |
| 237 | sels = {} |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 238 | if flags == [] or 'AIDS' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 239 | sels.update({x.aid: x for x in self.applications.values()}) |
Philipp Maier | bd8ed2c | 2021-03-18 17:09:33 +0100 | [diff] [blame] | 240 | if flags == [] or 'ANAMES' in flags: |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 241 | 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] | 242 | return sels |
| 243 | |
| 244 | def decode_select_response(self, data_hex): |
| 245 | """Decode the response to a SELECT command.""" |
| 246 | return data_hex |
| 247 | |
| 248 | |
| 249 | |
| 250 | class CardADF(CardDF): |
| 251 | """ADF (Application Dedicated File) in the smart card filesystem""" |
| 252 | def __init__(self, aid, **kwargs): |
| 253 | super().__init__(**kwargs) |
| 254 | self.aid = aid # Application Identifier |
| 255 | if self.parent: |
| 256 | self.parent.add_application(self) |
| 257 | |
| 258 | def __str__(self): |
| 259 | return "ADF(%s)" % (self.aid) |
| 260 | |
| 261 | def _path_element(self, prefer_name): |
| 262 | if self.name and prefer_name: |
| 263 | return self.name |
| 264 | else: |
| 265 | return self.aid |
| 266 | |
| 267 | |
| 268 | class CardEF(CardFile): |
| 269 | """EF (Entry File) in the smart card filesystem""" |
| 270 | def __init__(self, *, fid, **kwargs): |
| 271 | kwargs['fid'] = fid |
| 272 | super().__init__(**kwargs) |
| 273 | |
| 274 | def __str__(self): |
| 275 | return "EF(%s)" % (super().__str__()) |
| 276 | |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 277 | def get_selectables(self, flags = []): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 278 | """Get list of completions (EF names) from current DF""" |
| 279 | #global selectable names + those of the parent DF |
Philipp Maier | 786f781 | 2021-02-25 16:48:10 +0100 | [diff] [blame] | 280 | sels = super().get_selectables(flags) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 281 | sels.update({x.name:x for x in self.parent.children.values() if x != self}) |
| 282 | return sels |
| 283 | |
| 284 | |
| 285 | class TransparentEF(CardEF): |
| 286 | """Transparent EF (Entry File) in the smart card filesystem""" |
| 287 | |
| 288 | @with_default_category('Transparent EF Commands') |
| 289 | class ShellCommands(CommandSet): |
| 290 | def __init__(self): |
| 291 | super().__init__() |
| 292 | |
| 293 | read_bin_parser = argparse.ArgumentParser() |
| 294 | read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 295 | read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read') |
| 296 | @cmd2.with_argparser(read_bin_parser) |
| 297 | def do_read_binary(self, opts): |
| 298 | """Read binary data from a transparent EF""" |
| 299 | (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset) |
| 300 | self._cmd.poutput(data) |
| 301 | |
| 302 | def do_read_binary_decoded(self, opts): |
| 303 | """Read + decode data from a transparent EF""" |
| 304 | (data, sw) = self._cmd.rs.read_binary_dec() |
| 305 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 306 | |
| 307 | upd_bin_parser = argparse.ArgumentParser() |
| 308 | upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read') |
| 309 | upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 310 | @cmd2.with_argparser(upd_bin_parser) |
| 311 | def do_update_binary(self, opts): |
| 312 | """Update (Write) data of a transparent EF""" |
| 313 | (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset) |
| 314 | self._cmd.poutput(data) |
| 315 | |
| 316 | upd_bin_dec_parser = argparse.ArgumentParser() |
| 317 | upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write') |
| 318 | @cmd2.with_argparser(upd_bin_dec_parser) |
| 319 | def do_update_binary_decoded(self, opts): |
| 320 | """Encode + Update (Write) data of a transparent EF""" |
| 321 | data_json = json.loads(opts.data) |
| 322 | (data, sw) = self._cmd.rs.update_binary_dec(data_json) |
| 323 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 324 | |
| 325 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, size={1,None}): |
| 326 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 327 | self.size = size |
| 328 | self.shell_commands = [self.ShellCommands()] |
| 329 | |
| 330 | def decode_bin(self, raw_bin_data): |
| 331 | """Decode raw (binary) data into abstract representation. Overloaded by specific classes.""" |
| 332 | method = getattr(self, '_decode_bin', None) |
| 333 | if callable(method): |
| 334 | return method(raw_bin_data) |
| 335 | method = getattr(self, '_decode_hex', None) |
| 336 | if callable(method): |
| 337 | return method(b2h(raw_bin_data)) |
| 338 | return {'raw': raw_bin_data.hex()} |
| 339 | |
| 340 | def decode_hex(self, raw_hex_data): |
| 341 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 342 | method = getattr(self, '_decode_hex', None) |
| 343 | if callable(method): |
| 344 | return method(raw_hex_data) |
| 345 | raw_bin_data = h2b(raw_hex_data) |
| 346 | method = getattr(self, '_decode_bin', None) |
| 347 | if callable(method): |
| 348 | return method(raw_bin_data) |
| 349 | return {'raw': raw_bin_data.hex()} |
| 350 | |
| 351 | def encode_bin(self, abstract_data): |
| 352 | """Encode abstract representation into raw (binary) data. Overloaded by specific classes.""" |
| 353 | method = getattr(self, '_encode_bin', None) |
| 354 | if callable(method): |
| 355 | return method(abstract_data) |
| 356 | method = getattr(self, '_encode_hex', None) |
| 357 | if callable(method): |
| 358 | return h2b(method(abstract_data)) |
| 359 | raise NotImplementedError |
| 360 | |
| 361 | def encode_hex(self, abstract_data): |
| 362 | """Encode abstract representation into raw (hex string) data. Overloaded by specific classes.""" |
| 363 | method = getattr(self, '_encode_hex', None) |
| 364 | if callable(method): |
| 365 | return method(abstract_data) |
| 366 | method = getattr(self, '_encode_bin', None) |
| 367 | if callable(method): |
| 368 | raw_bin_data = method(abstract_data) |
| 369 | return b2h(raw_bin_data) |
| 370 | raise NotImplementedError |
| 371 | |
| 372 | |
| 373 | class LinFixedEF(CardEF): |
| 374 | """Linear Fixed EF (Entry File) in the smart card filesystem""" |
| 375 | |
| 376 | @with_default_category('Linear Fixed EF Commands') |
| 377 | class ShellCommands(CommandSet): |
| 378 | def __init__(self): |
| 379 | super().__init__() |
| 380 | |
| 381 | read_rec_parser = argparse.ArgumentParser() |
| 382 | 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] | 383 | 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] | 384 | @cmd2.with_argparser(read_rec_parser) |
| 385 | def do_read_record(self, opts): |
Philipp Maier | 4155573 | 2021-02-25 16:52:08 +0100 | [diff] [blame] | 386 | """Read one or multiple records from a record-oriented EF""" |
| 387 | for r in range(opts.count): |
| 388 | recnr = opts.record_nr + r |
| 389 | (data, sw) = self._cmd.rs.read_record(recnr) |
| 390 | if (len(data) > 0): |
| 391 | recstr = str(data) |
| 392 | else: |
| 393 | recstr = "(empty)" |
| 394 | self._cmd.poutput("%03d %s" % (recnr, recstr)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 395 | |
| 396 | read_rec_dec_parser = argparse.ArgumentParser() |
| 397 | read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 398 | @cmd2.with_argparser(read_rec_dec_parser) |
| 399 | def do_read_record_decoded(self, opts): |
| 400 | """Read + decode a record from a record-oriented EF""" |
| 401 | (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr) |
| 402 | self._cmd.poutput(json.dumps(data, indent=4)) |
| 403 | |
| 404 | upd_rec_parser = argparse.ArgumentParser() |
| 405 | upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 406 | upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 407 | @cmd2.with_argparser(upd_rec_parser) |
| 408 | def do_update_record(self, opts): |
| 409 | """Update (write) data to a record-oriented EF""" |
| 410 | (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data) |
| 411 | self._cmd.poutput(data) |
| 412 | |
| 413 | upd_rec_dec_parser = argparse.ArgumentParser() |
| 414 | upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read') |
| 415 | upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write') |
| 416 | @cmd2.with_argparser(upd_rec_dec_parser) |
| 417 | def do_update_record_decoded(self, opts): |
| 418 | """Encode + Update (write) data to a record-oriented EF""" |
| 419 | (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data) |
| 420 | self._cmd.poutput(data) |
| 421 | |
| 422 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}): |
| 423 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent) |
| 424 | self.rec_len = rec_len |
| 425 | self.shell_commands = [self.ShellCommands()] |
| 426 | |
| 427 | def decode_record_hex(self, raw_hex_data): |
| 428 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 429 | method = getattr(self, '_decode_record_hex', None) |
| 430 | if callable(method): |
| 431 | return method(raw_hex_data) |
| 432 | raw_bin_data = h2b(raw_hex_data) |
| 433 | method = getattr(self, '_decode_record_bin', None) |
| 434 | if callable(method): |
| 435 | return method(raw_bin_data) |
| 436 | return {'raw': raw_bin_data.hex()} |
| 437 | |
| 438 | def decode_record_bin(self, raw_bin_data): |
| 439 | """Decode raw (binary) data into abstract representation. Overloaded by specific classes.""" |
| 440 | method = getattr(self, '_decode_record_bin', None) |
| 441 | if callable(method): |
| 442 | return method(raw_bin_data) |
| 443 | raw_hex_data = b2h(raw_bin_data) |
| 444 | method = getattr(self, '_decode_record_hex', None) |
| 445 | if callable(method): |
| 446 | return method(raw_hex_data) |
| 447 | return {'raw': raw_hex_data} |
| 448 | |
| 449 | def encode_record_hex(self, abstract_data): |
| 450 | """Encode abstract representation into raw (hex string) data. Overloaded by specific classes.""" |
| 451 | method = getattr(self, '_encode_record_hex', None) |
| 452 | if callable(method): |
| 453 | return method(abstract_data) |
| 454 | method = getattr(self, '_encode_record_bin', None) |
| 455 | if callable(method): |
| 456 | raw_bin_data = method(abstract_data) |
| 457 | return b2h(raww_bin_data) |
| 458 | raise NotImplementedError |
| 459 | |
| 460 | def encode_record_bin(self, abstract_data): |
| 461 | """Encode abstract representation into raw (binary) data. Overloaded by specific classes.""" |
| 462 | method = getattr(self, '_encode_record_bin', None) |
| 463 | if callable(method): |
| 464 | return method(abstract_data) |
| 465 | method = getattr(self, '_encode_record_hex', None) |
| 466 | if callable(method): |
| 467 | return b2h(method(abstract_data)) |
| 468 | raise NotImplementedError |
| 469 | |
| 470 | class CyclicEF(LinFixedEF): |
| 471 | """Cyclic EF (Entry File) in the smart card filesystem""" |
| 472 | # we don't really have any special support for those; just recycling LinFixedEF here |
| 473 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}): |
| 474 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len) |
| 475 | |
| 476 | class TransRecEF(TransparentEF): |
| 477 | """Transparent EF (Entry File) containing fixed-size records. |
| 478 | These are the real odd-balls and mostly look like mistakes in the specification: |
| 479 | Specified as 'transparent' EF, but actually containing several fixed-length records |
| 480 | inside. |
| 481 | We add a special class for those, so the user only has to provide encoder/decoder functions |
| 482 | for a record, while this class takes care of split / merge of records. |
| 483 | """ |
| 484 | def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len=None, size={1,None}): |
| 485 | super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size) |
| 486 | self.rec_len = rec_len |
| 487 | |
| 488 | def decode_record_hex(self, raw_hex_data): |
| 489 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 490 | method = getattr(self, '_decode_record_hex', None) |
| 491 | if callable(method): |
| 492 | return method(raw_hex_data) |
| 493 | method = getattr(self, '_decode_record_bin', None) |
| 494 | if callable(method): |
| 495 | raw_bin_data = h2b(raw_hex_data) |
| 496 | return method(raw_bin_data) |
| 497 | return {'raw': raw_hex_data} |
| 498 | |
| 499 | def decode_record_bin(self, raw_bin_data): |
| 500 | """Decode raw (hex string) data into abstract representation. Overloaded by specific classes.""" |
| 501 | method = getattr(self, '_decode_record_bin', None) |
| 502 | if callable(method): |
| 503 | return method(raw_bin_data) |
| 504 | raw_hex_data = b2h(raw_bin_data) |
| 505 | method = getattr(self, '_decode_record_hex', None) |
| 506 | if callable(method): |
| 507 | return method(raw_hex_data) |
| 508 | return {'raw': raw_hex_data} |
| 509 | |
| 510 | def encode_record_hex(self, abstract_data): |
| 511 | """Encode abstract representation into raw (hex string) data. Overloaded by specific classes.""" |
| 512 | method = getattr(self, '_encode_record_hex', None) |
| 513 | if callable(method): |
| 514 | return method(abstract_data) |
| 515 | method = getattr(self, '_encode_record_bin', None) |
| 516 | if callable(method): |
| 517 | return h2b(method(abstract_data)) |
| 518 | raise NotImplementedError |
| 519 | |
| 520 | def encode_record_bin(self, abstract_data): |
| 521 | """Encode abstract representation into raw (binary) data. Overloaded by specific classes.""" |
| 522 | method = getattr(self, '_encode_record_bin', None) |
| 523 | if callable(method): |
| 524 | return method(abstract_data) |
| 525 | method = getattr(self, '_encode_record_hex', None) |
| 526 | if callable(method): |
| 527 | return h2b(method(abstract_data)) |
| 528 | raise NotImplementedError |
| 529 | |
| 530 | def _decode_bin(self, raw_bin_data): |
| 531 | chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)] |
| 532 | return [self.decode_record_bin(x) for x in chunks] |
| 533 | |
| 534 | def _encode_bin(self, abstract_data): |
| 535 | chunks = [self.encode_record_bin(x) for x in abstract_data] |
| 536 | # FIXME: pad to file size |
| 537 | return b''.join(chunks) |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | class RuntimeState(object): |
| 544 | """Represent the runtime state of a session with a card.""" |
| 545 | def __init__(self, card, profile): |
| 546 | self.mf = CardMF() |
| 547 | self.card = card |
| 548 | self.selected_file = self.mf |
| 549 | self.profile = profile |
| 550 | # add applications + MF-files from profile |
| 551 | for a in self.profile.applications: |
| 552 | self.mf.add_application(a) |
| 553 | for f in self.profile.files_in_mf: |
| 554 | self.mf.add_file(f) |
| 555 | |
| 556 | def get_cwd(self): |
| 557 | """Obtain the current working directory.""" |
| 558 | if isinstance(self.selected_file, CardDF): |
| 559 | return self.selected_file |
| 560 | else: |
| 561 | return self.selected_file.parent |
| 562 | |
| 563 | def get_application(self): |
| 564 | """Obtain the currently selected application (if any).""" |
| 565 | # iterate upwards from selected file; check if any is an ADF |
| 566 | node = self.selected_file |
| 567 | while node.parent != node: |
| 568 | if isinstance(node, CardADF): |
| 569 | return node |
| 570 | node = node.parent |
| 571 | return None |
| 572 | |
| 573 | def interpret_sw(self, sw): |
| 574 | """Interpret the given SW relative to the currently selected Application |
| 575 | or the underlying profile.""" |
| 576 | app = self.get_application() |
| 577 | if app: |
| 578 | # The application either comes with its own interpret_sw |
| 579 | # method or we will use the interpret_sw method from the |
| 580 | # card profile. |
| 581 | if hasattr(app, "interpret_sw"): |
| 582 | return app.interpret_sw(sw) |
| 583 | else: |
| 584 | return self.profile.interpret_sw(sw) |
| 585 | return app.interpret_sw(sw) |
| 586 | else: |
| 587 | return self.profile.interpret_sw(sw) |
| 588 | |
| 589 | def select(self, name, cmd_app=None): |
| 590 | """Change current directory""" |
| 591 | sels = self.selected_file.get_selectables() |
Philipp Maier | 7744b6e | 2021-03-11 14:29:37 +0100 | [diff] [blame] | 592 | if is_hex(name): |
| 593 | name = name.lower() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 594 | if name in sels: |
| 595 | f = sels[name] |
| 596 | # unregister commands of old file |
| 597 | if cmd_app and self.selected_file.shell_commands: |
| 598 | for c in self.selected_file.shell_commands: |
| 599 | cmd_app.unregister_command_set(c) |
| 600 | try: |
| 601 | if isinstance(f, CardADF): |
| 602 | (data, sw) = self.card._scc.select_adf(f.aid) |
| 603 | else: |
| 604 | (data, sw) = self.card._scc.select_file(f.fid) |
| 605 | self.selected_file = f |
| 606 | except SwMatchError as swm: |
| 607 | k = self.interpret_sw(swm.sw_actual) |
| 608 | if not k: |
| 609 | raise(swm) |
| 610 | raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1])) |
| 611 | # register commands of new file |
| 612 | if cmd_app and self.selected_file.shell_commands: |
| 613 | for c in self.selected_file.shell_commands: |
| 614 | cmd_app.register_command_set(c) |
| 615 | return f.decode_select_response(data) |
| 616 | #elif looks_like_fid(name): |
| 617 | else: |
| 618 | raise ValueError("Cannot select unknown %s" % (name)) |
| 619 | |
| 620 | def read_binary(self, length=None, offset=0): |
| 621 | if not isinstance(self.selected_file, TransparentEF): |
| 622 | raise TypeError("Only works with TransparentEF") |
| 623 | return self.card._scc.read_binary(self.selected_file.fid, length, offset) |
| 624 | |
| 625 | def read_binary_dec(self): |
| 626 | (data, sw) = self.read_binary() |
| 627 | dec_data = self.selected_file.decode_hex(data) |
| 628 | print("%s: %s -> %s" % (sw, data, dec_data)) |
| 629 | return (dec_data, sw) |
| 630 | |
| 631 | def update_binary(self, data_hex, offset=0): |
| 632 | if not isinstance(self.selected_file, TransparentEF): |
| 633 | raise TypeError("Only works with TransparentEF") |
| 634 | return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset) |
| 635 | |
| 636 | def update_binary_dec(self, data): |
| 637 | data_hex = self.selected_file.encode_hex(data) |
| 638 | print("%s -> %s" % (data, data_hex)) |
| 639 | return self.update_binary(data_hex) |
| 640 | |
| 641 | def read_record(self, rec_nr=0): |
| 642 | if not isinstance(self.selected_file, LinFixedEF): |
| 643 | raise TypeError("Only works with Linear Fixed EF") |
| 644 | # returns a string of hex nibbles |
| 645 | return self.card._scc.read_record(self.selected_file.fid, rec_nr) |
| 646 | |
| 647 | def read_record_dec(self, rec_nr=0): |
| 648 | (data, sw) = self.read_record(rec_nr) |
| 649 | return (self.selected_file.decode_record_hex(data), sw) |
| 650 | |
| 651 | def update_record(self, rec_nr, data_hex): |
| 652 | if not isinstance(self.selected_file, LinFixedEF): |
| 653 | raise TypeError("Only works with Linear Fixed EF") |
| 654 | return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex) |
| 655 | |
| 656 | def update_record_dec(self, rec_nr, data): |
| 657 | hex_data = self.selected_file.encode_record_hex(data) |
| 658 | return self.update_record(self, rec_nr, data_hex) |
| 659 | |
| 660 | |
| 661 | |
| 662 | class FileData(object): |
| 663 | """Represent the runtime, on-card data.""" |
| 664 | def __init__(self, fdesc): |
| 665 | self.desc = fdesc |
| 666 | self.fcp = None |
| 667 | |
| 668 | |
| 669 | def interpret_sw(sw_data, sw): |
| 670 | """Interpret a given status word within the profile. Returns tuple of |
| 671 | two strings""" |
| 672 | for class_str, swdict in sw_data.items(): |
| 673 | # first try direct match |
| 674 | if sw in swdict: |
| 675 | return (class_str, swdict[sw]) |
| 676 | # next try wildcard matches |
| 677 | for pattern, descr in swdict.items(): |
| 678 | if sw_match(sw, pattern): |
| 679 | return (class_str, descr) |
| 680 | return None |
| 681 | |
| 682 | class CardApplication(object): |
| 683 | """A card application is represented by an ADF (with contained hierarchy) and optionally |
| 684 | some SW definitions.""" |
| 685 | def __init__(self, name, adf=None, sw={}): |
| 686 | self.name = name |
| 687 | self.adf = adf |
| 688 | self.sw = sw |
| 689 | |
| 690 | def __str__(self): |
| 691 | return "APP(%s)" % (self.name) |
| 692 | |
| 693 | def interpret_sw(self, sw): |
| 694 | """Interpret a given status word within the application. Returns tuple of |
| 695 | two strings""" |
| 696 | return interpret_sw(self.sw, sw) |
| 697 | |
| 698 | class CardProfile(object): |
| 699 | """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of |
| 700 | applications as well as profile-specific SW and shell commands. Every card has |
| 701 | one card profile, but there may be multiple applications within that profile.""" |
| 702 | def __init__(self, name, desc=None, files_in_mf=[], sw=[], applications=[], shell_cmdsets=[]): |
| 703 | self.name = name |
| 704 | self.desc = desc |
| 705 | self.files_in_mf = files_in_mf |
| 706 | self.sw = sw |
| 707 | self.applications = applications |
| 708 | self.shell_cmdsets = shell_cmdsets |
| 709 | |
| 710 | def __str__(self): |
| 711 | return self.name |
| 712 | |
| 713 | def add_application(self, app): |
| 714 | self.applications.add(app) |
| 715 | |
| 716 | def interpret_sw(self, sw): |
| 717 | """Interpret a given status word within the profile. Returns tuple of |
| 718 | two strings""" |
| 719 | return interpret_sw(self.sw, sw) |
| 720 | |
| 721 | |
| 722 | ###################################################################### |
| 723 | |
| 724 | if __name__ == '__main__': |
| 725 | mf = CardMF() |
| 726 | |
| 727 | adf_usim = ADF('a0000000871002', name='ADF_USIM') |
| 728 | mf.add_application(adf_usim) |
| 729 | df_pb = CardDF('5f3a', name='DF.PHONEBOOK') |
| 730 | adf_usim.add_file(df_pb) |
| 731 | adf_usim.add_file(TransparentEF('6f05', name='EF.LI', size={2,16})) |
| 732 | adf_usim.add_file(TransparentEF('6f07', name='EF.IMSI', size={9,9})) |
| 733 | |
| 734 | rss = RuntimeState(mf, None) |
| 735 | |
| 736 | interp = code.InteractiveConsole(locals={'mf':mf, 'rss':rss}) |
| 737 | interp.interact() |