blob: fe8f591d5b77f180117ab95189724d034d4e8e89 [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 Welte13edf302022-07-21 15:19:23 +020052Size = Tuple[int, Optional[int]]
53
Harald Weltea6c0f882022-07-17 14:23:17 +020054def lchan_nr_from_cla(cla: int) -> int:
55 """Resolve the logical channel number from the CLA byte."""
56 # TS 102 221 10.1.1 Coding of Class Byte
57 if cla >> 4 in [0x0, 0xA, 0x8]:
58 # Table 10.3
59 return cla & 0x03
60 elif cla & 0xD0 in [0x40, 0xC0]:
61 # Table 10.4a
62 return 4 + (cla & 0x0F)
63 else:
64 raise ValueError('Could not determine logical channel for CLA=%2X' % cla)
65
Vadim Yanitskiy04b5d9d2022-07-07 03:05:30 +070066class CardFile:
Harald Welteb2edd142021-01-08 23:29:35 +010067 """Base class for all objects in the smart card filesystem.
68 Serve as a common ancestor to all other file types; rarely used directly.
69 """
70 RESERVED_NAMES = ['..', '.', '/', 'MF']
71 RESERVED_FIDS = ['3f00']
72
Harald Weltec91085e2022-02-10 18:05:45 +010073 def __init__(self, fid: str = None, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +010074 parent: Optional['CardDF'] = None, profile: Optional['CardProfile'] = None,
75 service: Optional[CardFileService] = None):
Harald Welteee3501f2021-04-02 13:00:18 +020076 """
77 Args:
78 fid : File Identifier (4 hex digits)
79 sfid : Short File Identifier (2 hex digits, optional)
80 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +020081 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +020082 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier5af7bdf2021-11-04 12:48:41 +010083 profile : Card profile that this file should be part of
Harald Welte9170fbf2022-02-11 21:54:37 +010084 service : Service (SST/UST/IST) associated with the file
Harald Welteee3501f2021-04-02 13:00:18 +020085 """
Harald Welteb2edd142021-01-08 23:29:35 +010086 if not isinstance(self, CardADF) and fid == None:
87 raise ValueError("fid is mandatory")
88 if fid:
89 fid = fid.lower()
90 self.fid = fid # file identifier
91 self.sfid = sfid # short file identifier
92 self.name = name # human readable name
93 self.desc = desc # human readable description
94 self.parent = parent
95 if self.parent and self.parent != self and self.fid:
96 self.parent.add_file(self)
Philipp Maier5af7bdf2021-11-04 12:48:41 +010097 self.profile = profile
Harald Welte9170fbf2022-02-11 21:54:37 +010098 self.service = service
Harald Weltec91085e2022-02-10 18:05:45 +010099 self.shell_commands = [] # type: List[CommandSet]
Harald Welteb2edd142021-01-08 23:29:35 +0100100
Harald Weltec91085e2022-02-10 18:05:45 +0100101 # Note: the basic properties (fid, name, ect.) are verified when
102 # the file is attached to a parent file. See method add_file() in
103 # class Card DF
Philipp Maier66061582021-03-09 21:57:57 +0100104
Harald Welteb2edd142021-01-08 23:29:35 +0100105 def __str__(self):
106 if self.name:
107 return self.name
108 else:
109 return self.fid
110
Harald Weltec91085e2022-02-10 18:05:45 +0100111 def _path_element(self, prefer_name: bool) -> Optional[str]:
Harald Welteb2edd142021-01-08 23:29:35 +0100112 if prefer_name and self.name:
113 return self.name
114 else:
115 return self.fid
116
Harald Welteb2e4b4a2022-07-19 23:48:45 +0200117 def fully_qualified_path_str(self, prefer_name: bool = True) -> str:
118 """Return fully qualified path to file as string.
119
120 Args:
121 prefer_name : Preferably build path of names; fall-back to FIDs as required
122 """
123 return '/'.join(self.fully_qualified_path(prefer_name))
124
Harald Weltec91085e2022-02-10 18:05:45 +0100125 def fully_qualified_path(self, prefer_name: bool = True) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200126 """Return fully qualified path to file as list of FID or name strings.
127
128 Args:
129 prefer_name : Preferably build path of names; fall-back to FIDs as required
130 """
Harald Welte1e456572021-04-02 17:16:30 +0200131 if self.parent and self.parent != self:
Harald Welteb2edd142021-01-08 23:29:35 +0100132 ret = self.parent.fully_qualified_path(prefer_name)
133 else:
134 ret = []
Harald Welte1e456572021-04-02 17:16:30 +0200135 elem = self._path_element(prefer_name)
136 if elem:
137 ret.append(elem)
Harald Welteb2edd142021-01-08 23:29:35 +0100138 return ret
139
Harald Welteaceb2a52022-02-12 21:41:59 +0100140 def fully_qualified_path_fobj(self) -> List['CardFile']:
141 """Return fully qualified path to file as list of CardFile instance references."""
142 if self.parent and self.parent != self:
143 ret = self.parent.fully_qualified_path_fobj()
144 else:
145 ret = []
146 if self:
147 ret.append(self)
148 return ret
149
150 def build_select_path_to(self, target: 'CardFile') -> Optional[List['CardFile']]:
151 """Build the relative sequence of files we need to traverse to get from us to 'target'."""
152 cur_fqpath = self.fully_qualified_path_fobj()
153 target_fqpath = target.fully_qualified_path_fobj()
154 inter_path = []
155 cur_fqpath.pop() # drop last element (currently selected file, doesn't need re-selection
156 cur_fqpath.reverse()
157 for ce in cur_fqpath:
158 inter_path.append(ce)
159 for i in range(0, len(target_fqpath)-1):
160 te = target_fqpath[i]
161 if te == ce:
162 for te2 in target_fqpath[i+1:]:
163 inter_path.append(te2)
164 # we found our common ancestor
165 return inter_path
166 return None
167
Harald Welteee3501f2021-04-02 13:00:18 +0200168 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +0100169 """Return the MF (root) of the file system."""
170 if self.parent == None:
171 return None
172 # iterate towards the top. MF has parent == self
173 node = self
Harald Welte1e456572021-04-02 17:16:30 +0200174 while node.parent and node.parent != node:
Harald Welteb2edd142021-01-08 23:29:35 +0100175 node = node.parent
Harald Welte1e456572021-04-02 17:16:30 +0200176 return cast(CardMF, node)
Harald Welteb2edd142021-01-08 23:29:35 +0100177
Harald Weltec91085e2022-02-10 18:05:45 +0100178 def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200179 """Return a dict of {'identifier': self} tuples.
180
181 Args:
182 alias : Add an alias with given name to 'self'
183 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
184 If not specified, all selectables will be returned.
185 Returns:
186 dict containing reference to 'self' for all identifiers.
187 """
Harald Welteb2edd142021-01-08 23:29:35 +0100188 sels = {}
189 if alias:
190 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100191 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100192 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100193 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100194 sels.update({self.name: self})
195 return sels
196
Harald Weltec91085e2022-02-10 18:05:45 +0100197 def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200198 """Return a dict of {'identifier': File} that is selectable from the current file.
199
200 Args:
201 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
202 If not specified, all selectables will be returned.
203 Returns:
204 dict containing all selectable items. Key is identifier (string), value
205 a reference to a CardFile (or derived class) instance.
206 """
Philipp Maier786f7812021-02-25 16:48:10 +0100207 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100208 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100209 if flags == [] or 'SELF' in flags:
210 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100211 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100212 if flags == [] or 'PARENT' in flags:
Harald Welte1e456572021-04-02 17:16:30 +0200213 if self.parent:
214 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100215 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100216 if flags == [] or 'MF' in flags:
217 mf = self.get_mf()
218 if mf:
Harald Weltec91085e2022-02-10 18:05:45 +0100219 sels.update(mf._get_self_selectables(flags=flags))
220 sels.update(mf.get_app_selectables(flags=flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100221 return sels
222
Harald Weltec91085e2022-02-10 18:05:45 +0100223 def get_selectable_names(self, flags=[]) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200224 """Return a dict of {'identifier': File} that is selectable from the current file.
225
226 Args:
227 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
228 If not specified, all selectables will be returned.
229 Returns:
Harald Welte1e456572021-04-02 17:16:30 +0200230 list containing all selectable names.
Harald Welteee3501f2021-04-02 13:00:18 +0200231 """
Philipp Maier786f7812021-02-25 16:48:10 +0100232 sels = self.get_selectables(flags)
Harald Welteb3d68c02022-01-21 15:31:29 +0100233 sel_keys = list(sels.keys())
234 sel_keys.sort()
235 return sel_keys
Harald Welteb2edd142021-01-08 23:29:35 +0100236
Harald Weltec91085e2022-02-10 18:05:45 +0100237 def decode_select_response(self, data_hex: str):
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100238 """Decode the response to a SELECT command.
239
240 Args:
Harald Weltec91085e2022-02-10 18:05:45 +0100241 data_hex: Hex string of the select response
242 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100243
Harald Weltec91085e2022-02-10 18:05:45 +0100244 # When the current file does not implement a custom select response decoder,
245 # we just ask the parent file to decode the select response. If this method
246 # is not overloaded by the current file we will again ask the parent file.
247 # This way we recursively travel up the file system tree until we hit a file
248 # that does implement a concrete decoder.
Harald Welte1e456572021-04-02 17:16:30 +0200249 if self.parent:
250 return self.parent.decode_select_response(data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +0100251
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100252 def get_profile(self):
253 """Get the profile associated with this file. If this file does not have any
254 profile assigned, try to find a file above (usually the MF) in the filesystem
255 hirarchy that has a profile assigned
256 """
257
258 # If we have a profile set, return it
259 if self.profile:
260 return self.profile
261
262 # Walk up recursively until we hit a parent that has a profile set
263 if self.parent:
264 return self.parent.get_profile()
265 return None
Harald Welteb2edd142021-01-08 23:29:35 +0100266
Harald Welte9170fbf2022-02-11 21:54:37 +0100267 def should_exist_for_services(self, services: List[int]):
268 """Assuming the provided list of activated services, should this file exist and be activated?."""
269 if self.service is None:
270 return None
271 elif isinstance(self.service, int):
272 # a single service determines the result
273 return self.service in services
274 elif isinstance(self.service, list):
275 # any of the services active -> true
276 for s in self.service:
277 if s in services:
278 return True
279 return False
280 elif isinstance(self.service, tuple):
281 # all of the services active -> true
282 for s in self.service:
283 if not s in services:
284 return False
285 return True
286 else:
287 raise ValueError("self.service must be either int or list or tuple")
288
Harald Weltec91085e2022-02-10 18:05:45 +0100289
Harald Welteb2edd142021-01-08 23:29:35 +0100290class CardDF(CardFile):
291 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100292
293 @with_default_category('DF/ADF Commands')
294 class ShellCommands(CommandSet):
295 def __init__(self):
296 super().__init__()
297
Harald Welteb2edd142021-01-08 23:29:35 +0100298 def __init__(self, **kwargs):
299 if not isinstance(self, CardADF):
300 if not 'fid' in kwargs:
301 raise TypeError('fid is mandatory for all DF')
302 super().__init__(**kwargs)
303 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100304 self.shell_commands = [self.ShellCommands()]
Harald Welte9170fbf2022-02-11 21:54:37 +0100305 # dict of CardFile affected by service(int), indexed by service
306 self.files_by_service = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100307
308 def __str__(self):
309 return "DF(%s)" % (super().__str__())
310
Harald Welte9170fbf2022-02-11 21:54:37 +0100311 def _add_file_services(self, child):
312 """Add a child (DF/EF) to the files_by_services of the parent."""
313 if not child.service:
314 return
315 if isinstance(child.service, int):
316 self.files_by_service.setdefault(child.service, []).append(child)
317 elif isinstance(child.service, list):
318 for service in child.service:
319 self.files_by_service.setdefault(service, []).append(child)
320 elif isinstance(child.service, tuple):
321 for service in child.service:
322 self.files_by_service.setdefault(service, []).append(child)
323 else:
324 raise ValueError
325
Harald Welted56f45d2022-07-16 11:46:59 +0200326 def _has_service(self):
327 if self.service:
328 return True
329 for c in self.children.values():
330 if isinstance(c, CardDF):
331 if c._has_service():
332 return True
333
Harald Weltec91085e2022-02-10 18:05:45 +0100334 def add_file(self, child: CardFile, ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200335 """Add a child (DF/EF) to this DF.
336 Args:
337 child: The new DF/EF to be added
338 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
339 """
Harald Welteb2edd142021-01-08 23:29:35 +0100340 if not isinstance(child, CardFile):
341 raise TypeError("Expected a File instance")
Harald Weltec91085e2022-02-10 18:05:45 +0100342 if not is_hex(child.fid, minlen=4, maxlen=4):
Philipp Maier3aec8712021-03-09 21:49:01 +0100343 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100344 if child.name in CardFile.RESERVED_NAMES:
345 raise ValueError("File name %s is a reserved name" % (child.name))
346 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100347 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100348 if child.fid in self.children:
349 if ignore_existing:
350 return
Harald Weltec91085e2022-02-10 18:05:45 +0100351 raise ValueError(
352 "File with given fid %s already exists in %s" % (child.fid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100353 if self.lookup_file_by_sfid(child.sfid):
Harald Weltec91085e2022-02-10 18:05:45 +0100354 raise ValueError(
355 "File with given sfid %s already exists in %s" % (child.sfid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100356 if self.lookup_file_by_name(child.name):
357 if ignore_existing:
358 return
Harald Weltec91085e2022-02-10 18:05:45 +0100359 raise ValueError(
360 "File with given name %s already exists in %s" % (child.name, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100361 self.children[child.fid] = child
362 child.parent = self
Harald Welte419bb492022-02-12 21:39:35 +0100363 # update the service -> file relationship table
Harald Welte9170fbf2022-02-11 21:54:37 +0100364 self._add_file_services(child)
Harald Welte419bb492022-02-12 21:39:35 +0100365 if isinstance(child, CardDF):
366 for c in child.children.values():
367 self._add_file_services(c)
368 if isinstance(c, CardDF):
Harald Welted56f45d2022-07-16 11:46:59 +0200369 for gc in c.children.values():
370 if isinstance(gc, CardDF):
371 if gc._has_service():
372 raise ValueError('TODO: implement recursive service -> file mapping')
Harald Welteb2edd142021-01-08 23:29:35 +0100373
Harald Weltec91085e2022-02-10 18:05:45 +0100374 def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200375 """Add a list of child (DF/EF) to this DF
376
377 Args:
378 children: List of new DF/EFs to be added
379 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
380 """
Harald Welteb2edd142021-01-08 23:29:35 +0100381 for child in children:
382 self.add_file(child, ignore_existing)
383
Harald Weltec91085e2022-02-10 18:05:45 +0100384 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200385 """Return a dict of {'identifier': File} that is selectable from the current DF.
386
387 Args:
388 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
389 If not specified, all selectables will be returned.
390 Returns:
391 dict containing all selectable items. Key is identifier (string), value
392 a reference to a CardFile (or derived class) instance.
393 """
Harald Welteb2edd142021-01-08 23:29:35 +0100394 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100395 sels = super().get_selectables(flags)
396 if flags == [] or 'FIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100397 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100398 if flags == [] or 'FNAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100399 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100400 return sels
401
Harald Weltec91085e2022-02-10 18:05:45 +0100402 def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200403 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100404 if name == None:
405 return None
406 for i in self.children.values():
407 if i.name and i.name == name:
408 return i
409 return None
410
Harald Weltec91085e2022-02-10 18:05:45 +0100411 def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200412 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100413 if sfid == None:
414 return None
415 for i in self.children.values():
Harald Welte1e456572021-04-02 17:16:30 +0200416 if i.sfid == int(str(sfid)):
Harald Welteb2edd142021-01-08 23:29:35 +0100417 return i
418 return None
419
Harald Weltec91085e2022-02-10 18:05:45 +0100420 def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200421 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100422 if fid in self.children:
423 return self.children[fid]
424 return None
425
426
427class CardMF(CardDF):
428 """MF (Master File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100429
Harald Welteb2edd142021-01-08 23:29:35 +0100430 def __init__(self, **kwargs):
431 # can be overridden; use setdefault
432 kwargs.setdefault('fid', '3f00')
433 kwargs.setdefault('name', 'MF')
434 kwargs.setdefault('desc', 'Master File (directory root)')
435 # cannot be overridden; use assignment
436 kwargs['parent'] = self
437 super().__init__(**kwargs)
438 self.applications = dict()
439
440 def __str__(self):
441 return "MF(%s)" % (self.fid)
442
Harald Weltec91085e2022-02-10 18:05:45 +0100443 def add_application_df(self, app: 'CardADF'):
Harald Welte5ce35242021-04-02 20:27:05 +0200444 """Add an Application to the MF"""
Harald Welteb2edd142021-01-08 23:29:35 +0100445 if not isinstance(app, CardADF):
446 raise TypeError("Expected an ADF instance")
447 if app.aid in self.applications:
448 raise ValueError("AID %s already exists" % (app.aid))
449 self.applications[app.aid] = app
Harald Weltec91085e2022-02-10 18:05:45 +0100450 app.parent = self
Harald Welteb2edd142021-01-08 23:29:35 +0100451
452 def get_app_names(self):
453 """Get list of completions (AID names)"""
Harald Welted53918c2022-02-12 18:20:49 +0100454 return list(self.applications.values())
Harald Welteb2edd142021-01-08 23:29:35 +0100455
Harald Weltec91085e2022-02-10 18:05:45 +0100456 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200457 """Return a dict of {'identifier': File} that is selectable from the current DF.
458
459 Args:
460 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
461 If not specified, all selectables will be returned.
462 Returns:
463 dict containing all selectable items. Key is identifier (string), value
464 a reference to a CardFile (or derived class) instance.
465 """
Philipp Maier786f7812021-02-25 16:48:10 +0100466 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100467 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100468 return sels
469
Harald Weltec91085e2022-02-10 18:05:45 +0100470 def get_app_selectables(self, flags=[]) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100471 """Get applications by AID + name"""
472 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100473 if flags == [] or 'AIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100474 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100475 if flags == [] or 'ANAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100476 sels.update(
477 {x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100478 return sels
479
Harald Weltec9752512022-02-11 16:31:15 +0100480 def decode_select_response(self, data_hex: Optional[str]) -> object:
Harald Welteee3501f2021-04-02 13:00:18 +0200481 """Decode the response to a SELECT command.
482
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100483 This is the fall-back method which automatically defers to the standard decoding
484 method defined by the card profile. When no profile is set, then no decoding is
Harald Weltec91085e2022-02-10 18:05:45 +0100485 performed. Specific derived classes (usually ADF) can overload this method to
486 install specific decoding.
Harald Welteee3501f2021-04-02 13:00:18 +0200487 """
Harald Welteb2edd142021-01-08 23:29:35 +0100488
Harald Weltec9752512022-02-11 16:31:15 +0100489 if not data_hex:
490 return data_hex
491
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100492 profile = self.get_profile()
Harald Welteb2edd142021-01-08 23:29:35 +0100493
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100494 if profile:
495 return profile.decode_select_response(data_hex)
496 else:
497 return data_hex
Harald Welteb2edd142021-01-08 23:29:35 +0100498
Harald Weltec91085e2022-02-10 18:05:45 +0100499
Harald Welteb2edd142021-01-08 23:29:35 +0100500class CardADF(CardDF):
501 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100502
503 def __init__(self, aid: str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100504 super().__init__(**kwargs)
Harald Welte5ce35242021-04-02 20:27:05 +0200505 # reference to CardApplication may be set from CardApplication constructor
Harald Weltefe8a7442021-04-10 11:51:54 +0200506 self.application = None # type: Optional[CardApplication]
Harald Welteb2edd142021-01-08 23:29:35 +0100507 self.aid = aid # Application Identifier
Harald Welte1e456572021-04-02 17:16:30 +0200508 mf = self.get_mf()
509 if mf:
Harald Welte5ce35242021-04-02 20:27:05 +0200510 mf.add_application_df(self)
Harald Welteb2edd142021-01-08 23:29:35 +0100511
512 def __str__(self):
Harald Welte4b003652022-07-16 11:55:07 +0200513 return "ADF(%s)" % (self.name if self.name else self.aid)
Harald Welteb2edd142021-01-08 23:29:35 +0100514
Harald Weltec91085e2022-02-10 18:05:45 +0100515 def _path_element(self, prefer_name: bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100516 if self.name and prefer_name:
517 return self.name
518 else:
519 return self.aid
520
521
522class CardEF(CardFile):
523 """EF (Entry File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100524
Harald Welteb2edd142021-01-08 23:29:35 +0100525 def __init__(self, *, fid, **kwargs):
526 kwargs['fid'] = fid
527 super().__init__(**kwargs)
528
529 def __str__(self):
530 return "EF(%s)" % (super().__str__())
531
Harald Weltec91085e2022-02-10 18:05:45 +0100532 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200533 """Return a dict of {'identifier': File} that is selectable from the current DF.
534
535 Args:
536 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
537 If not specified, all selectables will be returned.
538 Returns:
539 dict containing all selectable items. Key is identifier (string), value
540 a reference to a CardFile (or derived class) instance.
541 """
Harald Weltec91085e2022-02-10 18:05:45 +0100542 # global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100543 sels = super().get_selectables(flags)
Harald Weltec91085e2022-02-10 18:05:45 +0100544 sels.update(
545 {x.name: x for x in self.parent.children.values() if x != self})
Harald Welteb2edd142021-01-08 23:29:35 +0100546 return sels
547
548
549class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200550 """Transparent EF (Entry File) in the smart card filesystem.
551
552 A Transparent EF is a binary file with no formal structure. This is contrary to
553 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100554
555 @with_default_category('Transparent EF Commands')
556 class ShellCommands(CommandSet):
Harald Weltec9cdce32021-04-11 10:28:28 +0200557 """Shell commands specific for transparent EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100558
Harald Welteb2edd142021-01-08 23:29:35 +0100559 def __init__(self):
560 super().__init__()
561
Harald Welteaefd0642022-02-25 15:26:37 +0100562 dec_hex_parser = argparse.ArgumentParser()
563 dec_hex_parser.add_argument('--oneline', action='store_true',
564 help='No JSON pretty-printing, dump as a single line')
565 dec_hex_parser.add_argument('HEXSTR', help='Hex-string of encoded data to decode')
566
567 @cmd2.with_argparser(dec_hex_parser)
568 def do_decode_hex(self, opts):
569 """Decode command-line provided hex-string as if it was read from the file."""
Harald Weltea6c0f882022-07-17 14:23:17 +0200570 data = self._cmd.lchan.selected_file.decode_hex(opts.HEXSTR)
Harald Welteaefd0642022-02-25 15:26:37 +0100571 self._cmd.poutput_json(data, opts.oneline)
572
Harald Welteb2edd142021-01-08 23:29:35 +0100573 read_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100574 read_bin_parser.add_argument(
575 '--offset', type=int, default=0, help='Byte offset for start of read')
576 read_bin_parser.add_argument(
577 '--length', type=int, help='Number of bytes to read')
578
Harald Welteb2edd142021-01-08 23:29:35 +0100579 @cmd2.with_argparser(read_bin_parser)
580 def do_read_binary(self, opts):
581 """Read binary data from a transparent EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200582 (data, sw) = self._cmd.lchan.read_binary(opts.length, opts.offset)
Harald Welteb2edd142021-01-08 23:29:35 +0100583 self._cmd.poutput(data)
584
Harald Weltebcad86c2021-04-06 20:08:39 +0200585 read_bin_dec_parser = argparse.ArgumentParser()
586 read_bin_dec_parser.add_argument('--oneline', action='store_true',
587 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100588
Harald Weltebcad86c2021-04-06 20:08:39 +0200589 @cmd2.with_argparser(read_bin_dec_parser)
Harald Welteb2edd142021-01-08 23:29:35 +0100590 def do_read_binary_decoded(self, opts):
591 """Read + decode data from a transparent EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200592 (data, sw) = self._cmd.lchan.read_binary_dec()
Harald Welte1748b932021-04-06 21:12:25 +0200593 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100594
595 upd_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100596 upd_bin_parser.add_argument(
597 '--offset', type=int, default=0, help='Byte offset for start of read')
598 upd_bin_parser.add_argument(
599 'data', help='Data bytes (hex format) to write')
600
Harald Welteb2edd142021-01-08 23:29:35 +0100601 @cmd2.with_argparser(upd_bin_parser)
602 def do_update_binary(self, opts):
603 """Update (Write) data of a transparent EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200604 (data, sw) = self._cmd.lchan.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100605 if data:
606 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100607
608 upd_bin_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100609 upd_bin_dec_parser.add_argument(
610 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200611 upd_bin_dec_parser.add_argument('--json-path', type=str,
612 help='JSON path to modify specific element of file only')
Harald Weltec91085e2022-02-10 18:05:45 +0100613
Harald Welteb2edd142021-01-08 23:29:35 +0100614 @cmd2.with_argparser(upd_bin_dec_parser)
615 def do_update_binary_decoded(self, opts):
616 """Encode + Update (Write) data of a transparent EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200617 if opts.json_path:
Harald Weltea6c0f882022-07-17 14:23:17 +0200618 (data_json, sw) = self._cmd.lchan.read_binary_dec()
Harald Weltec91085e2022-02-10 18:05:45 +0100619 js_path_modify(data_json, opts.json_path,
620 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200621 else:
622 data_json = json.loads(opts.data)
Harald Weltea6c0f882022-07-17 14:23:17 +0200623 (data, sw) = self._cmd.lchan.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100624 if data:
Harald Welte1748b932021-04-06 21:12:25 +0200625 self._cmd.poutput_json(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100626
Harald Welte4145d3c2021-04-08 20:34:13 +0200627 def do_edit_binary_decoded(self, opts):
628 """Edit the JSON representation of the EF contents in an editor."""
Harald Weltea6c0f882022-07-17 14:23:17 +0200629 (orig_json, sw) = self._cmd.lchan.read_binary_dec()
Harald Welte4145d3c2021-04-08 20:34:13 +0200630 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
631 filename = '%s/file' % dirname
632 # write existing data as JSON to file
633 with open(filename, 'w') as text_file:
634 json.dump(orig_json, text_file, indent=4)
635 # run a text editor
636 self._cmd._run_editor(filename)
637 with open(filename, 'r') as text_file:
638 edited_json = json.load(text_file)
639 if edited_json == orig_json:
640 self._cmd.poutput("Data not modified, skipping write")
641 else:
Harald Weltea6c0f882022-07-17 14:23:17 +0200642 (data, sw) = self._cmd.lchan.update_binary_dec(edited_json)
Harald Welte4145d3c2021-04-08 20:34:13 +0200643 if data:
644 self._cmd.poutput_json(data)
645
Harald Weltec91085e2022-02-10 18:05:45 +0100646 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte13edf302022-07-21 15:19:23 +0200647 size: Size = (1, None), **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200648 """
649 Args:
650 fid : File Identifier (4 hex digits)
651 sfid : Short File Identifier (2 hex digits, optional)
652 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200653 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200654 parent : Parent CardFile object within filesystem hierarchy
655 size : tuple of (minimum_size, recommended_size)
656 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100657 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200658 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200659 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100660 self.size = size
661 self.shell_commands = [self.ShellCommands()]
662
Harald Weltec91085e2022-02-10 18:05:45 +0100663 def decode_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200664 """Decode raw (binary) data into abstract representation.
665
666 A derived class would typically provide a _decode_bin() or _decode_hex() method
667 for implementing this specifically for the given file. This function checks which
668 of the method exists, add calls them (with conversion, as needed).
669
670 Args:
671 raw_bin_data : binary encoded data
672 Returns:
673 abstract_data; dict representing the decoded data
674 """
Harald Welteb2edd142021-01-08 23:29:35 +0100675 method = getattr(self, '_decode_bin', None)
676 if callable(method):
677 return method(raw_bin_data)
678 method = getattr(self, '_decode_hex', None)
679 if callable(method):
680 return method(b2h(raw_bin_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200681 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200682 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200683 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100684 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100685 t.from_tlv(raw_bin_data)
686 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100687 return {'raw': raw_bin_data.hex()}
688
Harald Weltec91085e2022-02-10 18:05:45 +0100689 def decode_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200690 """Decode raw (hex string) data into abstract representation.
691
692 A derived class would typically provide a _decode_bin() or _decode_hex() method
693 for implementing this specifically for the given file. This function checks which
694 of the method exists, add calls them (with conversion, as needed).
695
696 Args:
697 raw_hex_data : hex-encoded data
698 Returns:
699 abstract_data; dict representing the decoded data
700 """
Harald Welteb2edd142021-01-08 23:29:35 +0100701 method = getattr(self, '_decode_hex', None)
702 if callable(method):
703 return method(raw_hex_data)
704 raw_bin_data = h2b(raw_hex_data)
705 method = getattr(self, '_decode_bin', None)
706 if callable(method):
707 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200708 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200709 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200710 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100711 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100712 t.from_tlv(raw_bin_data)
713 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100714 return {'raw': raw_bin_data.hex()}
715
Harald Weltec91085e2022-02-10 18:05:45 +0100716 def encode_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200717 """Encode abstract representation into raw (binary) data.
718
719 A derived class would typically provide an _encode_bin() or _encode_hex() method
720 for implementing this specifically for the given file. This function checks which
721 of the method exists, add calls them (with conversion, as needed).
722
723 Args:
724 abstract_data : dict representing the decoded data
725 Returns:
726 binary encoded data
727 """
Harald Welteb2edd142021-01-08 23:29:35 +0100728 method = getattr(self, '_encode_bin', None)
729 if callable(method):
730 return method(abstract_data)
731 method = getattr(self, '_encode_hex', None)
732 if callable(method):
733 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200734 if self._construct:
735 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200736 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100737 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100738 t.from_dict(abstract_data)
739 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100740 raise NotImplementedError(
741 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100742
Harald Weltec91085e2022-02-10 18:05:45 +0100743 def encode_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200744 """Encode abstract representation into raw (hex string) data.
745
746 A derived class would typically provide an _encode_bin() or _encode_hex() method
747 for implementing this specifically for the given file. This function checks which
748 of the method exists, add calls them (with conversion, as needed).
749
750 Args:
751 abstract_data : dict representing the decoded data
752 Returns:
753 hex string encoded data
754 """
Harald Welteb2edd142021-01-08 23:29:35 +0100755 method = getattr(self, '_encode_hex', None)
756 if callable(method):
757 return method(abstract_data)
758 method = getattr(self, '_encode_bin', None)
759 if callable(method):
760 raw_bin_data = method(abstract_data)
761 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200762 if self._construct:
763 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200764 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100765 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100766 t.from_dict(abstract_data)
767 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100768 raise NotImplementedError(
769 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100770
771
772class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200773 """Linear Fixed EF (Entry File) in the smart card filesystem.
774
775 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
776 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100777
778 @with_default_category('Linear Fixed EF Commands')
779 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200780 """Shell commands specific for Linear Fixed EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100781
Harald Welte9170fbf2022-02-11 21:54:37 +0100782 def __init__(self, **kwargs):
783 super().__init__(**kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100784
Harald Welteaefd0642022-02-25 15:26:37 +0100785 dec_hex_parser = argparse.ArgumentParser()
786 dec_hex_parser.add_argument('--oneline', action='store_true',
787 help='No JSON pretty-printing, dump as a single line')
788 dec_hex_parser.add_argument('HEXSTR', help='Hex-string of encoded data to decode')
789
790 @cmd2.with_argparser(dec_hex_parser)
791 def do_decode_hex(self, opts):
792 """Decode command-line provided hex-string as if it was read from the file."""
Harald Weltea6c0f882022-07-17 14:23:17 +0200793 data = self._cmd.lchan.selected_file.decode_record_hex(opts.HEXSTR)
Harald Welteaefd0642022-02-25 15:26:37 +0100794 self._cmd.poutput_json(data, opts.oneline)
795
Harald Welteb2edd142021-01-08 23:29:35 +0100796 read_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100797 read_rec_parser.add_argument(
798 'record_nr', type=int, help='Number of record to be read')
799 read_rec_parser.add_argument(
800 '--count', type=int, default=1, help='Number of records to be read, beginning at record_nr')
801
Harald Welteb2edd142021-01-08 23:29:35 +0100802 @cmd2.with_argparser(read_rec_parser)
803 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100804 """Read one or multiple records from a record-oriented EF"""
805 for r in range(opts.count):
806 recnr = opts.record_nr + r
Harald Weltea6c0f882022-07-17 14:23:17 +0200807 (data, sw) = self._cmd.lchan.read_record(recnr)
Philipp Maier41555732021-02-25 16:52:08 +0100808 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100809 recstr = str(data)
Philipp Maier41555732021-02-25 16:52:08 +0100810 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100811 recstr = "(empty)"
Philipp Maier41555732021-02-25 16:52:08 +0100812 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100813
814 read_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100815 read_rec_dec_parser.add_argument(
816 'record_nr', type=int, help='Number of record to be read')
Harald Weltebcad86c2021-04-06 20:08:39 +0200817 read_rec_dec_parser.add_argument('--oneline', action='store_true',
818 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100819
Harald Welteb2edd142021-01-08 23:29:35 +0100820 @cmd2.with_argparser(read_rec_dec_parser)
821 def do_read_record_decoded(self, opts):
822 """Read + decode a record from a record-oriented EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200823 (data, sw) = self._cmd.lchan.read_record_dec(opts.record_nr)
Harald Welte1748b932021-04-06 21:12:25 +0200824 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100825
Harald Welte850b72a2021-04-07 09:33:03 +0200826 read_recs_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100827
Harald Welte850b72a2021-04-07 09:33:03 +0200828 @cmd2.with_argparser(read_recs_parser)
829 def do_read_records(self, opts):
830 """Read all records from a record-oriented EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200831 num_of_rec = self._cmd.lchan.selected_file_num_of_rec()
Harald Welte850b72a2021-04-07 09:33:03 +0200832 for recnr in range(1, 1 + num_of_rec):
Harald Weltea6c0f882022-07-17 14:23:17 +0200833 (data, sw) = self._cmd.lchan.read_record(recnr)
Harald Welte850b72a2021-04-07 09:33:03 +0200834 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100835 recstr = str(data)
Harald Welte850b72a2021-04-07 09:33:03 +0200836 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100837 recstr = "(empty)"
Harald Welte850b72a2021-04-07 09:33:03 +0200838 self._cmd.poutput("%03d %s" % (recnr, recstr))
839
840 read_recs_dec_parser = argparse.ArgumentParser()
841 read_recs_dec_parser.add_argument('--oneline', action='store_true',
Harald Weltec91085e2022-02-10 18:05:45 +0100842 help='No JSON pretty-printing, dump as a single line')
843
Harald Welte850b72a2021-04-07 09:33:03 +0200844 @cmd2.with_argparser(read_recs_dec_parser)
845 def do_read_records_decoded(self, opts):
846 """Read + decode all records from a record-oriented EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200847 num_of_rec = self._cmd.lchan.selected_file_num_of_rec()
Harald Welte850b72a2021-04-07 09:33:03 +0200848 # collect all results in list so they are rendered as JSON list when printing
849 data_list = []
850 for recnr in range(1, 1 + num_of_rec):
Harald Weltea6c0f882022-07-17 14:23:17 +0200851 (data, sw) = self._cmd.lchan.read_record_dec(recnr)
Harald Welte850b72a2021-04-07 09:33:03 +0200852 data_list.append(data)
853 self._cmd.poutput_json(data_list, opts.oneline)
854
Harald Welteb2edd142021-01-08 23:29:35 +0100855 upd_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100856 upd_rec_parser.add_argument(
857 'record_nr', type=int, help='Number of record to be read')
858 upd_rec_parser.add_argument(
859 'data', help='Data bytes (hex format) to write')
860
Harald Welteb2edd142021-01-08 23:29:35 +0100861 @cmd2.with_argparser(upd_rec_parser)
862 def do_update_record(self, opts):
863 """Update (write) data to a record-oriented EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +0200864 (data, sw) = self._cmd.lchan.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100865 if data:
866 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100867
868 upd_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100869 upd_rec_dec_parser.add_argument(
870 'record_nr', type=int, help='Number of record to be read')
871 upd_rec_dec_parser.add_argument(
872 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200873 upd_rec_dec_parser.add_argument('--json-path', type=str,
874 help='JSON path to modify specific element of record only')
Harald Weltec91085e2022-02-10 18:05:45 +0100875
Harald Welteb2edd142021-01-08 23:29:35 +0100876 @cmd2.with_argparser(upd_rec_dec_parser)
877 def do_update_record_decoded(self, opts):
878 """Encode + Update (write) data to a record-oriented EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200879 if opts.json_path:
Harald Weltea6c0f882022-07-17 14:23:17 +0200880 (data_json, sw) = self._cmd.lchan.read_record_dec(opts.record_nr)
Harald Weltec91085e2022-02-10 18:05:45 +0100881 js_path_modify(data_json, opts.json_path,
882 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200883 else:
884 data_json = json.loads(opts.data)
Harald Weltea6c0f882022-07-17 14:23:17 +0200885 (data, sw) = self._cmd.lchan.update_record_dec(
Harald Weltec91085e2022-02-10 18:05:45 +0100886 opts.record_nr, data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100887 if data:
888 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100889
Harald Welte4145d3c2021-04-08 20:34:13 +0200890 edit_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100891 edit_rec_dec_parser.add_argument(
892 'record_nr', type=int, help='Number of record to be edited')
893
Harald Welte4145d3c2021-04-08 20:34:13 +0200894 @cmd2.with_argparser(edit_rec_dec_parser)
895 def do_edit_record_decoded(self, opts):
896 """Edit the JSON representation of one record in an editor."""
Harald Weltea6c0f882022-07-17 14:23:17 +0200897 (orig_json, sw) = self._cmd.lchan.read_record_dec(opts.record_nr)
Vadim Yanitskiy895fa6f2021-05-02 02:36:44 +0200898 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
Harald Welte4145d3c2021-04-08 20:34:13 +0200899 filename = '%s/file' % dirname
900 # write existing data as JSON to file
901 with open(filename, 'w') as text_file:
902 json.dump(orig_json, text_file, indent=4)
903 # run a text editor
904 self._cmd._run_editor(filename)
905 with open(filename, 'r') as text_file:
906 edited_json = json.load(text_file)
907 if edited_json == orig_json:
908 self._cmd.poutput("Data not modified, skipping write")
909 else:
Harald Weltea6c0f882022-07-17 14:23:17 +0200910 (data, sw) = self._cmd.lchan.update_record_dec(
Harald Weltec91085e2022-02-10 18:05:45 +0100911 opts.record_nr, edited_json)
Harald Welte4145d3c2021-04-08 20:34:13 +0200912 if data:
913 self._cmd.poutput_json(data)
Harald Welte4145d3c2021-04-08 20:34:13 +0200914
Harald Weltec91085e2022-02-10 18:05:45 +0100915 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100916 parent: Optional[CardDF] = None, rec_len={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200917 """
918 Args:
919 fid : File Identifier (4 hex digits)
920 sfid : Short File Identifier (2 hex digits, optional)
921 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200922 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200923 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier0adabf62021-04-20 22:36:41 +0200924 rec_len : set of {minimum_length, recommended_length}
Harald Welteee3501f2021-04-02 13:00:18 +0200925 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100926 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100927 self.rec_len = rec_len
928 self.shell_commands = [self.ShellCommands()]
Harald Welte2db5cfb2021-04-10 19:05:37 +0200929 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200930 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100931
Harald Weltec91085e2022-02-10 18:05:45 +0100932 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200933 """Decode raw (hex string) data into abstract representation.
934
935 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
936 method for implementing this specifically for the given file. This function checks which
937 of the method exists, add calls them (with conversion, as needed).
938
939 Args:
940 raw_hex_data : hex-encoded data
941 Returns:
942 abstract_data; dict representing the decoded data
943 """
Harald Welteb2edd142021-01-08 23:29:35 +0100944 method = getattr(self, '_decode_record_hex', None)
945 if callable(method):
946 return method(raw_hex_data)
947 raw_bin_data = h2b(raw_hex_data)
948 method = getattr(self, '_decode_record_bin', None)
949 if callable(method):
950 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200951 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200952 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200953 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100954 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100955 t.from_tlv(raw_bin_data)
956 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100957 return {'raw': raw_bin_data.hex()}
958
Harald Weltec91085e2022-02-10 18:05:45 +0100959 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200960 """Decode raw (binary) data into abstract representation.
961
962 A derived class would typically provide a _decode_record_bin() or _decode_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 raw_bin_data : binary encoded data
968 Returns:
969 abstract_data; dict representing the decoded data
970 """
Harald Welteb2edd142021-01-08 23:29:35 +0100971 method = getattr(self, '_decode_record_bin', None)
972 if callable(method):
973 return method(raw_bin_data)
974 raw_hex_data = b2h(raw_bin_data)
975 method = getattr(self, '_decode_record_hex', None)
976 if callable(method):
977 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200978 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200979 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200980 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100981 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100982 t.from_tlv(raw_bin_data)
983 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100984 return {'raw': raw_hex_data}
985
Harald Weltec91085e2022-02-10 18:05:45 +0100986 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200987 """Encode abstract representation into raw (hex string) data.
988
989 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
990 method for implementing this specifically for the given file. This function checks which
991 of the method exists, add calls them (with conversion, as needed).
992
993 Args:
994 abstract_data : dict representing the decoded data
995 Returns:
996 hex string encoded data
997 """
Harald Welteb2edd142021-01-08 23:29:35 +0100998 method = getattr(self, '_encode_record_hex', None)
999 if callable(method):
1000 return method(abstract_data)
1001 method = getattr(self, '_encode_record_bin', None)
1002 if callable(method):
1003 raw_bin_data = method(abstract_data)
Harald Welte1e456572021-04-02 17:16:30 +02001004 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001005 if self._construct:
1006 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +02001007 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001008 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001009 t.from_dict(abstract_data)
1010 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +01001011 raise NotImplementedError(
1012 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001013
Harald Weltec91085e2022-02-10 18:05:45 +01001014 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +02001015 """Encode abstract representation into raw (binary) data.
1016
1017 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1018 method for implementing this specifically for the given file. This function checks which
1019 of the method exists, add calls them (with conversion, as needed).
1020
1021 Args:
1022 abstract_data : dict representing the decoded data
1023 Returns:
1024 binary encoded data
1025 """
Harald Welteb2edd142021-01-08 23:29:35 +01001026 method = getattr(self, '_encode_record_bin', None)
1027 if callable(method):
1028 return method(abstract_data)
1029 method = getattr(self, '_encode_record_hex', None)
1030 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +02001031 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001032 if self._construct:
1033 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +02001034 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001035 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001036 t.from_dict(abstract_data)
1037 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +01001038 raise NotImplementedError(
1039 "%s encoder not yet implemented. Patches welcome." % self)
1040
Harald Welteb2edd142021-01-08 23:29:35 +01001041
1042class CyclicEF(LinFixedEF):
1043 """Cyclic EF (Entry File) in the smart card filesystem"""
1044 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Weltec91085e2022-02-10 18:05:45 +01001045
1046 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +01001047 rec_len={1, None}, **kwargs):
1048 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +01001049
Harald Welteb2edd142021-01-08 23:29:35 +01001050
1051class TransRecEF(TransparentEF):
1052 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +02001053
Harald Welteb2edd142021-01-08 23:29:35 +01001054 These are the real odd-balls and mostly look like mistakes in the specification:
1055 Specified as 'transparent' EF, but actually containing several fixed-length records
1056 inside.
1057 We add a special class for those, so the user only has to provide encoder/decoder functions
1058 for a record, while this class takes care of split / merge of records.
1059 """
Harald Weltec91085e2022-02-10 18:05:45 +01001060
1061 def __init__(self, fid: str, rec_len: int, sfid: str = None, name: str = None, desc: str = None,
Harald Welte13edf302022-07-21 15:19:23 +02001062 parent: Optional[CardDF] = None, size: Size = (1, None), **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +02001063 """
1064 Args:
1065 fid : File Identifier (4 hex digits)
1066 sfid : Short File Identifier (2 hex digits, optional)
Harald Weltec9cdce32021-04-11 10:28:28 +02001067 name : Brief name of the file, like EF_ICCID
1068 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +02001069 parent : Parent CardFile object within filesystem hierarchy
1070 rec_len : Length of the fixed-length records within transparent EF
1071 size : tuple of (minimum_size, recommended_size)
1072 """
Harald Welte9170fbf2022-02-11 21:54:37 +01001073 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +01001074 self.rec_len = rec_len
1075
Harald Weltec91085e2022-02-10 18:05:45 +01001076 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +02001077 """Decode raw (hex string) data into abstract representation.
1078
1079 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
1080 method for implementing this specifically for the given file. This function checks which
1081 of the method exists, add calls them (with conversion, as needed).
1082
1083 Args:
1084 raw_hex_data : hex-encoded data
1085 Returns:
1086 abstract_data; dict representing the decoded data
1087 """
Harald Welteb2edd142021-01-08 23:29:35 +01001088 method = getattr(self, '_decode_record_hex', None)
1089 if callable(method):
1090 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001091 raw_bin_data = h2b(raw_hex_data)
Harald Welteb2edd142021-01-08 23:29:35 +01001092 method = getattr(self, '_decode_record_bin', None)
1093 if callable(method):
Harald Welteb2edd142021-01-08 23:29:35 +01001094 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001095 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +02001096 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +02001097 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001098 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001099 t.from_tlv(raw_bin_data)
1100 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001101 return {'raw': raw_hex_data}
1102
Harald Weltec91085e2022-02-10 18:05:45 +01001103 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +02001104 """Decode raw (binary) data into abstract representation.
1105
1106 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
1107 method for implementing this specifically for the given file. This function checks which
1108 of the method exists, add calls them (with conversion, as needed).
1109
1110 Args:
1111 raw_bin_data : binary encoded data
1112 Returns:
1113 abstract_data; dict representing the decoded data
1114 """
Harald Welteb2edd142021-01-08 23:29:35 +01001115 method = getattr(self, '_decode_record_bin', None)
1116 if callable(method):
1117 return method(raw_bin_data)
1118 raw_hex_data = b2h(raw_bin_data)
1119 method = getattr(self, '_decode_record_hex', None)
1120 if callable(method):
1121 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001122 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +02001123 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +02001124 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001125 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001126 t.from_tlv(raw_bin_data)
1127 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001128 return {'raw': raw_hex_data}
1129
Harald Weltec91085e2022-02-10 18:05:45 +01001130 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +02001131 """Encode abstract representation into raw (hex string) data.
1132
1133 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1134 method for implementing this specifically for the given file. This function checks which
1135 of the method exists, add calls them (with conversion, as needed).
1136
1137 Args:
1138 abstract_data : dict representing the decoded data
1139 Returns:
1140 hex string encoded data
1141 """
Harald Welteb2edd142021-01-08 23:29:35 +01001142 method = getattr(self, '_encode_record_hex', None)
1143 if callable(method):
1144 return method(abstract_data)
1145 method = getattr(self, '_encode_record_bin', None)
1146 if callable(method):
Harald Welte1e456572021-04-02 17:16:30 +02001147 return b2h(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001148 if self._construct:
1149 return b2h(filter_dict(self._construct.build(abstract_data)))
Harald Weltefb506212021-05-29 21:28:24 +02001150 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001151 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001152 t.from_dict(abstract_data)
1153 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +01001154 raise NotImplementedError(
1155 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001156
Harald Weltec91085e2022-02-10 18:05:45 +01001157 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +02001158 """Encode abstract representation into raw (binary) data.
1159
1160 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1161 method for implementing this specifically for the given file. This function checks which
1162 of the method exists, add calls them (with conversion, as needed).
1163
1164 Args:
1165 abstract_data : dict representing the decoded data
1166 Returns:
1167 binary encoded data
1168 """
Harald Welteb2edd142021-01-08 23:29:35 +01001169 method = getattr(self, '_encode_record_bin', None)
1170 if callable(method):
1171 return method(abstract_data)
1172 method = getattr(self, '_encode_record_hex', None)
1173 if callable(method):
1174 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001175 if self._construct:
1176 return filter_dict(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +02001177 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001178 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001179 t.from_dict(abstract_data)
1180 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +01001181 raise NotImplementedError(
1182 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001183
Harald Weltec91085e2022-02-10 18:05:45 +01001184 def _decode_bin(self, raw_bin_data: bytearray):
1185 chunks = [raw_bin_data[i:i+self.rec_len]
1186 for i in range(0, len(raw_bin_data), self.rec_len)]
Harald Welteb2edd142021-01-08 23:29:35 +01001187 return [self.decode_record_bin(x) for x in chunks]
1188
Harald Welteee3501f2021-04-02 13:00:18 +02001189 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +01001190 chunks = [self.encode_record_bin(x) for x in abstract_data]
1191 # FIXME: pad to file size
1192 return b''.join(chunks)
1193
1194
Harald Welte917d98c2021-04-21 11:51:25 +02001195class BerTlvEF(CardEF):
Harald Welte27881622021-04-21 11:16:31 +02001196 """BER-TLV EF (Entry File) in the smart card filesystem.
1197 A BER-TLV EF is a binary file with a BER (Basic Encoding Rules) TLV structure
Harald Welteb2edd142021-01-08 23:29:35 +01001198
Harald Welte27881622021-04-21 11:16:31 +02001199 NOTE: We currently don't really support those, this class is simply a wrapper
1200 around TransparentEF as a place-holder, so we can already define EFs of BER-TLV
1201 type without fully supporting them."""
Harald Welteb2edd142021-01-08 23:29:35 +01001202
Harald Welte917d98c2021-04-21 11:51:25 +02001203 @with_default_category('BER-TLV EF Commands')
1204 class ShellCommands(CommandSet):
1205 """Shell commands specific for BER-TLV EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +01001206
Harald Welte917d98c2021-04-21 11:51:25 +02001207 def __init__(self):
1208 super().__init__()
1209
1210 retrieve_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001211 retrieve_data_parser.add_argument(
1212 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve')
1213
Harald Welte917d98c2021-04-21 11:51:25 +02001214 @cmd2.with_argparser(retrieve_data_parser)
1215 def do_retrieve_data(self, opts):
1216 """Retrieve (Read) data from a BER-TLV EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +02001217 (data, sw) = self._cmd.lchan.retrieve_data(opts.tag)
Harald Welte917d98c2021-04-21 11:51:25 +02001218 self._cmd.poutput(data)
1219
1220 def do_retrieve_tags(self, opts):
1221 """List tags available in a given BER-TLV EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +02001222 tags = self._cmd.lchan.retrieve_tags()
Harald Welte917d98c2021-04-21 11:51:25 +02001223 self._cmd.poutput(tags)
1224
1225 set_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001226 set_data_parser.add_argument(
1227 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1228 set_data_parser.add_argument(
1229 'data', help='Data bytes (hex format) to write')
1230
Harald Welte917d98c2021-04-21 11:51:25 +02001231 @cmd2.with_argparser(set_data_parser)
1232 def do_set_data(self, opts):
1233 """Set (Write) data for a given tag in a BER-TLV EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +02001234 (data, sw) = self._cmd.lchan.set_data(opts.tag, opts.data)
Harald Welte917d98c2021-04-21 11:51:25 +02001235 if data:
1236 self._cmd.poutput(data)
1237
1238 del_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001239 del_data_parser.add_argument(
1240 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1241
Harald Welte917d98c2021-04-21 11:51:25 +02001242 @cmd2.with_argparser(del_data_parser)
1243 def do_delete_data(self, opts):
1244 """Delete data for a given tag in a BER-TLV EF"""
Harald Weltea6c0f882022-07-17 14:23:17 +02001245 (data, sw) = self._cmd.lchan.set_data(opts.tag, None)
Harald Welte917d98c2021-04-21 11:51:25 +02001246 if data:
1247 self._cmd.poutput(data)
1248
Harald Weltec91085e2022-02-10 18:05:45 +01001249 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte13edf302022-07-21 15:19:23 +02001250 size: Size = (1, None), **kwargs):
Harald Welte917d98c2021-04-21 11:51:25 +02001251 """
1252 Args:
1253 fid : File Identifier (4 hex digits)
1254 sfid : Short File Identifier (2 hex digits, optional)
1255 name : Brief name of the file, lik EF_ICCID
1256 desc : Description of the file
1257 parent : Parent CardFile object within filesystem hierarchy
1258 size : tuple of (minimum_size, recommended_size)
1259 """
Harald Welte9170fbf2022-02-11 21:54:37 +01001260 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welte917d98c2021-04-21 11:51:25 +02001261 self._construct = None
1262 self.size = size
1263 self.shell_commands = [self.ShellCommands()]
1264
Harald Welteb2edd142021-01-08 23:29:35 +01001265
Vadim Yanitskiy04b5d9d2022-07-07 03:05:30 +07001266class RuntimeState:
Harald Welteb2edd142021-01-08 23:29:35 +01001267 """Represent the runtime state of a session with a card."""
Harald Weltec91085e2022-02-10 18:05:45 +01001268
1269 def __init__(self, card, profile: 'CardProfile'):
Harald Welteee3501f2021-04-02 13:00:18 +02001270 """
1271 Args:
1272 card : pysim.cards.Card instance
1273 profile : CardProfile instance
1274 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +01001275 self.mf = CardMF(profile=profile)
Harald Welteb2edd142021-01-08 23:29:35 +01001276 self.card = card
Harald Welteb2edd142021-01-08 23:29:35 +01001277 self.profile = profile
Harald Weltea6c0f882022-07-17 14:23:17 +02001278 self.lchan = {}
1279 # the basic logical channel always exists
1280 self.lchan[0] = RuntimeLchan(0, self)
Philipp Maier51cad0d2021-11-08 15:45:10 +01001281
1282 # make sure the class and selection control bytes, which are specified
1283 # by the card profile are used
Harald Weltec91085e2022-02-10 18:05:45 +01001284 self.card.set_apdu_parameter(
1285 cla=self.profile.cla, sel_ctrl=self.profile.sel_ctrl)
Philipp Maier51cad0d2021-11-08 15:45:10 +01001286
Harald Welte5ce35242021-04-02 20:27:05 +02001287 # add application ADFs + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001288 apps = self._match_applications()
1289 for a in apps:
Harald Welte5ce35242021-04-02 20:27:05 +02001290 if a.adf:
1291 self.mf.add_application_df(a.adf)
Harald Welteb2edd142021-01-08 23:29:35 +01001292 for f in self.profile.files_in_mf:
1293 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +01001294 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +01001295
Philipp Maier4e2e1d92021-11-08 15:36:01 +01001296 # make sure that when the runtime state is created, the card is also
1297 # in a defined state.
1298 self.reset()
1299
Philipp Maier1e896f32021-03-10 17:02:53 +01001300 def _match_applications(self):
1301 """match the applications from the profile with applications on the card"""
1302 apps_profile = self.profile.applications
Philipp Maierd454fe72021-11-08 15:32:23 +01001303
1304 # When the profile does not feature any applications, then we are done already
1305 if not apps_profile:
1306 return []
1307
1308 # Read AIDs from card and match them against the applications defined by the
1309 # card profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001310 aids_card = self.card.read_aids()
1311 apps_taken = []
1312 if aids_card:
1313 aids_taken = []
1314 print("AIDs on card:")
1315 for a in aids_card:
1316 for f in apps_profile:
1317 if f.aid in a:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001318 print(" %s: %s (EF.DIR)" % (f.name, a))
Philipp Maier1e896f32021-03-10 17:02:53 +01001319 aids_taken.append(a)
1320 apps_taken.append(f)
1321 aids_unknown = set(aids_card) - set(aids_taken)
1322 for a in aids_unknown:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001323 print(" unknown: %s (EF.DIR)" % a)
Philipp Maier1e896f32021-03-10 17:02:53 +01001324 else:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001325 print("warning: EF.DIR seems to be empty!")
1326
1327 # Some card applications may not be registered in EF.DIR, we will actively
1328 # probe for those applications
1329 for f in set(apps_profile) - set(apps_taken):
Bjoern Riemerda57ef12022-01-18 15:38:14 +01001330 try:
1331 data, sw = self.card.select_adf_by_aid(f.aid)
1332 if sw == "9000":
1333 print(" %s: %s" % (f.name, f.aid))
1334 apps_taken.append(f)
1335 except SwMatchError:
1336 pass
Philipp Maier1e896f32021-03-10 17:02:53 +01001337 return apps_taken
1338
Harald Weltea6c0f882022-07-17 14:23:17 +02001339 def reset(self, cmd_app=None) -> Hexstr:
1340 """Perform physical card reset and obtain ATR.
1341 Args:
1342 cmd_app : Command Application State (for unregistering old file commands)
1343 """
1344 # delete all lchan != 0 (basic lchan)
1345 for lchan_nr in self.lchan.keys():
1346 if lchan_nr == 0:
1347 continue
1348 del self.lchan[lchan_nr]
1349 atr = i2h(self.card.reset())
1350 # select MF to reset internal state and to verify card really works
1351 self.lchan[0].select('MF', cmd_app)
1352 self.lchan[0].selected_adf = None
1353 return atr
1354
1355 def add_lchan(self, lchan_nr: int) -> 'RuntimeLchan':
1356 """Add a logical channel to the runtime state. You shouldn't call this
1357 directly but always go through RuntimeLchan.add_lchan()."""
1358 if lchan_nr in self.lchan.keys():
1359 raise ValueError('Cannot create already-existing lchan %d' % lchan_nr)
1360 self.lchan[lchan_nr] = RuntimeLchan(lchan_nr, self)
1361 return self.lchan[lchan_nr]
1362
1363 def del_lchan(self, lchan_nr: int):
1364 if lchan_nr in self.lchan.keys():
1365 del self.lchan[lchan_nr]
1366 return True
1367 else:
1368 return False
1369
1370 def get_lchan_by_cla(self, cla) -> Optional['RuntimeLchan']:
1371 lchan_nr = lchan_nr_from_cla(cla)
1372 if lchan_nr in self.lchan.keys():
1373 return self.lchan[lchan_nr]
1374 else:
1375 return None
1376
1377
1378class RuntimeLchan:
1379 """Represent the runtime state of a logical channel with a card."""
1380
1381 def __init__(self, lchan_nr: int, rs: RuntimeState):
1382 self.lchan_nr = lchan_nr
1383 self.rs = rs
1384 self.selected_file = self.rs.mf
1385 self.selected_adf = None
1386 self.selected_file_fcp = None
1387 self.selected_file_fcp_hex = None
1388
1389 def add_lchan(self, lchan_nr: int) -> 'RuntimeLchan':
1390 """Add a new logical channel from the current logical channel. Just affects
1391 internal state, doesn't actually open a channel with the UICC."""
1392 new_lchan = self.rs.add_lchan(lchan_nr)
1393 # See TS 102 221 Table 8.3
1394 if self.lchan_nr != 0:
1395 new_lchan.selected_file = self.get_cwd()
1396 new_lchan.selected_adf = self.selected_adf
1397 return new_lchan
1398
Harald Welte747a9782022-02-13 17:52:28 +01001399 def selected_file_descriptor_byte(self) -> dict:
1400 return self.selected_file_fcp['file_descriptor']['file_descriptor_byte']
1401
1402 def selected_file_shareable(self) -> bool:
1403 return self.selected_file_descriptor_byte()['shareable']
1404
1405 def selected_file_structure(self) -> str:
1406 return self.selected_file_descriptor_byte()['structure']
1407
1408 def selected_file_type(self) -> str:
1409 return self.selected_file_descriptor_byte()['file_type']
1410
1411 def selected_file_num_of_rec(self) -> Optional[int]:
1412 return self.selected_file_fcp['file_descriptor'].get('num_of_rec')
1413
Harald Welteee3501f2021-04-02 13:00:18 +02001414 def get_cwd(self) -> CardDF:
1415 """Obtain the current working directory.
1416
1417 Returns:
1418 CardDF instance
1419 """
Harald Welteb2edd142021-01-08 23:29:35 +01001420 if isinstance(self.selected_file, CardDF):
1421 return self.selected_file
1422 else:
1423 return self.selected_file.parent
1424
Harald Welte5ce35242021-04-02 20:27:05 +02001425 def get_application_df(self) -> Optional[CardADF]:
1426 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +02001427
1428 Returns:
1429 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +01001430 # iterate upwards from selected file; check if any is an ADF
1431 node = self.selected_file
1432 while node.parent != node:
1433 if isinstance(node, CardADF):
1434 return node
1435 node = node.parent
1436 return None
1437
Harald Weltec91085e2022-02-10 18:05:45 +01001438 def interpret_sw(self, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001439 """Interpret a given status word relative to the currently selected application
1440 or the underlying card profile.
1441
1442 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001443 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001444
1445 Returns:
1446 Tuple of two strings
1447 """
Harald Welte86fbd392021-04-02 22:13:09 +02001448 res = None
Harald Welte5ce35242021-04-02 20:27:05 +02001449 adf = self.get_application_df()
1450 if adf:
1451 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +01001452 # The application either comes with its own interpret_sw
1453 # method or we will use the interpret_sw method from the
1454 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +02001455 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +02001456 res = app.interpret_sw(sw)
Harald Weltea6c0f882022-07-17 14:23:17 +02001457 return res or self.rs.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +01001458
Harald Weltec91085e2022-02-10 18:05:45 +01001459 def probe_file(self, fid: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001460 """Blindly try to select a file and automatically add a matching file
Harald Weltec91085e2022-02-10 18:05:45 +01001461 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +01001462 if not is_hex(fid, 4, 4):
Harald Weltec91085e2022-02-10 18:05:45 +01001463 raise ValueError(
1464 "Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
Philipp Maier63f572d2021-03-09 22:42:47 +01001465
1466 try:
Harald Weltea6c0f882022-07-17 14:23:17 +02001467 (data, sw) = self.rs.card._scc.select_file(fid)
Philipp Maier63f572d2021-03-09 22:42:47 +01001468 except SwMatchError as swm:
1469 k = self.interpret_sw(swm.sw_actual)
1470 if not k:
1471 raise(swm)
1472 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
1473
1474 select_resp = self.selected_file.decode_select_response(data)
Harald Welte747a9782022-02-13 17:52:28 +01001475 if (select_resp['file_descriptor']['file_descriptor_byte']['file_type'] == 'df'):
Harald Weltec91085e2022-02-10 18:05:45 +01001476 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(),
1477 desc="dedicated file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001478 else:
Harald Welte747a9782022-02-13 17:52:28 +01001479 if (select_resp['file_descriptor']['file_descriptor_byte']['structure'] == 'transparent'):
Harald Weltec91085e2022-02-10 18:05:45 +01001480 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1481 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001482 else:
Harald Weltec91085e2022-02-10 18:05:45 +01001483 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1484 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001485
1486 self.selected_file.add_files([f])
1487 self.selected_file = f
Philipp Maier6b8eedc2022-06-01 18:10:04 +02001488 return select_resp, data
Philipp Maier63f572d2021-03-09 22:42:47 +01001489
Harald Welteaceb2a52022-02-12 21:41:59 +01001490 def _select_pre(self, cmd_app):
1491 # unregister commands of old file
1492 if cmd_app and self.selected_file.shell_commands:
1493 for c in self.selected_file.shell_commands:
1494 cmd_app.unregister_command_set(c)
1495
1496 def _select_post(self, cmd_app):
1497 # register commands of new file
1498 if cmd_app and self.selected_file.shell_commands:
1499 for c in self.selected_file.shell_commands:
1500 cmd_app.register_command_set(c)
1501
1502 def select_file(self, file: CardFile, cmd_app=None):
1503 """Select a file (EF, DF, ADF, MF, ...).
1504
1505 Args:
1506 file : CardFile [or derived class] instance
1507 cmd_app : Command Application State (for unregistering old file commands)
1508 """
1509 # we need to find a path from our self.selected_file to the destination
1510 inter_path = self.selected_file.build_select_path_to(file)
1511 if not inter_path:
1512 raise RuntimeError('Cannot determine path from %s to %s' % (self.selected_file, file))
1513
1514 self._select_pre(cmd_app)
1515
1516 for p in inter_path:
1517 try:
1518 if isinstance(p, CardADF):
Harald Weltea6c0f882022-07-17 14:23:17 +02001519 (data, sw) = self.rs.card.select_adf_by_aid(p.aid)
Harald Welte46a7a3f2022-07-16 11:47:47 +02001520 self.selected_adf = p
Harald Welteaceb2a52022-02-12 21:41:59 +01001521 else:
Harald Weltea6c0f882022-07-17 14:23:17 +02001522 (data, sw) = self.rs.card._scc.select_file(p.fid)
Harald Welteaceb2a52022-02-12 21:41:59 +01001523 self.selected_file = p
1524 except SwMatchError as swm:
1525 self._select_post(cmd_app)
1526 raise(swm)
1527
1528 self._select_post(cmd_app)
1529
Harald Weltec91085e2022-02-10 18:05:45 +01001530 def select(self, name: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001531 """Select a file (EF, DF, ADF, MF, ...).
1532
1533 Args:
1534 name : Name of file to select
1535 cmd_app : Command Application State (for unregistering old file commands)
1536 """
Harald Welteee670bc2022-02-13 15:10:15 +01001537 # handling of entire paths with multiple directories/elements
1538 if '/' in name:
1539 prev_sel_file = self.selected_file
1540 pathlist = name.split('/')
1541 # treat /DF.GSM/foo like MF/DF.GSM/foo
1542 if pathlist[0] == '':
1543 pathlist[0] = 'MF'
1544 try:
1545 for p in pathlist:
1546 self.select(p, cmd_app)
1547 return
1548 except Exception as e:
1549 # if any intermediate step fails, go back to where we were
1550 self.select_file(prev_sel_file, cmd_app)
1551 raise e
1552
Harald Welteb2edd142021-01-08 23:29:35 +01001553 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +01001554 if is_hex(name):
1555 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +01001556
Harald Welteaceb2a52022-02-12 21:41:59 +01001557 self._select_pre(cmd_app)
Philipp Maier63f572d2021-03-09 22:42:47 +01001558
Harald Welteb2edd142021-01-08 23:29:35 +01001559 if name in sels:
1560 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +01001561 try:
1562 if isinstance(f, CardADF):
Harald Weltea6c0f882022-07-17 14:23:17 +02001563 (data, sw) = self.rs.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +01001564 else:
Harald Weltea6c0f882022-07-17 14:23:17 +02001565 (data, sw) = self.rs.card._scc.select_file(f.fid)
Harald Welteb2edd142021-01-08 23:29:35 +01001566 self.selected_file = f
1567 except SwMatchError as swm:
1568 k = self.interpret_sw(swm.sw_actual)
1569 if not k:
1570 raise(swm)
1571 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +01001572 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001573 else:
Philipp Maier6b8eedc2022-06-01 18:10:04 +02001574 (select_resp, data) = self.probe_file(name, cmd_app)
1575
Harald Welte2bb17f32022-02-15 15:41:55 +01001576 # store the raw + decoded FCP for later reference
1577 self.selected_file_fcp_hex = data
Harald Welte850b72a2021-04-07 09:33:03 +02001578 self.selected_file_fcp = select_resp
Philipp Maier63f572d2021-03-09 22:42:47 +01001579
Harald Welteaceb2a52022-02-12 21:41:59 +01001580 self._select_post(cmd_app)
Philipp Maier63f572d2021-03-09 22:42:47 +01001581 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +01001582
Harald Welte34b05d32021-05-25 22:03:13 +02001583 def status(self):
1584 """Request STATUS (current selected file FCP) from card."""
Harald Weltea6c0f882022-07-17 14:23:17 +02001585 (data, sw) = self.rs.card._scc.status()
Harald Welte34b05d32021-05-25 22:03:13 +02001586 return self.selected_file.decode_select_response(data)
1587
Harald Welte3c9b7842021-10-19 21:44:24 +02001588 def get_file_for_selectable(self, name: str):
1589 sels = self.selected_file.get_selectables()
1590 return sels[name]
1591
Harald Weltec91085e2022-02-10 18:05:45 +01001592 def activate_file(self, name: str):
Harald Welte485692b2021-05-25 22:21:44 +02001593 """Request ACTIVATE FILE of specified file."""
1594 sels = self.selected_file.get_selectables()
1595 f = sels[name]
Harald Weltea6c0f882022-07-17 14:23:17 +02001596 data, sw = self.rs.card._scc.activate_file(f.fid)
Harald Welte485692b2021-05-25 22:21:44 +02001597 return data, sw
1598
Harald Weltec91085e2022-02-10 18:05:45 +01001599 def read_binary(self, length: int = None, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001600 """Read [part of] a transparent EF binary data.
1601
1602 Args:
1603 length : Amount of data to read (None: as much as possible)
1604 offset : Offset into the file from which to read 'length' bytes
1605 Returns:
1606 binary data read from the file
1607 """
Harald Welteb2edd142021-01-08 23:29:35 +01001608 if not isinstance(self.selected_file, TransparentEF):
1609 raise TypeError("Only works with TransparentEF")
Harald Weltea6c0f882022-07-17 14:23:17 +02001610 return self.rs.card._scc.read_binary(self.selected_file.fid, length, offset)
Harald Welteb2edd142021-01-08 23:29:35 +01001611
Harald Welte2d4a64b2021-04-03 09:01:24 +02001612 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001613 """Read [part of] a transparent EF binary data and decode it.
1614
1615 Args:
1616 length : Amount of data to read (None: as much as possible)
1617 offset : Offset into the file from which to read 'length' bytes
1618 Returns:
1619 abstract decode data read from the file
1620 """
Harald Welteb2edd142021-01-08 23:29:35 +01001621 (data, sw) = self.read_binary()
1622 dec_data = self.selected_file.decode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001623 return (dec_data, sw)
1624
Harald Weltec91085e2022-02-10 18:05:45 +01001625 def update_binary(self, data_hex: str, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001626 """Update transparent EF binary data.
1627
1628 Args:
1629 data_hex : hex string of data to be written
1630 offset : Offset into the file from which to write 'data_hex'
1631 """
Harald Welteb2edd142021-01-08 23:29:35 +01001632 if not isinstance(self.selected_file, TransparentEF):
1633 raise TypeError("Only works with TransparentEF")
Harald Weltea6c0f882022-07-17 14:23:17 +02001634 return self.rs.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.rs.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001635
Harald Weltec91085e2022-02-10 18:05:45 +01001636 def update_binary_dec(self, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001637 """Update transparent EF from abstract data. Encodes the data to binary and
1638 then updates the EF with it.
1639
1640 Args:
1641 data : abstract data which is to be encoded and written
1642 """
Harald Welteb2edd142021-01-08 23:29:35 +01001643 data_hex = self.selected_file.encode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001644 return self.update_binary(data_hex)
1645
Harald Weltec91085e2022-02-10 18:05:45 +01001646 def read_record(self, rec_nr: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001647 """Read a record as binary data.
1648
1649 Args:
1650 rec_nr : Record number to read
1651 Returns:
1652 hex string of binary data contained in record
1653 """
Harald Welteb2edd142021-01-08 23:29:35 +01001654 if not isinstance(self.selected_file, LinFixedEF):
1655 raise TypeError("Only works with Linear Fixed EF")
1656 # returns a string of hex nibbles
Harald Weltea6c0f882022-07-17 14:23:17 +02001657 return self.rs.card._scc.read_record(self.selected_file.fid, rec_nr)
Harald Welteb2edd142021-01-08 23:29:35 +01001658
Harald Weltec91085e2022-02-10 18:05:45 +01001659 def read_record_dec(self, rec_nr: int = 0) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001660 """Read a record and decode it to abstract data.
1661
1662 Args:
1663 rec_nr : Record number to read
1664 Returns:
1665 abstract data contained in record
1666 """
Harald Welteb2edd142021-01-08 23:29:35 +01001667 (data, sw) = self.read_record(rec_nr)
1668 return (self.selected_file.decode_record_hex(data), sw)
1669
Harald Weltec91085e2022-02-10 18:05:45 +01001670 def update_record(self, rec_nr: int, data_hex: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001671 """Update a record with given binary data
1672
1673 Args:
1674 rec_nr : Record number to read
1675 data_hex : Hex string binary data to be written
1676 """
Harald Welteb2edd142021-01-08 23:29:35 +01001677 if not isinstance(self.selected_file, LinFixedEF):
1678 raise TypeError("Only works with Linear Fixed EF")
Harald Weltea6c0f882022-07-17 14:23:17 +02001679 return self.rs.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex, conserve=self.rs.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001680
Harald Weltec91085e2022-02-10 18:05:45 +01001681 def update_record_dec(self, rec_nr: int, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001682 """Update a record with given abstract data. Will encode abstract to binary data
1683 and then write it to the given record on the card.
1684
1685 Args:
1686 rec_nr : Record number to read
1687 data_hex : Abstract data to be written
1688 """
Harald Welte1e456572021-04-02 17:16:30 +02001689 data_hex = self.selected_file.encode_record_hex(data)
1690 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001691
Harald Weltec91085e2022-02-10 18:05:45 +01001692 def retrieve_data(self, tag: int = 0):
Harald Welte917d98c2021-04-21 11:51:25 +02001693 """Read a DO/TLV as binary data.
1694
1695 Args:
1696 tag : Tag of TLV/DO to read
1697 Returns:
1698 hex string of full BER-TLV DO including Tag and Length
1699 """
1700 if not isinstance(self.selected_file, BerTlvEF):
1701 raise TypeError("Only works with BER-TLV EF")
1702 # returns a string of hex nibbles
Harald Weltea6c0f882022-07-17 14:23:17 +02001703 return self.rs.card._scc.retrieve_data(self.selected_file.fid, tag)
Harald Welte917d98c2021-04-21 11:51:25 +02001704
1705 def retrieve_tags(self):
1706 """Retrieve tags available on BER-TLV EF.
1707
1708 Returns:
1709 list of integer tags contained in EF
1710 """
1711 if not isinstance(self.selected_file, BerTlvEF):
1712 raise TypeError("Only works with BER-TLV EF")
Harald Weltea6c0f882022-07-17 14:23:17 +02001713 data, sw = self.rs.card._scc.retrieve_data(self.selected_file.fid, 0x5c)
Harald Weltec1475302021-05-21 21:47:55 +02001714 tag, length, value, remainder = bertlv_parse_one(h2b(data))
Harald Welte917d98c2021-04-21 11:51:25 +02001715 return list(value)
1716
Harald Weltec91085e2022-02-10 18:05:45 +01001717 def set_data(self, tag: int, data_hex: str):
Harald Welte917d98c2021-04-21 11:51:25 +02001718 """Update a TLV/DO with given binary data
1719
1720 Args:
1721 tag : Tag of TLV/DO to be written
1722 data_hex : Hex string binary data to be written (value portion)
1723 """
1724 if not isinstance(self.selected_file, BerTlvEF):
1725 raise TypeError("Only works with BER-TLV EF")
Harald Weltea6c0f882022-07-17 14:23:17 +02001726 return self.rs.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.rs.conserve_write)
Harald Welte917d98c2021-04-21 11:51:25 +02001727
Philipp Maier5d698e52021-09-16 13:18:01 +02001728 def unregister_cmds(self, cmd_app=None):
1729 """Unregister all file specific commands."""
1730 if cmd_app and self.selected_file.shell_commands:
1731 for c in self.selected_file.shell_commands:
1732 cmd_app.unregister_command_set(c)
Harald Welte917d98c2021-04-21 11:51:25 +02001733
Harald Welteb2edd142021-01-08 23:29:35 +01001734
Vadim Yanitskiy04b5d9d2022-07-07 03:05:30 +07001735class FileData:
Harald Welteb2edd142021-01-08 23:29:35 +01001736 """Represent the runtime, on-card data."""
Harald Weltec91085e2022-02-10 18:05:45 +01001737
Harald Welteb2edd142021-01-08 23:29:35 +01001738 def __init__(self, fdesc):
1739 self.desc = fdesc
1740 self.fcp = None
1741
1742
Harald Weltec91085e2022-02-10 18:05:45 +01001743def interpret_sw(sw_data: dict, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001744 """Interpret a given status word.
1745
1746 Args:
1747 sw_data : Hierarchical dict of status word matches
1748 sw : status word to match (string of 4 hex digits)
1749 Returns:
1750 tuple of two strings (class_string, description)
1751 """
Harald Welteb2edd142021-01-08 23:29:35 +01001752 for class_str, swdict in sw_data.items():
1753 # first try direct match
1754 if sw in swdict:
1755 return (class_str, swdict[sw])
1756 # next try wildcard matches
1757 for pattern, descr in swdict.items():
1758 if sw_match(sw, pattern):
1759 return (class_str, descr)
1760 return None
1761
Harald Weltec91085e2022-02-10 18:05:45 +01001762
Vadim Yanitskiy04b5d9d2022-07-07 03:05:30 +07001763class CardApplication:
Harald Welteb2edd142021-01-08 23:29:35 +01001764 """A card application is represented by an ADF (with contained hierarchy) and optionally
1765 some SW definitions."""
Harald Weltec91085e2022-02-10 18:05:45 +01001766
1767 def __init__(self, name, adf: Optional[CardADF] = None, aid: str = None, sw: dict = None):
Harald Welteee3501f2021-04-02 13:00:18 +02001768 """
1769 Args:
1770 adf : ADF name
1771 sw : Dict of status word conversions
1772 """
Harald Welteb2edd142021-01-08 23:29:35 +01001773 self.name = name
1774 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001775 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001776 # back-reference from ADF to Applicaiton
1777 if self.adf:
1778 self.aid = aid or self.adf.aid
1779 self.adf.application = self
1780 else:
1781 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001782
1783 def __str__(self):
1784 return "APP(%s)" % (self.name)
1785
1786 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001787 """Interpret a given status word within the application.
1788
1789 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001790 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001791
1792 Returns:
1793 Tuple of two strings
1794 """
Harald Welteb2edd142021-01-08 23:29:35 +01001795 return interpret_sw(self.sw, sw)
1796
Harald Weltef44256c2021-10-14 15:53:39 +02001797
1798class CardModel(abc.ABC):
Harald Welte4c1dca02021-10-14 17:48:25 +02001799 """A specific card model, typically having some additional vendor-specific files. All
1800 you need to do is to define a sub-class with a list of ATRs or an overridden match
1801 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001802 _atrs = []
1803
1804 @classmethod
1805 @abc.abstractmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001806 def add_files(cls, rs: RuntimeState):
Harald Weltef44256c2021-10-14 15:53:39 +02001807 """Add model specific files to given RuntimeState."""
1808
1809 @classmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001810 def match(cls, scc: SimCardCommands) -> bool:
Harald Weltef44256c2021-10-14 15:53:39 +02001811 """Test if given card matches this model."""
1812 card_atr = scc.get_atr()
1813 for atr in cls._atrs:
1814 atr_bin = toBytes(atr)
1815 if atr_bin == card_atr:
1816 print("Detected CardModel:", cls.__name__)
1817 return True
1818 return False
1819
1820 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001821 def apply_matching_models(scc: SimCardCommands, rs: RuntimeState):
Harald Welte4c1dca02021-10-14 17:48:25 +02001822 """Check if any of the CardModel sub-classes 'match' the currently inserted card
1823 (by ATR or overriding the 'match' method). If so, call their 'add_files'
1824 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001825 for m in CardModel.__subclasses__():
1826 if m.match(scc):
1827 m.add_files(rs)