blob: 8303a4b3efeaa1f76e780d65011df6cfcb6aa952 [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"""
Harald Welte747a9782022-02-13 17:52:28 +0100776 num_of_rec = self._cmd.rs.selected_file_num_of_rec()
Harald Welte850b72a2021-04-07 09:33:03 +0200777 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"""
Harald Welte747a9782022-02-13 17:52:28 +0100792 num_of_rec = self._cmd.rs.selected_file_num_of_rec()
Harald Welte850b72a2021-04-07 09:33:03 +0200793 # 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 Welte747a9782022-02-13 17:52:28 +01001282 def selected_file_descriptor_byte(self) -> dict:
1283 return self.selected_file_fcp['file_descriptor']['file_descriptor_byte']
1284
1285 def selected_file_shareable(self) -> bool:
1286 return self.selected_file_descriptor_byte()['shareable']
1287
1288 def selected_file_structure(self) -> str:
1289 return self.selected_file_descriptor_byte()['structure']
1290
1291 def selected_file_type(self) -> str:
1292 return self.selected_file_descriptor_byte()['file_type']
1293
1294 def selected_file_num_of_rec(self) -> Optional[int]:
1295 return self.selected_file_fcp['file_descriptor'].get('num_of_rec')
1296
Harald Weltedaf2b392021-05-03 23:17:29 +02001297 def reset(self, cmd_app=None) -> Hexstr:
1298 """Perform physical card reset and obtain ATR.
1299 Args:
1300 cmd_app : Command Application State (for unregistering old file commands)
1301 """
Philipp Maier946226a2021-10-29 18:31:03 +02001302 atr = i2h(self.card.reset())
Harald Weltedaf2b392021-05-03 23:17:29 +02001303 # select MF to reset internal state and to verify card really works
1304 self.select('MF', cmd_app)
1305 return atr
1306
Harald Welteee3501f2021-04-02 13:00:18 +02001307 def get_cwd(self) -> CardDF:
1308 """Obtain the current working directory.
1309
1310 Returns:
1311 CardDF instance
1312 """
Harald Welteb2edd142021-01-08 23:29:35 +01001313 if isinstance(self.selected_file, CardDF):
1314 return self.selected_file
1315 else:
1316 return self.selected_file.parent
1317
Harald Welte5ce35242021-04-02 20:27:05 +02001318 def get_application_df(self) -> Optional[CardADF]:
1319 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +02001320
1321 Returns:
1322 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +01001323 # iterate upwards from selected file; check if any is an ADF
1324 node = self.selected_file
1325 while node.parent != node:
1326 if isinstance(node, CardADF):
1327 return node
1328 node = node.parent
1329 return None
1330
Harald Weltec91085e2022-02-10 18:05:45 +01001331 def interpret_sw(self, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001332 """Interpret a given status word relative to the currently selected application
1333 or the underlying card profile.
1334
1335 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001336 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001337
1338 Returns:
1339 Tuple of two strings
1340 """
Harald Welte86fbd392021-04-02 22:13:09 +02001341 res = None
Harald Welte5ce35242021-04-02 20:27:05 +02001342 adf = self.get_application_df()
1343 if adf:
1344 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +01001345 # The application either comes with its own interpret_sw
1346 # method or we will use the interpret_sw method from the
1347 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +02001348 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +02001349 res = app.interpret_sw(sw)
1350 return res or self.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +01001351
Harald Weltec91085e2022-02-10 18:05:45 +01001352 def probe_file(self, fid: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001353 """Blindly try to select a file and automatically add a matching file
Harald Weltec91085e2022-02-10 18:05:45 +01001354 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +01001355 if not is_hex(fid, 4, 4):
Harald Weltec91085e2022-02-10 18:05:45 +01001356 raise ValueError(
1357 "Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
Philipp Maier63f572d2021-03-09 22:42:47 +01001358
1359 try:
1360 (data, sw) = self.card._scc.select_file(fid)
1361 except SwMatchError as swm:
1362 k = self.interpret_sw(swm.sw_actual)
1363 if not k:
1364 raise(swm)
1365 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
1366
1367 select_resp = self.selected_file.decode_select_response(data)
Harald Welte747a9782022-02-13 17:52:28 +01001368 if (select_resp['file_descriptor']['file_descriptor_byte']['file_type'] == 'df'):
Harald Weltec91085e2022-02-10 18:05:45 +01001369 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(),
1370 desc="dedicated file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001371 else:
Harald Welte747a9782022-02-13 17:52:28 +01001372 if (select_resp['file_descriptor']['file_descriptor_byte']['structure'] == 'transparent'):
Harald Weltec91085e2022-02-10 18:05:45 +01001373 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1374 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001375 else:
Harald Weltec91085e2022-02-10 18:05:45 +01001376 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1377 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001378
1379 self.selected_file.add_files([f])
1380 self.selected_file = f
1381 return select_resp
1382
Harald Welteaceb2a52022-02-12 21:41:59 +01001383 def _select_pre(self, cmd_app):
1384 # unregister commands of old file
1385 if cmd_app and self.selected_file.shell_commands:
1386 for c in self.selected_file.shell_commands:
1387 cmd_app.unregister_command_set(c)
1388
1389 def _select_post(self, cmd_app):
1390 # register commands of new file
1391 if cmd_app and self.selected_file.shell_commands:
1392 for c in self.selected_file.shell_commands:
1393 cmd_app.register_command_set(c)
1394
1395 def select_file(self, file: CardFile, cmd_app=None):
1396 """Select a file (EF, DF, ADF, MF, ...).
1397
1398 Args:
1399 file : CardFile [or derived class] instance
1400 cmd_app : Command Application State (for unregistering old file commands)
1401 """
1402 # we need to find a path from our self.selected_file to the destination
1403 inter_path = self.selected_file.build_select_path_to(file)
1404 if not inter_path:
1405 raise RuntimeError('Cannot determine path from %s to %s' % (self.selected_file, file))
1406
1407 self._select_pre(cmd_app)
1408
1409 for p in inter_path:
1410 try:
1411 if isinstance(p, CardADF):
1412 (data, sw) = self.card.select_adf_by_aid(p.aid)
1413 else:
1414 (data, sw) = self.card._scc.select_file(p.fid)
1415 self.selected_file = p
1416 except SwMatchError as swm:
1417 self._select_post(cmd_app)
1418 raise(swm)
1419
1420 self._select_post(cmd_app)
1421
Harald Weltec91085e2022-02-10 18:05:45 +01001422 def select(self, name: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001423 """Select a file (EF, DF, ADF, MF, ...).
1424
1425 Args:
1426 name : Name of file to select
1427 cmd_app : Command Application State (for unregistering old file commands)
1428 """
Harald Welteee670bc2022-02-13 15:10:15 +01001429 # handling of entire paths with multiple directories/elements
1430 if '/' in name:
1431 prev_sel_file = self.selected_file
1432 pathlist = name.split('/')
1433 # treat /DF.GSM/foo like MF/DF.GSM/foo
1434 if pathlist[0] == '':
1435 pathlist[0] = 'MF'
1436 try:
1437 for p in pathlist:
1438 self.select(p, cmd_app)
1439 return
1440 except Exception as e:
1441 # if any intermediate step fails, go back to where we were
1442 self.select_file(prev_sel_file, cmd_app)
1443 raise e
1444
Harald Welteb2edd142021-01-08 23:29:35 +01001445 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +01001446 if is_hex(name):
1447 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +01001448
Harald Welteaceb2a52022-02-12 21:41:59 +01001449 self._select_pre(cmd_app)
Philipp Maier63f572d2021-03-09 22:42:47 +01001450
Harald Welteb2edd142021-01-08 23:29:35 +01001451 if name in sels:
1452 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +01001453 try:
1454 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001455 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +01001456 else:
1457 (data, sw) = self.card._scc.select_file(f.fid)
1458 self.selected_file = f
1459 except SwMatchError as swm:
1460 k = self.interpret_sw(swm.sw_actual)
1461 if not k:
1462 raise(swm)
1463 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +01001464 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001465 else:
Philipp Maier63f572d2021-03-09 22:42:47 +01001466 select_resp = self.probe_file(name, cmd_app)
Harald Welte850b72a2021-04-07 09:33:03 +02001467 # store the decoded FCP for later reference
1468 self.selected_file_fcp = select_resp
Philipp Maier63f572d2021-03-09 22:42:47 +01001469
Harald Welteaceb2a52022-02-12 21:41:59 +01001470 self._select_post(cmd_app)
Philipp Maier63f572d2021-03-09 22:42:47 +01001471 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +01001472
Harald Welte34b05d32021-05-25 22:03:13 +02001473 def status(self):
1474 """Request STATUS (current selected file FCP) from card."""
1475 (data, sw) = self.card._scc.status()
1476 return self.selected_file.decode_select_response(data)
1477
Harald Welte3c9b7842021-10-19 21:44:24 +02001478 def get_file_for_selectable(self, name: str):
1479 sels = self.selected_file.get_selectables()
1480 return sels[name]
1481
Harald Weltec91085e2022-02-10 18:05:45 +01001482 def activate_file(self, name: str):
Harald Welte485692b2021-05-25 22:21:44 +02001483 """Request ACTIVATE FILE of specified file."""
1484 sels = self.selected_file.get_selectables()
1485 f = sels[name]
1486 data, sw = self.card._scc.activate_file(f.fid)
1487 return data, sw
1488
Harald Weltec91085e2022-02-10 18:05:45 +01001489 def read_binary(self, length: int = None, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001490 """Read [part of] a transparent EF binary data.
1491
1492 Args:
1493 length : Amount of data to read (None: as much as possible)
1494 offset : Offset into the file from which to read 'length' bytes
1495 Returns:
1496 binary data read from the file
1497 """
Harald Welteb2edd142021-01-08 23:29:35 +01001498 if not isinstance(self.selected_file, TransparentEF):
1499 raise TypeError("Only works with TransparentEF")
1500 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
1501
Harald Welte2d4a64b2021-04-03 09:01:24 +02001502 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001503 """Read [part of] a transparent EF binary data and decode it.
1504
1505 Args:
1506 length : Amount of data to read (None: as much as possible)
1507 offset : Offset into the file from which to read 'length' bytes
1508 Returns:
1509 abstract decode data read from the file
1510 """
Harald Welteb2edd142021-01-08 23:29:35 +01001511 (data, sw) = self.read_binary()
1512 dec_data = self.selected_file.decode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001513 return (dec_data, sw)
1514
Harald Weltec91085e2022-02-10 18:05:45 +01001515 def update_binary(self, data_hex: str, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001516 """Update transparent EF binary data.
1517
1518 Args:
1519 data_hex : hex string of data to be written
1520 offset : Offset into the file from which to write 'data_hex'
1521 """
Harald Welteb2edd142021-01-08 23:29:35 +01001522 if not isinstance(self.selected_file, TransparentEF):
1523 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001524 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001525
Harald Weltec91085e2022-02-10 18:05:45 +01001526 def update_binary_dec(self, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001527 """Update transparent EF from abstract data. Encodes the data to binary and
1528 then updates the EF with it.
1529
1530 Args:
1531 data : abstract data which is to be encoded and written
1532 """
Harald Welteb2edd142021-01-08 23:29:35 +01001533 data_hex = self.selected_file.encode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001534 return self.update_binary(data_hex)
1535
Harald Weltec91085e2022-02-10 18:05:45 +01001536 def read_record(self, rec_nr: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001537 """Read a record as binary data.
1538
1539 Args:
1540 rec_nr : Record number to read
1541 Returns:
1542 hex string of binary data contained in record
1543 """
Harald Welteb2edd142021-01-08 23:29:35 +01001544 if not isinstance(self.selected_file, LinFixedEF):
1545 raise TypeError("Only works with Linear Fixed EF")
1546 # returns a string of hex nibbles
1547 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1548
Harald Weltec91085e2022-02-10 18:05:45 +01001549 def read_record_dec(self, rec_nr: int = 0) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001550 """Read a record and decode it to abstract data.
1551
1552 Args:
1553 rec_nr : Record number to read
1554 Returns:
1555 abstract data contained in record
1556 """
Harald Welteb2edd142021-01-08 23:29:35 +01001557 (data, sw) = self.read_record(rec_nr)
1558 return (self.selected_file.decode_record_hex(data), sw)
1559
Harald Weltec91085e2022-02-10 18:05:45 +01001560 def update_record(self, rec_nr: int, data_hex: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001561 """Update a record with given binary data
1562
1563 Args:
1564 rec_nr : Record number to read
1565 data_hex : Hex string binary data to be written
1566 """
Harald Welteb2edd142021-01-08 23:29:35 +01001567 if not isinstance(self.selected_file, LinFixedEF):
1568 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001569 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 +01001570
Harald Weltec91085e2022-02-10 18:05:45 +01001571 def update_record_dec(self, rec_nr: int, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001572 """Update a record with given abstract data. Will encode abstract to binary data
1573 and then write it to the given record on the card.
1574
1575 Args:
1576 rec_nr : Record number to read
1577 data_hex : Abstract data to be written
1578 """
Harald Welte1e456572021-04-02 17:16:30 +02001579 data_hex = self.selected_file.encode_record_hex(data)
1580 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001581
Harald Weltec91085e2022-02-10 18:05:45 +01001582 def retrieve_data(self, tag: int = 0):
Harald Welte917d98c2021-04-21 11:51:25 +02001583 """Read a DO/TLV as binary data.
1584
1585 Args:
1586 tag : Tag of TLV/DO to read
1587 Returns:
1588 hex string of full BER-TLV DO including Tag and Length
1589 """
1590 if not isinstance(self.selected_file, BerTlvEF):
1591 raise TypeError("Only works with BER-TLV EF")
1592 # returns a string of hex nibbles
1593 return self.card._scc.retrieve_data(self.selected_file.fid, tag)
1594
1595 def retrieve_tags(self):
1596 """Retrieve tags available on BER-TLV EF.
1597
1598 Returns:
1599 list of integer tags contained in EF
1600 """
1601 if not isinstance(self.selected_file, BerTlvEF):
1602 raise TypeError("Only works with BER-TLV EF")
1603 data, sw = self.card._scc.retrieve_data(self.selected_file.fid, 0x5c)
Harald Weltec1475302021-05-21 21:47:55 +02001604 tag, length, value, remainder = bertlv_parse_one(h2b(data))
Harald Welte917d98c2021-04-21 11:51:25 +02001605 return list(value)
1606
Harald Weltec91085e2022-02-10 18:05:45 +01001607 def set_data(self, tag: int, data_hex: str):
Harald Welte917d98c2021-04-21 11:51:25 +02001608 """Update a TLV/DO with given binary data
1609
1610 Args:
1611 tag : Tag of TLV/DO to be written
1612 data_hex : Hex string binary data to be written (value portion)
1613 """
1614 if not isinstance(self.selected_file, BerTlvEF):
1615 raise TypeError("Only works with BER-TLV EF")
1616 return self.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.conserve_write)
1617
Philipp Maier5d698e52021-09-16 13:18:01 +02001618 def unregister_cmds(self, cmd_app=None):
1619 """Unregister all file specific commands."""
1620 if cmd_app and self.selected_file.shell_commands:
1621 for c in self.selected_file.shell_commands:
1622 cmd_app.unregister_command_set(c)
Harald Welte917d98c2021-04-21 11:51:25 +02001623
Harald Welteb2edd142021-01-08 23:29:35 +01001624
Harald Welteb2edd142021-01-08 23:29:35 +01001625class FileData(object):
1626 """Represent the runtime, on-card data."""
Harald Weltec91085e2022-02-10 18:05:45 +01001627
Harald Welteb2edd142021-01-08 23:29:35 +01001628 def __init__(self, fdesc):
1629 self.desc = fdesc
1630 self.fcp = None
1631
1632
Harald Weltec91085e2022-02-10 18:05:45 +01001633def interpret_sw(sw_data: dict, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001634 """Interpret a given status word.
1635
1636 Args:
1637 sw_data : Hierarchical dict of status word matches
1638 sw : status word to match (string of 4 hex digits)
1639 Returns:
1640 tuple of two strings (class_string, description)
1641 """
Harald Welteb2edd142021-01-08 23:29:35 +01001642 for class_str, swdict in sw_data.items():
1643 # first try direct match
1644 if sw in swdict:
1645 return (class_str, swdict[sw])
1646 # next try wildcard matches
1647 for pattern, descr in swdict.items():
1648 if sw_match(sw, pattern):
1649 return (class_str, descr)
1650 return None
1651
Harald Weltec91085e2022-02-10 18:05:45 +01001652
Harald Welteb2edd142021-01-08 23:29:35 +01001653class CardApplication(object):
1654 """A card application is represented by an ADF (with contained hierarchy) and optionally
1655 some SW definitions."""
Harald Weltec91085e2022-02-10 18:05:45 +01001656
1657 def __init__(self, name, adf: Optional[CardADF] = None, aid: str = None, sw: dict = None):
Harald Welteee3501f2021-04-02 13:00:18 +02001658 """
1659 Args:
1660 adf : ADF name
1661 sw : Dict of status word conversions
1662 """
Harald Welteb2edd142021-01-08 23:29:35 +01001663 self.name = name
1664 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001665 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001666 # back-reference from ADF to Applicaiton
1667 if self.adf:
1668 self.aid = aid or self.adf.aid
1669 self.adf.application = self
1670 else:
1671 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001672
1673 def __str__(self):
1674 return "APP(%s)" % (self.name)
1675
1676 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001677 """Interpret a given status word within the application.
1678
1679 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001680 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001681
1682 Returns:
1683 Tuple of two strings
1684 """
Harald Welteb2edd142021-01-08 23:29:35 +01001685 return interpret_sw(self.sw, sw)
1686
Harald Weltef44256c2021-10-14 15:53:39 +02001687
1688class CardModel(abc.ABC):
Harald Welte4c1dca02021-10-14 17:48:25 +02001689 """A specific card model, typically having some additional vendor-specific files. All
1690 you need to do is to define a sub-class with a list of ATRs or an overridden match
1691 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001692 _atrs = []
1693
1694 @classmethod
1695 @abc.abstractmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001696 def add_files(cls, rs: RuntimeState):
Harald Weltef44256c2021-10-14 15:53:39 +02001697 """Add model specific files to given RuntimeState."""
1698
1699 @classmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001700 def match(cls, scc: SimCardCommands) -> bool:
Harald Weltef44256c2021-10-14 15:53:39 +02001701 """Test if given card matches this model."""
1702 card_atr = scc.get_atr()
1703 for atr in cls._atrs:
1704 atr_bin = toBytes(atr)
1705 if atr_bin == card_atr:
1706 print("Detected CardModel:", cls.__name__)
1707 return True
1708 return False
1709
1710 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001711 def apply_matching_models(scc: SimCardCommands, rs: RuntimeState):
Harald Welte4c1dca02021-10-14 17:48:25 +02001712 """Check if any of the CardModel sub-classes 'match' the currently inserted card
1713 (by ATR or overriding the 'match' method). If so, call their 'add_files'
1714 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001715 for m in CardModel.__subclasses__():
1716 if m.match(scc):
1717 m.add_files(rs)