blob: cb39b94a1c62c83839a48bcd5d2ff860fc5d97a1 [file] [log] [blame]
Harald Welteb2edd142021-01-08 23:29:35 +01001# coding=utf-8
2"""Representation of the ISO7816-4 filesystem model.
3
4The File (and its derived classes) represent the structure / hierarchy
5of the ISO7816-4 smart card file system with the MF, DF, EF and ADF
6entries, further sub-divided into the EF sub-types Transparent, Linear Fixed, etc.
7
8The classes are intended to represent the *specification* of the filesystem,
9not the actual contents / runtime state of interacting with a given smart card.
10
11(C) 2021 by Harald Welte <laforge@osmocom.org>
12
13This program is free software: you can redistribute it and/or modify
14it under the terms of the GNU General Public License as published by
15the Free Software Foundation, either version 2 of the License, or
16(at your option) any later version.
17
18This program is distributed in the hope that it will be useful,
19but WITHOUT ANY WARRANTY; without even the implied warranty of
20MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21GNU General Public License for more details.
22
23You should have received a copy of the GNU General Public License
24along with this program. If not, see <http://www.gnu.org/licenses/>.
25"""
26
27import code
28import json
29
30import cmd2
31from cmd2 import CommandSet, with_default_category, with_argparser
32import argparse
33
Philipp Maier3aec8712021-03-09 21:49:01 +010034from pySim.utils import sw_match, h2b, b2h, is_hex
Harald Welteb2edd142021-01-08 23:29:35 +010035from pySim.exceptions import *
36
37class 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 Maier66061582021-03-09 21:57:57 +010058 # 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 Welteb2edd142021-01-08 23:29:35 +010062 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 Maier786f7812021-02-25 16:48:10 +010093 def _get_self_selectables(self, alias=None, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +010094 """Return a dict of {'identifier': self} tuples"""
95 sels = {}
96 if alias:
97 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +010098 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +010099 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100100 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100101 sels.update({self.name: self})
102 return sels
103
Philipp Maier786f7812021-02-25 16:48:10 +0100104 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100105 """Return a dict of {'identifier': File} that is selectable from the current file."""
Philipp Maier786f7812021-02-25 16:48:10 +0100106 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100107 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100108 if flags == [] or 'SELF' in flags:
109 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100110 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100111 if flags == [] or 'PARENT' in flags:
112 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100113 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100114 if flags == [] or 'MF' in flags:
115 mf = self.get_mf()
116 if mf:
117 sels.update(mf._get_self_selectables(flags = flags))
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100118 sels.update(mf.get_app_selectables(flags = flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100119 return sels
120
Philipp Maier786f7812021-02-25 16:48:10 +0100121 def get_selectable_names(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100122 """Return a list of strings for all identifiers that are selectable from the current file."""
Philipp Maier786f7812021-02-25 16:48:10 +0100123 sels = self.get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100124 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
131class 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")
Philipp Maier3aec8712021-03-09 21:49:01 +0100147 if not is_hex(child.fid, minlen = 4, maxlen = 4):
148 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100149 if child.name in CardFile.RESERVED_NAMES:
150 raise ValueError("File name %s is a reserved name" % (child.name))
151 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100152 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100153 if child.fid in self.children:
154 if ignore_existing:
155 return
156 raise ValueError("File with given fid %s already exists" % (child.fid))
157 if self.lookup_file_by_sfid(child.sfid):
158 raise ValueError("File with given sfid %s already exists" % (child.sfid))
159 if self.lookup_file_by_name(child.name):
160 if ignore_existing:
161 return
162 raise ValueError("File with given name %s already exists" % (child.name))
163 self.children[child.fid] = child
164 child.parent = self
165
166 def add_files(self, children, ignore_existing=False):
167 """Add a list of child (DF/EF) to this DF"""
168 for child in children:
169 self.add_file(child, ignore_existing)
170
Philipp Maier786f7812021-02-25 16:48:10 +0100171 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100172 """Get selectable (DF/EF names) from current DF"""
173 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100174 sels = super().get_selectables(flags)
175 if flags == [] or 'FIDS' in flags:
176 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100177 if flags == [] or 'FNAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100178 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100179 return sels
180
181 def lookup_file_by_name(self, name):
182 if name == None:
183 return None
184 for i in self.children.values():
185 if i.name and i.name == name:
186 return i
187 return None
188
189 def lookup_file_by_sfid(self, sfid):
190 if sfid == None:
191 return None
192 for i in self.children.values():
193 if i.sfid == int(sfid):
194 return i
195 return None
196
197 def lookup_file_by_fid(self, fid):
198 if fid in self.children:
199 return self.children[fid]
200 return None
201
202
203class CardMF(CardDF):
204 """MF (Master File) in the smart card filesystem"""
205 def __init__(self, **kwargs):
206 # can be overridden; use setdefault
207 kwargs.setdefault('fid', '3f00')
208 kwargs.setdefault('name', 'MF')
209 kwargs.setdefault('desc', 'Master File (directory root)')
210 # cannot be overridden; use assignment
211 kwargs['parent'] = self
212 super().__init__(**kwargs)
213 self.applications = dict()
214
215 def __str__(self):
216 return "MF(%s)" % (self.fid)
217
218 def add_application(self, app):
219 """Add an ADF (Application Dedicated File) to the MF"""
220 if not isinstance(app, CardADF):
221 raise TypeError("Expected an ADF instance")
222 if app.aid in self.applications:
223 raise ValueError("AID %s already exists" % (app.aid))
224 self.applications[app.aid] = app
225 app.parent=self
226
227 def get_app_names(self):
228 """Get list of completions (AID names)"""
229 return [x.name for x in self.applications]
230
Philipp Maier786f7812021-02-25 16:48:10 +0100231 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100232 """Get list of completions (DF/EF/ADF names) from current DF"""
Philipp Maier786f7812021-02-25 16:48:10 +0100233 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100234 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100235 return sels
236
Philipp Maier786f7812021-02-25 16:48:10 +0100237 def get_app_selectables(self, flags = []):
238 """Get applications by AID + name"""
239 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100240 if flags == [] or 'AIDS' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100241 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100242 if flags == [] or 'ANAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100243 sels.update({x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100244 return sels
245
246 def decode_select_response(self, data_hex):
247 """Decode the response to a SELECT command."""
248 return data_hex
249
250
251
252class CardADF(CardDF):
253 """ADF (Application Dedicated File) in the smart card filesystem"""
254 def __init__(self, aid, **kwargs):
255 super().__init__(**kwargs)
256 self.aid = aid # Application Identifier
257 if self.parent:
258 self.parent.add_application(self)
259
260 def __str__(self):
261 return "ADF(%s)" % (self.aid)
262
263 def _path_element(self, prefer_name):
264 if self.name and prefer_name:
265 return self.name
266 else:
267 return self.aid
268
269
270class CardEF(CardFile):
271 """EF (Entry File) in the smart card filesystem"""
272 def __init__(self, *, fid, **kwargs):
273 kwargs['fid'] = fid
274 super().__init__(**kwargs)
275
276 def __str__(self):
277 return "EF(%s)" % (super().__str__())
278
Philipp Maier786f7812021-02-25 16:48:10 +0100279 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100280 """Get list of completions (EF names) from current DF"""
281 #global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100282 sels = super().get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100283 sels.update({x.name:x for x in self.parent.children.values() if x != self})
284 return sels
285
286
287class TransparentEF(CardEF):
288 """Transparent EF (Entry File) in the smart card filesystem"""
289
290 @with_default_category('Transparent EF Commands')
291 class ShellCommands(CommandSet):
292 def __init__(self):
293 super().__init__()
294
295 read_bin_parser = argparse.ArgumentParser()
296 read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
297 read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read')
298 @cmd2.with_argparser(read_bin_parser)
299 def do_read_binary(self, opts):
300 """Read binary data from a transparent EF"""
301 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
302 self._cmd.poutput(data)
303
304 def do_read_binary_decoded(self, opts):
305 """Read + decode data from a transparent EF"""
306 (data, sw) = self._cmd.rs.read_binary_dec()
307 self._cmd.poutput(json.dumps(data, indent=4))
308
309 upd_bin_parser = argparse.ArgumentParser()
310 upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
311 upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write')
312 @cmd2.with_argparser(upd_bin_parser)
313 def do_update_binary(self, opts):
314 """Update (Write) data of a transparent EF"""
315 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100316 if data:
317 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100318
319 upd_bin_dec_parser = argparse.ArgumentParser()
320 upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
321 @cmd2.with_argparser(upd_bin_dec_parser)
322 def do_update_binary_decoded(self, opts):
323 """Encode + Update (Write) data of a transparent EF"""
324 data_json = json.loads(opts.data)
325 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100326 if data:
327 self._cmd.poutput(json.dumps(data, indent=4))
Harald Welteb2edd142021-01-08 23:29:35 +0100328
329 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, size={1,None}):
330 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
331 self.size = size
332 self.shell_commands = [self.ShellCommands()]
333
334 def decode_bin(self, raw_bin_data):
335 """Decode raw (binary) data into abstract representation. Overloaded by specific classes."""
336 method = getattr(self, '_decode_bin', None)
337 if callable(method):
338 return method(raw_bin_data)
339 method = getattr(self, '_decode_hex', None)
340 if callable(method):
341 return method(b2h(raw_bin_data))
342 return {'raw': raw_bin_data.hex()}
343
344 def decode_hex(self, raw_hex_data):
345 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
346 method = getattr(self, '_decode_hex', None)
347 if callable(method):
348 return method(raw_hex_data)
349 raw_bin_data = h2b(raw_hex_data)
350 method = getattr(self, '_decode_bin', None)
351 if callable(method):
352 return method(raw_bin_data)
353 return {'raw': raw_bin_data.hex()}
354
355 def encode_bin(self, abstract_data):
356 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
357 method = getattr(self, '_encode_bin', None)
358 if callable(method):
359 return method(abstract_data)
360 method = getattr(self, '_encode_hex', None)
361 if callable(method):
362 return h2b(method(abstract_data))
363 raise NotImplementedError
364
365 def encode_hex(self, abstract_data):
366 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
367 method = getattr(self, '_encode_hex', None)
368 if callable(method):
369 return method(abstract_data)
370 method = getattr(self, '_encode_bin', None)
371 if callable(method):
372 raw_bin_data = method(abstract_data)
373 return b2h(raw_bin_data)
374 raise NotImplementedError
375
376
377class LinFixedEF(CardEF):
378 """Linear Fixed EF (Entry File) in the smart card filesystem"""
379
380 @with_default_category('Linear Fixed EF Commands')
381 class ShellCommands(CommandSet):
382 def __init__(self):
383 super().__init__()
384
385 read_rec_parser = argparse.ArgumentParser()
386 read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maier41555732021-02-25 16:52:08 +0100387 read_rec_parser.add_argument('--count', type=int, default=1, help='Number of records to be read, beginning at record_nr')
Harald Welteb2edd142021-01-08 23:29:35 +0100388 @cmd2.with_argparser(read_rec_parser)
389 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100390 """Read one or multiple records from a record-oriented EF"""
391 for r in range(opts.count):
392 recnr = opts.record_nr + r
393 (data, sw) = self._cmd.rs.read_record(recnr)
394 if (len(data) > 0):
395 recstr = str(data)
396 else:
397 recstr = "(empty)"
398 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100399
400 read_rec_dec_parser = argparse.ArgumentParser()
401 read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
402 @cmd2.with_argparser(read_rec_dec_parser)
403 def do_read_record_decoded(self, opts):
404 """Read + decode a record from a record-oriented EF"""
405 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
406 self._cmd.poutput(json.dumps(data, indent=4))
407
408 upd_rec_parser = argparse.ArgumentParser()
409 upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
410 upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write')
411 @cmd2.with_argparser(upd_rec_parser)
412 def do_update_record(self, opts):
413 """Update (write) data to a record-oriented EF"""
414 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100415 if data:
416 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100417
418 upd_rec_dec_parser = argparse.ArgumentParser()
419 upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
420 upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write')
421 @cmd2.with_argparser(upd_rec_dec_parser)
422 def do_update_record_decoded(self, opts):
423 """Encode + Update (write) data to a record-oriented EF"""
424 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100425 if data:
426 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100427
428 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}):
429 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
430 self.rec_len = rec_len
431 self.shell_commands = [self.ShellCommands()]
432
433 def decode_record_hex(self, raw_hex_data):
434 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
435 method = getattr(self, '_decode_record_hex', None)
436 if callable(method):
437 return method(raw_hex_data)
438 raw_bin_data = h2b(raw_hex_data)
439 method = getattr(self, '_decode_record_bin', None)
440 if callable(method):
441 return method(raw_bin_data)
442 return {'raw': raw_bin_data.hex()}
443
444 def decode_record_bin(self, raw_bin_data):
445 """Decode raw (binary) data into abstract representation. Overloaded by specific classes."""
446 method = getattr(self, '_decode_record_bin', None)
447 if callable(method):
448 return method(raw_bin_data)
449 raw_hex_data = b2h(raw_bin_data)
450 method = getattr(self, '_decode_record_hex', None)
451 if callable(method):
452 return method(raw_hex_data)
453 return {'raw': raw_hex_data}
454
455 def encode_record_hex(self, abstract_data):
456 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
457 method = getattr(self, '_encode_record_hex', None)
458 if callable(method):
459 return method(abstract_data)
460 method = getattr(self, '_encode_record_bin', None)
461 if callable(method):
462 raw_bin_data = method(abstract_data)
463 return b2h(raww_bin_data)
464 raise NotImplementedError
465
466 def encode_record_bin(self, abstract_data):
467 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
468 method = getattr(self, '_encode_record_bin', None)
469 if callable(method):
470 return method(abstract_data)
471 method = getattr(self, '_encode_record_hex', None)
472 if callable(method):
473 return b2h(method(abstract_data))
474 raise NotImplementedError
475
476class CyclicEF(LinFixedEF):
477 """Cyclic EF (Entry File) in the smart card filesystem"""
478 # we don't really have any special support for those; just recycling LinFixedEF here
479 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}):
480 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len)
481
482class TransRecEF(TransparentEF):
483 """Transparent EF (Entry File) containing fixed-size records.
484 These are the real odd-balls and mostly look like mistakes in the specification:
485 Specified as 'transparent' EF, but actually containing several fixed-length records
486 inside.
487 We add a special class for those, so the user only has to provide encoder/decoder functions
488 for a record, while this class takes care of split / merge of records.
489 """
490 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len=None, size={1,None}):
491 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
492 self.rec_len = rec_len
493
494 def decode_record_hex(self, raw_hex_data):
495 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
496 method = getattr(self, '_decode_record_hex', None)
497 if callable(method):
498 return method(raw_hex_data)
499 method = getattr(self, '_decode_record_bin', None)
500 if callable(method):
501 raw_bin_data = h2b(raw_hex_data)
502 return method(raw_bin_data)
503 return {'raw': raw_hex_data}
504
505 def decode_record_bin(self, raw_bin_data):
506 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
507 method = getattr(self, '_decode_record_bin', None)
508 if callable(method):
509 return method(raw_bin_data)
510 raw_hex_data = b2h(raw_bin_data)
511 method = getattr(self, '_decode_record_hex', None)
512 if callable(method):
513 return method(raw_hex_data)
514 return {'raw': raw_hex_data}
515
516 def encode_record_hex(self, abstract_data):
517 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
518 method = getattr(self, '_encode_record_hex', None)
519 if callable(method):
520 return method(abstract_data)
521 method = getattr(self, '_encode_record_bin', None)
522 if callable(method):
523 return h2b(method(abstract_data))
524 raise NotImplementedError
525
526 def encode_record_bin(self, abstract_data):
527 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
528 method = getattr(self, '_encode_record_bin', None)
529 if callable(method):
530 return method(abstract_data)
531 method = getattr(self, '_encode_record_hex', None)
532 if callable(method):
533 return h2b(method(abstract_data))
534 raise NotImplementedError
535
536 def _decode_bin(self, raw_bin_data):
537 chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)]
538 return [self.decode_record_bin(x) for x in chunks]
539
540 def _encode_bin(self, abstract_data):
541 chunks = [self.encode_record_bin(x) for x in abstract_data]
542 # FIXME: pad to file size
543 return b''.join(chunks)
544
545
546
547
548
549class RuntimeState(object):
550 """Represent the runtime state of a session with a card."""
551 def __init__(self, card, profile):
552 self.mf = CardMF()
553 self.card = card
554 self.selected_file = self.mf
555 self.profile = profile
556 # add applications + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +0100557 apps = self._match_applications()
558 for a in apps:
Harald Welteb2edd142021-01-08 23:29:35 +0100559 self.mf.add_application(a)
560 for f in self.profile.files_in_mf:
561 self.mf.add_file(f)
562
Philipp Maier1e896f32021-03-10 17:02:53 +0100563 def _match_applications(self):
564 """match the applications from the profile with applications on the card"""
565 apps_profile = self.profile.applications
566 aids_card = self.card.read_aids()
567 apps_taken = []
568 if aids_card:
569 aids_taken = []
570 print("AIDs on card:")
571 for a in aids_card:
572 for f in apps_profile:
573 if f.aid in a:
574 print(" %s: %s" % (f.name, a))
575 aids_taken.append(a)
576 apps_taken.append(f)
577 aids_unknown = set(aids_card) - set(aids_taken)
578 for a in aids_unknown:
579 print(" unknown: %s" % a)
580 else:
581 print("error: could not determine card applications")
582 return apps_taken
583
Harald Welteb2edd142021-01-08 23:29:35 +0100584 def get_cwd(self):
585 """Obtain the current working directory."""
586 if isinstance(self.selected_file, CardDF):
587 return self.selected_file
588 else:
589 return self.selected_file.parent
590
591 def get_application(self):
592 """Obtain the currently selected application (if any)."""
593 # iterate upwards from selected file; check if any is an ADF
594 node = self.selected_file
595 while node.parent != node:
596 if isinstance(node, CardADF):
597 return node
598 node = node.parent
599 return None
600
601 def interpret_sw(self, sw):
602 """Interpret the given SW relative to the currently selected Application
603 or the underlying profile."""
604 app = self.get_application()
605 if app:
606 # The application either comes with its own interpret_sw
607 # method or we will use the interpret_sw method from the
608 # card profile.
609 if hasattr(app, "interpret_sw"):
610 return app.interpret_sw(sw)
611 else:
612 return self.profile.interpret_sw(sw)
613 return app.interpret_sw(sw)
614 else:
615 return self.profile.interpret_sw(sw)
616
617 def select(self, name, cmd_app=None):
618 """Change current directory"""
619 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +0100620 if is_hex(name):
621 name = name.lower()
Harald Welteb2edd142021-01-08 23:29:35 +0100622 if name in sels:
623 f = sels[name]
624 # unregister commands of old file
625 if cmd_app and self.selected_file.shell_commands:
626 for c in self.selected_file.shell_commands:
627 cmd_app.unregister_command_set(c)
628 try:
629 if isinstance(f, CardADF):
630 (data, sw) = self.card._scc.select_adf(f.aid)
631 else:
632 (data, sw) = self.card._scc.select_file(f.fid)
633 self.selected_file = f
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 # register commands of new file
640 if cmd_app and self.selected_file.shell_commands:
641 for c in self.selected_file.shell_commands:
642 cmd_app.register_command_set(c)
643 return f.decode_select_response(data)
644 #elif looks_like_fid(name):
645 else:
646 raise ValueError("Cannot select unknown %s" % (name))
647
648 def read_binary(self, length=None, offset=0):
649 if not isinstance(self.selected_file, TransparentEF):
650 raise TypeError("Only works with TransparentEF")
651 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
652
653 def read_binary_dec(self):
654 (data, sw) = self.read_binary()
655 dec_data = self.selected_file.decode_hex(data)
656 print("%s: %s -> %s" % (sw, data, dec_data))
657 return (dec_data, sw)
658
659 def update_binary(self, data_hex, offset=0):
660 if not isinstance(self.selected_file, TransparentEF):
661 raise TypeError("Only works with TransparentEF")
662 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset)
663
664 def update_binary_dec(self, data):
665 data_hex = self.selected_file.encode_hex(data)
666 print("%s -> %s" % (data, data_hex))
667 return self.update_binary(data_hex)
668
669 def read_record(self, rec_nr=0):
670 if not isinstance(self.selected_file, LinFixedEF):
671 raise TypeError("Only works with Linear Fixed EF")
672 # returns a string of hex nibbles
673 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
674
675 def read_record_dec(self, rec_nr=0):
676 (data, sw) = self.read_record(rec_nr)
677 return (self.selected_file.decode_record_hex(data), sw)
678
679 def update_record(self, rec_nr, data_hex):
680 if not isinstance(self.selected_file, LinFixedEF):
681 raise TypeError("Only works with Linear Fixed EF")
682 return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex)
683
684 def update_record_dec(self, rec_nr, data):
685 hex_data = self.selected_file.encode_record_hex(data)
686 return self.update_record(self, rec_nr, data_hex)
687
688
689
690class FileData(object):
691 """Represent the runtime, on-card data."""
692 def __init__(self, fdesc):
693 self.desc = fdesc
694 self.fcp = None
695
696
697def interpret_sw(sw_data, sw):
698 """Interpret a given status word within the profile. Returns tuple of
699 two strings"""
700 for class_str, swdict in sw_data.items():
701 # first try direct match
702 if sw in swdict:
703 return (class_str, swdict[sw])
704 # next try wildcard matches
705 for pattern, descr in swdict.items():
706 if sw_match(sw, pattern):
707 return (class_str, descr)
708 return None
709
710class CardApplication(object):
711 """A card application is represented by an ADF (with contained hierarchy) and optionally
712 some SW definitions."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100713 def __init__(self, name, adf=None, sw=None):
Harald Welteb2edd142021-01-08 23:29:35 +0100714 self.name = name
715 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100716 self.sw = sw or dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100717
718 def __str__(self):
719 return "APP(%s)" % (self.name)
720
721 def interpret_sw(self, sw):
722 """Interpret a given status word within the application. Returns tuple of
723 two strings"""
724 return interpret_sw(self.sw, sw)
725
726class CardProfile(object):
727 """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of
728 applications as well as profile-specific SW and shell commands. Every card has
729 one card profile, but there may be multiple applications within that profile."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100730 def __init__(self, name, **kw):
Harald Welteb2edd142021-01-08 23:29:35 +0100731 self.name = name
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100732 self.desc = kw.get("desc", None)
733 self.files_in_mf = kw.get("files_in_mf", [])
734 self.sw = kw.get("sw", [])
735 self.applications = kw.get("applications", [])
736 self.shell_cmdsets = kw.get("shell_cmdsets", [])
Harald Welteb2edd142021-01-08 23:29:35 +0100737
738 def __str__(self):
739 return self.name
740
741 def add_application(self, app):
Philipp Maiereb72fa42021-03-26 21:29:57 +0100742 self.applications.append(app)
Harald Welteb2edd142021-01-08 23:29:35 +0100743
744 def interpret_sw(self, sw):
745 """Interpret a given status word within the profile. Returns tuple of
746 two strings"""
747 return interpret_sw(self.sw, sw)