blob: d1a7b5155856cb97f74ec2ddfbbf0046e9af0118 [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
Harald Welteee3501f2021-04-02 13:00:18 +020034from typing import Optional, Iterable, List, Any, Tuple
35
Philipp Maier3aec8712021-03-09 21:49:01 +010036from pySim.utils import sw_match, h2b, b2h, is_hex
Harald Welteb2edd142021-01-08 23:29:35 +010037from pySim.exceptions import *
38
39class CardFile(object):
40 """Base class for all objects in the smart card filesystem.
41 Serve as a common ancestor to all other file types; rarely used directly.
42 """
43 RESERVED_NAMES = ['..', '.', '/', 'MF']
44 RESERVED_FIDS = ['3f00']
45
Harald Welteee3501f2021-04-02 13:00:18 +020046 def __init__(self, fid:str=None, sfid:str=None, name:str=None, desc:str=None,
47 parent:Optional['CardDF']=None):
48 """
49 Args:
50 fid : File Identifier (4 hex digits)
51 sfid : Short File Identifier (2 hex digits, optional)
52 name : Brief name of the file, lik EF_ICCID
53 desc : Descriptoin of the file
54 parent : Parent CardFile object within filesystem hierarchy
55 """
Harald Welteb2edd142021-01-08 23:29:35 +010056 if not isinstance(self, CardADF) and fid == None:
57 raise ValueError("fid is mandatory")
58 if fid:
59 fid = fid.lower()
60 self.fid = fid # file identifier
61 self.sfid = sfid # short file identifier
62 self.name = name # human readable name
63 self.desc = desc # human readable description
64 self.parent = parent
65 if self.parent and self.parent != self and self.fid:
66 self.parent.add_file(self)
Harald Welteee3501f2021-04-02 13:00:18 +020067 self.shell_commands: List[CommandSet] = []
Harald Welteb2edd142021-01-08 23:29:35 +010068
Philipp Maier66061582021-03-09 21:57:57 +010069 # Note: the basic properties (fid, name, ect.) are verified when
70 # the file is attached to a parent file. See method add_file() in
71 # class Card DF
72
Harald Welteb2edd142021-01-08 23:29:35 +010073 def __str__(self):
74 if self.name:
75 return self.name
76 else:
77 return self.fid
78
Harald Welteee3501f2021-04-02 13:00:18 +020079 def _path_element(self, prefer_name:bool) -> Optional[str]:
Harald Welteb2edd142021-01-08 23:29:35 +010080 if prefer_name and self.name:
81 return self.name
82 else:
83 return self.fid
84
Harald Welteee3501f2021-04-02 13:00:18 +020085 def fully_qualified_path(self, prefer_name:bool=True):
86 """Return fully qualified path to file as list of FID or name strings.
87
88 Args:
89 prefer_name : Preferably build path of names; fall-back to FIDs as required
90 """
Harald Welteb2edd142021-01-08 23:29:35 +010091 if self.parent != self:
92 ret = self.parent.fully_qualified_path(prefer_name)
93 else:
94 ret = []
95 ret.append(self._path_element(prefer_name))
96 return ret
97
Harald Welteee3501f2021-04-02 13:00:18 +020098 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +010099 """Return the MF (root) of the file system."""
100 if self.parent == None:
101 return None
102 # iterate towards the top. MF has parent == self
103 node = self
104 while node.parent != node:
105 node = node.parent
106 return node
107
Harald Welteee3501f2021-04-02 13:00:18 +0200108 def _get_self_selectables(self, alias:str=None, flags = []) -> dict:
109 """Return a dict of {'identifier': self} tuples.
110
111 Args:
112 alias : Add an alias with given name to 'self'
113 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
114 If not specified, all selectables will be returned.
115 Returns:
116 dict containing reference to 'self' for all identifiers.
117 """
Harald Welteb2edd142021-01-08 23:29:35 +0100118 sels = {}
119 if alias:
120 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100121 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100122 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100123 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100124 sels.update({self.name: self})
125 return sels
126
Harald Welteee3501f2021-04-02 13:00:18 +0200127 def get_selectables(self, flags = []) -> dict:
128 """Return a dict of {'identifier': File} that is selectable from the current file.
129
130 Args:
131 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
132 If not specified, all selectables will be returned.
133 Returns:
134 dict containing all selectable items. Key is identifier (string), value
135 a reference to a CardFile (or derived class) instance.
136 """
Philipp Maier786f7812021-02-25 16:48:10 +0100137 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100138 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100139 if flags == [] or 'SELF' in flags:
140 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100141 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100142 if flags == [] or 'PARENT' in flags:
143 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100144 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100145 if flags == [] or 'MF' in flags:
146 mf = self.get_mf()
147 if mf:
148 sels.update(mf._get_self_selectables(flags = flags))
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100149 sels.update(mf.get_app_selectables(flags = flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100150 return sels
151
Harald Welteee3501f2021-04-02 13:00:18 +0200152 def get_selectable_names(self, flags = []) -> dict:
153 """Return a dict of {'identifier': File} that is selectable from the current file.
154
155 Args:
156 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
157 If not specified, all selectables will be returned.
158 Returns:
159 dict containing all selectable items. Key is identifier (string), value
160 a reference to a CardFile (or derived class) instance.
161 """
Philipp Maier786f7812021-02-25 16:48:10 +0100162 sels = self.get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100163 return sels.keys()
164
Harald Welteee3501f2021-04-02 13:00:18 +0200165 def decode_select_response(self, data_hex:str):
Harald Welteb2edd142021-01-08 23:29:35 +0100166 """Decode the response to a SELECT command."""
167 return self.parent.decode_select_response(data_hex)
168
169
170class CardDF(CardFile):
171 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100172
173 @with_default_category('DF/ADF Commands')
174 class ShellCommands(CommandSet):
175 def __init__(self):
176 super().__init__()
177
Harald Welteb2edd142021-01-08 23:29:35 +0100178 def __init__(self, **kwargs):
179 if not isinstance(self, CardADF):
180 if not 'fid' in kwargs:
181 raise TypeError('fid is mandatory for all DF')
182 super().__init__(**kwargs)
183 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100184 self.shell_commands = [self.ShellCommands()]
Harald Welteb2edd142021-01-08 23:29:35 +0100185
186 def __str__(self):
187 return "DF(%s)" % (super().__str__())
188
Harald Welteee3501f2021-04-02 13:00:18 +0200189 def add_file(self, child:CardFile, ignore_existing:bool=False):
190 """Add a child (DF/EF) to this DF.
191 Args:
192 child: The new DF/EF to be added
193 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
194 """
Harald Welteb2edd142021-01-08 23:29:35 +0100195 if not isinstance(child, CardFile):
196 raise TypeError("Expected a File instance")
Philipp Maier3aec8712021-03-09 21:49:01 +0100197 if not is_hex(child.fid, minlen = 4, maxlen = 4):
198 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100199 if child.name in CardFile.RESERVED_NAMES:
200 raise ValueError("File name %s is a reserved name" % (child.name))
201 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100202 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100203 if child.fid in self.children:
204 if ignore_existing:
205 return
206 raise ValueError("File with given fid %s already exists" % (child.fid))
207 if self.lookup_file_by_sfid(child.sfid):
208 raise ValueError("File with given sfid %s already exists" % (child.sfid))
209 if self.lookup_file_by_name(child.name):
210 if ignore_existing:
211 return
212 raise ValueError("File with given name %s already exists" % (child.name))
213 self.children[child.fid] = child
214 child.parent = self
215
Harald Welteee3501f2021-04-02 13:00:18 +0200216 def add_files(self, children:Iterable[CardFile], ignore_existing:bool=False):
217 """Add a list of child (DF/EF) to this DF
218
219 Args:
220 children: List of new DF/EFs to be added
221 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
222 """
Harald Welteb2edd142021-01-08 23:29:35 +0100223 for child in children:
224 self.add_file(child, ignore_existing)
225
Harald Welteee3501f2021-04-02 13:00:18 +0200226 def get_selectables(self, flags = []) -> dict:
227 """Return a dict of {'identifier': File} that is selectable from the current DF.
228
229 Args:
230 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
231 If not specified, all selectables will be returned.
232 Returns:
233 dict containing all selectable items. Key is identifier (string), value
234 a reference to a CardFile (or derived class) instance.
235 """
Harald Welteb2edd142021-01-08 23:29:35 +0100236 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100237 sels = super().get_selectables(flags)
238 if flags == [] or 'FIDS' in flags:
239 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100240 if flags == [] or 'FNAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100241 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100242 return sels
243
Harald Welteee3501f2021-04-02 13:00:18 +0200244 def lookup_file_by_name(self, name:str) -> Optional[CardFile]:
245 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100246 if name == None:
247 return None
248 for i in self.children.values():
249 if i.name and i.name == name:
250 return i
251 return None
252
Harald Welteee3501f2021-04-02 13:00:18 +0200253 def lookup_file_by_sfid(self, sfid:str) -> Optional[CardFile]:
254 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100255 if sfid == None:
256 return None
257 for i in self.children.values():
258 if i.sfid == int(sfid):
259 return i
260 return None
261
Harald Welteee3501f2021-04-02 13:00:18 +0200262 def lookup_file_by_fid(self, fid:str) -> Optional[CardFile]:
263 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100264 if fid in self.children:
265 return self.children[fid]
266 return None
267
268
269class CardMF(CardDF):
270 """MF (Master File) in the smart card filesystem"""
271 def __init__(self, **kwargs):
272 # can be overridden; use setdefault
273 kwargs.setdefault('fid', '3f00')
274 kwargs.setdefault('name', 'MF')
275 kwargs.setdefault('desc', 'Master File (directory root)')
276 # cannot be overridden; use assignment
277 kwargs['parent'] = self
278 super().__init__(**kwargs)
279 self.applications = dict()
280
281 def __str__(self):
282 return "MF(%s)" % (self.fid)
283
Harald Welteee3501f2021-04-02 13:00:18 +0200284 def add_application(self, app:'CardADF'):
Harald Welteb2edd142021-01-08 23:29:35 +0100285 """Add an ADF (Application Dedicated File) to the MF"""
286 if not isinstance(app, CardADF):
287 raise TypeError("Expected an ADF instance")
288 if app.aid in self.applications:
289 raise ValueError("AID %s already exists" % (app.aid))
290 self.applications[app.aid] = app
291 app.parent=self
292
293 def get_app_names(self):
294 """Get list of completions (AID names)"""
295 return [x.name for x in self.applications]
296
Harald Welteee3501f2021-04-02 13:00:18 +0200297 def get_selectables(self, flags = []) -> dict:
298 """Return a dict of {'identifier': File} that is selectable from the current DF.
299
300 Args:
301 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
302 If not specified, all selectables will be returned.
303 Returns:
304 dict containing all selectable items. Key is identifier (string), value
305 a reference to a CardFile (or derived class) instance.
306 """
Philipp Maier786f7812021-02-25 16:48:10 +0100307 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100308 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100309 return sels
310
Harald Welteee3501f2021-04-02 13:00:18 +0200311 def get_app_selectables(self, flags = []) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100312 """Get applications by AID + name"""
313 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100314 if flags == [] or 'AIDS' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100315 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100316 if flags == [] or 'ANAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100317 sels.update({x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100318 return sels
319
Harald Welteee3501f2021-04-02 13:00:18 +0200320 def decode_select_response(self, data_hex:str) -> Any:
321 """Decode the response to a SELECT command.
322
323 This is the fall-back method which doesn't perform any decoding. It mostly
324 exists so specific derived classes can overload it for actual decoding.
325 """
Harald Welteb2edd142021-01-08 23:29:35 +0100326 return data_hex
327
328
329
330class CardADF(CardDF):
331 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Welteee3501f2021-04-02 13:00:18 +0200332 def __init__(self, aid:str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100333 super().__init__(**kwargs)
334 self.aid = aid # Application Identifier
335 if self.parent:
336 self.parent.add_application(self)
337
338 def __str__(self):
339 return "ADF(%s)" % (self.aid)
340
Harald Welteee3501f2021-04-02 13:00:18 +0200341 def _path_element(self, prefer_name:bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100342 if self.name and prefer_name:
343 return self.name
344 else:
345 return self.aid
346
347
348class CardEF(CardFile):
349 """EF (Entry File) in the smart card filesystem"""
350 def __init__(self, *, fid, **kwargs):
351 kwargs['fid'] = fid
352 super().__init__(**kwargs)
353
354 def __str__(self):
355 return "EF(%s)" % (super().__str__())
356
Harald Welteee3501f2021-04-02 13:00:18 +0200357 def get_selectables(self, flags = []) -> dict:
358 """Return a dict of {'identifier': File} that is selectable from the current DF.
359
360 Args:
361 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
362 If not specified, all selectables will be returned.
363 Returns:
364 dict containing all selectable items. Key is identifier (string), value
365 a reference to a CardFile (or derived class) instance.
366 """
Harald Welteb2edd142021-01-08 23:29:35 +0100367 #global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100368 sels = super().get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100369 sels.update({x.name:x for x in self.parent.children.values() if x != self})
370 return sels
371
372
373class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200374 """Transparent EF (Entry File) in the smart card filesystem.
375
376 A Transparent EF is a binary file with no formal structure. This is contrary to
377 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100378
379 @with_default_category('Transparent EF Commands')
380 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200381 """Shell commands specific for Trransparent EFs."""
Harald Welteb2edd142021-01-08 23:29:35 +0100382 def __init__(self):
383 super().__init__()
384
385 read_bin_parser = argparse.ArgumentParser()
386 read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
387 read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read')
388 @cmd2.with_argparser(read_bin_parser)
389 def do_read_binary(self, opts):
390 """Read binary data from a transparent EF"""
391 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
392 self._cmd.poutput(data)
393
394 def do_read_binary_decoded(self, opts):
395 """Read + decode data from a transparent EF"""
396 (data, sw) = self._cmd.rs.read_binary_dec()
397 self._cmd.poutput(json.dumps(data, indent=4))
398
399 upd_bin_parser = argparse.ArgumentParser()
400 upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
401 upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write')
402 @cmd2.with_argparser(upd_bin_parser)
403 def do_update_binary(self, opts):
404 """Update (Write) data of a transparent EF"""
405 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100406 if data:
407 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100408
409 upd_bin_dec_parser = argparse.ArgumentParser()
410 upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
411 @cmd2.with_argparser(upd_bin_dec_parser)
412 def do_update_binary_decoded(self, opts):
413 """Encode + Update (Write) data of a transparent EF"""
414 data_json = json.loads(opts.data)
415 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100416 if data:
417 self._cmd.poutput(json.dumps(data, indent=4))
Harald Welteb2edd142021-01-08 23:29:35 +0100418
Harald Welteee3501f2021-04-02 13:00:18 +0200419 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
420 size={1,None}):
421 """
422 Args:
423 fid : File Identifier (4 hex digits)
424 sfid : Short File Identifier (2 hex digits, optional)
425 name : Brief name of the file, lik EF_ICCID
426 desc : Descriptoin of the file
427 parent : Parent CardFile object within filesystem hierarchy
428 size : tuple of (minimum_size, recommended_size)
429 """
Harald Welteb2edd142021-01-08 23:29:35 +0100430 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
431 self.size = size
432 self.shell_commands = [self.ShellCommands()]
433
Harald Welteee3501f2021-04-02 13:00:18 +0200434 def decode_bin(self, raw_bin_data:bytearray) -> dict:
435 """Decode raw (binary) data into abstract representation.
436
437 A derived class would typically provide a _decode_bin() or _decode_hex() method
438 for implementing this specifically for the given file. This function checks which
439 of the method exists, add calls them (with conversion, as needed).
440
441 Args:
442 raw_bin_data : binary encoded data
443 Returns:
444 abstract_data; dict representing the decoded data
445 """
Harald Welteb2edd142021-01-08 23:29:35 +0100446 method = getattr(self, '_decode_bin', None)
447 if callable(method):
448 return method(raw_bin_data)
449 method = getattr(self, '_decode_hex', None)
450 if callable(method):
451 return method(b2h(raw_bin_data))
452 return {'raw': raw_bin_data.hex()}
453
Harald Welteee3501f2021-04-02 13:00:18 +0200454 def decode_hex(self, raw_hex_data:str) -> dict:
455 """Decode raw (hex string) data into abstract representation.
456
457 A derived class would typically provide a _decode_bin() or _decode_hex() method
458 for implementing this specifically for the given file. This function checks which
459 of the method exists, add calls them (with conversion, as needed).
460
461 Args:
462 raw_hex_data : hex-encoded data
463 Returns:
464 abstract_data; dict representing the decoded data
465 """
Harald Welteb2edd142021-01-08 23:29:35 +0100466 method = getattr(self, '_decode_hex', None)
467 if callable(method):
468 return method(raw_hex_data)
469 raw_bin_data = h2b(raw_hex_data)
470 method = getattr(self, '_decode_bin', None)
471 if callable(method):
472 return method(raw_bin_data)
473 return {'raw': raw_bin_data.hex()}
474
Harald Welteee3501f2021-04-02 13:00:18 +0200475 def encode_bin(self, abstract_data:dict) -> bytearray:
476 """Encode abstract representation into raw (binary) data.
477
478 A derived class would typically provide an _encode_bin() or _encode_hex() method
479 for implementing this specifically for the given file. This function checks which
480 of the method exists, add calls them (with conversion, as needed).
481
482 Args:
483 abstract_data : dict representing the decoded data
484 Returns:
485 binary encoded data
486 """
Harald Welteb2edd142021-01-08 23:29:35 +0100487 method = getattr(self, '_encode_bin', None)
488 if callable(method):
489 return method(abstract_data)
490 method = getattr(self, '_encode_hex', None)
491 if callable(method):
492 return h2b(method(abstract_data))
493 raise NotImplementedError
494
Harald Welteee3501f2021-04-02 13:00:18 +0200495 def encode_hex(self, abstract_data:dict) -> str:
496 """Encode abstract representation into raw (hex string) data.
497
498 A derived class would typically provide an _encode_bin() or _encode_hex() method
499 for implementing this specifically for the given file. This function checks which
500 of the method exists, add calls them (with conversion, as needed).
501
502 Args:
503 abstract_data : dict representing the decoded data
504 Returns:
505 hex string encoded data
506 """
Harald Welteb2edd142021-01-08 23:29:35 +0100507 method = getattr(self, '_encode_hex', None)
508 if callable(method):
509 return method(abstract_data)
510 method = getattr(self, '_encode_bin', None)
511 if callable(method):
512 raw_bin_data = method(abstract_data)
513 return b2h(raw_bin_data)
514 raise NotImplementedError
515
516
517class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200518 """Linear Fixed EF (Entry File) in the smart card filesystem.
519
520 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
521 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100522
523 @with_default_category('Linear Fixed EF Commands')
524 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200525 """Shell commands specific for Linear Fixed EFs."""
Harald Welteb2edd142021-01-08 23:29:35 +0100526 def __init__(self):
527 super().__init__()
528
529 read_rec_parser = argparse.ArgumentParser()
530 read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maier41555732021-02-25 16:52:08 +0100531 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 +0100532 @cmd2.with_argparser(read_rec_parser)
533 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100534 """Read one or multiple records from a record-oriented EF"""
535 for r in range(opts.count):
536 recnr = opts.record_nr + r
537 (data, sw) = self._cmd.rs.read_record(recnr)
538 if (len(data) > 0):
539 recstr = str(data)
540 else:
541 recstr = "(empty)"
542 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100543
544 read_rec_dec_parser = argparse.ArgumentParser()
545 read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
546 @cmd2.with_argparser(read_rec_dec_parser)
547 def do_read_record_decoded(self, opts):
548 """Read + decode a record from a record-oriented EF"""
549 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
550 self._cmd.poutput(json.dumps(data, indent=4))
551
552 upd_rec_parser = argparse.ArgumentParser()
553 upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
554 upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write')
555 @cmd2.with_argparser(upd_rec_parser)
556 def do_update_record(self, opts):
557 """Update (write) data to a record-oriented EF"""
558 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100559 if data:
560 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100561
562 upd_rec_dec_parser = argparse.ArgumentParser()
563 upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
564 upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write')
565 @cmd2.with_argparser(upd_rec_dec_parser)
566 def do_update_record_decoded(self, opts):
567 """Encode + Update (write) data to a record-oriented EF"""
568 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100569 if data:
570 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100571
Harald Welteee3501f2021-04-02 13:00:18 +0200572 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None,
573 parent:Optional[CardDF]=None, rec_len={1,None}):
574 """
575 Args:
576 fid : File Identifier (4 hex digits)
577 sfid : Short File Identifier (2 hex digits, optional)
578 name : Brief name of the file, lik EF_ICCID
579 desc : Descriptoin of the file
580 parent : Parent CardFile object within filesystem hierarchy
581 rec_len : tuple of (minimum_length, recommended_length)
582 """
Harald Welteb2edd142021-01-08 23:29:35 +0100583 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
584 self.rec_len = rec_len
585 self.shell_commands = [self.ShellCommands()]
586
Harald Welteee3501f2021-04-02 13:00:18 +0200587 def decode_record_hex(self, raw_hex_data:str) -> dict:
588 """Decode raw (hex string) data into abstract representation.
589
590 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
591 method for implementing this specifically for the given file. This function checks which
592 of the method exists, add calls them (with conversion, as needed).
593
594 Args:
595 raw_hex_data : hex-encoded data
596 Returns:
597 abstract_data; dict representing the decoded data
598 """
Harald Welteb2edd142021-01-08 23:29:35 +0100599 method = getattr(self, '_decode_record_hex', None)
600 if callable(method):
601 return method(raw_hex_data)
602 raw_bin_data = h2b(raw_hex_data)
603 method = getattr(self, '_decode_record_bin', None)
604 if callable(method):
605 return method(raw_bin_data)
606 return {'raw': raw_bin_data.hex()}
607
Harald Welteee3501f2021-04-02 13:00:18 +0200608 def decode_record_bin(self, raw_bin_data:bytearray) -> dict:
609 """Decode raw (binary) data into abstract representation.
610
611 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
612 method for implementing this specifically for the given file. This function checks which
613 of the method exists, add calls them (with conversion, as needed).
614
615 Args:
616 raw_bin_data : binary encoded data
617 Returns:
618 abstract_data; dict representing the decoded data
619 """
Harald Welteb2edd142021-01-08 23:29:35 +0100620 method = getattr(self, '_decode_record_bin', None)
621 if callable(method):
622 return method(raw_bin_data)
623 raw_hex_data = b2h(raw_bin_data)
624 method = getattr(self, '_decode_record_hex', None)
625 if callable(method):
626 return method(raw_hex_data)
627 return {'raw': raw_hex_data}
628
Harald Welteee3501f2021-04-02 13:00:18 +0200629 def encode_record_hex(self, abstract_data:dict) -> str:
630 """Encode abstract representation into raw (hex string) data.
631
632 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
633 method for implementing this specifically for the given file. This function checks which
634 of the method exists, add calls them (with conversion, as needed).
635
636 Args:
637 abstract_data : dict representing the decoded data
638 Returns:
639 hex string encoded data
640 """
Harald Welteb2edd142021-01-08 23:29:35 +0100641 method = getattr(self, '_encode_record_hex', None)
642 if callable(method):
643 return method(abstract_data)
644 method = getattr(self, '_encode_record_bin', None)
645 if callable(method):
646 raw_bin_data = method(abstract_data)
Harald Welteee3501f2021-04-02 13:00:18 +0200647 return h2b(raw_bin_data)
Harald Welteb2edd142021-01-08 23:29:35 +0100648 raise NotImplementedError
649
Harald Welteee3501f2021-04-02 13:00:18 +0200650 def encode_record_bin(self, abstract_data:dict) -> bytearray:
651 """Encode abstract representation into raw (binary) data.
652
653 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
654 method for implementing this specifically for the given file. This function checks which
655 of the method exists, add calls them (with conversion, as needed).
656
657 Args:
658 abstract_data : dict representing the decoded data
659 Returns:
660 binary encoded data
661 """
Harald Welteb2edd142021-01-08 23:29:35 +0100662 method = getattr(self, '_encode_record_bin', None)
663 if callable(method):
664 return method(abstract_data)
665 method = getattr(self, '_encode_record_hex', None)
666 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +0200667 return h2b(method(abstract_data))
Harald Welteb2edd142021-01-08 23:29:35 +0100668 raise NotImplementedError
669
670class CyclicEF(LinFixedEF):
671 """Cyclic EF (Entry File) in the smart card filesystem"""
672 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Welteee3501f2021-04-02 13:00:18 +0200673 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
674 rec_len={1,None}):
Harald Welteb2edd142021-01-08 23:29:35 +0100675 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len)
676
677class TransRecEF(TransparentEF):
678 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +0200679
Harald Welteb2edd142021-01-08 23:29:35 +0100680 These are the real odd-balls and mostly look like mistakes in the specification:
681 Specified as 'transparent' EF, but actually containing several fixed-length records
682 inside.
683 We add a special class for those, so the user only has to provide encoder/decoder functions
684 for a record, while this class takes care of split / merge of records.
685 """
Harald Welteee3501f2021-04-02 13:00:18 +0200686 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None,
687 parent:Optional[CardDF]=None, rec_len:int=None, size={1,None}):
688 """
689 Args:
690 fid : File Identifier (4 hex digits)
691 sfid : Short File Identifier (2 hex digits, optional)
692 name : Brief name of the file, lik EF_ICCID
693 desc : Descriptoin of the file
694 parent : Parent CardFile object within filesystem hierarchy
695 rec_len : Length of the fixed-length records within transparent EF
696 size : tuple of (minimum_size, recommended_size)
697 """
Harald Welteb2edd142021-01-08 23:29:35 +0100698 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
699 self.rec_len = rec_len
700
Harald Welteee3501f2021-04-02 13:00:18 +0200701 def decode_record_hex(self, raw_hex_data:str) -> dict:
702 """Decode raw (hex string) data into abstract representation.
703
704 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
705 method for implementing this specifically for the given file. This function checks which
706 of the method exists, add calls them (with conversion, as needed).
707
708 Args:
709 raw_hex_data : hex-encoded data
710 Returns:
711 abstract_data; dict representing the decoded data
712 """
Harald Welteb2edd142021-01-08 23:29:35 +0100713 method = getattr(self, '_decode_record_hex', None)
714 if callable(method):
715 return method(raw_hex_data)
716 method = getattr(self, '_decode_record_bin', None)
717 if callable(method):
718 raw_bin_data = h2b(raw_hex_data)
719 return method(raw_bin_data)
720 return {'raw': raw_hex_data}
721
Harald Welteee3501f2021-04-02 13:00:18 +0200722 def decode_record_bin(self, raw_bin_data:bytearray) -> dict:
723 """Decode raw (binary) data into abstract representation.
724
725 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
726 method for implementing this specifically for the given file. This function checks which
727 of the method exists, add calls them (with conversion, as needed).
728
729 Args:
730 raw_bin_data : binary encoded data
731 Returns:
732 abstract_data; dict representing the decoded data
733 """
Harald Welteb2edd142021-01-08 23:29:35 +0100734 method = getattr(self, '_decode_record_bin', None)
735 if callable(method):
736 return method(raw_bin_data)
737 raw_hex_data = b2h(raw_bin_data)
738 method = getattr(self, '_decode_record_hex', None)
739 if callable(method):
740 return method(raw_hex_data)
741 return {'raw': raw_hex_data}
742
Harald Welteee3501f2021-04-02 13:00:18 +0200743 def encode_record_hex(self, abstract_data:dict) -> str:
744 """Encode abstract representation into raw (hex string) data.
745
746 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
747 method for implementing this specifically for the given file. This function checks which
748 of the method exists, add calls them (with conversion, as needed).
749
750 Args:
751 abstract_data : dict representing the decoded data
752 Returns:
753 hex string encoded data
754 """
Harald Welteb2edd142021-01-08 23:29:35 +0100755 method = getattr(self, '_encode_record_hex', None)
756 if callable(method):
757 return method(abstract_data)
758 method = getattr(self, '_encode_record_bin', None)
759 if callable(method):
760 return h2b(method(abstract_data))
761 raise NotImplementedError
762
Harald Welteee3501f2021-04-02 13:00:18 +0200763 def encode_record_bin(self, abstract_data:dict) -> bytearray:
764 """Encode abstract representation into raw (binary) data.
765
766 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
767 method for implementing this specifically for the given file. This function checks which
768 of the method exists, add calls them (with conversion, as needed).
769
770 Args:
771 abstract_data : dict representing the decoded data
772 Returns:
773 binary encoded data
774 """
Harald Welteb2edd142021-01-08 23:29:35 +0100775 method = getattr(self, '_encode_record_bin', None)
776 if callable(method):
777 return method(abstract_data)
778 method = getattr(self, '_encode_record_hex', None)
779 if callable(method):
780 return h2b(method(abstract_data))
781 raise NotImplementedError
782
Harald Welteee3501f2021-04-02 13:00:18 +0200783 def _decode_bin(self, raw_bin_data:bytearray):
Harald Welteb2edd142021-01-08 23:29:35 +0100784 chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)]
785 return [self.decode_record_bin(x) for x in chunks]
786
Harald Welteee3501f2021-04-02 13:00:18 +0200787 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +0100788 chunks = [self.encode_record_bin(x) for x in abstract_data]
789 # FIXME: pad to file size
790 return b''.join(chunks)
791
792
793
794
795
796class RuntimeState(object):
797 """Represent the runtime state of a session with a card."""
Harald Welteee3501f2021-04-02 13:00:18 +0200798 def __init__(self, card, profile:'CardProfile'):
799 """
800 Args:
801 card : pysim.cards.Card instance
802 profile : CardProfile instance
803 """
Harald Welteb2edd142021-01-08 23:29:35 +0100804 self.mf = CardMF()
805 self.card = card
806 self.selected_file = self.mf
807 self.profile = profile
808 # add applications + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +0100809 apps = self._match_applications()
810 for a in apps:
Harald Welteb2edd142021-01-08 23:29:35 +0100811 self.mf.add_application(a)
812 for f in self.profile.files_in_mf:
813 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +0100814 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +0100815
Philipp Maier1e896f32021-03-10 17:02:53 +0100816 def _match_applications(self):
817 """match the applications from the profile with applications on the card"""
818 apps_profile = self.profile.applications
819 aids_card = self.card.read_aids()
820 apps_taken = []
821 if aids_card:
822 aids_taken = []
823 print("AIDs on card:")
824 for a in aids_card:
825 for f in apps_profile:
826 if f.aid in a:
827 print(" %s: %s" % (f.name, a))
828 aids_taken.append(a)
829 apps_taken.append(f)
830 aids_unknown = set(aids_card) - set(aids_taken)
831 for a in aids_unknown:
832 print(" unknown: %s" % a)
833 else:
834 print("error: could not determine card applications")
835 return apps_taken
836
Harald Welteee3501f2021-04-02 13:00:18 +0200837 def get_cwd(self) -> CardDF:
838 """Obtain the current working directory.
839
840 Returns:
841 CardDF instance
842 """
Harald Welteb2edd142021-01-08 23:29:35 +0100843 if isinstance(self.selected_file, CardDF):
844 return self.selected_file
845 else:
846 return self.selected_file.parent
847
Harald Welteee3501f2021-04-02 13:00:18 +0200848 def get_application(self) -> Optional[CardADF]:
849 """Obtain the currently selected application (if any).
850
851 Returns:
852 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +0100853 # iterate upwards from selected file; check if any is an ADF
854 node = self.selected_file
855 while node.parent != node:
856 if isinstance(node, CardADF):
857 return node
858 node = node.parent
859 return None
860
Harald Welteee3501f2021-04-02 13:00:18 +0200861 def interpret_sw(self, sw:str):
862 """Interpret a given status word relative to the currently selected application
863 or the underlying card profile.
864
865 Args:
866 sw : Status word as string of 4 hexd digits
867
868 Returns:
869 Tuple of two strings
870 """
Harald Welteb2edd142021-01-08 23:29:35 +0100871 app = self.get_application()
872 if app:
873 # The application either comes with its own interpret_sw
874 # method or we will use the interpret_sw method from the
875 # card profile.
876 if hasattr(app, "interpret_sw"):
877 return app.interpret_sw(sw)
878 else:
879 return self.profile.interpret_sw(sw)
880 return app.interpret_sw(sw)
881 else:
882 return self.profile.interpret_sw(sw)
883
Harald Welteee3501f2021-04-02 13:00:18 +0200884 def probe_file(self, fid:str, cmd_app=None):
885 """Blindly try to select a file and automatically add a matching file
886 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100887 if not is_hex(fid, 4, 4):
888 raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
889
890 try:
891 (data, sw) = self.card._scc.select_file(fid)
892 except SwMatchError as swm:
893 k = self.interpret_sw(swm.sw_actual)
894 if not k:
895 raise(swm)
896 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
897
898 select_resp = self.selected_file.decode_select_response(data)
899 if (select_resp['file_descriptor']['file_type'] == 'df'):
900 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime")
901 else:
902 if (select_resp['file_descriptor']['structure'] == 'transparent'):
903 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime")
904 else:
905 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime")
906
907 self.selected_file.add_files([f])
908 self.selected_file = f
909 return select_resp
910
Harald Welteee3501f2021-04-02 13:00:18 +0200911 def select(self, name:str, cmd_app=None):
912 """Select a file (EF, DF, ADF, MF, ...).
913
914 Args:
915 name : Name of file to select
916 cmd_app : Command Application State (for unregistering old file commands)
917 """
Harald Welteb2edd142021-01-08 23:29:35 +0100918 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +0100919 if is_hex(name):
920 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +0100921
922 # unregister commands of old file
923 if cmd_app and self.selected_file.shell_commands:
924 for c in self.selected_file.shell_commands:
925 cmd_app.unregister_command_set(c)
926
Harald Welteb2edd142021-01-08 23:29:35 +0100927 if name in sels:
928 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +0100929 try:
930 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100931 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +0100932 else:
933 (data, sw) = self.card._scc.select_file(f.fid)
934 self.selected_file = f
935 except SwMatchError as swm:
936 k = self.interpret_sw(swm.sw_actual)
937 if not k:
938 raise(swm)
939 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +0100940 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100941 else:
Philipp Maier63f572d2021-03-09 22:42:47 +0100942 select_resp = self.probe_file(name, cmd_app)
943
944 # register commands of new file
945 if cmd_app and self.selected_file.shell_commands:
946 for c in self.selected_file.shell_commands:
947 cmd_app.register_command_set(c)
948
949 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +0100950
Harald Welteee3501f2021-04-02 13:00:18 +0200951 def read_binary(self, length:int=None, offset:int=0):
952 """Read [part of] a transparent EF binary data.
953
954 Args:
955 length : Amount of data to read (None: as much as possible)
956 offset : Offset into the file from which to read 'length' bytes
957 Returns:
958 binary data read from the file
959 """
Harald Welteb2edd142021-01-08 23:29:35 +0100960 if not isinstance(self.selected_file, TransparentEF):
961 raise TypeError("Only works with TransparentEF")
962 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
963
Harald Welteee3501f2021-04-02 13:00:18 +0200964 def read_binary_dec(self) -> dict:
965 """Read [part of] a transparent EF binary data and decode it.
966
967 Args:
968 length : Amount of data to read (None: as much as possible)
969 offset : Offset into the file from which to read 'length' bytes
970 Returns:
971 abstract decode data read from the file
972 """
Harald Welteb2edd142021-01-08 23:29:35 +0100973 (data, sw) = self.read_binary()
974 dec_data = self.selected_file.decode_hex(data)
975 print("%s: %s -> %s" % (sw, data, dec_data))
976 return (dec_data, sw)
977
Harald Welteee3501f2021-04-02 13:00:18 +0200978 def update_binary(self, data_hex:str, offset:int=0):
979 """Update transparent EF binary data.
980
981 Args:
982 data_hex : hex string of data to be written
983 offset : Offset into the file from which to write 'data_hex'
984 """
Harald Welteb2edd142021-01-08 23:29:35 +0100985 if not isinstance(self.selected_file, TransparentEF):
986 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +0100987 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +0100988
Harald Welteee3501f2021-04-02 13:00:18 +0200989 def update_binary_dec(self, data:dict):
990 """Update transparent EF from abstract data. Encodes the data to binary and
991 then updates the EF with it.
992
993 Args:
994 data : abstract data which is to be encoded and written
995 """
Harald Welteb2edd142021-01-08 23:29:35 +0100996 data_hex = self.selected_file.encode_hex(data)
997 print("%s -> %s" % (data, data_hex))
998 return self.update_binary(data_hex)
999
Harald Welteee3501f2021-04-02 13:00:18 +02001000 def read_record(self, rec_nr:int=0):
1001 """Read a record as binary data.
1002
1003 Args:
1004 rec_nr : Record number to read
1005 Returns:
1006 hex string of binary data contained in record
1007 """
Harald Welteb2edd142021-01-08 23:29:35 +01001008 if not isinstance(self.selected_file, LinFixedEF):
1009 raise TypeError("Only works with Linear Fixed EF")
1010 # returns a string of hex nibbles
1011 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1012
Harald Welteee3501f2021-04-02 13:00:18 +02001013 def read_record_dec(self, rec_nr:int=0) -> Tuple[dict, str]:
1014 """Read a record and decode it to abstract data.
1015
1016 Args:
1017 rec_nr : Record number to read
1018 Returns:
1019 abstract data contained in record
1020 """
Harald Welteb2edd142021-01-08 23:29:35 +01001021 (data, sw) = self.read_record(rec_nr)
1022 return (self.selected_file.decode_record_hex(data), sw)
1023
Harald Welteee3501f2021-04-02 13:00:18 +02001024 def update_record(self, rec_nr:int, data_hex:str):
1025 """Update a record with given binary data
1026
1027 Args:
1028 rec_nr : Record number to read
1029 data_hex : Hex string binary data to be written
1030 """
Harald Welteb2edd142021-01-08 23:29:35 +01001031 if not isinstance(self.selected_file, LinFixedEF):
1032 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001033 return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001034
Harald Welteee3501f2021-04-02 13:00:18 +02001035 def update_record_dec(self, rec_nr:int, data:dict):
1036 """Update a record with given abstract data. Will encode abstract to binary data
1037 and then write it to the given record on the card.
1038
1039 Args:
1040 rec_nr : Record number to read
1041 data_hex : Abstract data to be written
1042 """
Harald Welteb2edd142021-01-08 23:29:35 +01001043 hex_data = self.selected_file.encode_record_hex(data)
1044 return self.update_record(self, rec_nr, data_hex)
1045
1046
1047
1048class FileData(object):
1049 """Represent the runtime, on-card data."""
1050 def __init__(self, fdesc):
1051 self.desc = fdesc
1052 self.fcp = None
1053
1054
Harald Welteee3501f2021-04-02 13:00:18 +02001055def interpret_sw(sw_data:dict, sw:str):
1056 """Interpret a given status word.
1057
1058 Args:
1059 sw_data : Hierarchical dict of status word matches
1060 sw : status word to match (string of 4 hex digits)
1061 Returns:
1062 tuple of two strings (class_string, description)
1063 """
Harald Welteb2edd142021-01-08 23:29:35 +01001064 for class_str, swdict in sw_data.items():
1065 # first try direct match
1066 if sw in swdict:
1067 return (class_str, swdict[sw])
1068 # next try wildcard matches
1069 for pattern, descr in swdict.items():
1070 if sw_match(sw, pattern):
1071 return (class_str, descr)
1072 return None
1073
1074class CardApplication(object):
1075 """A card application is represented by an ADF (with contained hierarchy) and optionally
1076 some SW definitions."""
Harald Welteee3501f2021-04-02 13:00:18 +02001077 def __init__(self, name, adf:str=None, sw:dict=None):
1078 """
1079 Args:
1080 adf : ADF name
1081 sw : Dict of status word conversions
1082 """
Harald Welteb2edd142021-01-08 23:29:35 +01001083 self.name = name
1084 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001085 self.sw = sw or dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001086
1087 def __str__(self):
1088 return "APP(%s)" % (self.name)
1089
1090 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001091 """Interpret a given status word within the application.
1092
1093 Args:
1094 sw : Status word as string of 4 hexd digits
1095
1096 Returns:
1097 Tuple of two strings
1098 """
Harald Welteb2edd142021-01-08 23:29:35 +01001099 return interpret_sw(self.sw, sw)
1100
1101class CardProfile(object):
1102 """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of
1103 applications as well as profile-specific SW and shell commands. Every card has
1104 one card profile, but there may be multiple applications within that profile."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001105 def __init__(self, name, **kw):
Harald Welteee3501f2021-04-02 13:00:18 +02001106 """
1107 Args:
1108 desc (str) : Description
1109 files_in_mf : List of CardEF instances present in MF
1110 applications : List of CardApplications present on card
1111 sw : List of status word definitions
1112 shell_cmdsets : List of cmd2 shell command sets of profile-specific commands
1113 """
Harald Welteb2edd142021-01-08 23:29:35 +01001114 self.name = name
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001115 self.desc = kw.get("desc", None)
1116 self.files_in_mf = kw.get("files_in_mf", [])
1117 self.sw = kw.get("sw", [])
1118 self.applications = kw.get("applications", [])
1119 self.shell_cmdsets = kw.get("shell_cmdsets", [])
Harald Welteb2edd142021-01-08 23:29:35 +01001120
1121 def __str__(self):
1122 return self.name
1123
Harald Welteee3501f2021-04-02 13:00:18 +02001124 def add_application(self, app:CardApplication):
1125 """Add an application to a card profile.
1126
1127 Args:
1128 app : CardApplication instance to be added to profile
1129 """
Philipp Maiereb72fa42021-03-26 21:29:57 +01001130 self.applications.append(app)
Harald Welteb2edd142021-01-08 23:29:35 +01001131
Harald Welteee3501f2021-04-02 13:00:18 +02001132 def interpret_sw(self, sw:str):
1133 """Interpret a given status word within the profile.
1134
1135 Args:
1136 sw : Status word as string of 4 hexd digits
1137
1138 Returns:
1139 Tuple of two strings
1140 """
Harald Welteb2edd142021-01-08 23:29:35 +01001141 return interpret_sw(self.sw, sw)