blob: 9f3b221018472bdadad377e2bc80dc5fa900c284 [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."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100133
134 @with_default_category('DF/ADF Commands')
135 class ShellCommands(CommandSet):
136 def __init__(self):
137 super().__init__()
138
Harald Welteb2edd142021-01-08 23:29:35 +0100139 def __init__(self, **kwargs):
140 if not isinstance(self, CardADF):
141 if not 'fid' in kwargs:
142 raise TypeError('fid is mandatory for all DF')
143 super().__init__(**kwargs)
144 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100145 self.shell_commands = [self.ShellCommands()]
Harald Welteb2edd142021-01-08 23:29:35 +0100146
147 def __str__(self):
148 return "DF(%s)" % (super().__str__())
149
150 def add_file(self, child, ignore_existing=False):
151 """Add a child (DF/EF) to this DF"""
152 if not isinstance(child, CardFile):
153 raise TypeError("Expected a File instance")
Philipp Maier3aec8712021-03-09 21:49:01 +0100154 if not is_hex(child.fid, minlen = 4, maxlen = 4):
155 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100156 if child.name in CardFile.RESERVED_NAMES:
157 raise ValueError("File name %s is a reserved name" % (child.name))
158 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100159 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100160 if child.fid in self.children:
161 if ignore_existing:
162 return
163 raise ValueError("File with given fid %s already exists" % (child.fid))
164 if self.lookup_file_by_sfid(child.sfid):
165 raise ValueError("File with given sfid %s already exists" % (child.sfid))
166 if self.lookup_file_by_name(child.name):
167 if ignore_existing:
168 return
169 raise ValueError("File with given name %s already exists" % (child.name))
170 self.children[child.fid] = child
171 child.parent = self
172
173 def add_files(self, children, ignore_existing=False):
174 """Add a list of child (DF/EF) to this DF"""
175 for child in children:
176 self.add_file(child, ignore_existing)
177
Philipp Maier786f7812021-02-25 16:48:10 +0100178 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100179 """Get selectable (DF/EF names) from current DF"""
180 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100181 sels = super().get_selectables(flags)
182 if flags == [] or 'FIDS' in flags:
183 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100184 if flags == [] or 'FNAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100185 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100186 return sels
187
188 def lookup_file_by_name(self, name):
189 if name == None:
190 return None
191 for i in self.children.values():
192 if i.name and i.name == name:
193 return i
194 return None
195
196 def lookup_file_by_sfid(self, sfid):
197 if sfid == None:
198 return None
199 for i in self.children.values():
200 if i.sfid == int(sfid):
201 return i
202 return None
203
204 def lookup_file_by_fid(self, fid):
205 if fid in self.children:
206 return self.children[fid]
207 return None
208
209
210class CardMF(CardDF):
211 """MF (Master File) in the smart card filesystem"""
212 def __init__(self, **kwargs):
213 # can be overridden; use setdefault
214 kwargs.setdefault('fid', '3f00')
215 kwargs.setdefault('name', 'MF')
216 kwargs.setdefault('desc', 'Master File (directory root)')
217 # cannot be overridden; use assignment
218 kwargs['parent'] = self
219 super().__init__(**kwargs)
220 self.applications = dict()
221
222 def __str__(self):
223 return "MF(%s)" % (self.fid)
224
225 def add_application(self, app):
226 """Add an ADF (Application Dedicated File) to the MF"""
227 if not isinstance(app, CardADF):
228 raise TypeError("Expected an ADF instance")
229 if app.aid in self.applications:
230 raise ValueError("AID %s already exists" % (app.aid))
231 self.applications[app.aid] = app
232 app.parent=self
233
234 def get_app_names(self):
235 """Get list of completions (AID names)"""
236 return [x.name for x in self.applications]
237
Philipp Maier786f7812021-02-25 16:48:10 +0100238 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100239 """Get list of completions (DF/EF/ADF names) from current DF"""
Philipp Maier786f7812021-02-25 16:48:10 +0100240 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100241 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100242 return sels
243
Philipp Maier786f7812021-02-25 16:48:10 +0100244 def get_app_selectables(self, flags = []):
245 """Get applications by AID + name"""
246 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100247 if flags == [] or 'AIDS' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100248 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100249 if flags == [] or 'ANAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100250 sels.update({x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100251 return sels
252
253 def decode_select_response(self, data_hex):
254 """Decode the response to a SELECT command."""
255 return data_hex
256
257
258
259class CardADF(CardDF):
260 """ADF (Application Dedicated File) in the smart card filesystem"""
261 def __init__(self, aid, **kwargs):
262 super().__init__(**kwargs)
263 self.aid = aid # Application Identifier
264 if self.parent:
265 self.parent.add_application(self)
266
267 def __str__(self):
268 return "ADF(%s)" % (self.aid)
269
270 def _path_element(self, prefer_name):
271 if self.name and prefer_name:
272 return self.name
273 else:
274 return self.aid
275
276
277class CardEF(CardFile):
278 """EF (Entry File) in the smart card filesystem"""
279 def __init__(self, *, fid, **kwargs):
280 kwargs['fid'] = fid
281 super().__init__(**kwargs)
282
283 def __str__(self):
284 return "EF(%s)" % (super().__str__())
285
Philipp Maier786f7812021-02-25 16:48:10 +0100286 def get_selectables(self, flags = []):
Harald Welteb2edd142021-01-08 23:29:35 +0100287 """Get list of completions (EF names) from current DF"""
288 #global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100289 sels = super().get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100290 sels.update({x.name:x for x in self.parent.children.values() if x != self})
291 return sels
292
293
294class TransparentEF(CardEF):
295 """Transparent EF (Entry File) in the smart card filesystem"""
296
297 @with_default_category('Transparent EF Commands')
298 class ShellCommands(CommandSet):
299 def __init__(self):
300 super().__init__()
301
302 read_bin_parser = argparse.ArgumentParser()
303 read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
304 read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read')
305 @cmd2.with_argparser(read_bin_parser)
306 def do_read_binary(self, opts):
307 """Read binary data from a transparent EF"""
308 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
309 self._cmd.poutput(data)
310
311 def do_read_binary_decoded(self, opts):
312 """Read + decode data from a transparent EF"""
313 (data, sw) = self._cmd.rs.read_binary_dec()
314 self._cmd.poutput(json.dumps(data, indent=4))
315
316 upd_bin_parser = argparse.ArgumentParser()
317 upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
318 upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write')
319 @cmd2.with_argparser(upd_bin_parser)
320 def do_update_binary(self, opts):
321 """Update (Write) data of a transparent EF"""
322 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100323 if data:
324 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100325
326 upd_bin_dec_parser = argparse.ArgumentParser()
327 upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
328 @cmd2.with_argparser(upd_bin_dec_parser)
329 def do_update_binary_decoded(self, opts):
330 """Encode + Update (Write) data of a transparent EF"""
331 data_json = json.loads(opts.data)
332 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100333 if data:
334 self._cmd.poutput(json.dumps(data, indent=4))
Harald Welteb2edd142021-01-08 23:29:35 +0100335
336 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, size={1,None}):
337 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
338 self.size = size
339 self.shell_commands = [self.ShellCommands()]
340
341 def decode_bin(self, raw_bin_data):
342 """Decode raw (binary) data into abstract representation. Overloaded by specific classes."""
343 method = getattr(self, '_decode_bin', None)
344 if callable(method):
345 return method(raw_bin_data)
346 method = getattr(self, '_decode_hex', None)
347 if callable(method):
348 return method(b2h(raw_bin_data))
349 return {'raw': raw_bin_data.hex()}
350
351 def decode_hex(self, raw_hex_data):
352 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
353 method = getattr(self, '_decode_hex', None)
354 if callable(method):
355 return method(raw_hex_data)
356 raw_bin_data = h2b(raw_hex_data)
357 method = getattr(self, '_decode_bin', None)
358 if callable(method):
359 return method(raw_bin_data)
360 return {'raw': raw_bin_data.hex()}
361
362 def encode_bin(self, abstract_data):
363 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
364 method = getattr(self, '_encode_bin', None)
365 if callable(method):
366 return method(abstract_data)
367 method = getattr(self, '_encode_hex', None)
368 if callable(method):
369 return h2b(method(abstract_data))
370 raise NotImplementedError
371
372 def encode_hex(self, abstract_data):
373 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
374 method = getattr(self, '_encode_hex', None)
375 if callable(method):
376 return method(abstract_data)
377 method = getattr(self, '_encode_bin', None)
378 if callable(method):
379 raw_bin_data = method(abstract_data)
380 return b2h(raw_bin_data)
381 raise NotImplementedError
382
383
384class LinFixedEF(CardEF):
385 """Linear Fixed EF (Entry File) in the smart card filesystem"""
386
387 @with_default_category('Linear Fixed EF Commands')
388 class ShellCommands(CommandSet):
389 def __init__(self):
390 super().__init__()
391
392 read_rec_parser = argparse.ArgumentParser()
393 read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maier41555732021-02-25 16:52:08 +0100394 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 +0100395 @cmd2.with_argparser(read_rec_parser)
396 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100397 """Read one or multiple records from a record-oriented EF"""
398 for r in range(opts.count):
399 recnr = opts.record_nr + r
400 (data, sw) = self._cmd.rs.read_record(recnr)
401 if (len(data) > 0):
402 recstr = str(data)
403 else:
404 recstr = "(empty)"
405 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100406
407 read_rec_dec_parser = argparse.ArgumentParser()
408 read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
409 @cmd2.with_argparser(read_rec_dec_parser)
410 def do_read_record_decoded(self, opts):
411 """Read + decode a record from a record-oriented EF"""
412 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
413 self._cmd.poutput(json.dumps(data, indent=4))
414
415 upd_rec_parser = argparse.ArgumentParser()
416 upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
417 upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write')
418 @cmd2.with_argparser(upd_rec_parser)
419 def do_update_record(self, opts):
420 """Update (write) data to a record-oriented EF"""
421 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100422 if data:
423 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100424
425 upd_rec_dec_parser = argparse.ArgumentParser()
426 upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
427 upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write')
428 @cmd2.with_argparser(upd_rec_dec_parser)
429 def do_update_record_decoded(self, opts):
430 """Encode + Update (write) data to a record-oriented EF"""
431 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100432 if data:
433 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100434
435 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}):
436 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
437 self.rec_len = rec_len
438 self.shell_commands = [self.ShellCommands()]
439
440 def decode_record_hex(self, raw_hex_data):
441 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
442 method = getattr(self, '_decode_record_hex', None)
443 if callable(method):
444 return method(raw_hex_data)
445 raw_bin_data = h2b(raw_hex_data)
446 method = getattr(self, '_decode_record_bin', None)
447 if callable(method):
448 return method(raw_bin_data)
449 return {'raw': raw_bin_data.hex()}
450
451 def decode_record_bin(self, raw_bin_data):
452 """Decode raw (binary) data into abstract representation. Overloaded by specific classes."""
453 method = getattr(self, '_decode_record_bin', None)
454 if callable(method):
455 return method(raw_bin_data)
456 raw_hex_data = b2h(raw_bin_data)
457 method = getattr(self, '_decode_record_hex', None)
458 if callable(method):
459 return method(raw_hex_data)
460 return {'raw': raw_hex_data}
461
462 def encode_record_hex(self, abstract_data):
463 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
464 method = getattr(self, '_encode_record_hex', None)
465 if callable(method):
466 return method(abstract_data)
467 method = getattr(self, '_encode_record_bin', None)
468 if callable(method):
469 raw_bin_data = method(abstract_data)
470 return b2h(raww_bin_data)
471 raise NotImplementedError
472
473 def encode_record_bin(self, abstract_data):
474 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
475 method = getattr(self, '_encode_record_bin', None)
476 if callable(method):
477 return method(abstract_data)
478 method = getattr(self, '_encode_record_hex', None)
479 if callable(method):
480 return b2h(method(abstract_data))
481 raise NotImplementedError
482
483class CyclicEF(LinFixedEF):
484 """Cyclic EF (Entry File) in the smart card filesystem"""
485 # we don't really have any special support for those; just recycling LinFixedEF here
486 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len={1,None}):
487 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len)
488
489class TransRecEF(TransparentEF):
490 """Transparent EF (Entry File) containing fixed-size records.
491 These are the real odd-balls and mostly look like mistakes in the specification:
492 Specified as 'transparent' EF, but actually containing several fixed-length records
493 inside.
494 We add a special class for those, so the user only has to provide encoder/decoder functions
495 for a record, while this class takes care of split / merge of records.
496 """
497 def __init__(self, fid, sfid=None, name=None, desc=None, parent=None, rec_len=None, size={1,None}):
498 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
499 self.rec_len = rec_len
500
501 def decode_record_hex(self, raw_hex_data):
502 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
503 method = getattr(self, '_decode_record_hex', None)
504 if callable(method):
505 return method(raw_hex_data)
506 method = getattr(self, '_decode_record_bin', None)
507 if callable(method):
508 raw_bin_data = h2b(raw_hex_data)
509 return method(raw_bin_data)
510 return {'raw': raw_hex_data}
511
512 def decode_record_bin(self, raw_bin_data):
513 """Decode raw (hex string) data into abstract representation. Overloaded by specific classes."""
514 method = getattr(self, '_decode_record_bin', None)
515 if callable(method):
516 return method(raw_bin_data)
517 raw_hex_data = b2h(raw_bin_data)
518 method = getattr(self, '_decode_record_hex', None)
519 if callable(method):
520 return method(raw_hex_data)
521 return {'raw': raw_hex_data}
522
523 def encode_record_hex(self, abstract_data):
524 """Encode abstract representation into raw (hex string) data. Overloaded by specific classes."""
525 method = getattr(self, '_encode_record_hex', None)
526 if callable(method):
527 return method(abstract_data)
528 method = getattr(self, '_encode_record_bin', None)
529 if callable(method):
530 return h2b(method(abstract_data))
531 raise NotImplementedError
532
533 def encode_record_bin(self, abstract_data):
534 """Encode abstract representation into raw (binary) data. Overloaded by specific classes."""
535 method = getattr(self, '_encode_record_bin', None)
536 if callable(method):
537 return method(abstract_data)
538 method = getattr(self, '_encode_record_hex', None)
539 if callable(method):
540 return h2b(method(abstract_data))
541 raise NotImplementedError
542
543 def _decode_bin(self, raw_bin_data):
544 chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)]
545 return [self.decode_record_bin(x) for x in chunks]
546
547 def _encode_bin(self, abstract_data):
548 chunks = [self.encode_record_bin(x) for x in abstract_data]
549 # FIXME: pad to file size
550 return b''.join(chunks)
551
552
553
554
555
556class RuntimeState(object):
557 """Represent the runtime state of a session with a card."""
558 def __init__(self, card, profile):
559 self.mf = CardMF()
560 self.card = card
561 self.selected_file = self.mf
562 self.profile = profile
563 # add applications + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +0100564 apps = self._match_applications()
565 for a in apps:
Harald Welteb2edd142021-01-08 23:29:35 +0100566 self.mf.add_application(a)
567 for f in self.profile.files_in_mf:
568 self.mf.add_file(f)
569
Philipp Maier1e896f32021-03-10 17:02:53 +0100570 def _match_applications(self):
571 """match the applications from the profile with applications on the card"""
572 apps_profile = self.profile.applications
573 aids_card = self.card.read_aids()
574 apps_taken = []
575 if aids_card:
576 aids_taken = []
577 print("AIDs on card:")
578 for a in aids_card:
579 for f in apps_profile:
580 if f.aid in a:
581 print(" %s: %s" % (f.name, a))
582 aids_taken.append(a)
583 apps_taken.append(f)
584 aids_unknown = set(aids_card) - set(aids_taken)
585 for a in aids_unknown:
586 print(" unknown: %s" % a)
587 else:
588 print("error: could not determine card applications")
589 return apps_taken
590
Harald Welteb2edd142021-01-08 23:29:35 +0100591 def get_cwd(self):
592 """Obtain the current working directory."""
593 if isinstance(self.selected_file, CardDF):
594 return self.selected_file
595 else:
596 return self.selected_file.parent
597
598 def get_application(self):
599 """Obtain the currently selected application (if any)."""
600 # iterate upwards from selected file; check if any is an ADF
601 node = self.selected_file
602 while node.parent != node:
603 if isinstance(node, CardADF):
604 return node
605 node = node.parent
606 return None
607
608 def interpret_sw(self, sw):
609 """Interpret the given SW relative to the currently selected Application
610 or the underlying profile."""
611 app = self.get_application()
612 if app:
613 # The application either comes with its own interpret_sw
614 # method or we will use the interpret_sw method from the
615 # card profile.
616 if hasattr(app, "interpret_sw"):
617 return app.interpret_sw(sw)
618 else:
619 return self.profile.interpret_sw(sw)
620 return app.interpret_sw(sw)
621 else:
622 return self.profile.interpret_sw(sw)
623
Philipp Maier63f572d2021-03-09 22:42:47 +0100624 def probe_file(self, fid, cmd_app=None):
625 """
626 blindly try to select a file and automatically add a matching file
627 object if the file actually exists
628 """
629 if not is_hex(fid, 4, 4):
630 raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
631
632 try:
633 (data, sw) = self.card._scc.select_file(fid)
634 except SwMatchError as swm:
635 k = self.interpret_sw(swm.sw_actual)
636 if not k:
637 raise(swm)
638 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
639
640 select_resp = self.selected_file.decode_select_response(data)
641 if (select_resp['file_descriptor']['file_type'] == 'df'):
642 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime")
643 else:
644 if (select_resp['file_descriptor']['structure'] == 'transparent'):
645 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime")
646 else:
647 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime")
648
649 self.selected_file.add_files([f])
650 self.selected_file = f
651 return select_resp
652
Harald Welteb2edd142021-01-08 23:29:35 +0100653 def select(self, name, cmd_app=None):
654 """Change current directory"""
655 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +0100656 if is_hex(name):
657 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +0100658
659 # unregister commands of old file
660 if cmd_app and self.selected_file.shell_commands:
661 for c in self.selected_file.shell_commands:
662 cmd_app.unregister_command_set(c)
663
Harald Welteb2edd142021-01-08 23:29:35 +0100664 if name in sels:
665 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +0100666 try:
667 if isinstance(f, CardADF):
668 (data, sw) = self.card._scc.select_adf(f.aid)
669 else:
670 (data, sw) = self.card._scc.select_file(f.fid)
671 self.selected_file = f
672 except SwMatchError as swm:
673 k = self.interpret_sw(swm.sw_actual)
674 if not k:
675 raise(swm)
676 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +0100677 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100678 else:
Philipp Maier63f572d2021-03-09 22:42:47 +0100679 select_resp = self.probe_file(name, cmd_app)
680
681 # register commands of new file
682 if cmd_app and self.selected_file.shell_commands:
683 for c in self.selected_file.shell_commands:
684 cmd_app.register_command_set(c)
685
686 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +0100687
688 def read_binary(self, length=None, offset=0):
689 if not isinstance(self.selected_file, TransparentEF):
690 raise TypeError("Only works with TransparentEF")
691 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
692
693 def read_binary_dec(self):
694 (data, sw) = self.read_binary()
695 dec_data = self.selected_file.decode_hex(data)
696 print("%s: %s -> %s" % (sw, data, dec_data))
697 return (dec_data, sw)
698
699 def update_binary(self, data_hex, offset=0):
700 if not isinstance(self.selected_file, TransparentEF):
701 raise TypeError("Only works with TransparentEF")
702 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset)
703
704 def update_binary_dec(self, data):
705 data_hex = self.selected_file.encode_hex(data)
706 print("%s -> %s" % (data, data_hex))
707 return self.update_binary(data_hex)
708
709 def read_record(self, rec_nr=0):
710 if not isinstance(self.selected_file, LinFixedEF):
711 raise TypeError("Only works with Linear Fixed EF")
712 # returns a string of hex nibbles
713 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
714
715 def read_record_dec(self, rec_nr=0):
716 (data, sw) = self.read_record(rec_nr)
717 return (self.selected_file.decode_record_hex(data), sw)
718
719 def update_record(self, rec_nr, data_hex):
720 if not isinstance(self.selected_file, LinFixedEF):
721 raise TypeError("Only works with Linear Fixed EF")
722 return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex)
723
724 def update_record_dec(self, rec_nr, data):
725 hex_data = self.selected_file.encode_record_hex(data)
726 return self.update_record(self, rec_nr, data_hex)
727
728
729
730class FileData(object):
731 """Represent the runtime, on-card data."""
732 def __init__(self, fdesc):
733 self.desc = fdesc
734 self.fcp = None
735
736
737def interpret_sw(sw_data, sw):
738 """Interpret a given status word within the profile. Returns tuple of
739 two strings"""
740 for class_str, swdict in sw_data.items():
741 # first try direct match
742 if sw in swdict:
743 return (class_str, swdict[sw])
744 # next try wildcard matches
745 for pattern, descr in swdict.items():
746 if sw_match(sw, pattern):
747 return (class_str, descr)
748 return None
749
750class CardApplication(object):
751 """A card application is represented by an ADF (with contained hierarchy) and optionally
752 some SW definitions."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100753 def __init__(self, name, adf=None, sw=None):
Harald Welteb2edd142021-01-08 23:29:35 +0100754 self.name = name
755 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100756 self.sw = sw or dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100757
758 def __str__(self):
759 return "APP(%s)" % (self.name)
760
761 def interpret_sw(self, sw):
762 """Interpret a given status word within the application. Returns tuple of
763 two strings"""
764 return interpret_sw(self.sw, sw)
765
766class CardProfile(object):
767 """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of
768 applications as well as profile-specific SW and shell commands. Every card has
769 one card profile, but there may be multiple applications within that profile."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100770 def __init__(self, name, **kw):
Harald Welteb2edd142021-01-08 23:29:35 +0100771 self.name = name
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +0100772 self.desc = kw.get("desc", None)
773 self.files_in_mf = kw.get("files_in_mf", [])
774 self.sw = kw.get("sw", [])
775 self.applications = kw.get("applications", [])
776 self.shell_cmdsets = kw.get("shell_cmdsets", [])
Harald Welteb2edd142021-01-08 23:29:35 +0100777
778 def __str__(self):
779 return self.name
780
781 def add_application(self, app):
Philipp Maiereb72fa42021-03-26 21:29:57 +0100782 self.applications.append(app)
Harald Welteb2edd142021-01-08 23:29:35 +0100783
784 def interpret_sw(self, sw):
785 """Interpret a given status word within the profile. Returns tuple of
786 two strings"""
787 return interpret_sw(self.sw, sw)