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