blob: d1c3e1fd8b81453d9d787bf3b0090628e2ffef54 [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 Welte9170fbf2022-02-11 21:54:37 +010037from typing import cast, Optional, Iterable, List, Dict, Tuple, Union
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
Harald Welte9170fbf2022-02-11 21:54:37 +010047# int: a single service is associated with this file
48# list: any of the listed services requires this file
49# tuple: logical-and of the listed services requires this file
50CardFileService = Union[int, List[int], Tuple[int, ...]]
Harald Weltec91085e2022-02-10 18:05:45 +010051
Harald Welteb2edd142021-01-08 23:29:35 +010052class CardFile(object):
53 """Base class for all objects in the smart card filesystem.
54 Serve as a common ancestor to all other file types; rarely used directly.
55 """
56 RESERVED_NAMES = ['..', '.', '/', 'MF']
57 RESERVED_FIDS = ['3f00']
58
Harald Weltec91085e2022-02-10 18:05:45 +010059 def __init__(self, fid: str = None, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +010060 parent: Optional['CardDF'] = None, profile: Optional['CardProfile'] = None,
61 service: Optional[CardFileService] = None):
Harald Welteee3501f2021-04-02 13:00:18 +020062 """
63 Args:
64 fid : File Identifier (4 hex digits)
65 sfid : Short File Identifier (2 hex digits, optional)
66 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +020067 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +020068 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier5af7bdf2021-11-04 12:48:41 +010069 profile : Card profile that this file should be part of
Harald Welte9170fbf2022-02-11 21:54:37 +010070 service : Service (SST/UST/IST) associated with the file
Harald Welteee3501f2021-04-02 13:00:18 +020071 """
Harald Welteb2edd142021-01-08 23:29:35 +010072 if not isinstance(self, CardADF) and fid == None:
73 raise ValueError("fid is mandatory")
74 if fid:
75 fid = fid.lower()
76 self.fid = fid # file identifier
77 self.sfid = sfid # short file identifier
78 self.name = name # human readable name
79 self.desc = desc # human readable description
80 self.parent = parent
81 if self.parent and self.parent != self and self.fid:
82 self.parent.add_file(self)
Philipp Maier5af7bdf2021-11-04 12:48:41 +010083 self.profile = profile
Harald Welte9170fbf2022-02-11 21:54:37 +010084 self.service = service
Harald Weltec91085e2022-02-10 18:05:45 +010085 self.shell_commands = [] # type: List[CommandSet]
Harald Welteb2edd142021-01-08 23:29:35 +010086
Harald Weltec91085e2022-02-10 18:05:45 +010087 # Note: the basic properties (fid, name, ect.) are verified when
88 # the file is attached to a parent file. See method add_file() in
89 # class Card DF
Philipp Maier66061582021-03-09 21:57:57 +010090
Harald Welteb2edd142021-01-08 23:29:35 +010091 def __str__(self):
92 if self.name:
93 return self.name
94 else:
95 return self.fid
96
Harald Weltec91085e2022-02-10 18:05:45 +010097 def _path_element(self, prefer_name: bool) -> Optional[str]:
Harald Welteb2edd142021-01-08 23:29:35 +010098 if prefer_name and self.name:
99 return self.name
100 else:
101 return self.fid
102
Harald Weltec91085e2022-02-10 18:05:45 +0100103 def fully_qualified_path(self, prefer_name: bool = True) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200104 """Return fully qualified path to file as list of FID or name strings.
105
106 Args:
107 prefer_name : Preferably build path of names; fall-back to FIDs as required
108 """
Harald Welte1e456572021-04-02 17:16:30 +0200109 if self.parent and self.parent != self:
Harald Welteb2edd142021-01-08 23:29:35 +0100110 ret = self.parent.fully_qualified_path(prefer_name)
111 else:
112 ret = []
Harald Welte1e456572021-04-02 17:16:30 +0200113 elem = self._path_element(prefer_name)
114 if elem:
115 ret.append(elem)
Harald Welteb2edd142021-01-08 23:29:35 +0100116 return ret
117
Harald Welteaceb2a52022-02-12 21:41:59 +0100118 def fully_qualified_path_fobj(self) -> List['CardFile']:
119 """Return fully qualified path to file as list of CardFile instance references."""
120 if self.parent and self.parent != self:
121 ret = self.parent.fully_qualified_path_fobj()
122 else:
123 ret = []
124 if self:
125 ret.append(self)
126 return ret
127
128 def build_select_path_to(self, target: 'CardFile') -> Optional[List['CardFile']]:
129 """Build the relative sequence of files we need to traverse to get from us to 'target'."""
130 cur_fqpath = self.fully_qualified_path_fobj()
131 target_fqpath = target.fully_qualified_path_fobj()
132 inter_path = []
133 cur_fqpath.pop() # drop last element (currently selected file, doesn't need re-selection
134 cur_fqpath.reverse()
135 for ce in cur_fqpath:
136 inter_path.append(ce)
137 for i in range(0, len(target_fqpath)-1):
138 te = target_fqpath[i]
139 if te == ce:
140 for te2 in target_fqpath[i+1:]:
141 inter_path.append(te2)
142 # we found our common ancestor
143 return inter_path
144 return None
145
Harald Welteee3501f2021-04-02 13:00:18 +0200146 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +0100147 """Return the MF (root) of the file system."""
148 if self.parent == None:
149 return None
150 # iterate towards the top. MF has parent == self
151 node = self
Harald Welte1e456572021-04-02 17:16:30 +0200152 while node.parent and node.parent != node:
Harald Welteb2edd142021-01-08 23:29:35 +0100153 node = node.parent
Harald Welte1e456572021-04-02 17:16:30 +0200154 return cast(CardMF, node)
Harald Welteb2edd142021-01-08 23:29:35 +0100155
Harald Weltec91085e2022-02-10 18:05:45 +0100156 def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200157 """Return a dict of {'identifier': self} tuples.
158
159 Args:
160 alias : Add an alias with given name to 'self'
161 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
162 If not specified, all selectables will be returned.
163 Returns:
164 dict containing reference to 'self' for all identifiers.
165 """
Harald Welteb2edd142021-01-08 23:29:35 +0100166 sels = {}
167 if alias:
168 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100169 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100170 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100171 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100172 sels.update({self.name: self})
173 return sels
174
Harald Weltec91085e2022-02-10 18:05:45 +0100175 def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200176 """Return a dict of {'identifier': File} that is selectable from the current file.
177
178 Args:
179 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
180 If not specified, all selectables will be returned.
181 Returns:
182 dict containing all selectable items. Key is identifier (string), value
183 a reference to a CardFile (or derived class) instance.
184 """
Philipp Maier786f7812021-02-25 16:48:10 +0100185 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100186 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100187 if flags == [] or 'SELF' in flags:
188 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100189 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100190 if flags == [] or 'PARENT' in flags:
Harald Welte1e456572021-04-02 17:16:30 +0200191 if self.parent:
192 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100193 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100194 if flags == [] or 'MF' in flags:
195 mf = self.get_mf()
196 if mf:
Harald Weltec91085e2022-02-10 18:05:45 +0100197 sels.update(mf._get_self_selectables(flags=flags))
198 sels.update(mf.get_app_selectables(flags=flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100199 return sels
200
Harald Weltec91085e2022-02-10 18:05:45 +0100201 def get_selectable_names(self, flags=[]) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200202 """Return a dict of {'identifier': File} that is selectable from the current file.
203
204 Args:
205 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
206 If not specified, all selectables will be returned.
207 Returns:
Harald Welte1e456572021-04-02 17:16:30 +0200208 list containing all selectable names.
Harald Welteee3501f2021-04-02 13:00:18 +0200209 """
Philipp Maier786f7812021-02-25 16:48:10 +0100210 sels = self.get_selectables(flags)
Harald Welteb3d68c02022-01-21 15:31:29 +0100211 sel_keys = list(sels.keys())
212 sel_keys.sort()
213 return sel_keys
Harald Welteb2edd142021-01-08 23:29:35 +0100214
Harald Weltec91085e2022-02-10 18:05:45 +0100215 def decode_select_response(self, data_hex: str):
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100216 """Decode the response to a SELECT command.
217
218 Args:
Harald Weltec91085e2022-02-10 18:05:45 +0100219 data_hex: Hex string of the select response
220 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100221
Harald Weltec91085e2022-02-10 18:05:45 +0100222 # When the current file does not implement a custom select response decoder,
223 # we just ask the parent file to decode the select response. If this method
224 # is not overloaded by the current file we will again ask the parent file.
225 # This way we recursively travel up the file system tree until we hit a file
226 # that does implement a concrete decoder.
Harald Welte1e456572021-04-02 17:16:30 +0200227 if self.parent:
228 return self.parent.decode_select_response(data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +0100229
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100230 def get_profile(self):
231 """Get the profile associated with this file. If this file does not have any
232 profile assigned, try to find a file above (usually the MF) in the filesystem
233 hirarchy that has a profile assigned
234 """
235
236 # If we have a profile set, return it
237 if self.profile:
238 return self.profile
239
240 # Walk up recursively until we hit a parent that has a profile set
241 if self.parent:
242 return self.parent.get_profile()
243 return None
Harald Welteb2edd142021-01-08 23:29:35 +0100244
Harald Welte9170fbf2022-02-11 21:54:37 +0100245 def should_exist_for_services(self, services: List[int]):
246 """Assuming the provided list of activated services, should this file exist and be activated?."""
247 if self.service is None:
248 return None
249 elif isinstance(self.service, int):
250 # a single service determines the result
251 return self.service in services
252 elif isinstance(self.service, list):
253 # any of the services active -> true
254 for s in self.service:
255 if s in services:
256 return True
257 return False
258 elif isinstance(self.service, tuple):
259 # all of the services active -> true
260 for s in self.service:
261 if not s in services:
262 return False
263 return True
264 else:
265 raise ValueError("self.service must be either int or list or tuple")
266
Harald Weltec91085e2022-02-10 18:05:45 +0100267
Harald Welteb2edd142021-01-08 23:29:35 +0100268class CardDF(CardFile):
269 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100270
271 @with_default_category('DF/ADF Commands')
272 class ShellCommands(CommandSet):
273 def __init__(self):
274 super().__init__()
275
Harald Welteb2edd142021-01-08 23:29:35 +0100276 def __init__(self, **kwargs):
277 if not isinstance(self, CardADF):
278 if not 'fid' in kwargs:
279 raise TypeError('fid is mandatory for all DF')
280 super().__init__(**kwargs)
281 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100282 self.shell_commands = [self.ShellCommands()]
Harald Welte9170fbf2022-02-11 21:54:37 +0100283 # dict of CardFile affected by service(int), indexed by service
284 self.files_by_service = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100285
286 def __str__(self):
287 return "DF(%s)" % (super().__str__())
288
Harald Welte9170fbf2022-02-11 21:54:37 +0100289 def _add_file_services(self, child):
290 """Add a child (DF/EF) to the files_by_services of the parent."""
291 if not child.service:
292 return
293 if isinstance(child.service, int):
294 self.files_by_service.setdefault(child.service, []).append(child)
295 elif isinstance(child.service, list):
296 for service in child.service:
297 self.files_by_service.setdefault(service, []).append(child)
298 elif isinstance(child.service, tuple):
299 for service in child.service:
300 self.files_by_service.setdefault(service, []).append(child)
301 else:
302 raise ValueError
303
Harald Weltec91085e2022-02-10 18:05:45 +0100304 def add_file(self, child: CardFile, ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200305 """Add a child (DF/EF) to this DF.
306 Args:
307 child: The new DF/EF to be added
308 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
309 """
Harald Welteb2edd142021-01-08 23:29:35 +0100310 if not isinstance(child, CardFile):
311 raise TypeError("Expected a File instance")
Harald Weltec91085e2022-02-10 18:05:45 +0100312 if not is_hex(child.fid, minlen=4, maxlen=4):
Philipp Maier3aec8712021-03-09 21:49:01 +0100313 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100314 if child.name in CardFile.RESERVED_NAMES:
315 raise ValueError("File name %s is a reserved name" % (child.name))
316 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100317 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100318 if child.fid in self.children:
319 if ignore_existing:
320 return
Harald Weltec91085e2022-02-10 18:05:45 +0100321 raise ValueError(
322 "File with given fid %s already exists in %s" % (child.fid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100323 if self.lookup_file_by_sfid(child.sfid):
Harald Weltec91085e2022-02-10 18:05:45 +0100324 raise ValueError(
325 "File with given sfid %s already exists in %s" % (child.sfid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100326 if self.lookup_file_by_name(child.name):
327 if ignore_existing:
328 return
Harald Weltec91085e2022-02-10 18:05:45 +0100329 raise ValueError(
330 "File with given name %s already exists in %s" % (child.name, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100331 self.children[child.fid] = child
332 child.parent = self
Harald Welte419bb492022-02-12 21:39:35 +0100333 # update the service -> file relationship table
Harald Welte9170fbf2022-02-11 21:54:37 +0100334 self._add_file_services(child)
Harald Welte419bb492022-02-12 21:39:35 +0100335 if isinstance(child, CardDF):
336 for c in child.children.values():
337 self._add_file_services(c)
338 if isinstance(c, CardDF):
339 raise ValueError('TODO: implement recursive service -> file mapping')
Harald Welteb2edd142021-01-08 23:29:35 +0100340
Harald Weltec91085e2022-02-10 18:05:45 +0100341 def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200342 """Add a list of child (DF/EF) to this DF
343
344 Args:
345 children: List of new DF/EFs to be added
346 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
347 """
Harald Welteb2edd142021-01-08 23:29:35 +0100348 for child in children:
349 self.add_file(child, ignore_existing)
350
Harald Weltec91085e2022-02-10 18:05:45 +0100351 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200352 """Return a dict of {'identifier': File} that is selectable from the current DF.
353
354 Args:
355 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
356 If not specified, all selectables will be returned.
357 Returns:
358 dict containing all selectable items. Key is identifier (string), value
359 a reference to a CardFile (or derived class) instance.
360 """
Harald Welteb2edd142021-01-08 23:29:35 +0100361 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100362 sels = super().get_selectables(flags)
363 if flags == [] or 'FIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100364 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100365 if flags == [] or 'FNAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100366 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100367 return sels
368
Harald Weltec91085e2022-02-10 18:05:45 +0100369 def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200370 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100371 if name == None:
372 return None
373 for i in self.children.values():
374 if i.name and i.name == name:
375 return i
376 return None
377
Harald Weltec91085e2022-02-10 18:05:45 +0100378 def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200379 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100380 if sfid == None:
381 return None
382 for i in self.children.values():
Harald Welte1e456572021-04-02 17:16:30 +0200383 if i.sfid == int(str(sfid)):
Harald Welteb2edd142021-01-08 23:29:35 +0100384 return i
385 return None
386
Harald Weltec91085e2022-02-10 18:05:45 +0100387 def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200388 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100389 if fid in self.children:
390 return self.children[fid]
391 return None
392
393
394class CardMF(CardDF):
395 """MF (Master File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100396
Harald Welteb2edd142021-01-08 23:29:35 +0100397 def __init__(self, **kwargs):
398 # can be overridden; use setdefault
399 kwargs.setdefault('fid', '3f00')
400 kwargs.setdefault('name', 'MF')
401 kwargs.setdefault('desc', 'Master File (directory root)')
402 # cannot be overridden; use assignment
403 kwargs['parent'] = self
404 super().__init__(**kwargs)
405 self.applications = dict()
406
407 def __str__(self):
408 return "MF(%s)" % (self.fid)
409
Harald Weltec91085e2022-02-10 18:05:45 +0100410 def add_application_df(self, app: 'CardADF'):
Harald Welte5ce35242021-04-02 20:27:05 +0200411 """Add an Application to the MF"""
Harald Welteb2edd142021-01-08 23:29:35 +0100412 if not isinstance(app, CardADF):
413 raise TypeError("Expected an ADF instance")
414 if app.aid in self.applications:
415 raise ValueError("AID %s already exists" % (app.aid))
416 self.applications[app.aid] = app
Harald Weltec91085e2022-02-10 18:05:45 +0100417 app.parent = self
Harald Welteb2edd142021-01-08 23:29:35 +0100418
419 def get_app_names(self):
420 """Get list of completions (AID names)"""
Harald Welted53918c2022-02-12 18:20:49 +0100421 return list(self.applications.values())
Harald Welteb2edd142021-01-08 23:29:35 +0100422
Harald Weltec91085e2022-02-10 18:05:45 +0100423 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200424 """Return a dict of {'identifier': File} that is selectable from the current DF.
425
426 Args:
427 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
428 If not specified, all selectables will be returned.
429 Returns:
430 dict containing all selectable items. Key is identifier (string), value
431 a reference to a CardFile (or derived class) instance.
432 """
Philipp Maier786f7812021-02-25 16:48:10 +0100433 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100434 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100435 return sels
436
Harald Weltec91085e2022-02-10 18:05:45 +0100437 def get_app_selectables(self, flags=[]) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100438 """Get applications by AID + name"""
439 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100440 if flags == [] or 'AIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100441 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100442 if flags == [] or 'ANAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100443 sels.update(
444 {x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100445 return sels
446
Harald Weltec9752512022-02-11 16:31:15 +0100447 def decode_select_response(self, data_hex: Optional[str]) -> object:
Harald Welteee3501f2021-04-02 13:00:18 +0200448 """Decode the response to a SELECT command.
449
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100450 This is the fall-back method which automatically defers to the standard decoding
451 method defined by the card profile. When no profile is set, then no decoding is
Harald Weltec91085e2022-02-10 18:05:45 +0100452 performed. Specific derived classes (usually ADF) can overload this method to
453 install specific decoding.
Harald Welteee3501f2021-04-02 13:00:18 +0200454 """
Harald Welteb2edd142021-01-08 23:29:35 +0100455
Harald Weltec9752512022-02-11 16:31:15 +0100456 if not data_hex:
457 return data_hex
458
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100459 profile = self.get_profile()
Harald Welteb2edd142021-01-08 23:29:35 +0100460
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100461 if profile:
462 return profile.decode_select_response(data_hex)
463 else:
464 return data_hex
Harald Welteb2edd142021-01-08 23:29:35 +0100465
Harald Weltec91085e2022-02-10 18:05:45 +0100466
Harald Welteb2edd142021-01-08 23:29:35 +0100467class CardADF(CardDF):
468 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100469
470 def __init__(self, aid: str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100471 super().__init__(**kwargs)
Harald Welte5ce35242021-04-02 20:27:05 +0200472 # reference to CardApplication may be set from CardApplication constructor
Harald Weltefe8a7442021-04-10 11:51:54 +0200473 self.application = None # type: Optional[CardApplication]
Harald Welteb2edd142021-01-08 23:29:35 +0100474 self.aid = aid # Application Identifier
Harald Welte1e456572021-04-02 17:16:30 +0200475 mf = self.get_mf()
476 if mf:
Harald Welte5ce35242021-04-02 20:27:05 +0200477 mf.add_application_df(self)
Harald Welteb2edd142021-01-08 23:29:35 +0100478
479 def __str__(self):
480 return "ADF(%s)" % (self.aid)
481
Harald Weltec91085e2022-02-10 18:05:45 +0100482 def _path_element(self, prefer_name: bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100483 if self.name and prefer_name:
484 return self.name
485 else:
486 return self.aid
487
488
489class CardEF(CardFile):
490 """EF (Entry File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100491
Harald Welteb2edd142021-01-08 23:29:35 +0100492 def __init__(self, *, fid, **kwargs):
493 kwargs['fid'] = fid
494 super().__init__(**kwargs)
495
496 def __str__(self):
497 return "EF(%s)" % (super().__str__())
498
Harald Weltec91085e2022-02-10 18:05:45 +0100499 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200500 """Return a dict of {'identifier': File} that is selectable from the current DF.
501
502 Args:
503 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
504 If not specified, all selectables will be returned.
505 Returns:
506 dict containing all selectable items. Key is identifier (string), value
507 a reference to a CardFile (or derived class) instance.
508 """
Harald Weltec91085e2022-02-10 18:05:45 +0100509 # global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100510 sels = super().get_selectables(flags)
Harald Weltec91085e2022-02-10 18:05:45 +0100511 sels.update(
512 {x.name: x for x in self.parent.children.values() if x != self})
Harald Welteb2edd142021-01-08 23:29:35 +0100513 return sels
514
515
516class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200517 """Transparent EF (Entry File) in the smart card filesystem.
518
519 A Transparent EF is a binary file with no formal structure. This is contrary to
520 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100521
522 @with_default_category('Transparent EF Commands')
523 class ShellCommands(CommandSet):
Harald Weltec9cdce32021-04-11 10:28:28 +0200524 """Shell commands specific for transparent EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100525
Harald Welteb2edd142021-01-08 23:29:35 +0100526 def __init__(self):
527 super().__init__()
528
529 read_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100530 read_bin_parser.add_argument(
531 '--offset', type=int, default=0, help='Byte offset for start of read')
532 read_bin_parser.add_argument(
533 '--length', type=int, help='Number of bytes to read')
534
Harald Welteb2edd142021-01-08 23:29:35 +0100535 @cmd2.with_argparser(read_bin_parser)
536 def do_read_binary(self, opts):
537 """Read binary data from a transparent EF"""
538 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
539 self._cmd.poutput(data)
540
Harald Weltebcad86c2021-04-06 20:08:39 +0200541 read_bin_dec_parser = argparse.ArgumentParser()
542 read_bin_dec_parser.add_argument('--oneline', action='store_true',
543 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100544
Harald Weltebcad86c2021-04-06 20:08:39 +0200545 @cmd2.with_argparser(read_bin_dec_parser)
Harald Welteb2edd142021-01-08 23:29:35 +0100546 def do_read_binary_decoded(self, opts):
547 """Read + decode data from a transparent EF"""
548 (data, sw) = self._cmd.rs.read_binary_dec()
Harald Welte1748b932021-04-06 21:12:25 +0200549 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100550
551 upd_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100552 upd_bin_parser.add_argument(
553 '--offset', type=int, default=0, help='Byte offset for start of read')
554 upd_bin_parser.add_argument(
555 'data', help='Data bytes (hex format) to write')
556
Harald Welteb2edd142021-01-08 23:29:35 +0100557 @cmd2.with_argparser(upd_bin_parser)
558 def do_update_binary(self, opts):
559 """Update (Write) data of a transparent EF"""
560 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100561 if data:
562 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100563
564 upd_bin_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100565 upd_bin_dec_parser.add_argument(
566 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200567 upd_bin_dec_parser.add_argument('--json-path', type=str,
568 help='JSON path to modify specific element of file only')
Harald Weltec91085e2022-02-10 18:05:45 +0100569
Harald Welteb2edd142021-01-08 23:29:35 +0100570 @cmd2.with_argparser(upd_bin_dec_parser)
571 def do_update_binary_decoded(self, opts):
572 """Encode + Update (Write) data of a transparent EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200573 if opts.json_path:
574 (data_json, sw) = self._cmd.rs.read_binary_dec()
Harald Weltec91085e2022-02-10 18:05:45 +0100575 js_path_modify(data_json, opts.json_path,
576 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200577 else:
578 data_json = json.loads(opts.data)
Harald Welteb2edd142021-01-08 23:29:35 +0100579 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100580 if data:
Harald Welte1748b932021-04-06 21:12:25 +0200581 self._cmd.poutput_json(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100582
Harald Welte4145d3c2021-04-08 20:34:13 +0200583 def do_edit_binary_decoded(self, opts):
584 """Edit the JSON representation of the EF contents in an editor."""
585 (orig_json, sw) = self._cmd.rs.read_binary_dec()
586 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
587 filename = '%s/file' % dirname
588 # write existing data as JSON to file
589 with open(filename, 'w') as text_file:
590 json.dump(orig_json, text_file, indent=4)
591 # run a text editor
592 self._cmd._run_editor(filename)
593 with open(filename, 'r') as text_file:
594 edited_json = json.load(text_file)
595 if edited_json == orig_json:
596 self._cmd.poutput("Data not modified, skipping write")
597 else:
598 (data, sw) = self._cmd.rs.update_binary_dec(edited_json)
599 if data:
600 self._cmd.poutput_json(data)
601
Harald Weltec91085e2022-02-10 18:05:45 +0100602 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100603 size={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200604 """
605 Args:
606 fid : File Identifier (4 hex digits)
607 sfid : Short File Identifier (2 hex digits, optional)
608 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200609 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200610 parent : Parent CardFile object within filesystem hierarchy
611 size : tuple of (minimum_size, recommended_size)
612 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100613 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200614 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200615 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100616 self.size = size
617 self.shell_commands = [self.ShellCommands()]
618
Harald Weltec91085e2022-02-10 18:05:45 +0100619 def decode_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200620 """Decode raw (binary) data into abstract representation.
621
622 A derived class would typically provide a _decode_bin() or _decode_hex() method
623 for implementing this specifically for the given file. This function checks which
624 of the method exists, add calls them (with conversion, as needed).
625
626 Args:
627 raw_bin_data : binary encoded data
628 Returns:
629 abstract_data; dict representing the decoded data
630 """
Harald Welteb2edd142021-01-08 23:29:35 +0100631 method = getattr(self, '_decode_bin', None)
632 if callable(method):
633 return method(raw_bin_data)
634 method = getattr(self, '_decode_hex', None)
635 if callable(method):
636 return method(b2h(raw_bin_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200637 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200638 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200639 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100640 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100641 t.from_tlv(raw_bin_data)
642 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100643 return {'raw': raw_bin_data.hex()}
644
Harald Weltec91085e2022-02-10 18:05:45 +0100645 def decode_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200646 """Decode raw (hex string) data into abstract representation.
647
648 A derived class would typically provide a _decode_bin() or _decode_hex() method
649 for implementing this specifically for the given file. This function checks which
650 of the method exists, add calls them (with conversion, as needed).
651
652 Args:
653 raw_hex_data : hex-encoded data
654 Returns:
655 abstract_data; dict representing the decoded data
656 """
Harald Welteb2edd142021-01-08 23:29:35 +0100657 method = getattr(self, '_decode_hex', None)
658 if callable(method):
659 return method(raw_hex_data)
660 raw_bin_data = h2b(raw_hex_data)
661 method = getattr(self, '_decode_bin', None)
662 if callable(method):
663 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200664 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200665 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200666 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100667 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100668 t.from_tlv(raw_bin_data)
669 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100670 return {'raw': raw_bin_data.hex()}
671
Harald Weltec91085e2022-02-10 18:05:45 +0100672 def encode_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200673 """Encode abstract representation into raw (binary) data.
674
675 A derived class would typically provide an _encode_bin() or _encode_hex() method
676 for implementing this specifically for the given file. This function checks which
677 of the method exists, add calls them (with conversion, as needed).
678
679 Args:
680 abstract_data : dict representing the decoded data
681 Returns:
682 binary encoded data
683 """
Harald Welteb2edd142021-01-08 23:29:35 +0100684 method = getattr(self, '_encode_bin', None)
685 if callable(method):
686 return method(abstract_data)
687 method = getattr(self, '_encode_hex', None)
688 if callable(method):
689 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200690 if self._construct:
691 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200692 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100693 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100694 t.from_dict(abstract_data)
695 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100696 raise NotImplementedError(
697 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100698
Harald Weltec91085e2022-02-10 18:05:45 +0100699 def encode_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200700 """Encode abstract representation into raw (hex string) data.
701
702 A derived class would typically provide an _encode_bin() or _encode_hex() method
703 for implementing this specifically for the given file. This function checks which
704 of the method exists, add calls them (with conversion, as needed).
705
706 Args:
707 abstract_data : dict representing the decoded data
708 Returns:
709 hex string encoded data
710 """
Harald Welteb2edd142021-01-08 23:29:35 +0100711 method = getattr(self, '_encode_hex', None)
712 if callable(method):
713 return method(abstract_data)
714 method = getattr(self, '_encode_bin', None)
715 if callable(method):
716 raw_bin_data = method(abstract_data)
717 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200718 if self._construct:
719 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200720 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100721 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100722 t.from_dict(abstract_data)
723 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100724 raise NotImplementedError(
725 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100726
727
728class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200729 """Linear Fixed EF (Entry File) in the smart card filesystem.
730
731 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
732 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100733
734 @with_default_category('Linear Fixed EF Commands')
735 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200736 """Shell commands specific for Linear Fixed EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100737
Harald Welte9170fbf2022-02-11 21:54:37 +0100738 def __init__(self, **kwargs):
739 super().__init__(**kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100740
741 read_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100742 read_rec_parser.add_argument(
743 'record_nr', type=int, help='Number of record to be read')
744 read_rec_parser.add_argument(
745 '--count', type=int, default=1, help='Number of records to be read, beginning at record_nr')
746
Harald Welteb2edd142021-01-08 23:29:35 +0100747 @cmd2.with_argparser(read_rec_parser)
748 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100749 """Read one or multiple records from a record-oriented EF"""
750 for r in range(opts.count):
751 recnr = opts.record_nr + r
752 (data, sw) = self._cmd.rs.read_record(recnr)
753 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100754 recstr = str(data)
Philipp Maier41555732021-02-25 16:52:08 +0100755 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100756 recstr = "(empty)"
Philipp Maier41555732021-02-25 16:52:08 +0100757 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100758
759 read_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100760 read_rec_dec_parser.add_argument(
761 'record_nr', type=int, help='Number of record to be read')
Harald Weltebcad86c2021-04-06 20:08:39 +0200762 read_rec_dec_parser.add_argument('--oneline', action='store_true',
763 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100764
Harald Welteb2edd142021-01-08 23:29:35 +0100765 @cmd2.with_argparser(read_rec_dec_parser)
766 def do_read_record_decoded(self, opts):
767 """Read + decode a record from a record-oriented EF"""
768 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Welte1748b932021-04-06 21:12:25 +0200769 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100770
Harald Welte850b72a2021-04-07 09:33:03 +0200771 read_recs_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100772
Harald Welte850b72a2021-04-07 09:33:03 +0200773 @cmd2.with_argparser(read_recs_parser)
774 def do_read_records(self, opts):
775 """Read all records from a record-oriented EF"""
776 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
777 for recnr in range(1, 1 + num_of_rec):
778 (data, sw) = self._cmd.rs.read_record(recnr)
779 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100780 recstr = str(data)
Harald Welte850b72a2021-04-07 09:33:03 +0200781 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100782 recstr = "(empty)"
Harald Welte850b72a2021-04-07 09:33:03 +0200783 self._cmd.poutput("%03d %s" % (recnr, recstr))
784
785 read_recs_dec_parser = argparse.ArgumentParser()
786 read_recs_dec_parser.add_argument('--oneline', action='store_true',
Harald Weltec91085e2022-02-10 18:05:45 +0100787 help='No JSON pretty-printing, dump as a single line')
788
Harald Welte850b72a2021-04-07 09:33:03 +0200789 @cmd2.with_argparser(read_recs_dec_parser)
790 def do_read_records_decoded(self, opts):
791 """Read + decode all records from a record-oriented EF"""
792 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
793 # collect all results in list so they are rendered as JSON list when printing
794 data_list = []
795 for recnr in range(1, 1 + num_of_rec):
796 (data, sw) = self._cmd.rs.read_record_dec(recnr)
797 data_list.append(data)
798 self._cmd.poutput_json(data_list, opts.oneline)
799
Harald Welteb2edd142021-01-08 23:29:35 +0100800 upd_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100801 upd_rec_parser.add_argument(
802 'record_nr', type=int, help='Number of record to be read')
803 upd_rec_parser.add_argument(
804 'data', help='Data bytes (hex format) to write')
805
Harald Welteb2edd142021-01-08 23:29:35 +0100806 @cmd2.with_argparser(upd_rec_parser)
807 def do_update_record(self, opts):
808 """Update (write) data to a record-oriented EF"""
809 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100810 if data:
811 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100812
813 upd_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100814 upd_rec_dec_parser.add_argument(
815 'record_nr', type=int, help='Number of record to be read')
816 upd_rec_dec_parser.add_argument(
817 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200818 upd_rec_dec_parser.add_argument('--json-path', type=str,
819 help='JSON path to modify specific element of record only')
Harald Weltec91085e2022-02-10 18:05:45 +0100820
Harald Welteb2edd142021-01-08 23:29:35 +0100821 @cmd2.with_argparser(upd_rec_dec_parser)
822 def do_update_record_decoded(self, opts):
823 """Encode + Update (write) data to a record-oriented EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200824 if opts.json_path:
825 (data_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Weltec91085e2022-02-10 18:05:45 +0100826 js_path_modify(data_json, opts.json_path,
827 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200828 else:
829 data_json = json.loads(opts.data)
Harald Weltec91085e2022-02-10 18:05:45 +0100830 (data, sw) = self._cmd.rs.update_record_dec(
831 opts.record_nr, data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100832 if data:
833 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100834
Harald Welte4145d3c2021-04-08 20:34:13 +0200835 edit_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100836 edit_rec_dec_parser.add_argument(
837 'record_nr', type=int, help='Number of record to be edited')
838
Harald Welte4145d3c2021-04-08 20:34:13 +0200839 @cmd2.with_argparser(edit_rec_dec_parser)
840 def do_edit_record_decoded(self, opts):
841 """Edit the JSON representation of one record in an editor."""
842 (orig_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Vadim Yanitskiy895fa6f2021-05-02 02:36:44 +0200843 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
Harald Welte4145d3c2021-04-08 20:34:13 +0200844 filename = '%s/file' % dirname
845 # write existing data as JSON to file
846 with open(filename, 'w') as text_file:
847 json.dump(orig_json, text_file, indent=4)
848 # run a text editor
849 self._cmd._run_editor(filename)
850 with open(filename, 'r') as text_file:
851 edited_json = json.load(text_file)
852 if edited_json == orig_json:
853 self._cmd.poutput("Data not modified, skipping write")
854 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100855 (data, sw) = self._cmd.rs.update_record_dec(
856 opts.record_nr, edited_json)
Harald Welte4145d3c2021-04-08 20:34:13 +0200857 if data:
858 self._cmd.poutput_json(data)
Harald Welte4145d3c2021-04-08 20:34:13 +0200859
Harald Weltec91085e2022-02-10 18:05:45 +0100860 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100861 parent: Optional[CardDF] = None, rec_len={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200862 """
863 Args:
864 fid : File Identifier (4 hex digits)
865 sfid : Short File Identifier (2 hex digits, optional)
866 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200867 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200868 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier0adabf62021-04-20 22:36:41 +0200869 rec_len : set of {minimum_length, recommended_length}
Harald Welteee3501f2021-04-02 13:00:18 +0200870 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100871 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100872 self.rec_len = rec_len
873 self.shell_commands = [self.ShellCommands()]
Harald Welte2db5cfb2021-04-10 19:05:37 +0200874 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200875 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100876
Harald Weltec91085e2022-02-10 18:05:45 +0100877 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200878 """Decode raw (hex string) data into abstract representation.
879
880 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
881 method for implementing this specifically for the given file. This function checks which
882 of the method exists, add calls them (with conversion, as needed).
883
884 Args:
885 raw_hex_data : hex-encoded data
886 Returns:
887 abstract_data; dict representing the decoded data
888 """
Harald Welteb2edd142021-01-08 23:29:35 +0100889 method = getattr(self, '_decode_record_hex', None)
890 if callable(method):
891 return method(raw_hex_data)
892 raw_bin_data = h2b(raw_hex_data)
893 method = getattr(self, '_decode_record_bin', None)
894 if callable(method):
895 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200896 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200897 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200898 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100899 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100900 t.from_tlv(raw_bin_data)
901 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100902 return {'raw': raw_bin_data.hex()}
903
Harald Weltec91085e2022-02-10 18:05:45 +0100904 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200905 """Decode raw (binary) data into abstract representation.
906
907 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
908 method for implementing this specifically for the given file. This function checks which
909 of the method exists, add calls them (with conversion, as needed).
910
911 Args:
912 raw_bin_data : binary encoded data
913 Returns:
914 abstract_data; dict representing the decoded data
915 """
Harald Welteb2edd142021-01-08 23:29:35 +0100916 method = getattr(self, '_decode_record_bin', None)
917 if callable(method):
918 return method(raw_bin_data)
919 raw_hex_data = b2h(raw_bin_data)
920 method = getattr(self, '_decode_record_hex', None)
921 if callable(method):
922 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200923 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200924 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200925 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100926 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100927 t.from_tlv(raw_bin_data)
928 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100929 return {'raw': raw_hex_data}
930
Harald Weltec91085e2022-02-10 18:05:45 +0100931 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200932 """Encode abstract representation into raw (hex string) data.
933
934 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
935 method for implementing this specifically for the given file. This function checks which
936 of the method exists, add calls them (with conversion, as needed).
937
938 Args:
939 abstract_data : dict representing the decoded data
940 Returns:
941 hex string encoded data
942 """
Harald Welteb2edd142021-01-08 23:29:35 +0100943 method = getattr(self, '_encode_record_hex', None)
944 if callable(method):
945 return method(abstract_data)
946 method = getattr(self, '_encode_record_bin', None)
947 if callable(method):
948 raw_bin_data = method(abstract_data)
Harald Welte1e456572021-04-02 17:16:30 +0200949 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200950 if self._construct:
951 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200952 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100953 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100954 t.from_dict(abstract_data)
955 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100956 raise NotImplementedError(
957 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100958
Harald Weltec91085e2022-02-10 18:05:45 +0100959 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200960 """Encode abstract representation into raw (binary) data.
961
962 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
963 method for implementing this specifically for the given file. This function checks which
964 of the method exists, add calls them (with conversion, as needed).
965
966 Args:
967 abstract_data : dict representing the decoded data
968 Returns:
969 binary encoded data
970 """
Harald Welteb2edd142021-01-08 23:29:35 +0100971 method = getattr(self, '_encode_record_bin', None)
972 if callable(method):
973 return method(abstract_data)
974 method = getattr(self, '_encode_record_hex', None)
975 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +0200976 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200977 if self._construct:
978 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200979 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100980 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100981 t.from_dict(abstract_data)
982 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100983 raise NotImplementedError(
984 "%s encoder not yet implemented. Patches welcome." % self)
985
Harald Welteb2edd142021-01-08 23:29:35 +0100986
987class CyclicEF(LinFixedEF):
988 """Cyclic EF (Entry File) in the smart card filesystem"""
989 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Weltec91085e2022-02-10 18:05:45 +0100990
991 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100992 rec_len={1, None}, **kwargs):
993 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100994
Harald Welteb2edd142021-01-08 23:29:35 +0100995
996class TransRecEF(TransparentEF):
997 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +0200998
Harald Welteb2edd142021-01-08 23:29:35 +0100999 These are the real odd-balls and mostly look like mistakes in the specification:
1000 Specified as 'transparent' EF, but actually containing several fixed-length records
1001 inside.
1002 We add a special class for those, so the user only has to provide encoder/decoder functions
1003 for a record, while this class takes care of split / merge of records.
1004 """
Harald Weltec91085e2022-02-10 18:05:45 +01001005
1006 def __init__(self, fid: str, rec_len: int, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +01001007 parent: Optional[CardDF] = None, size={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +02001008 """
1009 Args:
1010 fid : File Identifier (4 hex digits)
1011 sfid : Short File Identifier (2 hex digits, optional)
Harald Weltec9cdce32021-04-11 10:28:28 +02001012 name : Brief name of the file, like EF_ICCID
1013 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +02001014 parent : Parent CardFile object within filesystem hierarchy
1015 rec_len : Length of the fixed-length records within transparent EF
1016 size : tuple of (minimum_size, recommended_size)
1017 """
Harald Welte9170fbf2022-02-11 21:54:37 +01001018 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +01001019 self.rec_len = rec_len
1020
Harald Weltec91085e2022-02-10 18:05:45 +01001021 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +02001022 """Decode raw (hex string) data into abstract representation.
1023
1024 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
1025 method for implementing this specifically for the given file. This function checks which
1026 of the method exists, add calls them (with conversion, as needed).
1027
1028 Args:
1029 raw_hex_data : hex-encoded data
1030 Returns:
1031 abstract_data; dict representing the decoded data
1032 """
Harald Welteb2edd142021-01-08 23:29:35 +01001033 method = getattr(self, '_decode_record_hex', None)
1034 if callable(method):
1035 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001036 raw_bin_data = h2b(raw_hex_data)
Harald Welteb2edd142021-01-08 23:29:35 +01001037 method = getattr(self, '_decode_record_bin', None)
1038 if callable(method):
Harald Welteb2edd142021-01-08 23:29:35 +01001039 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001040 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +02001041 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +02001042 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001043 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001044 t.from_tlv(raw_bin_data)
1045 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001046 return {'raw': raw_hex_data}
1047
Harald Weltec91085e2022-02-10 18:05:45 +01001048 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +02001049 """Decode raw (binary) data into abstract representation.
1050
1051 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
1052 method for implementing this specifically for the given file. This function checks which
1053 of the method exists, add calls them (with conversion, as needed).
1054
1055 Args:
1056 raw_bin_data : binary encoded data
1057 Returns:
1058 abstract_data; dict representing the decoded data
1059 """
Harald Welteb2edd142021-01-08 23:29:35 +01001060 method = getattr(self, '_decode_record_bin', None)
1061 if callable(method):
1062 return method(raw_bin_data)
1063 raw_hex_data = b2h(raw_bin_data)
1064 method = getattr(self, '_decode_record_hex', None)
1065 if callable(method):
1066 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001067 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +02001068 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +02001069 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001070 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001071 t.from_tlv(raw_bin_data)
1072 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001073 return {'raw': raw_hex_data}
1074
Harald Weltec91085e2022-02-10 18:05:45 +01001075 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +02001076 """Encode abstract representation into raw (hex string) data.
1077
1078 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1079 method for implementing this specifically for the given file. This function checks which
1080 of the method exists, add calls them (with conversion, as needed).
1081
1082 Args:
1083 abstract_data : dict representing the decoded data
1084 Returns:
1085 hex string encoded data
1086 """
Harald Welteb2edd142021-01-08 23:29:35 +01001087 method = getattr(self, '_encode_record_hex', None)
1088 if callable(method):
1089 return method(abstract_data)
1090 method = getattr(self, '_encode_record_bin', None)
1091 if callable(method):
Harald Welte1e456572021-04-02 17:16:30 +02001092 return b2h(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001093 if self._construct:
1094 return b2h(filter_dict(self._construct.build(abstract_data)))
Harald Weltefb506212021-05-29 21:28:24 +02001095 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001096 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001097 t.from_dict(abstract_data)
1098 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +01001099 raise NotImplementedError(
1100 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001101
Harald Weltec91085e2022-02-10 18:05:45 +01001102 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +02001103 """Encode abstract representation into raw (binary) data.
1104
1105 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1106 method for implementing this specifically for the given file. This function checks which
1107 of the method exists, add calls them (with conversion, as needed).
1108
1109 Args:
1110 abstract_data : dict representing the decoded data
1111 Returns:
1112 binary encoded data
1113 """
Harald Welteb2edd142021-01-08 23:29:35 +01001114 method = getattr(self, '_encode_record_bin', None)
1115 if callable(method):
1116 return method(abstract_data)
1117 method = getattr(self, '_encode_record_hex', None)
1118 if callable(method):
1119 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001120 if self._construct:
1121 return filter_dict(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +02001122 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001123 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001124 t.from_dict(abstract_data)
1125 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +01001126 raise NotImplementedError(
1127 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001128
Harald Weltec91085e2022-02-10 18:05:45 +01001129 def _decode_bin(self, raw_bin_data: bytearray):
1130 chunks = [raw_bin_data[i:i+self.rec_len]
1131 for i in range(0, len(raw_bin_data), self.rec_len)]
Harald Welteb2edd142021-01-08 23:29:35 +01001132 return [self.decode_record_bin(x) for x in chunks]
1133
Harald Welteee3501f2021-04-02 13:00:18 +02001134 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +01001135 chunks = [self.encode_record_bin(x) for x in abstract_data]
1136 # FIXME: pad to file size
1137 return b''.join(chunks)
1138
1139
Harald Welte917d98c2021-04-21 11:51:25 +02001140class BerTlvEF(CardEF):
Harald Welte27881622021-04-21 11:16:31 +02001141 """BER-TLV EF (Entry File) in the smart card filesystem.
1142 A BER-TLV EF is a binary file with a BER (Basic Encoding Rules) TLV structure
Harald Welteb2edd142021-01-08 23:29:35 +01001143
Harald Welte27881622021-04-21 11:16:31 +02001144 NOTE: We currently don't really support those, this class is simply a wrapper
1145 around TransparentEF as a place-holder, so we can already define EFs of BER-TLV
1146 type without fully supporting them."""
Harald Welteb2edd142021-01-08 23:29:35 +01001147
Harald Welte917d98c2021-04-21 11:51:25 +02001148 @with_default_category('BER-TLV EF Commands')
1149 class ShellCommands(CommandSet):
1150 """Shell commands specific for BER-TLV EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +01001151
Harald Welte917d98c2021-04-21 11:51:25 +02001152 def __init__(self):
1153 super().__init__()
1154
1155 retrieve_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001156 retrieve_data_parser.add_argument(
1157 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve')
1158
Harald Welte917d98c2021-04-21 11:51:25 +02001159 @cmd2.with_argparser(retrieve_data_parser)
1160 def do_retrieve_data(self, opts):
1161 """Retrieve (Read) data from a BER-TLV EF"""
1162 (data, sw) = self._cmd.rs.retrieve_data(opts.tag)
1163 self._cmd.poutput(data)
1164
1165 def do_retrieve_tags(self, opts):
1166 """List tags available in a given BER-TLV EF"""
1167 tags = self._cmd.rs.retrieve_tags()
1168 self._cmd.poutput(tags)
1169
1170 set_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001171 set_data_parser.add_argument(
1172 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1173 set_data_parser.add_argument(
1174 'data', help='Data bytes (hex format) to write')
1175
Harald Welte917d98c2021-04-21 11:51:25 +02001176 @cmd2.with_argparser(set_data_parser)
1177 def do_set_data(self, opts):
1178 """Set (Write) data for a given tag in a BER-TLV EF"""
1179 (data, sw) = self._cmd.rs.set_data(opts.tag, opts.data)
1180 if data:
1181 self._cmd.poutput(data)
1182
1183 del_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001184 del_data_parser.add_argument(
1185 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1186
Harald Welte917d98c2021-04-21 11:51:25 +02001187 @cmd2.with_argparser(del_data_parser)
1188 def do_delete_data(self, opts):
1189 """Delete data for a given tag in a BER-TLV EF"""
1190 (data, sw) = self._cmd.rs.set_data(opts.tag, None)
1191 if data:
1192 self._cmd.poutput(data)
1193
Harald Weltec91085e2022-02-10 18:05:45 +01001194 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +01001195 size={1, None}, **kwargs):
Harald Welte917d98c2021-04-21 11:51:25 +02001196 """
1197 Args:
1198 fid : File Identifier (4 hex digits)
1199 sfid : Short File Identifier (2 hex digits, optional)
1200 name : Brief name of the file, lik EF_ICCID
1201 desc : Description of the file
1202 parent : Parent CardFile object within filesystem hierarchy
1203 size : tuple of (minimum_size, recommended_size)
1204 """
Harald Welte9170fbf2022-02-11 21:54:37 +01001205 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welte917d98c2021-04-21 11:51:25 +02001206 self._construct = None
1207 self.size = size
1208 self.shell_commands = [self.ShellCommands()]
1209
Harald Welteb2edd142021-01-08 23:29:35 +01001210
1211class RuntimeState(object):
1212 """Represent the runtime state of a session with a card."""
Harald Weltec91085e2022-02-10 18:05:45 +01001213
1214 def __init__(self, card, profile: 'CardProfile'):
Harald Welteee3501f2021-04-02 13:00:18 +02001215 """
1216 Args:
1217 card : pysim.cards.Card instance
1218 profile : CardProfile instance
1219 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +01001220 self.mf = CardMF(profile=profile)
Harald Welteb2edd142021-01-08 23:29:35 +01001221 self.card = card
Harald Weltec91085e2022-02-10 18:05:45 +01001222 self.selected_file = self.mf # type: CardDF
Harald Welteb2edd142021-01-08 23:29:35 +01001223 self.profile = profile
Philipp Maier51cad0d2021-11-08 15:45:10 +01001224
1225 # make sure the class and selection control bytes, which are specified
1226 # by the card profile are used
Harald Weltec91085e2022-02-10 18:05:45 +01001227 self.card.set_apdu_parameter(
1228 cla=self.profile.cla, sel_ctrl=self.profile.sel_ctrl)
Philipp Maier51cad0d2021-11-08 15:45:10 +01001229
Harald Welte5ce35242021-04-02 20:27:05 +02001230 # add application ADFs + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001231 apps = self._match_applications()
1232 for a in apps:
Harald Welte5ce35242021-04-02 20:27:05 +02001233 if a.adf:
1234 self.mf.add_application_df(a.adf)
Harald Welteb2edd142021-01-08 23:29:35 +01001235 for f in self.profile.files_in_mf:
1236 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +01001237 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +01001238
Philipp Maier4e2e1d92021-11-08 15:36:01 +01001239 # make sure that when the runtime state is created, the card is also
1240 # in a defined state.
1241 self.reset()
1242
Philipp Maier1e896f32021-03-10 17:02:53 +01001243 def _match_applications(self):
1244 """match the applications from the profile with applications on the card"""
1245 apps_profile = self.profile.applications
Philipp Maierd454fe72021-11-08 15:32:23 +01001246
1247 # When the profile does not feature any applications, then we are done already
1248 if not apps_profile:
1249 return []
1250
1251 # Read AIDs from card and match them against the applications defined by the
1252 # card profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001253 aids_card = self.card.read_aids()
1254 apps_taken = []
1255 if aids_card:
1256 aids_taken = []
1257 print("AIDs on card:")
1258 for a in aids_card:
1259 for f in apps_profile:
1260 if f.aid in a:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001261 print(" %s: %s (EF.DIR)" % (f.name, a))
Philipp Maier1e896f32021-03-10 17:02:53 +01001262 aids_taken.append(a)
1263 apps_taken.append(f)
1264 aids_unknown = set(aids_card) - set(aids_taken)
1265 for a in aids_unknown:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001266 print(" unknown: %s (EF.DIR)" % a)
Philipp Maier1e896f32021-03-10 17:02:53 +01001267 else:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001268 print("warning: EF.DIR seems to be empty!")
1269
1270 # Some card applications may not be registered in EF.DIR, we will actively
1271 # probe for those applications
1272 for f in set(apps_profile) - set(apps_taken):
Bjoern Riemerda57ef12022-01-18 15:38:14 +01001273 try:
1274 data, sw = self.card.select_adf_by_aid(f.aid)
1275 if sw == "9000":
1276 print(" %s: %s" % (f.name, f.aid))
1277 apps_taken.append(f)
1278 except SwMatchError:
1279 pass
Philipp Maier1e896f32021-03-10 17:02:53 +01001280 return apps_taken
1281
Harald Weltedaf2b392021-05-03 23:17:29 +02001282 def reset(self, cmd_app=None) -> Hexstr:
1283 """Perform physical card reset and obtain ATR.
1284 Args:
1285 cmd_app : Command Application State (for unregistering old file commands)
1286 """
Philipp Maier946226a2021-10-29 18:31:03 +02001287 atr = i2h(self.card.reset())
Harald Weltedaf2b392021-05-03 23:17:29 +02001288 # select MF to reset internal state and to verify card really works
1289 self.select('MF', cmd_app)
1290 return atr
1291
Harald Welteee3501f2021-04-02 13:00:18 +02001292 def get_cwd(self) -> CardDF:
1293 """Obtain the current working directory.
1294
1295 Returns:
1296 CardDF instance
1297 """
Harald Welteb2edd142021-01-08 23:29:35 +01001298 if isinstance(self.selected_file, CardDF):
1299 return self.selected_file
1300 else:
1301 return self.selected_file.parent
1302
Harald Welte5ce35242021-04-02 20:27:05 +02001303 def get_application_df(self) -> Optional[CardADF]:
1304 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +02001305
1306 Returns:
1307 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +01001308 # iterate upwards from selected file; check if any is an ADF
1309 node = self.selected_file
1310 while node.parent != node:
1311 if isinstance(node, CardADF):
1312 return node
1313 node = node.parent
1314 return None
1315
Harald Weltec91085e2022-02-10 18:05:45 +01001316 def interpret_sw(self, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001317 """Interpret a given status word relative to the currently selected application
1318 or the underlying card profile.
1319
1320 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001321 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001322
1323 Returns:
1324 Tuple of two strings
1325 """
Harald Welte86fbd392021-04-02 22:13:09 +02001326 res = None
Harald Welte5ce35242021-04-02 20:27:05 +02001327 adf = self.get_application_df()
1328 if adf:
1329 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +01001330 # The application either comes with its own interpret_sw
1331 # method or we will use the interpret_sw method from the
1332 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +02001333 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +02001334 res = app.interpret_sw(sw)
1335 return res or self.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +01001336
Harald Weltec91085e2022-02-10 18:05:45 +01001337 def probe_file(self, fid: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001338 """Blindly try to select a file and automatically add a matching file
Harald Weltec91085e2022-02-10 18:05:45 +01001339 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +01001340 if not is_hex(fid, 4, 4):
Harald Weltec91085e2022-02-10 18:05:45 +01001341 raise ValueError(
1342 "Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
Philipp Maier63f572d2021-03-09 22:42:47 +01001343
1344 try:
1345 (data, sw) = self.card._scc.select_file(fid)
1346 except SwMatchError as swm:
1347 k = self.interpret_sw(swm.sw_actual)
1348 if not k:
1349 raise(swm)
1350 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
1351
1352 select_resp = self.selected_file.decode_select_response(data)
1353 if (select_resp['file_descriptor']['file_type'] == 'df'):
Harald Weltec91085e2022-02-10 18:05:45 +01001354 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(),
1355 desc="dedicated file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001356 else:
1357 if (select_resp['file_descriptor']['structure'] == 'transparent'):
Harald Weltec91085e2022-02-10 18:05:45 +01001358 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1359 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001360 else:
Harald Weltec91085e2022-02-10 18:05:45 +01001361 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1362 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001363
1364 self.selected_file.add_files([f])
1365 self.selected_file = f
1366 return select_resp
1367
Harald Welteaceb2a52022-02-12 21:41:59 +01001368 def _select_pre(self, cmd_app):
1369 # unregister commands of old file
1370 if cmd_app and self.selected_file.shell_commands:
1371 for c in self.selected_file.shell_commands:
1372 cmd_app.unregister_command_set(c)
1373
1374 def _select_post(self, cmd_app):
1375 # register commands of new file
1376 if cmd_app and self.selected_file.shell_commands:
1377 for c in self.selected_file.shell_commands:
1378 cmd_app.register_command_set(c)
1379
1380 def select_file(self, file: CardFile, cmd_app=None):
1381 """Select a file (EF, DF, ADF, MF, ...).
1382
1383 Args:
1384 file : CardFile [or derived class] instance
1385 cmd_app : Command Application State (for unregistering old file commands)
1386 """
1387 # we need to find a path from our self.selected_file to the destination
1388 inter_path = self.selected_file.build_select_path_to(file)
1389 if not inter_path:
1390 raise RuntimeError('Cannot determine path from %s to %s' % (self.selected_file, file))
1391
1392 self._select_pre(cmd_app)
1393
1394 for p in inter_path:
1395 try:
1396 if isinstance(p, CardADF):
1397 (data, sw) = self.card.select_adf_by_aid(p.aid)
1398 else:
1399 (data, sw) = self.card._scc.select_file(p.fid)
1400 self.selected_file = p
1401 except SwMatchError as swm:
1402 self._select_post(cmd_app)
1403 raise(swm)
1404
1405 self._select_post(cmd_app)
1406
Harald Weltec91085e2022-02-10 18:05:45 +01001407 def select(self, name: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001408 """Select a file (EF, DF, ADF, MF, ...).
1409
1410 Args:
1411 name : Name of file to select
1412 cmd_app : Command Application State (for unregistering old file commands)
1413 """
Harald Welteb2edd142021-01-08 23:29:35 +01001414 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +01001415 if is_hex(name):
1416 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +01001417
Harald Welteaceb2a52022-02-12 21:41:59 +01001418 self._select_pre(cmd_app)
Philipp Maier63f572d2021-03-09 22:42:47 +01001419
Harald Welteb2edd142021-01-08 23:29:35 +01001420 if name in sels:
1421 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +01001422 try:
1423 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001424 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +01001425 else:
1426 (data, sw) = self.card._scc.select_file(f.fid)
1427 self.selected_file = f
1428 except SwMatchError as swm:
1429 k = self.interpret_sw(swm.sw_actual)
1430 if not k:
1431 raise(swm)
1432 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +01001433 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001434 else:
Philipp Maier63f572d2021-03-09 22:42:47 +01001435 select_resp = self.probe_file(name, cmd_app)
Harald Welte850b72a2021-04-07 09:33:03 +02001436 # store the decoded FCP for later reference
1437 self.selected_file_fcp = select_resp
Philipp Maier63f572d2021-03-09 22:42:47 +01001438
Harald Welteaceb2a52022-02-12 21:41:59 +01001439 self._select_post(cmd_app)
Philipp Maier63f572d2021-03-09 22:42:47 +01001440 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +01001441
Harald Welte34b05d32021-05-25 22:03:13 +02001442 def status(self):
1443 """Request STATUS (current selected file FCP) from card."""
1444 (data, sw) = self.card._scc.status()
1445 return self.selected_file.decode_select_response(data)
1446
Harald Weltec91085e2022-02-10 18:05:45 +01001447 def activate_file(self, name: str):
Harald Welte485692b2021-05-25 22:21:44 +02001448 """Request ACTIVATE FILE of specified file."""
1449 sels = self.selected_file.get_selectables()
1450 f = sels[name]
1451 data, sw = self.card._scc.activate_file(f.fid)
1452 return data, sw
1453
Harald Weltec91085e2022-02-10 18:05:45 +01001454 def read_binary(self, length: int = None, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001455 """Read [part of] a transparent EF binary data.
1456
1457 Args:
1458 length : Amount of data to read (None: as much as possible)
1459 offset : Offset into the file from which to read 'length' bytes
1460 Returns:
1461 binary data read from the file
1462 """
Harald Welteb2edd142021-01-08 23:29:35 +01001463 if not isinstance(self.selected_file, TransparentEF):
1464 raise TypeError("Only works with TransparentEF")
1465 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
1466
Harald Welte2d4a64b2021-04-03 09:01:24 +02001467 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001468 """Read [part of] a transparent EF binary data and decode it.
1469
1470 Args:
1471 length : Amount of data to read (None: as much as possible)
1472 offset : Offset into the file from which to read 'length' bytes
1473 Returns:
1474 abstract decode data read from the file
1475 """
Harald Welteb2edd142021-01-08 23:29:35 +01001476 (data, sw) = self.read_binary()
1477 dec_data = self.selected_file.decode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001478 return (dec_data, sw)
1479
Harald Weltec91085e2022-02-10 18:05:45 +01001480 def update_binary(self, data_hex: str, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001481 """Update transparent EF binary data.
1482
1483 Args:
1484 data_hex : hex string of data to be written
1485 offset : Offset into the file from which to write 'data_hex'
1486 """
Harald Welteb2edd142021-01-08 23:29:35 +01001487 if not isinstance(self.selected_file, TransparentEF):
1488 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001489 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001490
Harald Weltec91085e2022-02-10 18:05:45 +01001491 def update_binary_dec(self, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001492 """Update transparent EF from abstract data. Encodes the data to binary and
1493 then updates the EF with it.
1494
1495 Args:
1496 data : abstract data which is to be encoded and written
1497 """
Harald Welteb2edd142021-01-08 23:29:35 +01001498 data_hex = self.selected_file.encode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001499 return self.update_binary(data_hex)
1500
Harald Weltec91085e2022-02-10 18:05:45 +01001501 def read_record(self, rec_nr: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001502 """Read a record as binary data.
1503
1504 Args:
1505 rec_nr : Record number to read
1506 Returns:
1507 hex string of binary data contained in record
1508 """
Harald Welteb2edd142021-01-08 23:29:35 +01001509 if not isinstance(self.selected_file, LinFixedEF):
1510 raise TypeError("Only works with Linear Fixed EF")
1511 # returns a string of hex nibbles
1512 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1513
Harald Weltec91085e2022-02-10 18:05:45 +01001514 def read_record_dec(self, rec_nr: int = 0) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001515 """Read a record and decode it to abstract data.
1516
1517 Args:
1518 rec_nr : Record number to read
1519 Returns:
1520 abstract data contained in record
1521 """
Harald Welteb2edd142021-01-08 23:29:35 +01001522 (data, sw) = self.read_record(rec_nr)
1523 return (self.selected_file.decode_record_hex(data), sw)
1524
Harald Weltec91085e2022-02-10 18:05:45 +01001525 def update_record(self, rec_nr: int, data_hex: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001526 """Update a record with given binary data
1527
1528 Args:
1529 rec_nr : Record number to read
1530 data_hex : Hex string binary data to be written
1531 """
Harald Welteb2edd142021-01-08 23:29:35 +01001532 if not isinstance(self.selected_file, LinFixedEF):
1533 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001534 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 +01001535
Harald Weltec91085e2022-02-10 18:05:45 +01001536 def update_record_dec(self, rec_nr: int, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001537 """Update a record with given abstract data. Will encode abstract to binary data
1538 and then write it to the given record on the card.
1539
1540 Args:
1541 rec_nr : Record number to read
1542 data_hex : Abstract data to be written
1543 """
Harald Welte1e456572021-04-02 17:16:30 +02001544 data_hex = self.selected_file.encode_record_hex(data)
1545 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001546
Harald Weltec91085e2022-02-10 18:05:45 +01001547 def retrieve_data(self, tag: int = 0):
Harald Welte917d98c2021-04-21 11:51:25 +02001548 """Read a DO/TLV as binary data.
1549
1550 Args:
1551 tag : Tag of TLV/DO to read
1552 Returns:
1553 hex string of full BER-TLV DO including Tag and Length
1554 """
1555 if not isinstance(self.selected_file, BerTlvEF):
1556 raise TypeError("Only works with BER-TLV EF")
1557 # returns a string of hex nibbles
1558 return self.card._scc.retrieve_data(self.selected_file.fid, tag)
1559
1560 def retrieve_tags(self):
1561 """Retrieve tags available on BER-TLV EF.
1562
1563 Returns:
1564 list of integer tags contained in EF
1565 """
1566 if not isinstance(self.selected_file, BerTlvEF):
1567 raise TypeError("Only works with BER-TLV EF")
1568 data, sw = self.card._scc.retrieve_data(self.selected_file.fid, 0x5c)
Harald Weltec1475302021-05-21 21:47:55 +02001569 tag, length, value, remainder = bertlv_parse_one(h2b(data))
Harald Welte917d98c2021-04-21 11:51:25 +02001570 return list(value)
1571
Harald Weltec91085e2022-02-10 18:05:45 +01001572 def set_data(self, tag: int, data_hex: str):
Harald Welte917d98c2021-04-21 11:51:25 +02001573 """Update a TLV/DO with given binary data
1574
1575 Args:
1576 tag : Tag of TLV/DO to be written
1577 data_hex : Hex string binary data to be written (value portion)
1578 """
1579 if not isinstance(self.selected_file, BerTlvEF):
1580 raise TypeError("Only works with BER-TLV EF")
1581 return self.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.conserve_write)
1582
Philipp Maier5d698e52021-09-16 13:18:01 +02001583 def unregister_cmds(self, cmd_app=None):
1584 """Unregister all file specific commands."""
1585 if cmd_app and self.selected_file.shell_commands:
1586 for c in self.selected_file.shell_commands:
1587 cmd_app.unregister_command_set(c)
Harald Welte917d98c2021-04-21 11:51:25 +02001588
Harald Welteb2edd142021-01-08 23:29:35 +01001589
Harald Welteb2edd142021-01-08 23:29:35 +01001590class FileData(object):
1591 """Represent the runtime, on-card data."""
Harald Weltec91085e2022-02-10 18:05:45 +01001592
Harald Welteb2edd142021-01-08 23:29:35 +01001593 def __init__(self, fdesc):
1594 self.desc = fdesc
1595 self.fcp = None
1596
1597
Harald Weltec91085e2022-02-10 18:05:45 +01001598def interpret_sw(sw_data: dict, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001599 """Interpret a given status word.
1600
1601 Args:
1602 sw_data : Hierarchical dict of status word matches
1603 sw : status word to match (string of 4 hex digits)
1604 Returns:
1605 tuple of two strings (class_string, description)
1606 """
Harald Welteb2edd142021-01-08 23:29:35 +01001607 for class_str, swdict in sw_data.items():
1608 # first try direct match
1609 if sw in swdict:
1610 return (class_str, swdict[sw])
1611 # next try wildcard matches
1612 for pattern, descr in swdict.items():
1613 if sw_match(sw, pattern):
1614 return (class_str, descr)
1615 return None
1616
Harald Weltec91085e2022-02-10 18:05:45 +01001617
Harald Welteb2edd142021-01-08 23:29:35 +01001618class CardApplication(object):
1619 """A card application is represented by an ADF (with contained hierarchy) and optionally
1620 some SW definitions."""
Harald Weltec91085e2022-02-10 18:05:45 +01001621
1622 def __init__(self, name, adf: Optional[CardADF] = None, aid: str = None, sw: dict = None):
Harald Welteee3501f2021-04-02 13:00:18 +02001623 """
1624 Args:
1625 adf : ADF name
1626 sw : Dict of status word conversions
1627 """
Harald Welteb2edd142021-01-08 23:29:35 +01001628 self.name = name
1629 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001630 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001631 # back-reference from ADF to Applicaiton
1632 if self.adf:
1633 self.aid = aid or self.adf.aid
1634 self.adf.application = self
1635 else:
1636 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001637
1638 def __str__(self):
1639 return "APP(%s)" % (self.name)
1640
1641 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001642 """Interpret a given status word within the application.
1643
1644 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001645 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001646
1647 Returns:
1648 Tuple of two strings
1649 """
Harald Welteb2edd142021-01-08 23:29:35 +01001650 return interpret_sw(self.sw, sw)
1651
Harald Weltef44256c2021-10-14 15:53:39 +02001652
1653class CardModel(abc.ABC):
Harald Welte4c1dca02021-10-14 17:48:25 +02001654 """A specific card model, typically having some additional vendor-specific files. All
1655 you need to do is to define a sub-class with a list of ATRs or an overridden match
1656 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001657 _atrs = []
1658
1659 @classmethod
1660 @abc.abstractmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001661 def add_files(cls, rs: RuntimeState):
Harald Weltef44256c2021-10-14 15:53:39 +02001662 """Add model specific files to given RuntimeState."""
1663
1664 @classmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001665 def match(cls, scc: SimCardCommands) -> bool:
Harald Weltef44256c2021-10-14 15:53:39 +02001666 """Test if given card matches this model."""
1667 card_atr = scc.get_atr()
1668 for atr in cls._atrs:
1669 atr_bin = toBytes(atr)
1670 if atr_bin == card_atr:
1671 print("Detected CardModel:", cls.__name__)
1672 return True
1673 return False
1674
1675 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001676 def apply_matching_models(scc: SimCardCommands, rs: RuntimeState):
Harald Welte4c1dca02021-10-14 17:48:25 +02001677 """Check if any of the CardModel sub-classes 'match' the currently inserted card
1678 (by ATR or overriding the 'match' method). If so, call their 'add_files'
1679 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001680 for m in CardModel.__subclasses__():
1681 if m.match(scc):
1682 m.add_files(rs)