blob: ab9b2f3bd2a4d382527235ee8db5b77c0558589f [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.
Harald Welteb2edd142021-01-08 23:29:35 +010010"""
11
Harald Welte5a4fd522021-04-02 16:05:26 +020012# (C) 2021 by Harald Welte <laforge@osmocom.org>
13#
14# This program is free software: you can redistribute it and/or modify
15# it under the terms of the GNU General Public License as published by
16# the Free Software Foundation, either version 2 of the License, or
17# (at your option) any later version.
18#
19# This program is distributed in the hope that it will be useful,
20# but WITHOUT ANY WARRANTY; without even the implied warranty of
21# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22# GNU General Public License for more details.
23#
24# You should have received a copy of the GNU General Public License
25# along with this program. If not, see <http://www.gnu.org/licenses/>.
26
Harald Welteb2edd142021-01-08 23:29:35 +010027import code
28import json
29
30import cmd2
31from cmd2 import CommandSet, with_default_category, with_argparser
32import argparse
33
Harald Welte1e456572021-04-02 17:16:30 +020034from typing import cast, Optional, Iterable, List, Any, Dict, Tuple
Harald Welteee3501f2021-04-02 13:00:18 +020035
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 Welte1e456572021-04-02 17:16:30 +020085 def fully_qualified_path(self, prefer_name:bool=True) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +020086 """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 Welte1e456572021-04-02 17:16:30 +020091 if self.parent and self.parent != self:
Harald Welteb2edd142021-01-08 23:29:35 +010092 ret = self.parent.fully_qualified_path(prefer_name)
93 else:
94 ret = []
Harald Welte1e456572021-04-02 17:16:30 +020095 elem = self._path_element(prefer_name)
96 if elem:
97 ret.append(elem)
Harald Welteb2edd142021-01-08 23:29:35 +010098 return ret
99
Harald Welteee3501f2021-04-02 13:00:18 +0200100 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +0100101 """Return the MF (root) of the file system."""
102 if self.parent == None:
103 return None
104 # iterate towards the top. MF has parent == self
105 node = self
Harald Welte1e456572021-04-02 17:16:30 +0200106 while node.parent and node.parent != node:
Harald Welteb2edd142021-01-08 23:29:35 +0100107 node = node.parent
Harald Welte1e456572021-04-02 17:16:30 +0200108 return cast(CardMF, node)
Harald Welteb2edd142021-01-08 23:29:35 +0100109
Harald Welte1e456572021-04-02 17:16:30 +0200110 def _get_self_selectables(self, alias:str=None, flags = []) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200111 """Return a dict of {'identifier': self} tuples.
112
113 Args:
114 alias : Add an alias with given name to 'self'
115 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
116 If not specified, all selectables will be returned.
117 Returns:
118 dict containing reference to 'self' for all identifiers.
119 """
Harald Welteb2edd142021-01-08 23:29:35 +0100120 sels = {}
121 if alias:
122 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100123 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100124 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100125 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100126 sels.update({self.name: self})
127 return sels
128
Harald Welte1e456572021-04-02 17:16:30 +0200129 def get_selectables(self, flags = []) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200130 """Return a dict of {'identifier': File} that is selectable from the current file.
131
132 Args:
133 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
134 If not specified, all selectables will be returned.
135 Returns:
136 dict containing all selectable items. Key is identifier (string), value
137 a reference to a CardFile (or derived class) instance.
138 """
Philipp Maier786f7812021-02-25 16:48:10 +0100139 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100140 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100141 if flags == [] or 'SELF' in flags:
142 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100143 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100144 if flags == [] or 'PARENT' in flags:
Harald Welte1e456572021-04-02 17:16:30 +0200145 if self.parent:
146 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100147 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100148 if flags == [] or 'MF' in flags:
149 mf = self.get_mf()
150 if mf:
151 sels.update(mf._get_self_selectables(flags = flags))
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100152 sels.update(mf.get_app_selectables(flags = flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100153 return sels
154
Harald Welte1e456572021-04-02 17:16:30 +0200155 def get_selectable_names(self, flags = []) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200156 """Return a dict of {'identifier': File} that is selectable from the current file.
157
158 Args:
159 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
160 If not specified, all selectables will be returned.
161 Returns:
Harald Welte1e456572021-04-02 17:16:30 +0200162 list containing all selectable names.
Harald Welteee3501f2021-04-02 13:00:18 +0200163 """
Philipp Maier786f7812021-02-25 16:48:10 +0100164 sels = self.get_selectables(flags)
Harald Welte1e456572021-04-02 17:16:30 +0200165 return list(sels.keys())
Harald Welteb2edd142021-01-08 23:29:35 +0100166
Harald Welteee3501f2021-04-02 13:00:18 +0200167 def decode_select_response(self, data_hex:str):
Harald Welteb2edd142021-01-08 23:29:35 +0100168 """Decode the response to a SELECT command."""
Harald Welte1e456572021-04-02 17:16:30 +0200169 if self.parent:
170 return self.parent.decode_select_response(data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +0100171
172
173class CardDF(CardFile):
174 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100175
176 @with_default_category('DF/ADF Commands')
177 class ShellCommands(CommandSet):
178 def __init__(self):
179 super().__init__()
180
Harald Welteb2edd142021-01-08 23:29:35 +0100181 def __init__(self, **kwargs):
182 if not isinstance(self, CardADF):
183 if not 'fid' in kwargs:
184 raise TypeError('fid is mandatory for all DF')
185 super().__init__(**kwargs)
186 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100187 self.shell_commands = [self.ShellCommands()]
Harald Welteb2edd142021-01-08 23:29:35 +0100188
189 def __str__(self):
190 return "DF(%s)" % (super().__str__())
191
Harald Welteee3501f2021-04-02 13:00:18 +0200192 def add_file(self, child:CardFile, ignore_existing:bool=False):
193 """Add a child (DF/EF) to this DF.
194 Args:
195 child: The new DF/EF to be added
196 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
197 """
Harald Welteb2edd142021-01-08 23:29:35 +0100198 if not isinstance(child, CardFile):
199 raise TypeError("Expected a File instance")
Philipp Maier3aec8712021-03-09 21:49:01 +0100200 if not is_hex(child.fid, minlen = 4, maxlen = 4):
201 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100202 if child.name in CardFile.RESERVED_NAMES:
203 raise ValueError("File name %s is a reserved name" % (child.name))
204 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100205 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100206 if child.fid in self.children:
207 if ignore_existing:
208 return
209 raise ValueError("File with given fid %s already exists" % (child.fid))
210 if self.lookup_file_by_sfid(child.sfid):
211 raise ValueError("File with given sfid %s already exists" % (child.sfid))
212 if self.lookup_file_by_name(child.name):
213 if ignore_existing:
214 return
215 raise ValueError("File with given name %s already exists" % (child.name))
216 self.children[child.fid] = child
217 child.parent = self
218
Harald Welteee3501f2021-04-02 13:00:18 +0200219 def add_files(self, children:Iterable[CardFile], ignore_existing:bool=False):
220 """Add a list of child (DF/EF) to this DF
221
222 Args:
223 children: List of new DF/EFs to be added
224 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
225 """
Harald Welteb2edd142021-01-08 23:29:35 +0100226 for child in children:
227 self.add_file(child, ignore_existing)
228
Harald Welteee3501f2021-04-02 13:00:18 +0200229 def get_selectables(self, flags = []) -> dict:
230 """Return a dict of {'identifier': File} that is selectable from the current DF.
231
232 Args:
233 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
234 If not specified, all selectables will be returned.
235 Returns:
236 dict containing all selectable items. Key is identifier (string), value
237 a reference to a CardFile (or derived class) instance.
238 """
Harald Welteb2edd142021-01-08 23:29:35 +0100239 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100240 sels = super().get_selectables(flags)
241 if flags == [] or 'FIDS' in flags:
242 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100243 if flags == [] or 'FNAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100244 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100245 return sels
246
Harald Welte1e456572021-04-02 17:16:30 +0200247 def lookup_file_by_name(self, name:Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200248 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100249 if name == None:
250 return None
251 for i in self.children.values():
252 if i.name and i.name == name:
253 return i
254 return None
255
Harald Welte1e456572021-04-02 17:16:30 +0200256 def lookup_file_by_sfid(self, sfid:Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200257 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100258 if sfid == None:
259 return None
260 for i in self.children.values():
Harald Welte1e456572021-04-02 17:16:30 +0200261 if i.sfid == int(str(sfid)):
Harald Welteb2edd142021-01-08 23:29:35 +0100262 return i
263 return None
264
Harald Welteee3501f2021-04-02 13:00:18 +0200265 def lookup_file_by_fid(self, fid:str) -> Optional[CardFile]:
266 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100267 if fid in self.children:
268 return self.children[fid]
269 return None
270
271
272class CardMF(CardDF):
273 """MF (Master File) in the smart card filesystem"""
274 def __init__(self, **kwargs):
275 # can be overridden; use setdefault
276 kwargs.setdefault('fid', '3f00')
277 kwargs.setdefault('name', 'MF')
278 kwargs.setdefault('desc', 'Master File (directory root)')
279 # cannot be overridden; use assignment
280 kwargs['parent'] = self
281 super().__init__(**kwargs)
282 self.applications = dict()
283
284 def __str__(self):
285 return "MF(%s)" % (self.fid)
286
Harald Welte5ce35242021-04-02 20:27:05 +0200287 def add_application_df(self, app:'CardADF'):
288 """Add an Application to the MF"""
Harald Welteb2edd142021-01-08 23:29:35 +0100289 if not isinstance(app, CardADF):
290 raise TypeError("Expected an ADF instance")
291 if app.aid in self.applications:
292 raise ValueError("AID %s already exists" % (app.aid))
293 self.applications[app.aid] = app
294 app.parent=self
295
296 def get_app_names(self):
297 """Get list of completions (AID names)"""
298 return [x.name for x in self.applications]
299
Harald Welteee3501f2021-04-02 13:00:18 +0200300 def get_selectables(self, flags = []) -> dict:
301 """Return a dict of {'identifier': File} that is selectable from the current DF.
302
303 Args:
304 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
305 If not specified, all selectables will be returned.
306 Returns:
307 dict containing all selectable items. Key is identifier (string), value
308 a reference to a CardFile (or derived class) instance.
309 """
Philipp Maier786f7812021-02-25 16:48:10 +0100310 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100311 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100312 return sels
313
Harald Welteee3501f2021-04-02 13:00:18 +0200314 def get_app_selectables(self, flags = []) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100315 """Get applications by AID + name"""
316 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100317 if flags == [] or 'AIDS' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100318 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100319 if flags == [] or 'ANAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100320 sels.update({x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100321 return sels
322
Harald Welteee3501f2021-04-02 13:00:18 +0200323 def decode_select_response(self, data_hex:str) -> Any:
324 """Decode the response to a SELECT command.
325
326 This is the fall-back method which doesn't perform any decoding. It mostly
327 exists so specific derived classes can overload it for actual decoding.
328 """
Harald Welteb2edd142021-01-08 23:29:35 +0100329 return data_hex
330
331
332
333class CardADF(CardDF):
334 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Welteee3501f2021-04-02 13:00:18 +0200335 def __init__(self, aid:str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100336 super().__init__(**kwargs)
Harald Welte5ce35242021-04-02 20:27:05 +0200337 # reference to CardApplication may be set from CardApplication constructor
338 self.application:Optional[CardApplication] = None
Harald Welteb2edd142021-01-08 23:29:35 +0100339 self.aid = aid # Application Identifier
Harald Welte1e456572021-04-02 17:16:30 +0200340 mf = self.get_mf()
341 if mf:
Harald Welte5ce35242021-04-02 20:27:05 +0200342 mf.add_application_df(self)
Harald Welteb2edd142021-01-08 23:29:35 +0100343
344 def __str__(self):
345 return "ADF(%s)" % (self.aid)
346
Harald Welteee3501f2021-04-02 13:00:18 +0200347 def _path_element(self, prefer_name:bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100348 if self.name and prefer_name:
349 return self.name
350 else:
351 return self.aid
352
353
354class CardEF(CardFile):
355 """EF (Entry File) in the smart card filesystem"""
356 def __init__(self, *, fid, **kwargs):
357 kwargs['fid'] = fid
358 super().__init__(**kwargs)
359
360 def __str__(self):
361 return "EF(%s)" % (super().__str__())
362
Harald Welteee3501f2021-04-02 13:00:18 +0200363 def get_selectables(self, flags = []) -> dict:
364 """Return a dict of {'identifier': File} that is selectable from the current DF.
365
366 Args:
367 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
368 If not specified, all selectables will be returned.
369 Returns:
370 dict containing all selectable items. Key is identifier (string), value
371 a reference to a CardFile (or derived class) instance.
372 """
Harald Welteb2edd142021-01-08 23:29:35 +0100373 #global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100374 sels = super().get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100375 sels.update({x.name:x for x in self.parent.children.values() if x != self})
376 return sels
377
378
379class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200380 """Transparent EF (Entry File) in the smart card filesystem.
381
382 A Transparent EF is a binary file with no formal structure. This is contrary to
383 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100384
385 @with_default_category('Transparent EF Commands')
386 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200387 """Shell commands specific for Trransparent EFs."""
Harald Welteb2edd142021-01-08 23:29:35 +0100388 def __init__(self):
389 super().__init__()
390
391 read_bin_parser = argparse.ArgumentParser()
392 read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
393 read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read')
394 @cmd2.with_argparser(read_bin_parser)
395 def do_read_binary(self, opts):
396 """Read binary data from a transparent EF"""
397 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
398 self._cmd.poutput(data)
399
Harald Weltebcad86c2021-04-06 20:08:39 +0200400 read_bin_dec_parser = argparse.ArgumentParser()
401 read_bin_dec_parser.add_argument('--oneline', action='store_true',
402 help='No JSON pretty-printing, dump as a single line')
403 @cmd2.with_argparser(read_bin_dec_parser)
Harald Welteb2edd142021-01-08 23:29:35 +0100404 def do_read_binary_decoded(self, opts):
405 """Read + decode data from a transparent EF"""
406 (data, sw) = self._cmd.rs.read_binary_dec()
Harald Welte1748b932021-04-06 21:12:25 +0200407 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100408
409 upd_bin_parser = argparse.ArgumentParser()
410 upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
411 upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write')
412 @cmd2.with_argparser(upd_bin_parser)
413 def do_update_binary(self, opts):
414 """Update (Write) data of a transparent EF"""
415 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100416 if data:
417 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100418
419 upd_bin_dec_parser = argparse.ArgumentParser()
420 upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
421 @cmd2.with_argparser(upd_bin_dec_parser)
422 def do_update_binary_decoded(self, opts):
423 """Encode + Update (Write) data of a transparent EF"""
424 data_json = json.loads(opts.data)
425 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100426 if data:
Harald Welte1748b932021-04-06 21:12:25 +0200427 self._cmd.poutput_json(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100428
Harald Welteee3501f2021-04-02 13:00:18 +0200429 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
430 size={1,None}):
431 """
432 Args:
433 fid : File Identifier (4 hex digits)
434 sfid : Short File Identifier (2 hex digits, optional)
435 name : Brief name of the file, lik EF_ICCID
436 desc : Descriptoin of the file
437 parent : Parent CardFile object within filesystem hierarchy
438 size : tuple of (minimum_size, recommended_size)
439 """
Harald Welteb2edd142021-01-08 23:29:35 +0100440 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
441 self.size = size
442 self.shell_commands = [self.ShellCommands()]
443
Harald Welteee3501f2021-04-02 13:00:18 +0200444 def decode_bin(self, raw_bin_data:bytearray) -> dict:
445 """Decode raw (binary) data into abstract representation.
446
447 A derived class would typically provide a _decode_bin() or _decode_hex() method
448 for implementing this specifically for the given file. This function checks which
449 of the method exists, add calls them (with conversion, as needed).
450
451 Args:
452 raw_bin_data : binary encoded data
453 Returns:
454 abstract_data; dict representing the decoded data
455 """
Harald Welteb2edd142021-01-08 23:29:35 +0100456 method = getattr(self, '_decode_bin', None)
457 if callable(method):
458 return method(raw_bin_data)
459 method = getattr(self, '_decode_hex', None)
460 if callable(method):
461 return method(b2h(raw_bin_data))
462 return {'raw': raw_bin_data.hex()}
463
Harald Welteee3501f2021-04-02 13:00:18 +0200464 def decode_hex(self, raw_hex_data:str) -> dict:
465 """Decode raw (hex string) data into abstract representation.
466
467 A derived class would typically provide a _decode_bin() or _decode_hex() method
468 for implementing this specifically for the given file. This function checks which
469 of the method exists, add calls them (with conversion, as needed).
470
471 Args:
472 raw_hex_data : hex-encoded data
473 Returns:
474 abstract_data; dict representing the decoded data
475 """
Harald Welteb2edd142021-01-08 23:29:35 +0100476 method = getattr(self, '_decode_hex', None)
477 if callable(method):
478 return method(raw_hex_data)
479 raw_bin_data = h2b(raw_hex_data)
480 method = getattr(self, '_decode_bin', None)
481 if callable(method):
482 return method(raw_bin_data)
483 return {'raw': raw_bin_data.hex()}
484
Harald Welteee3501f2021-04-02 13:00:18 +0200485 def encode_bin(self, abstract_data:dict) -> bytearray:
486 """Encode abstract representation into raw (binary) data.
487
488 A derived class would typically provide an _encode_bin() or _encode_hex() method
489 for implementing this specifically for the given file. This function checks which
490 of the method exists, add calls them (with conversion, as needed).
491
492 Args:
493 abstract_data : dict representing the decoded data
494 Returns:
495 binary encoded data
496 """
Harald Welteb2edd142021-01-08 23:29:35 +0100497 method = getattr(self, '_encode_bin', None)
498 if callable(method):
499 return method(abstract_data)
500 method = getattr(self, '_encode_hex', None)
501 if callable(method):
502 return h2b(method(abstract_data))
503 raise NotImplementedError
504
Harald Welteee3501f2021-04-02 13:00:18 +0200505 def encode_hex(self, abstract_data:dict) -> str:
506 """Encode abstract representation into raw (hex string) data.
507
508 A derived class would typically provide an _encode_bin() or _encode_hex() method
509 for implementing this specifically for the given file. This function checks which
510 of the method exists, add calls them (with conversion, as needed).
511
512 Args:
513 abstract_data : dict representing the decoded data
514 Returns:
515 hex string encoded data
516 """
Harald Welteb2edd142021-01-08 23:29:35 +0100517 method = getattr(self, '_encode_hex', None)
518 if callable(method):
519 return method(abstract_data)
520 method = getattr(self, '_encode_bin', None)
521 if callable(method):
522 raw_bin_data = method(abstract_data)
523 return b2h(raw_bin_data)
524 raise NotImplementedError
525
526
527class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200528 """Linear Fixed EF (Entry File) in the smart card filesystem.
529
530 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
531 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100532
533 @with_default_category('Linear Fixed EF Commands')
534 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200535 """Shell commands specific for Linear Fixed EFs."""
Harald Welteb2edd142021-01-08 23:29:35 +0100536 def __init__(self):
537 super().__init__()
538
539 read_rec_parser = argparse.ArgumentParser()
540 read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maier41555732021-02-25 16:52:08 +0100541 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 +0100542 @cmd2.with_argparser(read_rec_parser)
543 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100544 """Read one or multiple records from a record-oriented EF"""
545 for r in range(opts.count):
546 recnr = opts.record_nr + r
547 (data, sw) = self._cmd.rs.read_record(recnr)
548 if (len(data) > 0):
549 recstr = str(data)
550 else:
551 recstr = "(empty)"
552 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100553
554 read_rec_dec_parser = argparse.ArgumentParser()
555 read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Harald Weltebcad86c2021-04-06 20:08:39 +0200556 read_rec_dec_parser.add_argument('--oneline', action='store_true',
557 help='No JSON pretty-printing, dump as a single line')
Harald Welteb2edd142021-01-08 23:29:35 +0100558 @cmd2.with_argparser(read_rec_dec_parser)
559 def do_read_record_decoded(self, opts):
560 """Read + decode a record from a record-oriented EF"""
561 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Welte1748b932021-04-06 21:12:25 +0200562 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100563
564 upd_rec_parser = argparse.ArgumentParser()
565 upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
566 upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write')
567 @cmd2.with_argparser(upd_rec_parser)
568 def do_update_record(self, opts):
569 """Update (write) data to a record-oriented EF"""
570 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100571 if data:
572 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100573
574 upd_rec_dec_parser = argparse.ArgumentParser()
575 upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
576 upd_rec_dec_parser.add_argument('data', help='Data bytes (hex format) to write')
577 @cmd2.with_argparser(upd_rec_dec_parser)
578 def do_update_record_decoded(self, opts):
579 """Encode + Update (write) data to a record-oriented EF"""
580 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100581 if data:
582 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100583
Harald Welteee3501f2021-04-02 13:00:18 +0200584 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None,
585 parent:Optional[CardDF]=None, rec_len={1,None}):
586 """
587 Args:
588 fid : File Identifier (4 hex digits)
589 sfid : Short File Identifier (2 hex digits, optional)
590 name : Brief name of the file, lik EF_ICCID
591 desc : Descriptoin of the file
592 parent : Parent CardFile object within filesystem hierarchy
593 rec_len : tuple of (minimum_length, recommended_length)
594 """
Harald Welteb2edd142021-01-08 23:29:35 +0100595 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
596 self.rec_len = rec_len
597 self.shell_commands = [self.ShellCommands()]
598
Harald Welteee3501f2021-04-02 13:00:18 +0200599 def decode_record_hex(self, raw_hex_data:str) -> dict:
600 """Decode raw (hex string) data into abstract representation.
601
602 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
603 method for implementing this specifically for the given file. This function checks which
604 of the method exists, add calls them (with conversion, as needed).
605
606 Args:
607 raw_hex_data : hex-encoded data
608 Returns:
609 abstract_data; dict representing the decoded data
610 """
Harald Welteb2edd142021-01-08 23:29:35 +0100611 method = getattr(self, '_decode_record_hex', None)
612 if callable(method):
613 return method(raw_hex_data)
614 raw_bin_data = h2b(raw_hex_data)
615 method = getattr(self, '_decode_record_bin', None)
616 if callable(method):
617 return method(raw_bin_data)
618 return {'raw': raw_bin_data.hex()}
619
Harald Welteee3501f2021-04-02 13:00:18 +0200620 def decode_record_bin(self, raw_bin_data:bytearray) -> dict:
621 """Decode raw (binary) data into abstract representation.
622
623 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
624 method for implementing this specifically for the given file. This function checks which
625 of the method exists, add calls them (with conversion, as needed).
626
627 Args:
628 raw_bin_data : binary encoded data
629 Returns:
630 abstract_data; dict representing the decoded data
631 """
Harald Welteb2edd142021-01-08 23:29:35 +0100632 method = getattr(self, '_decode_record_bin', None)
633 if callable(method):
634 return method(raw_bin_data)
635 raw_hex_data = b2h(raw_bin_data)
636 method = getattr(self, '_decode_record_hex', None)
637 if callable(method):
638 return method(raw_hex_data)
639 return {'raw': raw_hex_data}
640
Harald Welteee3501f2021-04-02 13:00:18 +0200641 def encode_record_hex(self, abstract_data:dict) -> str:
642 """Encode abstract representation into raw (hex string) data.
643
644 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
645 method for implementing this specifically for the given file. This function checks which
646 of the method exists, add calls them (with conversion, as needed).
647
648 Args:
649 abstract_data : dict representing the decoded data
650 Returns:
651 hex string encoded data
652 """
Harald Welteb2edd142021-01-08 23:29:35 +0100653 method = getattr(self, '_encode_record_hex', None)
654 if callable(method):
655 return method(abstract_data)
656 method = getattr(self, '_encode_record_bin', None)
657 if callable(method):
658 raw_bin_data = method(abstract_data)
Harald Welte1e456572021-04-02 17:16:30 +0200659 return b2h(raw_bin_data)
Harald Welteb2edd142021-01-08 23:29:35 +0100660 raise NotImplementedError
661
Harald Welteee3501f2021-04-02 13:00:18 +0200662 def encode_record_bin(self, abstract_data:dict) -> bytearray:
663 """Encode abstract representation into raw (binary) data.
664
665 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
666 method for implementing this specifically for the given file. This function checks which
667 of the method exists, add calls them (with conversion, as needed).
668
669 Args:
670 abstract_data : dict representing the decoded data
671 Returns:
672 binary encoded data
673 """
Harald Welteb2edd142021-01-08 23:29:35 +0100674 method = getattr(self, '_encode_record_bin', None)
675 if callable(method):
676 return method(abstract_data)
677 method = getattr(self, '_encode_record_hex', None)
678 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +0200679 return h2b(method(abstract_data))
Harald Welteb2edd142021-01-08 23:29:35 +0100680 raise NotImplementedError
681
682class CyclicEF(LinFixedEF):
683 """Cyclic EF (Entry File) in the smart card filesystem"""
684 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Welteee3501f2021-04-02 13:00:18 +0200685 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
686 rec_len={1,None}):
Harald Welteb2edd142021-01-08 23:29:35 +0100687 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len)
688
689class TransRecEF(TransparentEF):
690 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +0200691
Harald Welteb2edd142021-01-08 23:29:35 +0100692 These are the real odd-balls and mostly look like mistakes in the specification:
693 Specified as 'transparent' EF, but actually containing several fixed-length records
694 inside.
695 We add a special class for those, so the user only has to provide encoder/decoder functions
696 for a record, while this class takes care of split / merge of records.
697 """
Harald Welte1e456572021-04-02 17:16:30 +0200698 def __init__(self, fid:str, rec_len:int, sfid:str=None, name:str=None, desc:str=None,
699 parent:Optional[CardDF]=None, size={1,None}):
Harald Welteee3501f2021-04-02 13:00:18 +0200700 """
701 Args:
702 fid : File Identifier (4 hex digits)
703 sfid : Short File Identifier (2 hex digits, optional)
704 name : Brief name of the file, lik EF_ICCID
705 desc : Descriptoin of the file
706 parent : Parent CardFile object within filesystem hierarchy
707 rec_len : Length of the fixed-length records within transparent EF
708 size : tuple of (minimum_size, recommended_size)
709 """
Harald Welteb2edd142021-01-08 23:29:35 +0100710 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
711 self.rec_len = rec_len
712
Harald Welteee3501f2021-04-02 13:00:18 +0200713 def decode_record_hex(self, raw_hex_data:str) -> dict:
714 """Decode raw (hex string) data into abstract representation.
715
716 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
717 method for implementing this specifically for the given file. This function checks which
718 of the method exists, add calls them (with conversion, as needed).
719
720 Args:
721 raw_hex_data : hex-encoded data
722 Returns:
723 abstract_data; dict representing the decoded data
724 """
Harald Welteb2edd142021-01-08 23:29:35 +0100725 method = getattr(self, '_decode_record_hex', None)
726 if callable(method):
727 return method(raw_hex_data)
728 method = getattr(self, '_decode_record_bin', None)
729 if callable(method):
730 raw_bin_data = h2b(raw_hex_data)
731 return method(raw_bin_data)
732 return {'raw': raw_hex_data}
733
Harald Welteee3501f2021-04-02 13:00:18 +0200734 def decode_record_bin(self, raw_bin_data:bytearray) -> dict:
735 """Decode raw (binary) data into abstract representation.
736
737 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
738 method for implementing this specifically for the given file. This function checks which
739 of the method exists, add calls them (with conversion, as needed).
740
741 Args:
742 raw_bin_data : binary encoded data
743 Returns:
744 abstract_data; dict representing the decoded data
745 """
Harald Welteb2edd142021-01-08 23:29:35 +0100746 method = getattr(self, '_decode_record_bin', None)
747 if callable(method):
748 return method(raw_bin_data)
749 raw_hex_data = b2h(raw_bin_data)
750 method = getattr(self, '_decode_record_hex', None)
751 if callable(method):
752 return method(raw_hex_data)
753 return {'raw': raw_hex_data}
754
Harald Welteee3501f2021-04-02 13:00:18 +0200755 def encode_record_hex(self, abstract_data:dict) -> str:
756 """Encode abstract representation into raw (hex string) data.
757
758 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
759 method for implementing this specifically for the given file. This function checks which
760 of the method exists, add calls them (with conversion, as needed).
761
762 Args:
763 abstract_data : dict representing the decoded data
764 Returns:
765 hex string encoded data
766 """
Harald Welteb2edd142021-01-08 23:29:35 +0100767 method = getattr(self, '_encode_record_hex', None)
768 if callable(method):
769 return method(abstract_data)
770 method = getattr(self, '_encode_record_bin', None)
771 if callable(method):
Harald Welte1e456572021-04-02 17:16:30 +0200772 return b2h(method(abstract_data))
Harald Welteb2edd142021-01-08 23:29:35 +0100773 raise NotImplementedError
774
Harald Welteee3501f2021-04-02 13:00:18 +0200775 def encode_record_bin(self, abstract_data:dict) -> bytearray:
776 """Encode abstract representation into raw (binary) data.
777
778 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
779 method for implementing this specifically for the given file. This function checks which
780 of the method exists, add calls them (with conversion, as needed).
781
782 Args:
783 abstract_data : dict representing the decoded data
784 Returns:
785 binary encoded data
786 """
Harald Welteb2edd142021-01-08 23:29:35 +0100787 method = getattr(self, '_encode_record_bin', None)
788 if callable(method):
789 return method(abstract_data)
790 method = getattr(self, '_encode_record_hex', None)
791 if callable(method):
792 return h2b(method(abstract_data))
793 raise NotImplementedError
794
Harald Welteee3501f2021-04-02 13:00:18 +0200795 def _decode_bin(self, raw_bin_data:bytearray):
Harald Welteb2edd142021-01-08 23:29:35 +0100796 chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)]
797 return [self.decode_record_bin(x) for x in chunks]
798
Harald Welteee3501f2021-04-02 13:00:18 +0200799 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +0100800 chunks = [self.encode_record_bin(x) for x in abstract_data]
801 # FIXME: pad to file size
802 return b''.join(chunks)
803
804
805
806
807
808class RuntimeState(object):
809 """Represent the runtime state of a session with a card."""
Harald Welteee3501f2021-04-02 13:00:18 +0200810 def __init__(self, card, profile:'CardProfile'):
811 """
812 Args:
813 card : pysim.cards.Card instance
814 profile : CardProfile instance
815 """
Harald Welteb2edd142021-01-08 23:29:35 +0100816 self.mf = CardMF()
817 self.card = card
Harald Welte5ce35242021-04-02 20:27:05 +0200818 self.selected_file:CardDF = self.mf
Harald Welteb2edd142021-01-08 23:29:35 +0100819 self.profile = profile
Harald Welte5ce35242021-04-02 20:27:05 +0200820 # add application ADFs + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +0100821 apps = self._match_applications()
822 for a in apps:
Harald Welte5ce35242021-04-02 20:27:05 +0200823 if a.adf:
824 self.mf.add_application_df(a.adf)
Harald Welteb2edd142021-01-08 23:29:35 +0100825 for f in self.profile.files_in_mf:
826 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +0100827 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +0100828
Philipp Maier1e896f32021-03-10 17:02:53 +0100829 def _match_applications(self):
830 """match the applications from the profile with applications on the card"""
831 apps_profile = self.profile.applications
832 aids_card = self.card.read_aids()
833 apps_taken = []
834 if aids_card:
835 aids_taken = []
836 print("AIDs on card:")
837 for a in aids_card:
838 for f in apps_profile:
839 if f.aid in a:
840 print(" %s: %s" % (f.name, a))
841 aids_taken.append(a)
842 apps_taken.append(f)
843 aids_unknown = set(aids_card) - set(aids_taken)
844 for a in aids_unknown:
845 print(" unknown: %s" % a)
846 else:
847 print("error: could not determine card applications")
848 return apps_taken
849
Harald Welteee3501f2021-04-02 13:00:18 +0200850 def get_cwd(self) -> CardDF:
851 """Obtain the current working directory.
852
853 Returns:
854 CardDF instance
855 """
Harald Welteb2edd142021-01-08 23:29:35 +0100856 if isinstance(self.selected_file, CardDF):
857 return self.selected_file
858 else:
859 return self.selected_file.parent
860
Harald Welte5ce35242021-04-02 20:27:05 +0200861 def get_application_df(self) -> Optional[CardADF]:
862 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +0200863
864 Returns:
865 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +0100866 # iterate upwards from selected file; check if any is an ADF
867 node = self.selected_file
868 while node.parent != node:
869 if isinstance(node, CardADF):
870 return node
871 node = node.parent
872 return None
873
Harald Welteee3501f2021-04-02 13:00:18 +0200874 def interpret_sw(self, sw:str):
875 """Interpret a given status word relative to the currently selected application
876 or the underlying card profile.
877
878 Args:
879 sw : Status word as string of 4 hexd digits
880
881 Returns:
882 Tuple of two strings
883 """
Harald Welte86fbd392021-04-02 22:13:09 +0200884 res = None
Harald Welte5ce35242021-04-02 20:27:05 +0200885 adf = self.get_application_df()
886 if adf:
887 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +0100888 # The application either comes with its own interpret_sw
889 # method or we will use the interpret_sw method from the
890 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +0200891 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +0200892 res = app.interpret_sw(sw)
893 return res or self.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +0100894
Harald Welteee3501f2021-04-02 13:00:18 +0200895 def probe_file(self, fid:str, cmd_app=None):
896 """Blindly try to select a file and automatically add a matching file
897 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100898 if not is_hex(fid, 4, 4):
899 raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
900
901 try:
902 (data, sw) = self.card._scc.select_file(fid)
903 except SwMatchError as swm:
904 k = self.interpret_sw(swm.sw_actual)
905 if not k:
906 raise(swm)
907 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
908
909 select_resp = self.selected_file.decode_select_response(data)
910 if (select_resp['file_descriptor']['file_type'] == 'df'):
911 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime")
912 else:
913 if (select_resp['file_descriptor']['structure'] == 'transparent'):
914 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime")
915 else:
916 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementry file, manually added at runtime")
917
918 self.selected_file.add_files([f])
919 self.selected_file = f
920 return select_resp
921
Harald Welteee3501f2021-04-02 13:00:18 +0200922 def select(self, name:str, cmd_app=None):
923 """Select a file (EF, DF, ADF, MF, ...).
924
925 Args:
926 name : Name of file to select
927 cmd_app : Command Application State (for unregistering old file commands)
928 """
Harald Welteb2edd142021-01-08 23:29:35 +0100929 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +0100930 if is_hex(name):
931 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +0100932
933 # unregister commands of old file
934 if cmd_app and self.selected_file.shell_commands:
935 for c in self.selected_file.shell_commands:
936 cmd_app.unregister_command_set(c)
937
Harald Welteb2edd142021-01-08 23:29:35 +0100938 if name in sels:
939 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +0100940 try:
941 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100942 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +0100943 else:
944 (data, sw) = self.card._scc.select_file(f.fid)
945 self.selected_file = f
946 except SwMatchError as swm:
947 k = self.interpret_sw(swm.sw_actual)
948 if not k:
949 raise(swm)
950 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +0100951 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100952 else:
Philipp Maier63f572d2021-03-09 22:42:47 +0100953 select_resp = self.probe_file(name, cmd_app)
954
955 # register commands of new file
956 if cmd_app and self.selected_file.shell_commands:
957 for c in self.selected_file.shell_commands:
958 cmd_app.register_command_set(c)
959
960 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +0100961
Harald Welteee3501f2021-04-02 13:00:18 +0200962 def read_binary(self, length:int=None, offset:int=0):
963 """Read [part of] a transparent EF binary data.
964
965 Args:
966 length : Amount of data to read (None: as much as possible)
967 offset : Offset into the file from which to read 'length' bytes
968 Returns:
969 binary data read from the file
970 """
Harald Welteb2edd142021-01-08 23:29:35 +0100971 if not isinstance(self.selected_file, TransparentEF):
972 raise TypeError("Only works with TransparentEF")
973 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
974
Harald Welte2d4a64b2021-04-03 09:01:24 +0200975 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200976 """Read [part of] a transparent EF binary data and decode it.
977
978 Args:
979 length : Amount of data to read (None: as much as possible)
980 offset : Offset into the file from which to read 'length' bytes
981 Returns:
982 abstract decode data read from the file
983 """
Harald Welteb2edd142021-01-08 23:29:35 +0100984 (data, sw) = self.read_binary()
985 dec_data = self.selected_file.decode_hex(data)
986 print("%s: %s -> %s" % (sw, data, dec_data))
987 return (dec_data, sw)
988
Harald Welteee3501f2021-04-02 13:00:18 +0200989 def update_binary(self, data_hex:str, offset:int=0):
990 """Update transparent EF binary data.
991
992 Args:
993 data_hex : hex string of data to be written
994 offset : Offset into the file from which to write 'data_hex'
995 """
Harald Welteb2edd142021-01-08 23:29:35 +0100996 if not isinstance(self.selected_file, TransparentEF):
997 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +0100998 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +0100999
Harald Welteee3501f2021-04-02 13:00:18 +02001000 def update_binary_dec(self, data:dict):
1001 """Update transparent EF from abstract data. Encodes the data to binary and
1002 then updates the EF with it.
1003
1004 Args:
1005 data : abstract data which is to be encoded and written
1006 """
Harald Welteb2edd142021-01-08 23:29:35 +01001007 data_hex = self.selected_file.encode_hex(data)
1008 print("%s -> %s" % (data, data_hex))
1009 return self.update_binary(data_hex)
1010
Harald Welteee3501f2021-04-02 13:00:18 +02001011 def read_record(self, rec_nr:int=0):
1012 """Read a record as binary data.
1013
1014 Args:
1015 rec_nr : Record number to read
1016 Returns:
1017 hex string of binary data contained in record
1018 """
Harald Welteb2edd142021-01-08 23:29:35 +01001019 if not isinstance(self.selected_file, LinFixedEF):
1020 raise TypeError("Only works with Linear Fixed EF")
1021 # returns a string of hex nibbles
1022 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1023
Harald Welteee3501f2021-04-02 13:00:18 +02001024 def read_record_dec(self, rec_nr:int=0) -> Tuple[dict, str]:
1025 """Read a record and decode it to abstract data.
1026
1027 Args:
1028 rec_nr : Record number to read
1029 Returns:
1030 abstract data contained in record
1031 """
Harald Welteb2edd142021-01-08 23:29:35 +01001032 (data, sw) = self.read_record(rec_nr)
1033 return (self.selected_file.decode_record_hex(data), sw)
1034
Harald Welteee3501f2021-04-02 13:00:18 +02001035 def update_record(self, rec_nr:int, data_hex:str):
1036 """Update a record with given binary data
1037
1038 Args:
1039 rec_nr : Record number to read
1040 data_hex : Hex string binary data to be written
1041 """
Harald Welteb2edd142021-01-08 23:29:35 +01001042 if not isinstance(self.selected_file, LinFixedEF):
1043 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001044 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 +01001045
Harald Welteee3501f2021-04-02 13:00:18 +02001046 def update_record_dec(self, rec_nr:int, data:dict):
1047 """Update a record with given abstract data. Will encode abstract to binary data
1048 and then write it to the given record on the card.
1049
1050 Args:
1051 rec_nr : Record number to read
1052 data_hex : Abstract data to be written
1053 """
Harald Welte1e456572021-04-02 17:16:30 +02001054 data_hex = self.selected_file.encode_record_hex(data)
1055 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001056
1057
1058
1059class FileData(object):
1060 """Represent the runtime, on-card data."""
1061 def __init__(self, fdesc):
1062 self.desc = fdesc
1063 self.fcp = None
1064
1065
Harald Welteee3501f2021-04-02 13:00:18 +02001066def interpret_sw(sw_data:dict, sw:str):
1067 """Interpret a given status word.
1068
1069 Args:
1070 sw_data : Hierarchical dict of status word matches
1071 sw : status word to match (string of 4 hex digits)
1072 Returns:
1073 tuple of two strings (class_string, description)
1074 """
Harald Welteb2edd142021-01-08 23:29:35 +01001075 for class_str, swdict in sw_data.items():
1076 # first try direct match
1077 if sw in swdict:
1078 return (class_str, swdict[sw])
1079 # next try wildcard matches
1080 for pattern, descr in swdict.items():
1081 if sw_match(sw, pattern):
1082 return (class_str, descr)
1083 return None
1084
1085class CardApplication(object):
1086 """A card application is represented by an ADF (with contained hierarchy) and optionally
1087 some SW definitions."""
Harald Welte5ce35242021-04-02 20:27:05 +02001088 def __init__(self, name, adf:Optional[CardADF]=None, aid:str=None, sw:dict=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001089 """
1090 Args:
1091 adf : ADF name
1092 sw : Dict of status word conversions
1093 """
Harald Welteb2edd142021-01-08 23:29:35 +01001094 self.name = name
1095 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001096 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001097 # back-reference from ADF to Applicaiton
1098 if self.adf:
1099 self.aid = aid or self.adf.aid
1100 self.adf.application = self
1101 else:
1102 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001103
1104 def __str__(self):
1105 return "APP(%s)" % (self.name)
1106
1107 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001108 """Interpret a given status word within the application.
1109
1110 Args:
1111 sw : Status word as string of 4 hexd digits
1112
1113 Returns:
1114 Tuple of two strings
1115 """
Harald Welteb2edd142021-01-08 23:29:35 +01001116 return interpret_sw(self.sw, sw)
1117
1118class CardProfile(object):
1119 """A Card Profile describes a card, it's filessystem hierarchy, an [initial] list of
1120 applications as well as profile-specific SW and shell commands. Every card has
1121 one card profile, but there may be multiple applications within that profile."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001122 def __init__(self, name, **kw):
Harald Welteee3501f2021-04-02 13:00:18 +02001123 """
1124 Args:
1125 desc (str) : Description
1126 files_in_mf : List of CardEF instances present in MF
1127 applications : List of CardApplications present on card
1128 sw : List of status word definitions
1129 shell_cmdsets : List of cmd2 shell command sets of profile-specific commands
1130 """
Harald Welteb2edd142021-01-08 23:29:35 +01001131 self.name = name
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001132 self.desc = kw.get("desc", None)
1133 self.files_in_mf = kw.get("files_in_mf", [])
1134 self.sw = kw.get("sw", [])
1135 self.applications = kw.get("applications", [])
1136 self.shell_cmdsets = kw.get("shell_cmdsets", [])
Harald Welteb2edd142021-01-08 23:29:35 +01001137
1138 def __str__(self):
1139 return self.name
1140
Harald Welteee3501f2021-04-02 13:00:18 +02001141 def add_application(self, app:CardApplication):
1142 """Add an application to a card profile.
1143
1144 Args:
1145 app : CardApplication instance to be added to profile
1146 """
Philipp Maiereb72fa42021-03-26 21:29:57 +01001147 self.applications.append(app)
Harald Welteb2edd142021-01-08 23:29:35 +01001148
Harald Welteee3501f2021-04-02 13:00:18 +02001149 def interpret_sw(self, sw:str):
1150 """Interpret a given status word within the profile.
1151
1152 Args:
1153 sw : Status word as string of 4 hexd digits
1154
1155 Returns:
1156 Tuple of two strings
1157 """
Harald Welteb2edd142021-01-08 23:29:35 +01001158 return interpret_sw(self.sw, sw)