blob: fe781de915dfc4ee491fed848499b5ae30c5a91d [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
Harald Welte4145d3c2021-04-08 20:34:13 +020028import tempfile
Harald Welteb2edd142021-01-08 23:29:35 +010029import json
Harald Weltef44256c2021-10-14 15:53:39 +020030import abc
31import inspect
Harald Welteb2edd142021-01-08 23:29:35 +010032
33import cmd2
34from cmd2 import CommandSet, with_default_category, with_argparser
35import argparse
36
Harald Welte1e456572021-04-02 17:16:30 +020037from typing import cast, Optional, Iterable, List, Any, Dict, Tuple
Harald Welteee3501f2021-04-02 13:00:18 +020038
Harald Weltef44256c2021-10-14 15:53:39 +020039from smartcard.util import toBytes
40
Harald Weltedaf2b392021-05-03 23:17:29 +020041from pySim.utils import sw_match, h2b, b2h, i2h, is_hex, auto_int, bertlv_parse_one, Hexstr
Harald Welte07c7b1f2021-05-28 22:01:29 +020042from pySim.construct import filter_dict, parse_construct
Harald Welteb2edd142021-01-08 23:29:35 +010043from pySim.exceptions import *
Harald Welte0d4e98a2021-04-07 00:14:40 +020044from pySim.jsonpath import js_path_find, js_path_modify
Harald Weltef44256c2021-10-14 15:53:39 +020045from pySim.commands import SimCardCommands
Harald Welteb2edd142021-01-08 23:29:35 +010046
47class CardFile(object):
48 """Base class for all objects in the smart card filesystem.
49 Serve as a common ancestor to all other file types; rarely used directly.
50 """
51 RESERVED_NAMES = ['..', '.', '/', 'MF']
52 RESERVED_FIDS = ['3f00']
53
Harald Welteee3501f2021-04-02 13:00:18 +020054 def __init__(self, fid:str=None, sfid:str=None, name:str=None, desc:str=None,
55 parent:Optional['CardDF']=None):
56 """
57 Args:
58 fid : File Identifier (4 hex digits)
59 sfid : Short File Identifier (2 hex digits, optional)
60 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +020061 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +020062 parent : Parent CardFile object within filesystem hierarchy
63 """
Harald Welteb2edd142021-01-08 23:29:35 +010064 if not isinstance(self, CardADF) and fid == None:
65 raise ValueError("fid is mandatory")
66 if fid:
67 fid = fid.lower()
68 self.fid = fid # file identifier
69 self.sfid = sfid # short file identifier
70 self.name = name # human readable name
71 self.desc = desc # human readable description
72 self.parent = parent
73 if self.parent and self.parent != self and self.fid:
74 self.parent.add_file(self)
Vadim Yanitskiya0040792021-04-09 22:44:44 +020075 self.shell_commands = [] # type: List[CommandSet]
Harald Welteb2edd142021-01-08 23:29:35 +010076
Philipp Maier66061582021-03-09 21:57:57 +010077 # Note: the basic properties (fid, name, ect.) are verified when
78 # the file is attached to a parent file. See method add_file() in
79 # class Card DF
80
Harald Welteb2edd142021-01-08 23:29:35 +010081 def __str__(self):
82 if self.name:
83 return self.name
84 else:
85 return self.fid
86
Harald Welteee3501f2021-04-02 13:00:18 +020087 def _path_element(self, prefer_name:bool) -> Optional[str]:
Harald Welteb2edd142021-01-08 23:29:35 +010088 if prefer_name and self.name:
89 return self.name
90 else:
91 return self.fid
92
Harald Welte1e456572021-04-02 17:16:30 +020093 def fully_qualified_path(self, prefer_name:bool=True) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +020094 """Return fully qualified path to file as list of FID or name strings.
95
96 Args:
97 prefer_name : Preferably build path of names; fall-back to FIDs as required
98 """
Harald Welte1e456572021-04-02 17:16:30 +020099 if self.parent and self.parent != self:
Harald Welteb2edd142021-01-08 23:29:35 +0100100 ret = self.parent.fully_qualified_path(prefer_name)
101 else:
102 ret = []
Harald Welte1e456572021-04-02 17:16:30 +0200103 elem = self._path_element(prefer_name)
104 if elem:
105 ret.append(elem)
Harald Welteb2edd142021-01-08 23:29:35 +0100106 return ret
107
Harald Welteee3501f2021-04-02 13:00:18 +0200108 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +0100109 """Return the MF (root) of the file system."""
110 if self.parent == None:
111 return None
112 # iterate towards the top. MF has parent == self
113 node = self
Harald Welte1e456572021-04-02 17:16:30 +0200114 while node.parent and node.parent != node:
Harald Welteb2edd142021-01-08 23:29:35 +0100115 node = node.parent
Harald Welte1e456572021-04-02 17:16:30 +0200116 return cast(CardMF, node)
Harald Welteb2edd142021-01-08 23:29:35 +0100117
Harald Welte1e456572021-04-02 17:16:30 +0200118 def _get_self_selectables(self, alias:str=None, flags = []) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200119 """Return a dict of {'identifier': self} tuples.
120
121 Args:
122 alias : Add an alias with given name to 'self'
123 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
124 If not specified, all selectables will be returned.
125 Returns:
126 dict containing reference to 'self' for all identifiers.
127 """
Harald Welteb2edd142021-01-08 23:29:35 +0100128 sels = {}
129 if alias:
130 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100131 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100132 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100133 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100134 sels.update({self.name: self})
135 return sels
136
Harald Welte1e456572021-04-02 17:16:30 +0200137 def get_selectables(self, flags = []) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200138 """Return a dict of {'identifier': File} that is selectable from the current file.
139
140 Args:
141 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
142 If not specified, all selectables will be returned.
143 Returns:
144 dict containing all selectable items. Key is identifier (string), value
145 a reference to a CardFile (or derived class) instance.
146 """
Philipp Maier786f7812021-02-25 16:48:10 +0100147 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100148 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100149 if flags == [] or 'SELF' in flags:
150 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100151 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100152 if flags == [] or 'PARENT' in flags:
Harald Welte1e456572021-04-02 17:16:30 +0200153 if self.parent:
154 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100155 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100156 if flags == [] or 'MF' in flags:
157 mf = self.get_mf()
158 if mf:
159 sels.update(mf._get_self_selectables(flags = flags))
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100160 sels.update(mf.get_app_selectables(flags = flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100161 return sels
162
Harald Welte1e456572021-04-02 17:16:30 +0200163 def get_selectable_names(self, flags = []) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200164 """Return a dict of {'identifier': File} that is selectable from the current file.
165
166 Args:
167 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
168 If not specified, all selectables will be returned.
169 Returns:
Harald Welte1e456572021-04-02 17:16:30 +0200170 list containing all selectable names.
Harald Welteee3501f2021-04-02 13:00:18 +0200171 """
Philipp Maier786f7812021-02-25 16:48:10 +0100172 sels = self.get_selectables(flags)
Harald Welte1e456572021-04-02 17:16:30 +0200173 return list(sels.keys())
Harald Welteb2edd142021-01-08 23:29:35 +0100174
Harald Welteee3501f2021-04-02 13:00:18 +0200175 def decode_select_response(self, data_hex:str):
Harald Welteb2edd142021-01-08 23:29:35 +0100176 """Decode the response to a SELECT command."""
Harald Welte1e456572021-04-02 17:16:30 +0200177 if self.parent:
178 return self.parent.decode_select_response(data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +0100179
180
181class CardDF(CardFile):
182 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100183
184 @with_default_category('DF/ADF Commands')
185 class ShellCommands(CommandSet):
186 def __init__(self):
187 super().__init__()
188
Harald Welteb2edd142021-01-08 23:29:35 +0100189 def __init__(self, **kwargs):
190 if not isinstance(self, CardADF):
191 if not 'fid' in kwargs:
192 raise TypeError('fid is mandatory for all DF')
193 super().__init__(**kwargs)
194 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100195 self.shell_commands = [self.ShellCommands()]
Harald Welteb2edd142021-01-08 23:29:35 +0100196
197 def __str__(self):
198 return "DF(%s)" % (super().__str__())
199
Harald Welteee3501f2021-04-02 13:00:18 +0200200 def add_file(self, child:CardFile, ignore_existing:bool=False):
201 """Add a child (DF/EF) to this DF.
202 Args:
203 child: The new DF/EF to be added
204 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
205 """
Harald Welteb2edd142021-01-08 23:29:35 +0100206 if not isinstance(child, CardFile):
207 raise TypeError("Expected a File instance")
Philipp Maier3aec8712021-03-09 21:49:01 +0100208 if not is_hex(child.fid, minlen = 4, maxlen = 4):
209 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100210 if child.name in CardFile.RESERVED_NAMES:
211 raise ValueError("File name %s is a reserved name" % (child.name))
212 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100213 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100214 if child.fid in self.children:
215 if ignore_existing:
216 return
Harald Welte977035c2021-04-21 11:01:26 +0200217 raise ValueError("File with given fid %s already exists in %s" % (child.fid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100218 if self.lookup_file_by_sfid(child.sfid):
Harald Welte977035c2021-04-21 11:01:26 +0200219 raise ValueError("File with given sfid %s already exists in %s" % (child.sfid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100220 if self.lookup_file_by_name(child.name):
221 if ignore_existing:
222 return
Harald Welte977035c2021-04-21 11:01:26 +0200223 raise ValueError("File with given name %s already exists in %s" % (child.name, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100224 self.children[child.fid] = child
225 child.parent = self
226
Harald Welteee3501f2021-04-02 13:00:18 +0200227 def add_files(self, children:Iterable[CardFile], ignore_existing:bool=False):
228 """Add a list of child (DF/EF) to this DF
229
230 Args:
231 children: List of new DF/EFs to be added
232 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
233 """
Harald Welteb2edd142021-01-08 23:29:35 +0100234 for child in children:
235 self.add_file(child, ignore_existing)
236
Harald Welteee3501f2021-04-02 13:00:18 +0200237 def get_selectables(self, flags = []) -> dict:
238 """Return a dict of {'identifier': File} that is selectable from the current DF.
239
240 Args:
241 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
242 If not specified, all selectables will be returned.
243 Returns:
244 dict containing all selectable items. Key is identifier (string), value
245 a reference to a CardFile (or derived class) instance.
246 """
Harald Welteb2edd142021-01-08 23:29:35 +0100247 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100248 sels = super().get_selectables(flags)
249 if flags == [] or 'FIDS' in flags:
250 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100251 if flags == [] or 'FNAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100252 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100253 return sels
254
Harald Welte1e456572021-04-02 17:16:30 +0200255 def lookup_file_by_name(self, name:Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200256 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100257 if name == None:
258 return None
259 for i in self.children.values():
260 if i.name and i.name == name:
261 return i
262 return None
263
Harald Welte1e456572021-04-02 17:16:30 +0200264 def lookup_file_by_sfid(self, sfid:Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200265 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100266 if sfid == None:
267 return None
268 for i in self.children.values():
Harald Welte1e456572021-04-02 17:16:30 +0200269 if i.sfid == int(str(sfid)):
Harald Welteb2edd142021-01-08 23:29:35 +0100270 return i
271 return None
272
Harald Welteee3501f2021-04-02 13:00:18 +0200273 def lookup_file_by_fid(self, fid:str) -> Optional[CardFile]:
274 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100275 if fid in self.children:
276 return self.children[fid]
277 return None
278
279
280class CardMF(CardDF):
281 """MF (Master File) in the smart card filesystem"""
282 def __init__(self, **kwargs):
283 # can be overridden; use setdefault
284 kwargs.setdefault('fid', '3f00')
285 kwargs.setdefault('name', 'MF')
286 kwargs.setdefault('desc', 'Master File (directory root)')
287 # cannot be overridden; use assignment
288 kwargs['parent'] = self
289 super().__init__(**kwargs)
290 self.applications = dict()
291
292 def __str__(self):
293 return "MF(%s)" % (self.fid)
294
Harald Welte5ce35242021-04-02 20:27:05 +0200295 def add_application_df(self, app:'CardADF'):
296 """Add an Application to the MF"""
Harald Welteb2edd142021-01-08 23:29:35 +0100297 if not isinstance(app, CardADF):
298 raise TypeError("Expected an ADF instance")
299 if app.aid in self.applications:
300 raise ValueError("AID %s already exists" % (app.aid))
301 self.applications[app.aid] = app
302 app.parent=self
303
304 def get_app_names(self):
305 """Get list of completions (AID names)"""
306 return [x.name for x in self.applications]
307
Harald Welteee3501f2021-04-02 13:00:18 +0200308 def get_selectables(self, flags = []) -> dict:
309 """Return a dict of {'identifier': File} that is selectable from the current DF.
310
311 Args:
312 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
313 If not specified, all selectables will be returned.
314 Returns:
315 dict containing all selectable items. Key is identifier (string), value
316 a reference to a CardFile (or derived class) instance.
317 """
Philipp Maier786f7812021-02-25 16:48:10 +0100318 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100319 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100320 return sels
321
Harald Welteee3501f2021-04-02 13:00:18 +0200322 def get_app_selectables(self, flags = []) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100323 """Get applications by AID + name"""
324 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100325 if flags == [] or 'AIDS' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100326 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100327 if flags == [] or 'ANAMES' in flags:
Philipp Maier786f7812021-02-25 16:48:10 +0100328 sels.update({x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100329 return sels
330
Harald Welteee3501f2021-04-02 13:00:18 +0200331 def decode_select_response(self, data_hex:str) -> Any:
332 """Decode the response to a SELECT command.
333
334 This is the fall-back method which doesn't perform any decoding. It mostly
335 exists so specific derived classes can overload it for actual decoding.
336 """
Harald Welteb2edd142021-01-08 23:29:35 +0100337 return data_hex
338
339
340
341class CardADF(CardDF):
342 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Welteee3501f2021-04-02 13:00:18 +0200343 def __init__(self, aid:str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100344 super().__init__(**kwargs)
Harald Welte5ce35242021-04-02 20:27:05 +0200345 # reference to CardApplication may be set from CardApplication constructor
Harald Weltefe8a7442021-04-10 11:51:54 +0200346 self.application = None # type: Optional[CardApplication]
Harald Welteb2edd142021-01-08 23:29:35 +0100347 self.aid = aid # Application Identifier
Harald Welte1e456572021-04-02 17:16:30 +0200348 mf = self.get_mf()
349 if mf:
Harald Welte5ce35242021-04-02 20:27:05 +0200350 mf.add_application_df(self)
Harald Welteb2edd142021-01-08 23:29:35 +0100351
352 def __str__(self):
353 return "ADF(%s)" % (self.aid)
354
Harald Welteee3501f2021-04-02 13:00:18 +0200355 def _path_element(self, prefer_name:bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100356 if self.name and prefer_name:
357 return self.name
358 else:
359 return self.aid
360
361
362class CardEF(CardFile):
363 """EF (Entry File) in the smart card filesystem"""
364 def __init__(self, *, fid, **kwargs):
365 kwargs['fid'] = fid
366 super().__init__(**kwargs)
367
368 def __str__(self):
369 return "EF(%s)" % (super().__str__())
370
Harald Welteee3501f2021-04-02 13:00:18 +0200371 def get_selectables(self, flags = []) -> dict:
372 """Return a dict of {'identifier': File} that is selectable from the current DF.
373
374 Args:
375 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
376 If not specified, all selectables will be returned.
377 Returns:
378 dict containing all selectable items. Key is identifier (string), value
379 a reference to a CardFile (or derived class) instance.
380 """
Harald Welteb2edd142021-01-08 23:29:35 +0100381 #global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100382 sels = super().get_selectables(flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100383 sels.update({x.name:x for x in self.parent.children.values() if x != self})
384 return sels
385
386
387class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200388 """Transparent EF (Entry File) in the smart card filesystem.
389
390 A Transparent EF is a binary file with no formal structure. This is contrary to
391 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100392
393 @with_default_category('Transparent EF Commands')
394 class ShellCommands(CommandSet):
Harald Weltec9cdce32021-04-11 10:28:28 +0200395 """Shell commands specific for transparent EFs."""
Harald Welteb2edd142021-01-08 23:29:35 +0100396 def __init__(self):
397 super().__init__()
398
399 read_bin_parser = argparse.ArgumentParser()
400 read_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
401 read_bin_parser.add_argument('--length', type=int, help='Number of bytes to read')
402 @cmd2.with_argparser(read_bin_parser)
403 def do_read_binary(self, opts):
404 """Read binary data from a transparent EF"""
405 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
406 self._cmd.poutput(data)
407
Harald Weltebcad86c2021-04-06 20:08:39 +0200408 read_bin_dec_parser = argparse.ArgumentParser()
409 read_bin_dec_parser.add_argument('--oneline', action='store_true',
410 help='No JSON pretty-printing, dump as a single line')
411 @cmd2.with_argparser(read_bin_dec_parser)
Harald Welteb2edd142021-01-08 23:29:35 +0100412 def do_read_binary_decoded(self, opts):
413 """Read + decode data from a transparent EF"""
414 (data, sw) = self._cmd.rs.read_binary_dec()
Harald Welte1748b932021-04-06 21:12:25 +0200415 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100416
417 upd_bin_parser = argparse.ArgumentParser()
418 upd_bin_parser.add_argument('--offset', type=int, default=0, help='Byte offset for start of read')
419 upd_bin_parser.add_argument('data', help='Data bytes (hex format) to write')
420 @cmd2.with_argparser(upd_bin_parser)
421 def do_update_binary(self, opts):
422 """Update (Write) data of a transparent EF"""
423 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100424 if data:
425 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100426
427 upd_bin_dec_parser = argparse.ArgumentParser()
428 upd_bin_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200429 upd_bin_dec_parser.add_argument('--json-path', type=str,
430 help='JSON path to modify specific element of file only')
Harald Welteb2edd142021-01-08 23:29:35 +0100431 @cmd2.with_argparser(upd_bin_dec_parser)
432 def do_update_binary_decoded(self, opts):
433 """Encode + Update (Write) data of a transparent EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200434 if opts.json_path:
435 (data_json, sw) = self._cmd.rs.read_binary_dec()
436 js_path_modify(data_json, opts.json_path, json.loads(opts.data))
437 else:
438 data_json = json.loads(opts.data)
Harald Welteb2edd142021-01-08 23:29:35 +0100439 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100440 if data:
Harald Welte1748b932021-04-06 21:12:25 +0200441 self._cmd.poutput_json(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100442
Harald Welte4145d3c2021-04-08 20:34:13 +0200443 def do_edit_binary_decoded(self, opts):
444 """Edit the JSON representation of the EF contents in an editor."""
445 (orig_json, sw) = self._cmd.rs.read_binary_dec()
446 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
447 filename = '%s/file' % dirname
448 # write existing data as JSON to file
449 with open(filename, 'w') as text_file:
450 json.dump(orig_json, text_file, indent=4)
451 # run a text editor
452 self._cmd._run_editor(filename)
453 with open(filename, 'r') as text_file:
454 edited_json = json.load(text_file)
455 if edited_json == orig_json:
456 self._cmd.poutput("Data not modified, skipping write")
457 else:
458 (data, sw) = self._cmd.rs.update_binary_dec(edited_json)
459 if data:
460 self._cmd.poutput_json(data)
461
462
Harald Welteee3501f2021-04-02 13:00:18 +0200463 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
464 size={1,None}):
465 """
466 Args:
467 fid : File Identifier (4 hex digits)
468 sfid : Short File Identifier (2 hex digits, optional)
469 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200470 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200471 parent : Parent CardFile object within filesystem hierarchy
472 size : tuple of (minimum_size, recommended_size)
473 """
Harald Welteb2edd142021-01-08 23:29:35 +0100474 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200475 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200476 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100477 self.size = size
478 self.shell_commands = [self.ShellCommands()]
479
Harald Welteee3501f2021-04-02 13:00:18 +0200480 def decode_bin(self, raw_bin_data:bytearray) -> dict:
481 """Decode raw (binary) data into abstract representation.
482
483 A derived class would typically provide a _decode_bin() or _decode_hex() method
484 for implementing this specifically for the given file. This function checks which
485 of the method exists, add calls them (with conversion, as needed).
486
487 Args:
488 raw_bin_data : binary encoded data
489 Returns:
490 abstract_data; dict representing the decoded data
491 """
Harald Welteb2edd142021-01-08 23:29:35 +0100492 method = getattr(self, '_decode_bin', None)
493 if callable(method):
494 return method(raw_bin_data)
495 method = getattr(self, '_decode_hex', None)
496 if callable(method):
497 return method(b2h(raw_bin_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200498 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200499 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200500 elif self._tlv:
501 self._tlv.from_tlv(raw_bin_data)
502 return self._tlv.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100503 return {'raw': raw_bin_data.hex()}
504
Harald Welteee3501f2021-04-02 13:00:18 +0200505 def decode_hex(self, raw_hex_data:str) -> dict:
506 """Decode raw (hex string) data into abstract representation.
507
508 A derived class would typically provide a _decode_bin() or _decode_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 raw_hex_data : hex-encoded data
514 Returns:
515 abstract_data; dict representing the decoded data
516 """
Harald Welteb2edd142021-01-08 23:29:35 +0100517 method = getattr(self, '_decode_hex', None)
518 if callable(method):
519 return method(raw_hex_data)
520 raw_bin_data = h2b(raw_hex_data)
521 method = getattr(self, '_decode_bin', None)
522 if callable(method):
523 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200524 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200525 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200526 elif self._tlv:
527 self._tlv.from_tlv(raw_bin_data)
528 return self._tlv.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100529 return {'raw': raw_bin_data.hex()}
530
Harald Welteee3501f2021-04-02 13:00:18 +0200531 def encode_bin(self, abstract_data:dict) -> bytearray:
532 """Encode abstract representation into raw (binary) data.
533
534 A derived class would typically provide an _encode_bin() or _encode_hex() method
535 for implementing this specifically for the given file. This function checks which
536 of the method exists, add calls them (with conversion, as needed).
537
538 Args:
539 abstract_data : dict representing the decoded data
540 Returns:
541 binary encoded data
542 """
Harald Welteb2edd142021-01-08 23:29:35 +0100543 method = getattr(self, '_encode_bin', None)
544 if callable(method):
545 return method(abstract_data)
546 method = getattr(self, '_encode_hex', None)
547 if callable(method):
548 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200549 if self._construct:
550 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200551 elif self._tlv:
552 self._tlv.from_dict(abstract_data)
553 return self._tlv.to_tlv()
Harald Welte1aae4a02021-10-14 16:12:42 +0200554 raise NotImplementedError("%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100555
Harald Welteee3501f2021-04-02 13:00:18 +0200556 def encode_hex(self, abstract_data:dict) -> str:
557 """Encode abstract representation into raw (hex string) data.
558
559 A derived class would typically provide an _encode_bin() or _encode_hex() method
560 for implementing this specifically for the given file. This function checks which
561 of the method exists, add calls them (with conversion, as needed).
562
563 Args:
564 abstract_data : dict representing the decoded data
565 Returns:
566 hex string encoded data
567 """
Harald Welteb2edd142021-01-08 23:29:35 +0100568 method = getattr(self, '_encode_hex', None)
569 if callable(method):
570 return method(abstract_data)
571 method = getattr(self, '_encode_bin', None)
572 if callable(method):
573 raw_bin_data = method(abstract_data)
574 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200575 if self._construct:
576 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200577 elif self._tlv:
578 self._tlv.from_dict(abstract_data)
579 return b2h(self._tlv.to_tlv())
Harald Welte1aae4a02021-10-14 16:12:42 +0200580 raise NotImplementedError("%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100581
582
583class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200584 """Linear Fixed EF (Entry File) in the smart card filesystem.
585
586 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
587 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100588
589 @with_default_category('Linear Fixed EF Commands')
590 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200591 """Shell commands specific for Linear Fixed EFs."""
Harald Welteb2edd142021-01-08 23:29:35 +0100592 def __init__(self):
593 super().__init__()
594
595 read_rec_parser = argparse.ArgumentParser()
596 read_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maier41555732021-02-25 16:52:08 +0100597 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 +0100598 @cmd2.with_argparser(read_rec_parser)
599 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100600 """Read one or multiple records from a record-oriented EF"""
601 for r in range(opts.count):
602 recnr = opts.record_nr + r
603 (data, sw) = self._cmd.rs.read_record(recnr)
604 if (len(data) > 0):
605 recstr = str(data)
606 else:
607 recstr = "(empty)"
608 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100609
610 read_rec_dec_parser = argparse.ArgumentParser()
611 read_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Harald Weltebcad86c2021-04-06 20:08:39 +0200612 read_rec_dec_parser.add_argument('--oneline', action='store_true',
613 help='No JSON pretty-printing, dump as a single line')
Harald Welteb2edd142021-01-08 23:29:35 +0100614 @cmd2.with_argparser(read_rec_dec_parser)
615 def do_read_record_decoded(self, opts):
616 """Read + decode a record from a record-oriented EF"""
617 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Welte1748b932021-04-06 21:12:25 +0200618 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100619
Harald Welte850b72a2021-04-07 09:33:03 +0200620 read_recs_parser = argparse.ArgumentParser()
621 @cmd2.with_argparser(read_recs_parser)
622 def do_read_records(self, opts):
623 """Read all records from a record-oriented EF"""
624 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
625 for recnr in range(1, 1 + num_of_rec):
626 (data, sw) = self._cmd.rs.read_record(recnr)
627 if (len(data) > 0):
628 recstr = str(data)
629 else:
630 recstr = "(empty)"
631 self._cmd.poutput("%03d %s" % (recnr, recstr))
632
633 read_recs_dec_parser = argparse.ArgumentParser()
634 read_recs_dec_parser.add_argument('--oneline', action='store_true',
635 help='No JSON pretty-printing, dump as a single line')
636 @cmd2.with_argparser(read_recs_dec_parser)
637 def do_read_records_decoded(self, opts):
638 """Read + decode all records from a record-oriented EF"""
639 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
640 # collect all results in list so they are rendered as JSON list when printing
641 data_list = []
642 for recnr in range(1, 1 + num_of_rec):
643 (data, sw) = self._cmd.rs.read_record_dec(recnr)
644 data_list.append(data)
645 self._cmd.poutput_json(data_list, opts.oneline)
646
Harald Welteb2edd142021-01-08 23:29:35 +0100647 upd_rec_parser = argparse.ArgumentParser()
648 upd_rec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
649 upd_rec_parser.add_argument('data', help='Data bytes (hex format) to write')
650 @cmd2.with_argparser(upd_rec_parser)
651 def do_update_record(self, opts):
652 """Update (write) data to a record-oriented EF"""
653 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100654 if data:
655 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100656
657 upd_rec_dec_parser = argparse.ArgumentParser()
658 upd_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be read')
Philipp Maierfe1fb032021-04-20 22:33:12 +0200659 upd_rec_dec_parser.add_argument('data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200660 upd_rec_dec_parser.add_argument('--json-path', type=str,
661 help='JSON path to modify specific element of record only')
Harald Welteb2edd142021-01-08 23:29:35 +0100662 @cmd2.with_argparser(upd_rec_dec_parser)
663 def do_update_record_decoded(self, opts):
664 """Encode + Update (write) data to a record-oriented EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200665 if opts.json_path:
666 (data_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
667 js_path_modify(data_json, opts.json_path, json.loads(opts.data))
668 else:
669 data_json = json.loads(opts.data)
670 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100671 if data:
672 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100673
Harald Welte4145d3c2021-04-08 20:34:13 +0200674 edit_rec_dec_parser = argparse.ArgumentParser()
675 edit_rec_dec_parser.add_argument('record_nr', type=int, help='Number of record to be edited')
676 @cmd2.with_argparser(edit_rec_dec_parser)
677 def do_edit_record_decoded(self, opts):
678 """Edit the JSON representation of one record in an editor."""
679 (orig_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Vadim Yanitskiy895fa6f2021-05-02 02:36:44 +0200680 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
Harald Welte4145d3c2021-04-08 20:34:13 +0200681 filename = '%s/file' % dirname
682 # write existing data as JSON to file
683 with open(filename, 'w') as text_file:
684 json.dump(orig_json, text_file, indent=4)
685 # run a text editor
686 self._cmd._run_editor(filename)
687 with open(filename, 'r') as text_file:
688 edited_json = json.load(text_file)
689 if edited_json == orig_json:
690 self._cmd.poutput("Data not modified, skipping write")
691 else:
692 (data, sw) = self._cmd.rs.update_record_dec(opts.record_nr, edited_json)
693 if data:
694 self._cmd.poutput_json(data)
Harald Welte4145d3c2021-04-08 20:34:13 +0200695
696
Harald Welteee3501f2021-04-02 13:00:18 +0200697 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None,
698 parent:Optional[CardDF]=None, rec_len={1,None}):
699 """
700 Args:
701 fid : File Identifier (4 hex digits)
702 sfid : Short File Identifier (2 hex digits, optional)
703 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200704 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200705 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier0adabf62021-04-20 22:36:41 +0200706 rec_len : set of {minimum_length, recommended_length}
Harald Welteee3501f2021-04-02 13:00:18 +0200707 """
Harald Welteb2edd142021-01-08 23:29:35 +0100708 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
709 self.rec_len = rec_len
710 self.shell_commands = [self.ShellCommands()]
Harald Welte2db5cfb2021-04-10 19:05:37 +0200711 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200712 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100713
Harald Welteee3501f2021-04-02 13:00:18 +0200714 def decode_record_hex(self, raw_hex_data:str) -> dict:
715 """Decode raw (hex string) data into abstract representation.
716
717 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
718 method for implementing this specifically for the given file. This function checks which
719 of the method exists, add calls them (with conversion, as needed).
720
721 Args:
722 raw_hex_data : hex-encoded data
723 Returns:
724 abstract_data; dict representing the decoded data
725 """
Harald Welteb2edd142021-01-08 23:29:35 +0100726 method = getattr(self, '_decode_record_hex', None)
727 if callable(method):
728 return method(raw_hex_data)
729 raw_bin_data = h2b(raw_hex_data)
730 method = getattr(self, '_decode_record_bin', None)
731 if callable(method):
732 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200733 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200734 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200735 elif self._tlv:
736 self._tlv.from_tlv(raw_bin_data)
737 return self._tlv.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100738 return {'raw': raw_bin_data.hex()}
739
Harald Welteee3501f2021-04-02 13:00:18 +0200740 def decode_record_bin(self, raw_bin_data:bytearray) -> dict:
741 """Decode raw (binary) data into abstract representation.
742
743 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
744 method for implementing this specifically for the given file. This function checks which
745 of the method exists, add calls them (with conversion, as needed).
746
747 Args:
748 raw_bin_data : binary encoded data
749 Returns:
750 abstract_data; dict representing the decoded data
751 """
Harald Welteb2edd142021-01-08 23:29:35 +0100752 method = getattr(self, '_decode_record_bin', None)
753 if callable(method):
754 return method(raw_bin_data)
755 raw_hex_data = b2h(raw_bin_data)
756 method = getattr(self, '_decode_record_hex', None)
757 if callable(method):
758 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200759 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200760 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200761 elif self._tlv:
762 self._tlv.from_tlv(raw_bin_data)
763 return self._tlv.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100764 return {'raw': raw_hex_data}
765
Harald Welteee3501f2021-04-02 13:00:18 +0200766 def encode_record_hex(self, abstract_data:dict) -> str:
767 """Encode abstract representation into raw (hex string) data.
768
769 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
770 method for implementing this specifically for the given file. This function checks which
771 of the method exists, add calls them (with conversion, as needed).
772
773 Args:
774 abstract_data : dict representing the decoded data
775 Returns:
776 hex string encoded data
777 """
Harald Welteb2edd142021-01-08 23:29:35 +0100778 method = getattr(self, '_encode_record_hex', None)
779 if callable(method):
780 return method(abstract_data)
781 method = getattr(self, '_encode_record_bin', None)
782 if callable(method):
783 raw_bin_data = method(abstract_data)
Harald Welte1e456572021-04-02 17:16:30 +0200784 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200785 if self._construct:
786 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200787 elif self._tlv:
788 self._tlv.from_dict(abstract_data)
789 return b2h(self._tlv.to_tlv())
Harald Welte1aae4a02021-10-14 16:12:42 +0200790 raise NotImplementedError("%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100791
Harald Welteee3501f2021-04-02 13:00:18 +0200792 def encode_record_bin(self, abstract_data:dict) -> bytearray:
793 """Encode abstract representation into raw (binary) data.
794
795 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
796 method for implementing this specifically for the given file. This function checks which
797 of the method exists, add calls them (with conversion, as needed).
798
799 Args:
800 abstract_data : dict representing the decoded data
801 Returns:
802 binary encoded data
803 """
Harald Welteb2edd142021-01-08 23:29:35 +0100804 method = getattr(self, '_encode_record_bin', None)
805 if callable(method):
806 return method(abstract_data)
807 method = getattr(self, '_encode_record_hex', None)
808 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +0200809 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200810 if self._construct:
811 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200812 elif self._tlv:
813 self._tlv.from_dict(abstract_data)
814 return self._tlv.to_tlv()
Harald Welte1aae4a02021-10-14 16:12:42 +0200815 raise NotImplementedError("%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100816
817class CyclicEF(LinFixedEF):
818 """Cyclic EF (Entry File) in the smart card filesystem"""
819 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Welteee3501f2021-04-02 13:00:18 +0200820 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
821 rec_len={1,None}):
Harald Welteb2edd142021-01-08 23:29:35 +0100822 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len)
823
824class TransRecEF(TransparentEF):
825 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +0200826
Harald Welteb2edd142021-01-08 23:29:35 +0100827 These are the real odd-balls and mostly look like mistakes in the specification:
828 Specified as 'transparent' EF, but actually containing several fixed-length records
829 inside.
830 We add a special class for those, so the user only has to provide encoder/decoder functions
831 for a record, while this class takes care of split / merge of records.
832 """
Harald Welte1e456572021-04-02 17:16:30 +0200833 def __init__(self, fid:str, rec_len:int, sfid:str=None, name:str=None, desc:str=None,
834 parent:Optional[CardDF]=None, size={1,None}):
Harald Welteee3501f2021-04-02 13:00:18 +0200835 """
836 Args:
837 fid : File Identifier (4 hex digits)
838 sfid : Short File Identifier (2 hex digits, optional)
Harald Weltec9cdce32021-04-11 10:28:28 +0200839 name : Brief name of the file, like EF_ICCID
840 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200841 parent : Parent CardFile object within filesystem hierarchy
842 rec_len : Length of the fixed-length records within transparent EF
843 size : tuple of (minimum_size, recommended_size)
844 """
Harald Welteb2edd142021-01-08 23:29:35 +0100845 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
846 self.rec_len = rec_len
847
Harald Welteee3501f2021-04-02 13:00:18 +0200848 def decode_record_hex(self, raw_hex_data:str) -> dict:
849 """Decode raw (hex string) data into abstract representation.
850
851 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
852 method for implementing this specifically for the given file. This function checks which
853 of the method exists, add calls them (with conversion, as needed).
854
855 Args:
856 raw_hex_data : hex-encoded data
857 Returns:
858 abstract_data; dict representing the decoded data
859 """
Harald Welteb2edd142021-01-08 23:29:35 +0100860 method = getattr(self, '_decode_record_hex', None)
861 if callable(method):
862 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200863 raw_bin_data = h2b(raw_hex_data)
Harald Welteb2edd142021-01-08 23:29:35 +0100864 method = getattr(self, '_decode_record_bin', None)
865 if callable(method):
Harald Welteb2edd142021-01-08 23:29:35 +0100866 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200867 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200868 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200869 elif self._tlv:
870 self._tlv.from_tlv(raw_bin_data)
871 return self._tlv.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100872 return {'raw': raw_hex_data}
873
Harald Welteee3501f2021-04-02 13:00:18 +0200874 def decode_record_bin(self, raw_bin_data:bytearray) -> dict:
875 """Decode raw (binary) data into abstract representation.
876
877 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
878 method for implementing this specifically for the given file. This function checks which
879 of the method exists, add calls them (with conversion, as needed).
880
881 Args:
882 raw_bin_data : binary encoded data
883 Returns:
884 abstract_data; dict representing the decoded data
885 """
Harald Welteb2edd142021-01-08 23:29:35 +0100886 method = getattr(self, '_decode_record_bin', None)
887 if callable(method):
888 return method(raw_bin_data)
889 raw_hex_data = b2h(raw_bin_data)
890 method = getattr(self, '_decode_record_hex', None)
891 if callable(method):
892 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200893 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200894 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200895 elif self._tlv:
896 self._tlv.from_tlv(raw_bin_data)
897 return self._tlv.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100898 return {'raw': raw_hex_data}
899
Harald Welteee3501f2021-04-02 13:00:18 +0200900 def encode_record_hex(self, abstract_data:dict) -> str:
901 """Encode abstract representation into raw (hex string) data.
902
903 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
904 method for implementing this specifically for the given file. This function checks which
905 of the method exists, add calls them (with conversion, as needed).
906
907 Args:
908 abstract_data : dict representing the decoded data
909 Returns:
910 hex string encoded data
911 """
Harald Welteb2edd142021-01-08 23:29:35 +0100912 method = getattr(self, '_encode_record_hex', None)
913 if callable(method):
914 return method(abstract_data)
915 method = getattr(self, '_encode_record_bin', None)
916 if callable(method):
Harald Welte1e456572021-04-02 17:16:30 +0200917 return b2h(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200918 if self._construct:
919 return b2h(filter_dict(self._construct.build(abstract_data)))
Harald Weltefb506212021-05-29 21:28:24 +0200920 elif self._tlv:
921 self._tlv.from_dict(abstract_data)
922 return b2h(self._tlv.to_tlv())
Harald Welte1aae4a02021-10-14 16:12:42 +0200923 raise NotImplementedError("%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100924
Harald Welteee3501f2021-04-02 13:00:18 +0200925 def encode_record_bin(self, abstract_data:dict) -> bytearray:
926 """Encode abstract representation into raw (binary) data.
927
928 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
929 method for implementing this specifically for the given file. This function checks which
930 of the method exists, add calls them (with conversion, as needed).
931
932 Args:
933 abstract_data : dict representing the decoded data
934 Returns:
935 binary encoded data
936 """
Harald Welteb2edd142021-01-08 23:29:35 +0100937 method = getattr(self, '_encode_record_bin', None)
938 if callable(method):
939 return method(abstract_data)
940 method = getattr(self, '_encode_record_hex', None)
941 if callable(method):
942 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200943 if self._construct:
944 return filter_dict(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200945 elif self._tlv:
946 self._tlv.from_dict(abstract_data)
947 return self._tlv.to_tlv()
Harald Welte1aae4a02021-10-14 16:12:42 +0200948 raise NotImplementedError("%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100949
Harald Welteee3501f2021-04-02 13:00:18 +0200950 def _decode_bin(self, raw_bin_data:bytearray):
Harald Welteb2edd142021-01-08 23:29:35 +0100951 chunks = [raw_bin_data[i:i+self.rec_len] for i in range(0, len(raw_bin_data), self.rec_len)]
952 return [self.decode_record_bin(x) for x in chunks]
953
Harald Welteee3501f2021-04-02 13:00:18 +0200954 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +0100955 chunks = [self.encode_record_bin(x) for x in abstract_data]
956 # FIXME: pad to file size
957 return b''.join(chunks)
958
959
Harald Welte917d98c2021-04-21 11:51:25 +0200960class BerTlvEF(CardEF):
Harald Welte27881622021-04-21 11:16:31 +0200961 """BER-TLV EF (Entry File) in the smart card filesystem.
962 A BER-TLV EF is a binary file with a BER (Basic Encoding Rules) TLV structure
Harald Welteb2edd142021-01-08 23:29:35 +0100963
Harald Welte27881622021-04-21 11:16:31 +0200964 NOTE: We currently don't really support those, this class is simply a wrapper
965 around TransparentEF as a place-holder, so we can already define EFs of BER-TLV
966 type without fully supporting them."""
Harald Welteb2edd142021-01-08 23:29:35 +0100967
Harald Welte917d98c2021-04-21 11:51:25 +0200968 @with_default_category('BER-TLV EF Commands')
969 class ShellCommands(CommandSet):
970 """Shell commands specific for BER-TLV EFs."""
971 def __init__(self):
972 super().__init__()
973
974 retrieve_data_parser = argparse.ArgumentParser()
975 retrieve_data_parser.add_argument('tag', type=auto_int, help='BER-TLV Tag of value to retrieve')
976 @cmd2.with_argparser(retrieve_data_parser)
977 def do_retrieve_data(self, opts):
978 """Retrieve (Read) data from a BER-TLV EF"""
979 (data, sw) = self._cmd.rs.retrieve_data(opts.tag)
980 self._cmd.poutput(data)
981
982 def do_retrieve_tags(self, opts):
983 """List tags available in a given BER-TLV EF"""
984 tags = self._cmd.rs.retrieve_tags()
985 self._cmd.poutput(tags)
986
987 set_data_parser = argparse.ArgumentParser()
988 set_data_parser.add_argument('tag', type=auto_int, help='BER-TLV Tag of value to set')
989 set_data_parser.add_argument('data', help='Data bytes (hex format) to write')
990 @cmd2.with_argparser(set_data_parser)
991 def do_set_data(self, opts):
992 """Set (Write) data for a given tag in a BER-TLV EF"""
993 (data, sw) = self._cmd.rs.set_data(opts.tag, opts.data)
994 if data:
995 self._cmd.poutput(data)
996
997 del_data_parser = argparse.ArgumentParser()
998 del_data_parser.add_argument('tag', type=auto_int, help='BER-TLV Tag of value to set')
999 @cmd2.with_argparser(del_data_parser)
1000 def do_delete_data(self, opts):
1001 """Delete data for a given tag in a BER-TLV EF"""
1002 (data, sw) = self._cmd.rs.set_data(opts.tag, None)
1003 if data:
1004 self._cmd.poutput(data)
1005
1006
1007 def __init__(self, fid:str, sfid:str=None, name:str=None, desc:str=None, parent:CardDF=None,
1008 size={1,None}):
1009 """
1010 Args:
1011 fid : File Identifier (4 hex digits)
1012 sfid : Short File Identifier (2 hex digits, optional)
1013 name : Brief name of the file, lik EF_ICCID
1014 desc : Description of the file
1015 parent : Parent CardFile object within filesystem hierarchy
1016 size : tuple of (minimum_size, recommended_size)
1017 """
1018 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
1019 self._construct = None
1020 self.size = size
1021 self.shell_commands = [self.ShellCommands()]
1022
Harald Welteb2edd142021-01-08 23:29:35 +01001023
1024class RuntimeState(object):
1025 """Represent the runtime state of a session with a card."""
Harald Welteee3501f2021-04-02 13:00:18 +02001026 def __init__(self, card, profile:'CardProfile'):
1027 """
1028 Args:
1029 card : pysim.cards.Card instance
1030 profile : CardProfile instance
1031 """
Harald Welteb2edd142021-01-08 23:29:35 +01001032 self.mf = CardMF()
1033 self.card = card
Harald Weltefe8a7442021-04-10 11:51:54 +02001034 self.selected_file = self.mf # type: CardDF
Harald Welteb2edd142021-01-08 23:29:35 +01001035 self.profile = profile
Harald Welte5ce35242021-04-02 20:27:05 +02001036 # add application ADFs + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001037 apps = self._match_applications()
1038 for a in apps:
Harald Welte5ce35242021-04-02 20:27:05 +02001039 if a.adf:
1040 self.mf.add_application_df(a.adf)
Harald Welteb2edd142021-01-08 23:29:35 +01001041 for f in self.profile.files_in_mf:
1042 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +01001043 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +01001044
Philipp Maier1e896f32021-03-10 17:02:53 +01001045 def _match_applications(self):
1046 """match the applications from the profile with applications on the card"""
1047 apps_profile = self.profile.applications
1048 aids_card = self.card.read_aids()
1049 apps_taken = []
1050 if aids_card:
1051 aids_taken = []
1052 print("AIDs on card:")
1053 for a in aids_card:
1054 for f in apps_profile:
1055 if f.aid in a:
1056 print(" %s: %s" % (f.name, a))
1057 aids_taken.append(a)
1058 apps_taken.append(f)
1059 aids_unknown = set(aids_card) - set(aids_taken)
1060 for a in aids_unknown:
1061 print(" unknown: %s" % a)
1062 else:
1063 print("error: could not determine card applications")
1064 return apps_taken
1065
Harald Weltedaf2b392021-05-03 23:17:29 +02001066 def reset(self, cmd_app=None) -> Hexstr:
1067 """Perform physical card reset and obtain ATR.
1068 Args:
1069 cmd_app : Command Application State (for unregistering old file commands)
1070 """
1071 self.card._scc._tp.reset_card()
1072 atr = i2h(self.card._scc._tp.get_atr())
1073 # select MF to reset internal state and to verify card really works
1074 self.select('MF', cmd_app)
1075 return atr
1076
Harald Welteee3501f2021-04-02 13:00:18 +02001077 def get_cwd(self) -> CardDF:
1078 """Obtain the current working directory.
1079
1080 Returns:
1081 CardDF instance
1082 """
Harald Welteb2edd142021-01-08 23:29:35 +01001083 if isinstance(self.selected_file, CardDF):
1084 return self.selected_file
1085 else:
1086 return self.selected_file.parent
1087
Harald Welte5ce35242021-04-02 20:27:05 +02001088 def get_application_df(self) -> Optional[CardADF]:
1089 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +02001090
1091 Returns:
1092 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +01001093 # iterate upwards from selected file; check if any is an ADF
1094 node = self.selected_file
1095 while node.parent != node:
1096 if isinstance(node, CardADF):
1097 return node
1098 node = node.parent
1099 return None
1100
Harald Welteee3501f2021-04-02 13:00:18 +02001101 def interpret_sw(self, sw:str):
1102 """Interpret a given status word relative to the currently selected application
1103 or the underlying card profile.
1104
1105 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001106 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001107
1108 Returns:
1109 Tuple of two strings
1110 """
Harald Welte86fbd392021-04-02 22:13:09 +02001111 res = None
Harald Welte5ce35242021-04-02 20:27:05 +02001112 adf = self.get_application_df()
1113 if adf:
1114 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +01001115 # The application either comes with its own interpret_sw
1116 # method or we will use the interpret_sw method from the
1117 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +02001118 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +02001119 res = app.interpret_sw(sw)
1120 return res or self.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +01001121
Harald Welteee3501f2021-04-02 13:00:18 +02001122 def probe_file(self, fid:str, cmd_app=None):
1123 """Blindly try to select a file and automatically add a matching file
1124 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +01001125 if not is_hex(fid, 4, 4):
1126 raise ValueError("Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
1127
1128 try:
1129 (data, sw) = self.card._scc.select_file(fid)
1130 except SwMatchError as swm:
1131 k = self.interpret_sw(swm.sw_actual)
1132 if not k:
1133 raise(swm)
1134 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
1135
1136 select_resp = self.selected_file.decode_select_response(data)
1137 if (select_resp['file_descriptor']['file_type'] == 'df'):
1138 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(), desc="dedicated file, manually added at runtime")
1139 else:
1140 if (select_resp['file_descriptor']['structure'] == 'transparent'):
Harald Weltec9cdce32021-04-11 10:28:28 +02001141 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001142 else:
Harald Weltec9cdce32021-04-11 10:28:28 +02001143 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(), desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001144
1145 self.selected_file.add_files([f])
1146 self.selected_file = f
1147 return select_resp
1148
Harald Welteee3501f2021-04-02 13:00:18 +02001149 def select(self, name:str, cmd_app=None):
1150 """Select a file (EF, DF, ADF, MF, ...).
1151
1152 Args:
1153 name : Name of file to select
1154 cmd_app : Command Application State (for unregistering old file commands)
1155 """
Harald Welteb2edd142021-01-08 23:29:35 +01001156 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +01001157 if is_hex(name):
1158 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +01001159
1160 # unregister commands of old file
1161 if cmd_app and self.selected_file.shell_commands:
1162 for c in self.selected_file.shell_commands:
1163 cmd_app.unregister_command_set(c)
1164
Harald Welteb2edd142021-01-08 23:29:35 +01001165 if name in sels:
1166 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +01001167 try:
1168 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001169 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +01001170 else:
1171 (data, sw) = self.card._scc.select_file(f.fid)
1172 self.selected_file = f
1173 except SwMatchError as swm:
1174 k = self.interpret_sw(swm.sw_actual)
1175 if not k:
1176 raise(swm)
1177 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +01001178 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001179 else:
Philipp Maier63f572d2021-03-09 22:42:47 +01001180 select_resp = self.probe_file(name, cmd_app)
Harald Welte850b72a2021-04-07 09:33:03 +02001181 # store the decoded FCP for later reference
1182 self.selected_file_fcp = select_resp
Philipp Maier63f572d2021-03-09 22:42:47 +01001183
1184 # register commands of new file
1185 if cmd_app and self.selected_file.shell_commands:
1186 for c in self.selected_file.shell_commands:
1187 cmd_app.register_command_set(c)
1188
1189 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +01001190
Harald Welte34b05d32021-05-25 22:03:13 +02001191 def status(self):
1192 """Request STATUS (current selected file FCP) from card."""
1193 (data, sw) = self.card._scc.status()
1194 return self.selected_file.decode_select_response(data)
1195
Harald Welte485692b2021-05-25 22:21:44 +02001196 def activate_file(self, name:str):
1197 """Request ACTIVATE FILE of specified file."""
1198 sels = self.selected_file.get_selectables()
1199 f = sels[name]
1200 data, sw = self.card._scc.activate_file(f.fid)
1201 return data, sw
1202
Harald Welteee3501f2021-04-02 13:00:18 +02001203 def read_binary(self, length:int=None, offset:int=0):
1204 """Read [part of] a transparent EF binary data.
1205
1206 Args:
1207 length : Amount of data to read (None: as much as possible)
1208 offset : Offset into the file from which to read 'length' bytes
1209 Returns:
1210 binary data read from the file
1211 """
Harald Welteb2edd142021-01-08 23:29:35 +01001212 if not isinstance(self.selected_file, TransparentEF):
1213 raise TypeError("Only works with TransparentEF")
1214 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
1215
Harald Welte2d4a64b2021-04-03 09:01:24 +02001216 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001217 """Read [part of] a transparent EF binary data and decode it.
1218
1219 Args:
1220 length : Amount of data to read (None: as much as possible)
1221 offset : Offset into the file from which to read 'length' bytes
1222 Returns:
1223 abstract decode data read from the file
1224 """
Harald Welteb2edd142021-01-08 23:29:35 +01001225 (data, sw) = self.read_binary()
1226 dec_data = self.selected_file.decode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001227 return (dec_data, sw)
1228
Harald Welteee3501f2021-04-02 13:00:18 +02001229 def update_binary(self, data_hex:str, offset:int=0):
1230 """Update transparent EF binary data.
1231
1232 Args:
1233 data_hex : hex string of data to be written
1234 offset : Offset into the file from which to write 'data_hex'
1235 """
Harald Welteb2edd142021-01-08 23:29:35 +01001236 if not isinstance(self.selected_file, TransparentEF):
1237 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001238 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001239
Harald Welteee3501f2021-04-02 13:00:18 +02001240 def update_binary_dec(self, data:dict):
1241 """Update transparent EF from abstract data. Encodes the data to binary and
1242 then updates the EF with it.
1243
1244 Args:
1245 data : abstract data which is to be encoded and written
1246 """
Harald Welteb2edd142021-01-08 23:29:35 +01001247 data_hex = self.selected_file.encode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001248 return self.update_binary(data_hex)
1249
Harald Welteee3501f2021-04-02 13:00:18 +02001250 def read_record(self, rec_nr:int=0):
1251 """Read a record as binary data.
1252
1253 Args:
1254 rec_nr : Record number to read
1255 Returns:
1256 hex string of binary data contained in record
1257 """
Harald Welteb2edd142021-01-08 23:29:35 +01001258 if not isinstance(self.selected_file, LinFixedEF):
1259 raise TypeError("Only works with Linear Fixed EF")
1260 # returns a string of hex nibbles
1261 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1262
Harald Welteee3501f2021-04-02 13:00:18 +02001263 def read_record_dec(self, rec_nr:int=0) -> Tuple[dict, str]:
1264 """Read a record and decode it to abstract data.
1265
1266 Args:
1267 rec_nr : Record number to read
1268 Returns:
1269 abstract data contained in record
1270 """
Harald Welteb2edd142021-01-08 23:29:35 +01001271 (data, sw) = self.read_record(rec_nr)
1272 return (self.selected_file.decode_record_hex(data), sw)
1273
Harald Welteee3501f2021-04-02 13:00:18 +02001274 def update_record(self, rec_nr:int, data_hex:str):
1275 """Update a record with given binary data
1276
1277 Args:
1278 rec_nr : Record number to read
1279 data_hex : Hex string binary data to be written
1280 """
Harald Welteb2edd142021-01-08 23:29:35 +01001281 if not isinstance(self.selected_file, LinFixedEF):
1282 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001283 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 +01001284
Harald Welteee3501f2021-04-02 13:00:18 +02001285 def update_record_dec(self, rec_nr:int, data:dict):
1286 """Update a record with given abstract data. Will encode abstract to binary data
1287 and then write it to the given record on the card.
1288
1289 Args:
1290 rec_nr : Record number to read
1291 data_hex : Abstract data to be written
1292 """
Harald Welte1e456572021-04-02 17:16:30 +02001293 data_hex = self.selected_file.encode_record_hex(data)
1294 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001295
Harald Welte917d98c2021-04-21 11:51:25 +02001296 def retrieve_data(self, tag:int=0):
1297 """Read a DO/TLV as binary data.
1298
1299 Args:
1300 tag : Tag of TLV/DO to read
1301 Returns:
1302 hex string of full BER-TLV DO including Tag and Length
1303 """
1304 if not isinstance(self.selected_file, BerTlvEF):
1305 raise TypeError("Only works with BER-TLV EF")
1306 # returns a string of hex nibbles
1307 return self.card._scc.retrieve_data(self.selected_file.fid, tag)
1308
1309 def retrieve_tags(self):
1310 """Retrieve tags available on BER-TLV EF.
1311
1312 Returns:
1313 list of integer tags contained in EF
1314 """
1315 if not isinstance(self.selected_file, BerTlvEF):
1316 raise TypeError("Only works with BER-TLV EF")
1317 data, sw = self.card._scc.retrieve_data(self.selected_file.fid, 0x5c)
Harald Weltec1475302021-05-21 21:47:55 +02001318 tag, length, value, remainder = bertlv_parse_one(h2b(data))
Harald Welte917d98c2021-04-21 11:51:25 +02001319 return list(value)
1320
1321 def set_data(self, tag:int, data_hex:str):
1322 """Update a TLV/DO with given binary data
1323
1324 Args:
1325 tag : Tag of TLV/DO to be written
1326 data_hex : Hex string binary data to be written (value portion)
1327 """
1328 if not isinstance(self.selected_file, BerTlvEF):
1329 raise TypeError("Only works with BER-TLV EF")
1330 return self.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.conserve_write)
1331
1332
Harald Welteb2edd142021-01-08 23:29:35 +01001333
1334
1335class FileData(object):
1336 """Represent the runtime, on-card data."""
1337 def __init__(self, fdesc):
1338 self.desc = fdesc
1339 self.fcp = None
1340
1341
Harald Welteee3501f2021-04-02 13:00:18 +02001342def interpret_sw(sw_data:dict, sw:str):
1343 """Interpret a given status word.
1344
1345 Args:
1346 sw_data : Hierarchical dict of status word matches
1347 sw : status word to match (string of 4 hex digits)
1348 Returns:
1349 tuple of two strings (class_string, description)
1350 """
Harald Welteb2edd142021-01-08 23:29:35 +01001351 for class_str, swdict in sw_data.items():
1352 # first try direct match
1353 if sw in swdict:
1354 return (class_str, swdict[sw])
1355 # next try wildcard matches
1356 for pattern, descr in swdict.items():
1357 if sw_match(sw, pattern):
1358 return (class_str, descr)
1359 return None
1360
1361class CardApplication(object):
1362 """A card application is represented by an ADF (with contained hierarchy) and optionally
1363 some SW definitions."""
Harald Welte5ce35242021-04-02 20:27:05 +02001364 def __init__(self, name, adf:Optional[CardADF]=None, aid:str=None, sw:dict=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001365 """
1366 Args:
1367 adf : ADF name
1368 sw : Dict of status word conversions
1369 """
Harald Welteb2edd142021-01-08 23:29:35 +01001370 self.name = name
1371 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001372 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001373 # back-reference from ADF to Applicaiton
1374 if self.adf:
1375 self.aid = aid or self.adf.aid
1376 self.adf.application = self
1377 else:
1378 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001379
1380 def __str__(self):
1381 return "APP(%s)" % (self.name)
1382
1383 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001384 """Interpret a given status word within the application.
1385
1386 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001387 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001388
1389 Returns:
1390 Tuple of two strings
1391 """
Harald Welteb2edd142021-01-08 23:29:35 +01001392 return interpret_sw(self.sw, sw)
1393
1394class CardProfile(object):
Harald Weltec9cdce32021-04-11 10:28:28 +02001395 """A Card Profile describes a card, it's filesystem hierarchy, an [initial] list of
Harald Welteb2edd142021-01-08 23:29:35 +01001396 applications as well as profile-specific SW and shell commands. Every card has
1397 one card profile, but there may be multiple applications within that profile."""
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001398 def __init__(self, name, **kw):
Harald Welteee3501f2021-04-02 13:00:18 +02001399 """
1400 Args:
1401 desc (str) : Description
1402 files_in_mf : List of CardEF instances present in MF
1403 applications : List of CardApplications present on card
1404 sw : List of status word definitions
1405 shell_cmdsets : List of cmd2 shell command sets of profile-specific commands
1406 """
Harald Welteb2edd142021-01-08 23:29:35 +01001407 self.name = name
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001408 self.desc = kw.get("desc", None)
1409 self.files_in_mf = kw.get("files_in_mf", [])
1410 self.sw = kw.get("sw", [])
1411 self.applications = kw.get("applications", [])
1412 self.shell_cmdsets = kw.get("shell_cmdsets", [])
Harald Welteb2edd142021-01-08 23:29:35 +01001413
1414 def __str__(self):
1415 return self.name
1416
Harald Welteee3501f2021-04-02 13:00:18 +02001417 def add_application(self, app:CardApplication):
1418 """Add an application to a card profile.
1419
1420 Args:
1421 app : CardApplication instance to be added to profile
1422 """
Philipp Maiereb72fa42021-03-26 21:29:57 +01001423 self.applications.append(app)
Harald Welteb2edd142021-01-08 23:29:35 +01001424
Harald Welteee3501f2021-04-02 13:00:18 +02001425 def interpret_sw(self, sw:str):
1426 """Interpret a given status word within the profile.
1427
1428 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001429 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001430
1431 Returns:
1432 Tuple of two strings
1433 """
Harald Welteb2edd142021-01-08 23:29:35 +01001434 return interpret_sw(self.sw, sw)
Harald Weltef44256c2021-10-14 15:53:39 +02001435
1436
1437class CardModel(abc.ABC):
Harald Welte4c1dca02021-10-14 17:48:25 +02001438 """A specific card model, typically having some additional vendor-specific files. All
1439 you need to do is to define a sub-class with a list of ATRs or an overridden match
1440 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001441 _atrs = []
1442
1443 @classmethod
1444 @abc.abstractmethod
1445 def add_files(cls, rs:RuntimeState):
1446 """Add model specific files to given RuntimeState."""
1447
1448 @classmethod
1449 def match(cls, scc:SimCardCommands) -> bool:
1450 """Test if given card matches this model."""
1451 card_atr = scc.get_atr()
1452 for atr in cls._atrs:
1453 atr_bin = toBytes(atr)
1454 if atr_bin == card_atr:
1455 print("Detected CardModel:", cls.__name__)
1456 return True
1457 return False
1458
1459 @staticmethod
1460 def apply_matching_models(scc:SimCardCommands, rs:RuntimeState):
Harald Welte4c1dca02021-10-14 17:48:25 +02001461 """Check if any of the CardModel sub-classes 'match' the currently inserted card
1462 (by ATR or overriding the 'match' method). If so, call their 'add_files'
1463 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001464 for m in CardModel.__subclasses__():
1465 if m.match(scc):
1466 m.add_files(rs)