blob: 04fa2504e9ab81a805a959a313155f7c63b14f44 [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)
316 self._cmd.poutput(data)
317
318 upd_bin_dec_parser = argparse.ArgumentParser()
319 upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
320 @cmd2.with_argparser(upd_bin_dec_parser)
321 def do_update_binary_decoded(self, opts):
322 """Encode + Update (Write) data of a transparent EF"""
323 data_json = json.loads(opts.data)
324 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
325 self._cmd.poutput(json.dumps(data, indent=4))
326
327 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, size={1,None}):
328 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
329 self.size = size
330 self.shell_commands = [self.ShellCommands()]
331
332 def decode_bin(self, raw_bin_data):
333 """Decode raw (binary) data into abstract representation. Overloaded by specific classes."""
334 method = getattr(self, '_decode_bin', None)
335 if callable(method):
336 return method(raw_bin_data)
337 method = getattr(self, '_decode_hex', None)
338 if callable(method):
339 return method(b2h(raw_bin_data))
340 return {'raw': raw_bin_data.hex()}
341
342 def decode_hex(self, raw_hex_data):
343 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
344 method = getattr(self, '_decode_hex', None)
345 if callable(method):
346 return method(raw_hex_data)
347 raw_bin_data = h2b(raw_hex_data)
348 method = getattr(self, '_decode_bin', None)
349 if callable(method):
350 return method(raw_bin_data)
351 return {'raw': raw_bin_data.hex()}
352
353 def encode_bin(self, abstract_data):
354 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
355 method = getattr(self, '_encode_bin', None)
356 if callable(method):
357 return method(abstract_data)
358 method = getattr(self, '_encode_hex', None)
359 if callable(method):
360 return h2b(method(abstract_data))
361 raise NotImplementedError
362
363 def encode_hex(self, abstract_data):
364 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
365 method = getattr(self, '_encode_hex', None)
366 if callable(method):
367 return method(abstract_data)
368 method = getattr(self, '_encode_bin', None)
369 if callable(method):
370 raw_bin_data = method(abstract_data)
371 return b2h(raw_bin_data)
372 raise NotImplementedError
373
374
375class LinFixedEF(CardEF):
376 """Linear Fixed EF (Entry File) in the smart card filesystem"""
377
378 @with_default_category('Linear Fixed EF Commands')
379 class ShellCommands(CommandSet):
380 def __init__(self):
381 super().__init__()
382
383 read_rec_parser = argparse.ArgumentParser()
384 read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maier41555732021-02-25 16:52:08 +0100385 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 +0100386 @cmd2.with_argparser(read_rec_parser)
387 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100388 """Read one or multiple records from a record-oriented EF"""
389 for r in range(opts.count):
390 recnr = opts.record_nr + r
391 (data, sw) = self._cmd.rs.read_record(recnr)
392 if (len(data) > 0):
393 recstr = str(data)
394 else:
395 recstr = "(empty)"
396 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100397
398 read_rec_dec_parser = argparse.ArgumentParser()
399 read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
400 @cmd2.with_argparser(read_rec_dec_parser)
401 def do_read_record_decoded(self, opts):
402 """Read + decode a record from a record-oriented EF"""
403 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
404 self._cmd.poutput(json.dumps(data, indent=4))
405
406 upd_rec_parser = argparse.ArgumentParser()
407 upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
408 upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write')
409 @cmd2.with_argparser(upd_rec_parser)
410 def do_update_record(self, opts):
411 """Update (write) data to a record-oriented EF"""
412 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
413 self._cmd.poutput(data)
414
415 upd_rec_dec_parser = argparse.ArgumentParser()
416 upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
417 upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write')
418 @cmd2.with_argparser(upd_rec_dec_parser)
419 def do_update_record_decoded(self, opts):
420 """Encode + Update (write) data to a record-oriented EF"""
421 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data)
422 self._cmd.poutput(data)
423
424 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}):
425 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
426 self.rec_len = rec_len
427 self.shell_commands = [self.ShellCommands()]
428
429 def decode_record_hex(self, raw_hex_data):
430 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
431 method = getattr(self, '_decode_record_hex', None)
432 if callable(method):
433 return method(raw_hex_data)
434 raw_bin_data = h2b(raw_hex_data)
435 method = getattr(self, '_decode_record_bin', None)
436 if callable(method):
437 return method(raw_bin_data)
438 return {'raw': raw_bin_data.hex()}
439
440 def decode_record_bin(self, raw_bin_data):
441 """Decode raw (binary) data into abstract representation. Overloaded by specific classes."""
442 method = getattr(self, '_decode_record_bin', None)
443 if callable(method):
444 return method(raw_bin_data)
445 raw_hex_data = b2h(raw_bin_data)
446 method = getattr(self, '_decode_record_hex', None)
447 if callable(method):
448 return method(raw_hex_data)
449 return {'raw': raw_hex_data}
450
451 def encode_record_hex(self, abstract_data):
452 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
453 method = getattr(self, '_encode_record_hex', None)
454 if callable(method):
455 return method(abstract_data)
456 method = getattr(self, '_encode_record_bin', None)
457 if callable(method):
458 raw_bin_data = method(abstract_data)
459 return b2h(raww_bin_data)
460 raise NotImplementedError
461
462 def encode_record_bin(self, abstract_data):
463 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
464 method = getattr(self, '_encode_record_bin', None)
465 if callable(method):
466 return method(abstract_data)
467 method = getattr(self, '_encode_record_hex', None)
468 if callable(method):
469 return b2h(method(abstract_data))
470 raise NotImplementedError
471
472class CyclicEF(LinFixedEF):
473 """Cyclic EF (Entry File) in the smart card filesystem"""
474 # we don't really have any special support for those; just recycling LinFixedEF here
475 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}):
476 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len)
477
478class TransRecEF(TransparentEF):
479 """Transparent EF (Entry File) containing fixed-size records.
480 These are the real odd-balls and mostly look like mistakes in the specification:
481 Specified as 'transparent' EF, but actually containing several fixed-length records
482 inside.
483 We add a special class for those, so the user only has to provide encoder/decoder functions
484 for a record, while this class takes care of split / merge of records.
485 """
486 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len=None, size={1,None}):
487 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
488 self.rec_len = rec_len
489
490 def decode_record_hex(self, raw_hex_data):
491 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
492 method = getattr(self, '_decode_record_hex', None)
493 if callable(method):
494 return method(raw_hex_data)
495 method = getattr(self, '_decode_record_bin', None)
496 if callable(method):
497 raw_bin_data = h2b(raw_hex_data)
498 return method(raw_bin_data)
499 return {'raw': raw_hex_data}
500
501 def decode_record_bin(self, raw_bin_data):
502 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
503 method = getattr(self, '_decode_record_bin', None)
504 if callable(method):
505 return method(raw_bin_data)
506 raw_hex_data = b2h(raw_bin_data)
507 method = getattr(self, '_decode_record_hex', None)
508 if callable(method):
509 return method(raw_hex_data)
510 return {'raw': raw_hex_data}
511
512 def encode_record_hex(self, abstract_data):
513 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
514 method = getattr(self, '_encode_record_hex', None)
515 if callable(method):
516 return method(abstract_data)
517 method = getattr(self, '_encode_record_bin', None)
518 if callable(method):
519 return h2b(method(abstract_data))
520 raise NotImplementedError
521
522 def encode_record_bin(self, abstract_data):
523 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
524 method = getattr(self, '_encode_record_bin', None)
525 if callable(method):
526 return method(abstract_data)
527 method = getattr(self, '_encode_record_hex', None)
528 if callable(method):
529 return h2b(method(abstract_data))
530 raise NotImplementedError
531
532 def _decode_bin(self, raw_bin_data):
533 chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)]
534 return [self.decode_record_bin(x) for x in chunks]
535
536 def _encode_bin(self, abstract_data):
537 chunks = [self.encode_record_bin(x) for x in abstract_data]
538 # FIXME: pad to file size
539 return b''.join(chunks)
540
541
542
543
544
545class RuntimeState(object):
546 """Represent the runtime state of a session with a card."""
547 def __init__(self, card, profile):
548 self.mf = CardMF()
549 self.card = card
550 self.selected_file = self.mf
551 self.profile = profile
552 # add applications + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +0100553 apps = self._match_applications()
554 for a in apps:
Harald Welteb2edd142021-01-08 23:29:35 +0100555 self.mf.add_application(a)
556 for f in self.profile.files_in_mf:
557 self.mf.add_file(f)
558
Philipp Maier1e896f32021-03-10 17:02:53 +0100559 def _match_applications(self):
560 """match the applications from the profile with applications on the card"""
561 apps_profile = self.profile.applications
562 aids_card = self.card.read_aids()
563 apps_taken = []
564 if aids_card:
565 aids_taken = []
566 print("AIDs on card:")
567 for a in aids_card:
568 for f in apps_profile:
569 if f.aid in a:
570 print(" %s: %s" % (f.name, a))
571 aids_taken.append(a)
572 apps_taken.append(f)
573 aids_unknown = set(aids_card) - set(aids_taken)
574 for a in aids_unknown:
575 print(" unknown: %s" % a)
576 else:
577 print("error: could not determine card applications")
578 return apps_taken
579
Harald Welteb2edd142021-01-08 23:29:35 +0100580 def get_cwd(self):
581 """Obtain the current working directory."""
582 if isinstance(self.selected_file, CardDF):
583 return self.selected_file
584 else:
585 return self.selected_file.parent
586
587 def get_application(self):
588 """Obtain the currently selected application (if any)."""
589 # iterate upwards from selected file; check if any is an ADF
590 node = self.selected_file
591 while node.parent != node:
592 if isinstance(node, CardADF):
593 return node
594 node = node.parent
595 return None
596
597 def interpret_sw(self, sw):
598 """Interpret the given SW relative to the currently selected Application
599 or the underlying profile."""
600 app = self.get_application()
601 if app:
602 # The application either comes with its own interpret_sw
603 # method or we will use the interpret_sw method from the
604 # card profile.
605 if hasattr(app, "interpret_sw"):
606 return app.interpret_sw(sw)
607 else:
608 return self.profile.interpret_sw(sw)
609 return app.interpret_sw(sw)
610 else:
611 return self.profile.interpret_sw(sw)
612
613 def select(self, name, cmd_app=None):
614 """Change current directory"""
615 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +0100616 if is_hex(name):
617 name = name.lower()
Harald Welteb2edd142021-01-08 23:29:35 +0100618 if name in sels:
619 f = sels[name]
620 # unregister commands of old file
621 if cmd_app and self.selected_file.shell_commands:
622 for c in self.selected_file.shell_commands:
623 cmd_app.unregister_command_set(c)
624 try:
625 if isinstance(f, CardADF):
626 (data, sw) = self.card._scc.select_adf(f.aid)
627 else:
628 (data, sw) = self.card._scc.select_file(f.fid)
629 self.selected_file = f
630 except SwMatchError as swm:
631 k = self.interpret_sw(swm.sw_actual)
632 if not k:
633 raise(swm)
634 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
635 # register commands of new file
636 if cmd_app and self.selected_file.shell_commands:
637 for c in self.selected_file.shell_commands:
638 cmd_app.register_command_set(c)
639 return f.decode_select_response(data)
640 #elif looks_like_fid(name):
641 else:
642 raise ValueError("Cannot select unknown %s" % (name))
643
644 def read_binary(self, length=None, offset=0):
645 if not isinstance(self.selected_file, TransparentEF):
646 raise TypeError("Only works with TransparentEF")
647 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
648
649 def read_binary_dec(self):
650 (data, sw) = self.read_binary()
651 dec_data = self.selected_file.decode_hex(data)
652 print("%s: %s -> %s" % (sw, data, dec_data))
653 return (dec_data, sw)
654
655 def update_binary(self, data_hex, offset=0):
656 if not isinstance(self.selected_file, TransparentEF):
657 raise TypeError("Only works with TransparentEF")
658 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset)
659
660 def update_binary_dec(self, data):
661 data_hex = self.selected_file.encode_hex(data)
662 print("%s -> %s" % (data, data_hex))
663 return self.update_binary(data_hex)
664
665 def read_record(self, rec_nr=0):
666 if not isinstance(self.selected_file, LinFixedEF):
667 raise TypeError("Only works with Linear Fixed EF")
668 # returns a string of hex nibbles
669 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
670
671 def read_record_dec(self, rec_nr=0):
672 (data, sw) = self.read_record(rec_nr)
673 return (self.selected_file.decode_record_hex(data), sw)
674
675 def update_record(self, rec_nr, data_hex):
676 if not isinstance(self.selected_file, LinFixedEF):
677 raise TypeError("Only works with Linear Fixed EF")
678 return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex)
679
680 def update_record_dec(self, rec_nr, data):
681 hex_data = self.selected_file.encode_record_hex(data)
682 return self.update_record(self, rec_nr, data_hex)
683
684
685
686class FileData(object):
687 """Represent the runtime, on-card data."""
688 def __init__(self, fdesc):
689 self.desc = fdesc
690 self.fcp = None
691
692
693def interpret_sw(sw_data, sw):
694 """Interpret a given status word within the profile. Returns tuple of
695 two strings"""
696 for class_str, swdict in sw_data.items():
697 # first try direct match
698 if sw in swdict:
699 return (class_str, swdict[sw])
700 # next try wildcard matches
701 for pattern, descr in swdict.items():
702 if sw_match(sw, pattern):
703 return (class_str, descr)
704 return None
705
706class CardApplication(object):
707 """A card application is represented by an ADF (with contained hierarchy) and optionally
708 some SW definitions."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100709 def __init__(self, name, adf=None, sw=None):
Harald Welteb2edd142021-01-08 23:29:35 +0100710 self.name = name
711 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100712 self.sw = sw or dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100713
714 def __str__(self):
715 return "APP(%s)" % (self.name)
716
717 def interpret_sw(self, sw):
718 """Interpret a given status word within the application. Returns tuple of
719 two strings"""
720 return interpret_sw(self.sw, sw)
721
722class CardProfile(object):
723 """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of
724 applications as well as profile-specific SW and shell commands. Every card has
725 one card profile, but there may be multiple applications within that profile."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100726 def __init__(self, name, **kw):
Harald Welteb2edd142021-01-08 23:29:35 +0100727 self.name = name
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100728 self.desc = kw.get("desc", None)
729 self.files_in_mf = kw.get("files_in_mf", [])
730 self.sw = kw.get("sw", [])
731 self.applications = kw.get("applications", [])
732 self.shell_cmdsets = kw.get("shell_cmdsets", [])
Harald Welteb2edd142021-01-08 23:29:35 +0100733
734 def __str__(self):
735 return self.name
736
737 def add_application(self, app):
Philipp Maiereb72fa42021-03-26 21:29:57 +0100738 self.applications.append(app)
Harald Welteb2edd142021-01-08 23:29:35 +0100739
740 def interpret_sw(self, sw):
741 """Interpret a given status word within the profile. Returns tuple of
742 two strings"""
743 return interpret_sw(self.sw, sw)