blob: a323c5b39bb23ff73446919cfca053a160c84ec9 [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
Philipp Maier9e42e7f2021-11-16 15:46:42 +010037from typing import cast, Optional, Iterable, List, Dict, Tuple
Harald Welteee3501f2021-04-02 13:00:18 +020038
Harald Weltef44256c2021-10-14 15:53:39 +020039from smartcard.util import toBytes
40
Harald Weltedaf2b392021-05-03 23:17:29 +020041from pySim.utils import sw_match, h2b, b2h, i2h, is_hex, auto_int, bertlv_parse_one, Hexstr
Harald Welte07c7b1f2021-05-28 22:01:29 +020042from pySim.construct import filter_dict, parse_construct
Harald Welteb2edd142021-01-08 23:29:35 +010043from pySim.exceptions import *
Harald Welte0d4e98a2021-04-07 00:14:40 +020044from pySim.jsonpath import js_path_find, js_path_modify
Harald Weltef44256c2021-10-14 15:53:39 +020045from pySim.commands import SimCardCommands
Harald Welteb2edd142021-01-08 23:29:35 +010046
Harald Weltec91085e2022-02-10 18:05:45 +010047
Harald Welteb2edd142021-01-08 23:29:35 +010048class CardFile(object):
49 """Base class for all objects in the smart card filesystem.
50 Serve as a common ancestor to all other file types; rarely used directly.
51 """
52 RESERVED_NAMES = ['..', '.', '/', 'MF']
53 RESERVED_FIDS = ['3f00']
54
Harald Weltec91085e2022-02-10 18:05:45 +010055 def __init__(self, fid: str = None, sfid: str = None, name: str = None, desc: str = None,
56 parent: Optional['CardDF'] = None, profile: Optional['CardProfile'] = None):
Harald Welteee3501f2021-04-02 13:00:18 +020057 """
58 Args:
59 fid : File Identifier (4 hex digits)
60 sfid : Short File Identifier (2 hex digits, optional)
61 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +020062 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +020063 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier5af7bdf2021-11-04 12:48:41 +010064 profile : Card profile that this file should be part of
Harald Welteee3501f2021-04-02 13:00:18 +020065 """
Harald Welteb2edd142021-01-08 23:29:35 +010066 if not isinstance(self, CardADF) and fid == None:
67 raise ValueError("fid is mandatory")
68 if fid:
69 fid = fid.lower()
70 self.fid = fid # file identifier
71 self.sfid = sfid # short file identifier
72 self.name = name # human readable name
73 self.desc = desc # human readable description
74 self.parent = parent
75 if self.parent and self.parent != self and self.fid:
76 self.parent.add_file(self)
Philipp Maier5af7bdf2021-11-04 12:48:41 +010077 self.profile = profile
Harald Weltec91085e2022-02-10 18:05:45 +010078 self.shell_commands = [] # type: List[CommandSet]
Harald Welteb2edd142021-01-08 23:29:35 +010079
Harald Weltec91085e2022-02-10 18:05:45 +010080 # Note: the basic properties (fid, name, ect.) are verified when
81 # the file is attached to a parent file. See method add_file() in
82 # class Card DF
Philipp Maier66061582021-03-09 21:57:57 +010083
Harald Welteb2edd142021-01-08 23:29:35 +010084 def __str__(self):
85 if self.name:
86 return self.name
87 else:
88 return self.fid
89
Harald Weltec91085e2022-02-10 18:05:45 +010090 def _path_element(self, prefer_name: bool) -> Optional[str]:
Harald Welteb2edd142021-01-08 23:29:35 +010091 if prefer_name and self.name:
92 return self.name
93 else:
94 return self.fid
95
Harald Weltec91085e2022-02-10 18:05:45 +010096 def fully_qualified_path(self, prefer_name: bool = True) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +020097 """Return fully qualified path to file as list of FID or name strings.
98
99 Args:
100 prefer_name : Preferably build path of names; fall-back to FIDs as required
101 """
Harald Welte1e456572021-04-02 17:16:30 +0200102 if self.parent and self.parent != self:
Harald Welteb2edd142021-01-08 23:29:35 +0100103 ret = self.parent.fully_qualified_path(prefer_name)
104 else:
105 ret = []
Harald Welte1e456572021-04-02 17:16:30 +0200106 elem = self._path_element(prefer_name)
107 if elem:
108 ret.append(elem)
Harald Welteb2edd142021-01-08 23:29:35 +0100109 return ret
110
Harald Welteee3501f2021-04-02 13:00:18 +0200111 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +0100112 """Return the MF (root) of the file system."""
113 if self.parent == None:
114 return None
115 # iterate towards the top. MF has parent == self
116 node = self
Harald Welte1e456572021-04-02 17:16:30 +0200117 while node.parent and node.parent != node:
Harald Welteb2edd142021-01-08 23:29:35 +0100118 node = node.parent
Harald Welte1e456572021-04-02 17:16:30 +0200119 return cast(CardMF, node)
Harald Welteb2edd142021-01-08 23:29:35 +0100120
Harald Weltec91085e2022-02-10 18:05:45 +0100121 def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200122 """Return a dict of {'identifier': self} tuples.
123
124 Args:
125 alias : Add an alias with given name to 'self'
126 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
127 If not specified, all selectables will be returned.
128 Returns:
129 dict containing reference to 'self' for all identifiers.
130 """
Harald Welteb2edd142021-01-08 23:29:35 +0100131 sels = {}
132 if alias:
133 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100134 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100135 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100136 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100137 sels.update({self.name: self})
138 return sels
139
Harald Weltec91085e2022-02-10 18:05:45 +0100140 def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200141 """Return a dict of {'identifier': File} that is selectable from the current file.
142
143 Args:
144 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
145 If not specified, all selectables will be returned.
146 Returns:
147 dict containing all selectable items. Key is identifier (string), value
148 a reference to a CardFile (or derived class) instance.
149 """
Philipp Maier786f7812021-02-25 16:48:10 +0100150 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100151 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100152 if flags == [] or 'SELF' in flags:
153 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100154 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100155 if flags == [] or 'PARENT' in flags:
Harald Welte1e456572021-04-02 17:16:30 +0200156 if self.parent:
157 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100158 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100159 if flags == [] or 'MF' in flags:
160 mf = self.get_mf()
161 if mf:
Harald Weltec91085e2022-02-10 18:05:45 +0100162 sels.update(mf._get_self_selectables(flags=flags))
163 sels.update(mf.get_app_selectables(flags=flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100164 return sels
165
Harald Weltec91085e2022-02-10 18:05:45 +0100166 def get_selectable_names(self, flags=[]) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200167 """Return a dict of {'identifier': File} that is selectable from the current file.
168
169 Args:
170 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
171 If not specified, all selectables will be returned.
172 Returns:
Harald Welte1e456572021-04-02 17:16:30 +0200173 list containing all selectable names.
Harald Welteee3501f2021-04-02 13:00:18 +0200174 """
Philipp Maier786f7812021-02-25 16:48:10 +0100175 sels = self.get_selectables(flags)
Harald Welteb3d68c02022-01-21 15:31:29 +0100176 sel_keys = list(sels.keys())
177 sel_keys.sort()
178 return sel_keys
Harald Welteb2edd142021-01-08 23:29:35 +0100179
Harald Weltec91085e2022-02-10 18:05:45 +0100180 def decode_select_response(self, data_hex: str):
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100181 """Decode the response to a SELECT command.
182
183 Args:
Harald Weltec91085e2022-02-10 18:05:45 +0100184 data_hex: Hex string of the select response
185 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100186
Harald Weltec91085e2022-02-10 18:05:45 +0100187 # When the current file does not implement a custom select response decoder,
188 # we just ask the parent file to decode the select response. If this method
189 # is not overloaded by the current file we will again ask the parent file.
190 # This way we recursively travel up the file system tree until we hit a file
191 # that does implement a concrete decoder.
Harald Welte1e456572021-04-02 17:16:30 +0200192 if self.parent:
193 return self.parent.decode_select_response(data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +0100194
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100195 def get_profile(self):
196 """Get the profile associated with this file. If this file does not have any
197 profile assigned, try to find a file above (usually the MF) in the filesystem
198 hirarchy that has a profile assigned
199 """
200
201 # If we have a profile set, return it
202 if self.profile:
203 return self.profile
204
205 # Walk up recursively until we hit a parent that has a profile set
206 if self.parent:
207 return self.parent.get_profile()
208 return None
Harald Welteb2edd142021-01-08 23:29:35 +0100209
Harald Weltec91085e2022-02-10 18:05:45 +0100210
Harald Welteb2edd142021-01-08 23:29:35 +0100211class CardDF(CardFile):
212 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100213
214 @with_default_category('DF/ADF Commands')
215 class ShellCommands(CommandSet):
216 def __init__(self):
217 super().__init__()
218
Harald Welteb2edd142021-01-08 23:29:35 +0100219 def __init__(self, **kwargs):
220 if not isinstance(self, CardADF):
221 if not 'fid' in kwargs:
222 raise TypeError('fid is mandatory for all DF')
223 super().__init__(**kwargs)
224 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100225 self.shell_commands = [self.ShellCommands()]
Harald Welteb2edd142021-01-08 23:29:35 +0100226
227 def __str__(self):
228 return "DF(%s)" % (super().__str__())
229
Harald Weltec91085e2022-02-10 18:05:45 +0100230 def add_file(self, child: CardFile, ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200231 """Add a child (DF/EF) to this DF.
232 Args:
233 child: The new DF/EF to be added
234 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
235 """
Harald Welteb2edd142021-01-08 23:29:35 +0100236 if not isinstance(child, CardFile):
237 raise TypeError("Expected a File instance")
Harald Weltec91085e2022-02-10 18:05:45 +0100238 if not is_hex(child.fid, minlen=4, maxlen=4):
Philipp Maier3aec8712021-03-09 21:49:01 +0100239 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100240 if child.name in CardFile.RESERVED_NAMES:
241 raise ValueError("File name %s is a reserved name" % (child.name))
242 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100243 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100244 if child.fid in self.children:
245 if ignore_existing:
246 return
Harald Weltec91085e2022-02-10 18:05:45 +0100247 raise ValueError(
248 "File with given fid %s already exists in %s" % (child.fid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100249 if self.lookup_file_by_sfid(child.sfid):
Harald Weltec91085e2022-02-10 18:05:45 +0100250 raise ValueError(
251 "File with given sfid %s already exists in %s" % (child.sfid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100252 if self.lookup_file_by_name(child.name):
253 if ignore_existing:
254 return
Harald Weltec91085e2022-02-10 18:05:45 +0100255 raise ValueError(
256 "File with given name %s already exists in %s" % (child.name, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100257 self.children[child.fid] = child
258 child.parent = self
259
Harald Weltec91085e2022-02-10 18:05:45 +0100260 def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200261 """Add a list of child (DF/EF) to this DF
262
263 Args:
264 children: List of new DF/EFs to be added
265 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
266 """
Harald Welteb2edd142021-01-08 23:29:35 +0100267 for child in children:
268 self.add_file(child, ignore_existing)
269
Harald Weltec91085e2022-02-10 18:05:45 +0100270 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200271 """Return a dict of {'identifier': File} that is selectable from the current DF.
272
273 Args:
274 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
275 If not specified, all selectables will be returned.
276 Returns:
277 dict containing all selectable items. Key is identifier (string), value
278 a reference to a CardFile (or derived class) instance.
279 """
Harald Welteb2edd142021-01-08 23:29:35 +0100280 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100281 sels = super().get_selectables(flags)
282 if flags == [] or 'FIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100283 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100284 if flags == [] or 'FNAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100285 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100286 return sels
287
Harald Weltec91085e2022-02-10 18:05:45 +0100288 def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200289 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100290 if name == None:
291 return None
292 for i in self.children.values():
293 if i.name and i.name == name:
294 return i
295 return None
296
Harald Weltec91085e2022-02-10 18:05:45 +0100297 def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200298 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100299 if sfid == None:
300 return None
301 for i in self.children.values():
Harald Welte1e456572021-04-02 17:16:30 +0200302 if i.sfid == int(str(sfid)):
Harald Welteb2edd142021-01-08 23:29:35 +0100303 return i
304 return None
305
Harald Weltec91085e2022-02-10 18:05:45 +0100306 def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200307 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100308 if fid in self.children:
309 return self.children[fid]
310 return None
311
312
313class CardMF(CardDF):
314 """MF (Master File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100315
Harald Welteb2edd142021-01-08 23:29:35 +0100316 def __init__(self, **kwargs):
317 # can be overridden; use setdefault
318 kwargs.setdefault('fid', '3f00')
319 kwargs.setdefault('name', 'MF')
320 kwargs.setdefault('desc', 'Master File (directory root)')
321 # cannot be overridden; use assignment
322 kwargs['parent'] = self
323 super().__init__(**kwargs)
324 self.applications = dict()
325
326 def __str__(self):
327 return "MF(%s)" % (self.fid)
328
Harald Weltec91085e2022-02-10 18:05:45 +0100329 def add_application_df(self, app: 'CardADF'):
Harald Welte5ce35242021-04-02 20:27:05 +0200330 """Add an Application to the MF"""
Harald Welteb2edd142021-01-08 23:29:35 +0100331 if not isinstance(app, CardADF):
332 raise TypeError("Expected an ADF instance")
333 if app.aid in self.applications:
334 raise ValueError("AID %s already exists" % (app.aid))
335 self.applications[app.aid] = app
Harald Weltec91085e2022-02-10 18:05:45 +0100336 app.parent = self
Harald Welteb2edd142021-01-08 23:29:35 +0100337
338 def get_app_names(self):
339 """Get list of completions (AID names)"""
340 return [x.name for x in self.applications]
341
Harald Weltec91085e2022-02-10 18:05:45 +0100342 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200343 """Return a dict of {'identifier': File} that is selectable from the current DF.
344
345 Args:
346 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
347 If not specified, all selectables will be returned.
348 Returns:
349 dict containing all selectable items. Key is identifier (string), value
350 a reference to a CardFile (or derived class) instance.
351 """
Philipp Maier786f7812021-02-25 16:48:10 +0100352 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100353 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100354 return sels
355
Harald Weltec91085e2022-02-10 18:05:45 +0100356 def get_app_selectables(self, flags=[]) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100357 """Get applications by AID + name"""
358 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100359 if flags == [] or 'AIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100360 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100361 if flags == [] or 'ANAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100362 sels.update(
363 {x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100364 return sels
365
Harald Weltec91085e2022-02-10 18:05:45 +0100366 def decode_select_response(self, data_hex: str) -> object:
Harald Welteee3501f2021-04-02 13:00:18 +0200367 """Decode the response to a SELECT command.
368
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100369 This is the fall-back method which automatically defers to the standard decoding
370 method defined by the card profile. When no profile is set, then no decoding is
Harald Weltec91085e2022-02-10 18:05:45 +0100371 performed. Specific derived classes (usually ADF) can overload this method to
372 install specific decoding.
Harald Welteee3501f2021-04-02 13:00:18 +0200373 """
Harald Welteb2edd142021-01-08 23:29:35 +0100374
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100375 profile = self.get_profile()
Harald Welteb2edd142021-01-08 23:29:35 +0100376
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100377 if profile:
378 return profile.decode_select_response(data_hex)
379 else:
380 return data_hex
Harald Welteb2edd142021-01-08 23:29:35 +0100381
Harald Weltec91085e2022-02-10 18:05:45 +0100382
Harald Welteb2edd142021-01-08 23:29:35 +0100383class CardADF(CardDF):
384 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100385
386 def __init__(self, aid: str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100387 super().__init__(**kwargs)
Harald Welte5ce35242021-04-02 20:27:05 +0200388 # reference to CardApplication may be set from CardApplication constructor
Harald Weltefe8a7442021-04-10 11:51:54 +0200389 self.application = None # type: Optional[CardApplication]
Harald Welteb2edd142021-01-08 23:29:35 +0100390 self.aid = aid # Application Identifier
Harald Welte1e456572021-04-02 17:16:30 +0200391 mf = self.get_mf()
392 if mf:
Harald Welte5ce35242021-04-02 20:27:05 +0200393 mf.add_application_df(self)
Harald Welteb2edd142021-01-08 23:29:35 +0100394
395 def __str__(self):
396 return "ADF(%s)" % (self.aid)
397
Harald Weltec91085e2022-02-10 18:05:45 +0100398 def _path_element(self, prefer_name: bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100399 if self.name and prefer_name:
400 return self.name
401 else:
402 return self.aid
403
404
405class CardEF(CardFile):
406 """EF (Entry File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100407
Harald Welteb2edd142021-01-08 23:29:35 +0100408 def __init__(self, *, fid, **kwargs):
409 kwargs['fid'] = fid
410 super().__init__(**kwargs)
411
412 def __str__(self):
413 return "EF(%s)" % (super().__str__())
414
Harald Weltec91085e2022-02-10 18:05:45 +0100415 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200416 """Return a dict of {'identifier': File} that is selectable from the current DF.
417
418 Args:
419 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
420 If not specified, all selectables will be returned.
421 Returns:
422 dict containing all selectable items. Key is identifier (string), value
423 a reference to a CardFile (or derived class) instance.
424 """
Harald Weltec91085e2022-02-10 18:05:45 +0100425 # global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100426 sels = super().get_selectables(flags)
Harald Weltec91085e2022-02-10 18:05:45 +0100427 sels.update(
428 {x.name: x for x in self.parent.children.values() if x != self})
Harald Welteb2edd142021-01-08 23:29:35 +0100429 return sels
430
431
432class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200433 """Transparent EF (Entry File) in the smart card filesystem.
434
435 A Transparent EF is a binary file with no formal structure. This is contrary to
436 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100437
438 @with_default_category('Transparent EF Commands')
439 class ShellCommands(CommandSet):
Harald Weltec9cdce32021-04-11 10:28:28 +0200440 """Shell commands specific for transparent EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100441
Harald Welteb2edd142021-01-08 23:29:35 +0100442 def __init__(self):
443 super().__init__()
444
445 read_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100446 read_bin_parser.add_argument(
447 '--offset', type=int, default=0, help='Byte offset for start of read')
448 read_bin_parser.add_argument(
449 '--length', type=int, help='Number of bytes to read')
450
Harald Welteb2edd142021-01-08 23:29:35 +0100451 @cmd2.with_argparser(read_bin_parser)
452 def do_read_binary(self, opts):
453 """Read binary data from a transparent EF"""
454 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
455 self._cmd.poutput(data)
456
Harald Weltebcad86c2021-04-06 20:08:39 +0200457 read_bin_dec_parser = argparse.ArgumentParser()
458 read_bin_dec_parser.add_argument('--oneline', action='store_true',
459 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100460
Harald Weltebcad86c2021-04-06 20:08:39 +0200461 @cmd2.with_argparser(read_bin_dec_parser)
Harald Welteb2edd142021-01-08 23:29:35 +0100462 def do_read_binary_decoded(self, opts):
463 """Read + decode data from a transparent EF"""
464 (data, sw) = self._cmd.rs.read_binary_dec()
Harald Welte1748b932021-04-06 21:12:25 +0200465 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100466
467 upd_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100468 upd_bin_parser.add_argument(
469 '--offset', type=int, default=0, help='Byte offset for start of read')
470 upd_bin_parser.add_argument(
471 'data', help='Data bytes (hex format) to write')
472
Harald Welteb2edd142021-01-08 23:29:35 +0100473 @cmd2.with_argparser(upd_bin_parser)
474 def do_update_binary(self, opts):
475 """Update (Write) data of a transparent EF"""
476 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100477 if data:
478 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100479
480 upd_bin_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100481 upd_bin_dec_parser.add_argument(
482 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200483 upd_bin_dec_parser.add_argument('--json-path', type=str,
484 help='JSON path to modify specific element of file only')
Harald Weltec91085e2022-02-10 18:05:45 +0100485
Harald Welteb2edd142021-01-08 23:29:35 +0100486 @cmd2.with_argparser(upd_bin_dec_parser)
487 def do_update_binary_decoded(self, opts):
488 """Encode + Update (Write) data of a transparent EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200489 if opts.json_path:
490 (data_json, sw) = self._cmd.rs.read_binary_dec()
Harald Weltec91085e2022-02-10 18:05:45 +0100491 js_path_modify(data_json, opts.json_path,
492 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200493 else:
494 data_json = json.loads(opts.data)
Harald Welteb2edd142021-01-08 23:29:35 +0100495 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100496 if data:
Harald Welte1748b932021-04-06 21:12:25 +0200497 self._cmd.poutput_json(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100498
Harald Welte4145d3c2021-04-08 20:34:13 +0200499 def do_edit_binary_decoded(self, opts):
500 """Edit the JSON representation of the EF contents in an editor."""
501 (orig_json, sw) = self._cmd.rs.read_binary_dec()
502 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
503 filename = '%s/file' % dirname
504 # write existing data as JSON to file
505 with open(filename, 'w') as text_file:
506 json.dump(orig_json, text_file, indent=4)
507 # run a text editor
508 self._cmd._run_editor(filename)
509 with open(filename, 'r') as text_file:
510 edited_json = json.load(text_file)
511 if edited_json == orig_json:
512 self._cmd.poutput("Data not modified, skipping write")
513 else:
514 (data, sw) = self._cmd.rs.update_binary_dec(edited_json)
515 if data:
516 self._cmd.poutput_json(data)
517
Harald Weltec91085e2022-02-10 18:05:45 +0100518 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
519 size={1, None}):
Harald Welteee3501f2021-04-02 13:00:18 +0200520 """
521 Args:
522 fid : File Identifier (4 hex digits)
523 sfid : Short File Identifier (2 hex digits, optional)
524 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200525 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200526 parent : Parent CardFile object within filesystem hierarchy
527 size : tuple of (minimum_size, recommended_size)
528 """
Harald Welteb2edd142021-01-08 23:29:35 +0100529 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200530 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200531 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100532 self.size = size
533 self.shell_commands = [self.ShellCommands()]
534
Harald Weltec91085e2022-02-10 18:05:45 +0100535 def decode_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200536 """Decode raw (binary) data into abstract representation.
537
538 A derived class would typically provide a _decode_bin() or _decode_hex() method
539 for implementing this specifically for the given file. This function checks which
540 of the method exists, add calls them (with conversion, as needed).
541
542 Args:
543 raw_bin_data : binary encoded data
544 Returns:
545 abstract_data; dict representing the decoded data
546 """
Harald Welteb2edd142021-01-08 23:29:35 +0100547 method = getattr(self, '_decode_bin', None)
548 if callable(method):
549 return method(raw_bin_data)
550 method = getattr(self, '_decode_hex', None)
551 if callable(method):
552 return method(b2h(raw_bin_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200553 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200554 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200555 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100556 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100557 t.from_tlv(raw_bin_data)
558 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100559 return {'raw': raw_bin_data.hex()}
560
Harald Weltec91085e2022-02-10 18:05:45 +0100561 def decode_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200562 """Decode raw (hex string) data into abstract representation.
563
564 A derived class would typically provide a _decode_bin() or _decode_hex() method
565 for implementing this specifically for the given file. This function checks which
566 of the method exists, add calls them (with conversion, as needed).
567
568 Args:
569 raw_hex_data : hex-encoded data
570 Returns:
571 abstract_data; dict representing the decoded data
572 """
Harald Welteb2edd142021-01-08 23:29:35 +0100573 method = getattr(self, '_decode_hex', None)
574 if callable(method):
575 return method(raw_hex_data)
576 raw_bin_data = h2b(raw_hex_data)
577 method = getattr(self, '_decode_bin', None)
578 if callable(method):
579 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200580 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200581 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200582 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100583 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100584 t.from_tlv(raw_bin_data)
585 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100586 return {'raw': raw_bin_data.hex()}
587
Harald Weltec91085e2022-02-10 18:05:45 +0100588 def encode_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200589 """Encode abstract representation into raw (binary) data.
590
591 A derived class would typically provide an _encode_bin() or _encode_hex() method
592 for implementing this specifically for the given file. This function checks which
593 of the method exists, add calls them (with conversion, as needed).
594
595 Args:
596 abstract_data : dict representing the decoded data
597 Returns:
598 binary encoded data
599 """
Harald Welteb2edd142021-01-08 23:29:35 +0100600 method = getattr(self, '_encode_bin', None)
601 if callable(method):
602 return method(abstract_data)
603 method = getattr(self, '_encode_hex', None)
604 if callable(method):
605 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200606 if self._construct:
607 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200608 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100609 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100610 t.from_dict(abstract_data)
611 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100612 raise NotImplementedError(
613 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100614
Harald Weltec91085e2022-02-10 18:05:45 +0100615 def encode_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200616 """Encode abstract representation into raw (hex string) data.
617
618 A derived class would typically provide an _encode_bin() or _encode_hex() method
619 for implementing this specifically for the given file. This function checks which
620 of the method exists, add calls them (with conversion, as needed).
621
622 Args:
623 abstract_data : dict representing the decoded data
624 Returns:
625 hex string encoded data
626 """
Harald Welteb2edd142021-01-08 23:29:35 +0100627 method = getattr(self, '_encode_hex', None)
628 if callable(method):
629 return method(abstract_data)
630 method = getattr(self, '_encode_bin', None)
631 if callable(method):
632 raw_bin_data = method(abstract_data)
633 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200634 if self._construct:
635 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200636 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100637 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100638 t.from_dict(abstract_data)
639 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100640 raise NotImplementedError(
641 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100642
643
644class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200645 """Linear Fixed EF (Entry File) in the smart card filesystem.
646
647 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
648 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100649
650 @with_default_category('Linear Fixed EF Commands')
651 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200652 """Shell commands specific for Linear Fixed EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100653
Harald Welteb2edd142021-01-08 23:29:35 +0100654 def __init__(self):
655 super().__init__()
656
657 read_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100658 read_rec_parser.add_argument(
659 'record_nr', type=int, help='Number of record to be read')
660 read_rec_parser.add_argument(
661 '--count', type=int, default=1, help='Number of records to be read, beginning at record_nr')
662
Harald Welteb2edd142021-01-08 23:29:35 +0100663 @cmd2.with_argparser(read_rec_parser)
664 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100665 """Read one or multiple records from a record-oriented EF"""
666 for r in range(opts.count):
667 recnr = opts.record_nr + r
668 (data, sw) = self._cmd.rs.read_record(recnr)
669 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100670 recstr = str(data)
Philipp Maier41555732021-02-25 16:52:08 +0100671 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100672 recstr = "(empty)"
Philipp Maier41555732021-02-25 16:52:08 +0100673 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100674
675 read_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100676 read_rec_dec_parser.add_argument(
677 'record_nr', type=int, help='Number of record to be read')
Harald Weltebcad86c2021-04-06 20:08:39 +0200678 read_rec_dec_parser.add_argument('--oneline', action='store_true',
679 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100680
Harald Welteb2edd142021-01-08 23:29:35 +0100681 @cmd2.with_argparser(read_rec_dec_parser)
682 def do_read_record_decoded(self, opts):
683 """Read + decode a record from a record-oriented EF"""
684 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Welte1748b932021-04-06 21:12:25 +0200685 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100686
Harald Welte850b72a2021-04-07 09:33:03 +0200687 read_recs_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100688
Harald Welte850b72a2021-04-07 09:33:03 +0200689 @cmd2.with_argparser(read_recs_parser)
690 def do_read_records(self, opts):
691 """Read all records from a record-oriented EF"""
692 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
693 for recnr in range(1, 1 + num_of_rec):
694 (data, sw) = self._cmd.rs.read_record(recnr)
695 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100696 recstr = str(data)
Harald Welte850b72a2021-04-07 09:33:03 +0200697 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100698 recstr = "(empty)"
Harald Welte850b72a2021-04-07 09:33:03 +0200699 self._cmd.poutput("%03d %s" % (recnr, recstr))
700
701 read_recs_dec_parser = argparse.ArgumentParser()
702 read_recs_dec_parser.add_argument('--oneline', action='store_true',
Harald Weltec91085e2022-02-10 18:05:45 +0100703 help='No JSON pretty-printing, dump as a single line')
704
Harald Welte850b72a2021-04-07 09:33:03 +0200705 @cmd2.with_argparser(read_recs_dec_parser)
706 def do_read_records_decoded(self, opts):
707 """Read + decode all records from a record-oriented EF"""
708 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
709 # collect all results in list so they are rendered as JSON list when printing
710 data_list = []
711 for recnr in range(1, 1 + num_of_rec):
712 (data, sw) = self._cmd.rs.read_record_dec(recnr)
713 data_list.append(data)
714 self._cmd.poutput_json(data_list, opts.oneline)
715
Harald Welteb2edd142021-01-08 23:29:35 +0100716 upd_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100717 upd_rec_parser.add_argument(
718 'record_nr', type=int, help='Number of record to be read')
719 upd_rec_parser.add_argument(
720 'data', help='Data bytes (hex format) to write')
721
Harald Welteb2edd142021-01-08 23:29:35 +0100722 @cmd2.with_argparser(upd_rec_parser)
723 def do_update_record(self, opts):
724 """Update (write) data to a record-oriented EF"""
725 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100726 if data:
727 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100728
729 upd_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100730 upd_rec_dec_parser.add_argument(
731 'record_nr', type=int, help='Number of record to be read')
732 upd_rec_dec_parser.add_argument(
733 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200734 upd_rec_dec_parser.add_argument('--json-path', type=str,
735 help='JSON path to modify specific element of record only')
Harald Weltec91085e2022-02-10 18:05:45 +0100736
Harald Welteb2edd142021-01-08 23:29:35 +0100737 @cmd2.with_argparser(upd_rec_dec_parser)
738 def do_update_record_decoded(self, opts):
739 """Encode + Update (write) data to a record-oriented EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200740 if opts.json_path:
741 (data_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Weltec91085e2022-02-10 18:05:45 +0100742 js_path_modify(data_json, opts.json_path,
743 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200744 else:
745 data_json = json.loads(opts.data)
Harald Weltec91085e2022-02-10 18:05:45 +0100746 (data, sw) = self._cmd.rs.update_record_dec(
747 opts.record_nr, data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100748 if data:
749 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100750
Harald Welte4145d3c2021-04-08 20:34:13 +0200751 edit_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100752 edit_rec_dec_parser.add_argument(
753 'record_nr', type=int, help='Number of record to be edited')
754
Harald Welte4145d3c2021-04-08 20:34:13 +0200755 @cmd2.with_argparser(edit_rec_dec_parser)
756 def do_edit_record_decoded(self, opts):
757 """Edit the JSON representation of one record in an editor."""
758 (orig_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Vadim Yanitskiy895fa6f2021-05-02 02:36:44 +0200759 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
Harald Welte4145d3c2021-04-08 20:34:13 +0200760 filename = '%s/file' % dirname
761 # write existing data as JSON to file
762 with open(filename, 'w') as text_file:
763 json.dump(orig_json, text_file, indent=4)
764 # run a text editor
765 self._cmd._run_editor(filename)
766 with open(filename, 'r') as text_file:
767 edited_json = json.load(text_file)
768 if edited_json == orig_json:
769 self._cmd.poutput("Data not modified, skipping write")
770 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100771 (data, sw) = self._cmd.rs.update_record_dec(
772 opts.record_nr, edited_json)
Harald Welte4145d3c2021-04-08 20:34:13 +0200773 if data:
774 self._cmd.poutput_json(data)
Harald Welte4145d3c2021-04-08 20:34:13 +0200775
Harald Weltec91085e2022-02-10 18:05:45 +0100776 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None,
777 parent: Optional[CardDF] = None, rec_len={1, None}):
Harald Welteee3501f2021-04-02 13:00:18 +0200778 """
779 Args:
780 fid : File Identifier (4 hex digits)
781 sfid : Short File Identifier (2 hex digits, optional)
782 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200783 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200784 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier0adabf62021-04-20 22:36:41 +0200785 rec_len : set of {minimum_length, recommended_length}
Harald Welteee3501f2021-04-02 13:00:18 +0200786 """
Harald Welteb2edd142021-01-08 23:29:35 +0100787 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
788 self.rec_len = rec_len
789 self.shell_commands = [self.ShellCommands()]
Harald Welte2db5cfb2021-04-10 19:05:37 +0200790 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200791 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100792
Harald Weltec91085e2022-02-10 18:05:45 +0100793 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200794 """Decode raw (hex string) data into abstract representation.
795
796 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
797 method for implementing this specifically for the given file. This function checks which
798 of the method exists, add calls them (with conversion, as needed).
799
800 Args:
801 raw_hex_data : hex-encoded data
802 Returns:
803 abstract_data; dict representing the decoded data
804 """
Harald Welteb2edd142021-01-08 23:29:35 +0100805 method = getattr(self, '_decode_record_hex', None)
806 if callable(method):
807 return method(raw_hex_data)
808 raw_bin_data = h2b(raw_hex_data)
809 method = getattr(self, '_decode_record_bin', None)
810 if callable(method):
811 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200812 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200813 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200814 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100815 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100816 t.from_tlv(raw_bin_data)
817 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100818 return {'raw': raw_bin_data.hex()}
819
Harald Weltec91085e2022-02-10 18:05:45 +0100820 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200821 """Decode raw (binary) data into abstract representation.
822
823 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
824 method for implementing this specifically for the given file. This function checks which
825 of the method exists, add calls them (with conversion, as needed).
826
827 Args:
828 raw_bin_data : binary encoded data
829 Returns:
830 abstract_data; dict representing the decoded data
831 """
Harald Welteb2edd142021-01-08 23:29:35 +0100832 method = getattr(self, '_decode_record_bin', None)
833 if callable(method):
834 return method(raw_bin_data)
835 raw_hex_data = b2h(raw_bin_data)
836 method = getattr(self, '_decode_record_hex', None)
837 if callable(method):
838 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200839 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200840 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200841 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100842 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100843 t.from_tlv(raw_bin_data)
844 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100845 return {'raw': raw_hex_data}
846
Harald Weltec91085e2022-02-10 18:05:45 +0100847 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200848 """Encode abstract representation into raw (hex string) data.
849
850 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
851 method for implementing this specifically for the given file. This function checks which
852 of the method exists, add calls them (with conversion, as needed).
853
854 Args:
855 abstract_data : dict representing the decoded data
856 Returns:
857 hex string encoded data
858 """
Harald Welteb2edd142021-01-08 23:29:35 +0100859 method = getattr(self, '_encode_record_hex', None)
860 if callable(method):
861 return method(abstract_data)
862 method = getattr(self, '_encode_record_bin', None)
863 if callable(method):
864 raw_bin_data = method(abstract_data)
Harald Welte1e456572021-04-02 17:16:30 +0200865 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200866 if self._construct:
867 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200868 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100869 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100870 t.from_dict(abstract_data)
871 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100872 raise NotImplementedError(
873 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100874
Harald Weltec91085e2022-02-10 18:05:45 +0100875 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200876 """Encode abstract representation into raw (binary) data.
877
878 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
879 method for implementing this specifically for the given file. This function checks which
880 of the method exists, add calls them (with conversion, as needed).
881
882 Args:
883 abstract_data : dict representing the decoded data
884 Returns:
885 binary encoded data
886 """
Harald Welteb2edd142021-01-08 23:29:35 +0100887 method = getattr(self, '_encode_record_bin', None)
888 if callable(method):
889 return method(abstract_data)
890 method = getattr(self, '_encode_record_hex', None)
891 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +0200892 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200893 if self._construct:
894 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200895 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100896 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100897 t.from_dict(abstract_data)
898 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100899 raise NotImplementedError(
900 "%s encoder not yet implemented. Patches welcome." % self)
901
Harald Welteb2edd142021-01-08 23:29:35 +0100902
903class CyclicEF(LinFixedEF):
904 """Cyclic EF (Entry File) in the smart card filesystem"""
905 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Weltec91085e2022-02-10 18:05:45 +0100906
907 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
908 rec_len={1, None}):
909 super().__init__(fid=fid, sfid=sfid, name=name,
910 desc=desc, parent=parent, rec_len=rec_len)
911
Harald Welteb2edd142021-01-08 23:29:35 +0100912
913class TransRecEF(TransparentEF):
914 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +0200915
Harald Welteb2edd142021-01-08 23:29:35 +0100916 These are the real odd-balls and mostly look like mistakes in the specification:
917 Specified as 'transparent' EF, but actually containing several fixed-length records
918 inside.
919 We add a special class for those, so the user only has to provide encoder/decoder functions
920 for a record, while this class takes care of split / merge of records.
921 """
Harald Weltec91085e2022-02-10 18:05:45 +0100922
923 def __init__(self, fid: str, rec_len: int, sfid: str = None, name: str = None, desc: str = None,
924 parent: Optional[CardDF] = None, size={1, None}):
Harald Welteee3501f2021-04-02 13:00:18 +0200925 """
926 Args:
927 fid : File Identifier (4 hex digits)
928 sfid : Short File Identifier (2 hex digits, optional)
Harald Weltec9cdce32021-04-11 10:28:28 +0200929 name : Brief name of the file, like EF_ICCID
930 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200931 parent : Parent CardFile object within filesystem hierarchy
932 rec_len : Length of the fixed-length records within transparent EF
933 size : tuple of (minimum_size, recommended_size)
934 """
Harald Welteb2edd142021-01-08 23:29:35 +0100935 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size)
936 self.rec_len = rec_len
937
Harald Weltec91085e2022-02-10 18:05:45 +0100938 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200939 """Decode raw (hex string) data into abstract representation.
940
941 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
942 method for implementing this specifically for the given file. This function checks which
943 of the method exists, add calls them (with conversion, as needed).
944
945 Args:
946 raw_hex_data : hex-encoded data
947 Returns:
948 abstract_data; dict representing the decoded data
949 """
Harald Welteb2edd142021-01-08 23:29:35 +0100950 method = getattr(self, '_decode_record_hex', None)
951 if callable(method):
952 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200953 raw_bin_data = h2b(raw_hex_data)
Harald Welteb2edd142021-01-08 23:29:35 +0100954 method = getattr(self, '_decode_record_bin', None)
955 if callable(method):
Harald Welteb2edd142021-01-08 23:29:35 +0100956 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200957 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200958 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200959 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100960 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100961 t.from_tlv(raw_bin_data)
962 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100963 return {'raw': raw_hex_data}
964
Harald Weltec91085e2022-02-10 18:05:45 +0100965 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200966 """Decode raw (binary) data into abstract representation.
967
968 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
969 method for implementing this specifically for the given file. This function checks which
970 of the method exists, add calls them (with conversion, as needed).
971
972 Args:
973 raw_bin_data : binary encoded data
974 Returns:
975 abstract_data; dict representing the decoded data
976 """
Harald Welteb2edd142021-01-08 23:29:35 +0100977 method = getattr(self, '_decode_record_bin', None)
978 if callable(method):
979 return method(raw_bin_data)
980 raw_hex_data = b2h(raw_bin_data)
981 method = getattr(self, '_decode_record_hex', None)
982 if callable(method):
983 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200984 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200985 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200986 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100987 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100988 t.from_tlv(raw_bin_data)
989 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100990 return {'raw': raw_hex_data}
991
Harald Weltec91085e2022-02-10 18:05:45 +0100992 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200993 """Encode abstract representation into raw (hex string) data.
994
995 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
996 method for implementing this specifically for the given file. This function checks which
997 of the method exists, add calls them (with conversion, as needed).
998
999 Args:
1000 abstract_data : dict representing the decoded data
1001 Returns:
1002 hex string encoded data
1003 """
Harald Welteb2edd142021-01-08 23:29:35 +01001004 method = getattr(self, '_encode_record_hex', None)
1005 if callable(method):
1006 return method(abstract_data)
1007 method = getattr(self, '_encode_record_bin', None)
1008 if callable(method):
Harald Welte1e456572021-04-02 17:16:30 +02001009 return b2h(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001010 if self._construct:
1011 return b2h(filter_dict(self._construct.build(abstract_data)))
Harald Weltefb506212021-05-29 21:28:24 +02001012 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001013 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001014 t.from_dict(abstract_data)
1015 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +01001016 raise NotImplementedError(
1017 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001018
Harald Weltec91085e2022-02-10 18:05:45 +01001019 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +02001020 """Encode abstract representation into raw (binary) data.
1021
1022 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1023 method for implementing this specifically for the given file. This function checks which
1024 of the method exists, add calls them (with conversion, as needed).
1025
1026 Args:
1027 abstract_data : dict representing the decoded data
1028 Returns:
1029 binary encoded data
1030 """
Harald Welteb2edd142021-01-08 23:29:35 +01001031 method = getattr(self, '_encode_record_bin', None)
1032 if callable(method):
1033 return method(abstract_data)
1034 method = getattr(self, '_encode_record_hex', None)
1035 if callable(method):
1036 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001037 if self._construct:
1038 return filter_dict(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +02001039 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001040 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001041 t.from_dict(abstract_data)
1042 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +01001043 raise NotImplementedError(
1044 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001045
Harald Weltec91085e2022-02-10 18:05:45 +01001046 def _decode_bin(self, raw_bin_data: bytearray):
1047 chunks = [raw_bin_data[i:i+self.rec_len]
1048 for i in range(0, len(raw_bin_data), self.rec_len)]
Harald Welteb2edd142021-01-08 23:29:35 +01001049 return [self.decode_record_bin(x) for x in chunks]
1050
Harald Welteee3501f2021-04-02 13:00:18 +02001051 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +01001052 chunks = [self.encode_record_bin(x) for x in abstract_data]
1053 # FIXME: pad to file size
1054 return b''.join(chunks)
1055
1056
Harald Welte917d98c2021-04-21 11:51:25 +02001057class BerTlvEF(CardEF):
Harald Welte27881622021-04-21 11:16:31 +02001058 """BER-TLV EF (Entry File) in the smart card filesystem.
1059 A BER-TLV EF is a binary file with a BER (Basic Encoding Rules) TLV structure
Harald Welteb2edd142021-01-08 23:29:35 +01001060
Harald Welte27881622021-04-21 11:16:31 +02001061 NOTE: We currently don't really support those, this class is simply a wrapper
1062 around TransparentEF as a place-holder, so we can already define EFs of BER-TLV
1063 type without fully supporting them."""
Harald Welteb2edd142021-01-08 23:29:35 +01001064
Harald Welte917d98c2021-04-21 11:51:25 +02001065 @with_default_category('BER-TLV EF Commands')
1066 class ShellCommands(CommandSet):
1067 """Shell commands specific for BER-TLV EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +01001068
Harald Welte917d98c2021-04-21 11:51:25 +02001069 def __init__(self):
1070 super().__init__()
1071
1072 retrieve_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001073 retrieve_data_parser.add_argument(
1074 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve')
1075
Harald Welte917d98c2021-04-21 11:51:25 +02001076 @cmd2.with_argparser(retrieve_data_parser)
1077 def do_retrieve_data(self, opts):
1078 """Retrieve (Read) data from a BER-TLV EF"""
1079 (data, sw) = self._cmd.rs.retrieve_data(opts.tag)
1080 self._cmd.poutput(data)
1081
1082 def do_retrieve_tags(self, opts):
1083 """List tags available in a given BER-TLV EF"""
1084 tags = self._cmd.rs.retrieve_tags()
1085 self._cmd.poutput(tags)
1086
1087 set_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001088 set_data_parser.add_argument(
1089 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1090 set_data_parser.add_argument(
1091 'data', help='Data bytes (hex format) to write')
1092
Harald Welte917d98c2021-04-21 11:51:25 +02001093 @cmd2.with_argparser(set_data_parser)
1094 def do_set_data(self, opts):
1095 """Set (Write) data for a given tag in a BER-TLV EF"""
1096 (data, sw) = self._cmd.rs.set_data(opts.tag, opts.data)
1097 if data:
1098 self._cmd.poutput(data)
1099
1100 del_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001101 del_data_parser.add_argument(
1102 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1103
Harald Welte917d98c2021-04-21 11:51:25 +02001104 @cmd2.with_argparser(del_data_parser)
1105 def do_delete_data(self, opts):
1106 """Delete data for a given tag in a BER-TLV EF"""
1107 (data, sw) = self._cmd.rs.set_data(opts.tag, None)
1108 if data:
1109 self._cmd.poutput(data)
1110
Harald Weltec91085e2022-02-10 18:05:45 +01001111 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
1112 size={1, None}):
Harald Welte917d98c2021-04-21 11:51:25 +02001113 """
1114 Args:
1115 fid : File Identifier (4 hex digits)
1116 sfid : Short File Identifier (2 hex digits, optional)
1117 name : Brief name of the file, lik EF_ICCID
1118 desc : Description of the file
1119 parent : Parent CardFile object within filesystem hierarchy
1120 size : tuple of (minimum_size, recommended_size)
1121 """
1122 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent)
1123 self._construct = None
1124 self.size = size
1125 self.shell_commands = [self.ShellCommands()]
1126
Harald Welteb2edd142021-01-08 23:29:35 +01001127
1128class RuntimeState(object):
1129 """Represent the runtime state of a session with a card."""
Harald Weltec91085e2022-02-10 18:05:45 +01001130
1131 def __init__(self, card, profile: 'CardProfile'):
Harald Welteee3501f2021-04-02 13:00:18 +02001132 """
1133 Args:
1134 card : pysim.cards.Card instance
1135 profile : CardProfile instance
1136 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +01001137 self.mf = CardMF(profile=profile)
Harald Welteb2edd142021-01-08 23:29:35 +01001138 self.card = card
Harald Weltec91085e2022-02-10 18:05:45 +01001139 self.selected_file = self.mf # type: CardDF
Harald Welteb2edd142021-01-08 23:29:35 +01001140 self.profile = profile
Philipp Maier51cad0d2021-11-08 15:45:10 +01001141
1142 # make sure the class and selection control bytes, which are specified
1143 # by the card profile are used
Harald Weltec91085e2022-02-10 18:05:45 +01001144 self.card.set_apdu_parameter(
1145 cla=self.profile.cla, sel_ctrl=self.profile.sel_ctrl)
Philipp Maier51cad0d2021-11-08 15:45:10 +01001146
Harald Welte5ce35242021-04-02 20:27:05 +02001147 # add application ADFs + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001148 apps = self._match_applications()
1149 for a in apps:
Harald Welte5ce35242021-04-02 20:27:05 +02001150 if a.adf:
1151 self.mf.add_application_df(a.adf)
Harald Welteb2edd142021-01-08 23:29:35 +01001152 for f in self.profile.files_in_mf:
1153 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +01001154 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +01001155
Philipp Maier4e2e1d92021-11-08 15:36:01 +01001156 # make sure that when the runtime state is created, the card is also
1157 # in a defined state.
1158 self.reset()
1159
Philipp Maier1e896f32021-03-10 17:02:53 +01001160 def _match_applications(self):
1161 """match the applications from the profile with applications on the card"""
1162 apps_profile = self.profile.applications
Philipp Maierd454fe72021-11-08 15:32:23 +01001163
1164 # When the profile does not feature any applications, then we are done already
1165 if not apps_profile:
1166 return []
1167
1168 # Read AIDs from card and match them against the applications defined by the
1169 # card profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001170 aids_card = self.card.read_aids()
1171 apps_taken = []
1172 if aids_card:
1173 aids_taken = []
1174 print("AIDs on card:")
1175 for a in aids_card:
1176 for f in apps_profile:
1177 if f.aid in a:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001178 print(" %s: %s (EF.DIR)" % (f.name, a))
Philipp Maier1e896f32021-03-10 17:02:53 +01001179 aids_taken.append(a)
1180 apps_taken.append(f)
1181 aids_unknown = set(aids_card) - set(aids_taken)
1182 for a in aids_unknown:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001183 print(" unknown: %s (EF.DIR)" % a)
Philipp Maier1e896f32021-03-10 17:02:53 +01001184 else:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001185 print("warning: EF.DIR seems to be empty!")
1186
1187 # Some card applications may not be registered in EF.DIR, we will actively
1188 # probe for those applications
1189 for f in set(apps_profile) - set(apps_taken):
Bjoern Riemerda57ef12022-01-18 15:38:14 +01001190 try:
1191 data, sw = self.card.select_adf_by_aid(f.aid)
1192 if sw == "9000":
1193 print(" %s: %s" % (f.name, f.aid))
1194 apps_taken.append(f)
1195 except SwMatchError:
1196 pass
Philipp Maier1e896f32021-03-10 17:02:53 +01001197 return apps_taken
1198
Harald Weltedaf2b392021-05-03 23:17:29 +02001199 def reset(self, cmd_app=None) -> Hexstr:
1200 """Perform physical card reset and obtain ATR.
1201 Args:
1202 cmd_app : Command Application State (for unregistering old file commands)
1203 """
Philipp Maier946226a2021-10-29 18:31:03 +02001204 atr = i2h(self.card.reset())
Harald Weltedaf2b392021-05-03 23:17:29 +02001205 # select MF to reset internal state and to verify card really works
1206 self.select('MF', cmd_app)
1207 return atr
1208
Harald Welteee3501f2021-04-02 13:00:18 +02001209 def get_cwd(self) -> CardDF:
1210 """Obtain the current working directory.
1211
1212 Returns:
1213 CardDF instance
1214 """
Harald Welteb2edd142021-01-08 23:29:35 +01001215 if isinstance(self.selected_file, CardDF):
1216 return self.selected_file
1217 else:
1218 return self.selected_file.parent
1219
Harald Welte5ce35242021-04-02 20:27:05 +02001220 def get_application_df(self) -> Optional[CardADF]:
1221 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +02001222
1223 Returns:
1224 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +01001225 # iterate upwards from selected file; check if any is an ADF
1226 node = self.selected_file
1227 while node.parent != node:
1228 if isinstance(node, CardADF):
1229 return node
1230 node = node.parent
1231 return None
1232
Harald Weltec91085e2022-02-10 18:05:45 +01001233 def interpret_sw(self, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001234 """Interpret a given status word relative to the currently selected application
1235 or the underlying card profile.
1236
1237 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001238 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001239
1240 Returns:
1241 Tuple of two strings
1242 """
Harald Welte86fbd392021-04-02 22:13:09 +02001243 res = None
Harald Welte5ce35242021-04-02 20:27:05 +02001244 adf = self.get_application_df()
1245 if adf:
1246 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +01001247 # The application either comes with its own interpret_sw
1248 # method or we will use the interpret_sw method from the
1249 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +02001250 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +02001251 res = app.interpret_sw(sw)
1252 return res or self.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +01001253
Harald Weltec91085e2022-02-10 18:05:45 +01001254 def probe_file(self, fid: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001255 """Blindly try to select a file and automatically add a matching file
Harald Weltec91085e2022-02-10 18:05:45 +01001256 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +01001257 if not is_hex(fid, 4, 4):
Harald Weltec91085e2022-02-10 18:05:45 +01001258 raise ValueError(
1259 "Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
Philipp Maier63f572d2021-03-09 22:42:47 +01001260
1261 try:
1262 (data, sw) = self.card._scc.select_file(fid)
1263 except SwMatchError as swm:
1264 k = self.interpret_sw(swm.sw_actual)
1265 if not k:
1266 raise(swm)
1267 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
1268
1269 select_resp = self.selected_file.decode_select_response(data)
1270 if (select_resp['file_descriptor']['file_type'] == 'df'):
Harald Weltec91085e2022-02-10 18:05:45 +01001271 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(),
1272 desc="dedicated file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001273 else:
1274 if (select_resp['file_descriptor']['structure'] == 'transparent'):
Harald Weltec91085e2022-02-10 18:05:45 +01001275 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1276 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001277 else:
Harald Weltec91085e2022-02-10 18:05:45 +01001278 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1279 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001280
1281 self.selected_file.add_files([f])
1282 self.selected_file = f
1283 return select_resp
1284
Harald Weltec91085e2022-02-10 18:05:45 +01001285 def select(self, name: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001286 """Select a file (EF, DF, ADF, MF, ...).
1287
1288 Args:
1289 name : Name of file to select
1290 cmd_app : Command Application State (for unregistering old file commands)
1291 """
Harald Welteb2edd142021-01-08 23:29:35 +01001292 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +01001293 if is_hex(name):
1294 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +01001295
1296 # unregister commands of old file
1297 if cmd_app and self.selected_file.shell_commands:
1298 for c in self.selected_file.shell_commands:
1299 cmd_app.unregister_command_set(c)
1300
Harald Welteb2edd142021-01-08 23:29:35 +01001301 if name in sels:
1302 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +01001303 try:
1304 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001305 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +01001306 else:
1307 (data, sw) = self.card._scc.select_file(f.fid)
1308 self.selected_file = f
1309 except SwMatchError as swm:
1310 k = self.interpret_sw(swm.sw_actual)
1311 if not k:
1312 raise(swm)
1313 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +01001314 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001315 else:
Philipp Maier63f572d2021-03-09 22:42:47 +01001316 select_resp = self.probe_file(name, cmd_app)
Harald Welte850b72a2021-04-07 09:33:03 +02001317 # store the decoded FCP for later reference
1318 self.selected_file_fcp = select_resp
Philipp Maier63f572d2021-03-09 22:42:47 +01001319
1320 # register commands of new file
1321 if cmd_app and self.selected_file.shell_commands:
1322 for c in self.selected_file.shell_commands:
1323 cmd_app.register_command_set(c)
1324
1325 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +01001326
Harald Welte34b05d32021-05-25 22:03:13 +02001327 def status(self):
1328 """Request STATUS (current selected file FCP) from card."""
1329 (data, sw) = self.card._scc.status()
1330 return self.selected_file.decode_select_response(data)
1331
Harald Weltec91085e2022-02-10 18:05:45 +01001332 def activate_file(self, name: str):
Harald Welte485692b2021-05-25 22:21:44 +02001333 """Request ACTIVATE FILE of specified file."""
1334 sels = self.selected_file.get_selectables()
1335 f = sels[name]
1336 data, sw = self.card._scc.activate_file(f.fid)
1337 return data, sw
1338
Harald Weltec91085e2022-02-10 18:05:45 +01001339 def read_binary(self, length: int = None, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001340 """Read [part of] a transparent EF binary data.
1341
1342 Args:
1343 length : Amount of data to read (None: as much as possible)
1344 offset : Offset into the file from which to read 'length' bytes
1345 Returns:
1346 binary data read from the file
1347 """
Harald Welteb2edd142021-01-08 23:29:35 +01001348 if not isinstance(self.selected_file, TransparentEF):
1349 raise TypeError("Only works with TransparentEF")
1350 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
1351
Harald Welte2d4a64b2021-04-03 09:01:24 +02001352 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001353 """Read [part of] a transparent EF binary data and decode it.
1354
1355 Args:
1356 length : Amount of data to read (None: as much as possible)
1357 offset : Offset into the file from which to read 'length' bytes
1358 Returns:
1359 abstract decode data read from the file
1360 """
Harald Welteb2edd142021-01-08 23:29:35 +01001361 (data, sw) = self.read_binary()
1362 dec_data = self.selected_file.decode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001363 return (dec_data, sw)
1364
Harald Weltec91085e2022-02-10 18:05:45 +01001365 def update_binary(self, data_hex: str, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001366 """Update transparent EF binary data.
1367
1368 Args:
1369 data_hex : hex string of data to be written
1370 offset : Offset into the file from which to write 'data_hex'
1371 """
Harald Welteb2edd142021-01-08 23:29:35 +01001372 if not isinstance(self.selected_file, TransparentEF):
1373 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001374 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001375
Harald Weltec91085e2022-02-10 18:05:45 +01001376 def update_binary_dec(self, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001377 """Update transparent EF from abstract data. Encodes the data to binary and
1378 then updates the EF with it.
1379
1380 Args:
1381 data : abstract data which is to be encoded and written
1382 """
Harald Welteb2edd142021-01-08 23:29:35 +01001383 data_hex = self.selected_file.encode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001384 return self.update_binary(data_hex)
1385
Harald Weltec91085e2022-02-10 18:05:45 +01001386 def read_record(self, rec_nr: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001387 """Read a record as binary data.
1388
1389 Args:
1390 rec_nr : Record number to read
1391 Returns:
1392 hex string of binary data contained in record
1393 """
Harald Welteb2edd142021-01-08 23:29:35 +01001394 if not isinstance(self.selected_file, LinFixedEF):
1395 raise TypeError("Only works with Linear Fixed EF")
1396 # returns a string of hex nibbles
1397 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1398
Harald Weltec91085e2022-02-10 18:05:45 +01001399 def read_record_dec(self, rec_nr: int = 0) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001400 """Read a record and decode it to abstract data.
1401
1402 Args:
1403 rec_nr : Record number to read
1404 Returns:
1405 abstract data contained in record
1406 """
Harald Welteb2edd142021-01-08 23:29:35 +01001407 (data, sw) = self.read_record(rec_nr)
1408 return (self.selected_file.decode_record_hex(data), sw)
1409
Harald Weltec91085e2022-02-10 18:05:45 +01001410 def update_record(self, rec_nr: int, data_hex: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001411 """Update a record with given binary data
1412
1413 Args:
1414 rec_nr : Record number to read
1415 data_hex : Hex string binary data to be written
1416 """
Harald Welteb2edd142021-01-08 23:29:35 +01001417 if not isinstance(self.selected_file, LinFixedEF):
1418 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001419 return self.card._scc.update_record(self.selected_file.fid, rec_nr, data_hex, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001420
Harald Weltec91085e2022-02-10 18:05:45 +01001421 def update_record_dec(self, rec_nr: int, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001422 """Update a record with given abstract data. Will encode abstract to binary data
1423 and then write it to the given record on the card.
1424
1425 Args:
1426 rec_nr : Record number to read
1427 data_hex : Abstract data to be written
1428 """
Harald Welte1e456572021-04-02 17:16:30 +02001429 data_hex = self.selected_file.encode_record_hex(data)
1430 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001431
Harald Weltec91085e2022-02-10 18:05:45 +01001432 def retrieve_data(self, tag: int = 0):
Harald Welte917d98c2021-04-21 11:51:25 +02001433 """Read a DO/TLV as binary data.
1434
1435 Args:
1436 tag : Tag of TLV/DO to read
1437 Returns:
1438 hex string of full BER-TLV DO including Tag and Length
1439 """
1440 if not isinstance(self.selected_file, BerTlvEF):
1441 raise TypeError("Only works with BER-TLV EF")
1442 # returns a string of hex nibbles
1443 return self.card._scc.retrieve_data(self.selected_file.fid, tag)
1444
1445 def retrieve_tags(self):
1446 """Retrieve tags available on BER-TLV EF.
1447
1448 Returns:
1449 list of integer tags contained in EF
1450 """
1451 if not isinstance(self.selected_file, BerTlvEF):
1452 raise TypeError("Only works with BER-TLV EF")
1453 data, sw = self.card._scc.retrieve_data(self.selected_file.fid, 0x5c)
Harald Weltec1475302021-05-21 21:47:55 +02001454 tag, length, value, remainder = bertlv_parse_one(h2b(data))
Harald Welte917d98c2021-04-21 11:51:25 +02001455 return list(value)
1456
Harald Weltec91085e2022-02-10 18:05:45 +01001457 def set_data(self, tag: int, data_hex: str):
Harald Welte917d98c2021-04-21 11:51:25 +02001458 """Update a TLV/DO with given binary data
1459
1460 Args:
1461 tag : Tag of TLV/DO to be written
1462 data_hex : Hex string binary data to be written (value portion)
1463 """
1464 if not isinstance(self.selected_file, BerTlvEF):
1465 raise TypeError("Only works with BER-TLV EF")
1466 return self.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.conserve_write)
1467
Philipp Maier5d698e52021-09-16 13:18:01 +02001468 def unregister_cmds(self, cmd_app=None):
1469 """Unregister all file specific commands."""
1470 if cmd_app and self.selected_file.shell_commands:
1471 for c in self.selected_file.shell_commands:
1472 cmd_app.unregister_command_set(c)
Harald Welte917d98c2021-04-21 11:51:25 +02001473
Harald Welteb2edd142021-01-08 23:29:35 +01001474
Harald Welteb2edd142021-01-08 23:29:35 +01001475class FileData(object):
1476 """Represent the runtime, on-card data."""
Harald Weltec91085e2022-02-10 18:05:45 +01001477
Harald Welteb2edd142021-01-08 23:29:35 +01001478 def __init__(self, fdesc):
1479 self.desc = fdesc
1480 self.fcp = None
1481
1482
Harald Weltec91085e2022-02-10 18:05:45 +01001483def interpret_sw(sw_data: dict, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001484 """Interpret a given status word.
1485
1486 Args:
1487 sw_data : Hierarchical dict of status word matches
1488 sw : status word to match (string of 4 hex digits)
1489 Returns:
1490 tuple of two strings (class_string, description)
1491 """
Harald Welteb2edd142021-01-08 23:29:35 +01001492 for class_str, swdict in sw_data.items():
1493 # first try direct match
1494 if sw in swdict:
1495 return (class_str, swdict[sw])
1496 # next try wildcard matches
1497 for pattern, descr in swdict.items():
1498 if sw_match(sw, pattern):
1499 return (class_str, descr)
1500 return None
1501
Harald Weltec91085e2022-02-10 18:05:45 +01001502
Harald Welteb2edd142021-01-08 23:29:35 +01001503class CardApplication(object):
1504 """A card application is represented by an ADF (with contained hierarchy) and optionally
1505 some SW definitions."""
Harald Weltec91085e2022-02-10 18:05:45 +01001506
1507 def __init__(self, name, adf: Optional[CardADF] = None, aid: str = None, sw: dict = None):
Harald Welteee3501f2021-04-02 13:00:18 +02001508 """
1509 Args:
1510 adf : ADF name
1511 sw : Dict of status word conversions
1512 """
Harald Welteb2edd142021-01-08 23:29:35 +01001513 self.name = name
1514 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001515 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001516 # back-reference from ADF to Applicaiton
1517 if self.adf:
1518 self.aid = aid or self.adf.aid
1519 self.adf.application = self
1520 else:
1521 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001522
1523 def __str__(self):
1524 return "APP(%s)" % (self.name)
1525
1526 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001527 """Interpret a given status word within the application.
1528
1529 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001530 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001531
1532 Returns:
1533 Tuple of two strings
1534 """
Harald Welteb2edd142021-01-08 23:29:35 +01001535 return interpret_sw(self.sw, sw)
1536
Harald Weltef44256c2021-10-14 15:53:39 +02001537
1538class CardModel(abc.ABC):
Harald Welte4c1dca02021-10-14 17:48:25 +02001539 """A specific card model, typically having some additional vendor-specific files. All
1540 you need to do is to define a sub-class with a list of ATRs or an overridden match
1541 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001542 _atrs = []
1543
1544 @classmethod
1545 @abc.abstractmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001546 def add_files(cls, rs: RuntimeState):
Harald Weltef44256c2021-10-14 15:53:39 +02001547 """Add model specific files to given RuntimeState."""
1548
1549 @classmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001550 def match(cls, scc: SimCardCommands) -> bool:
Harald Weltef44256c2021-10-14 15:53:39 +02001551 """Test if given card matches this model."""
1552 card_atr = scc.get_atr()
1553 for atr in cls._atrs:
1554 atr_bin = toBytes(atr)
1555 if atr_bin == card_atr:
1556 print("Detected CardModel:", cls.__name__)
1557 return True
1558 return False
1559
1560 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001561 def apply_matching_models(scc: SimCardCommands, rs: RuntimeState):
Harald Welte4c1dca02021-10-14 17:48:25 +02001562 """Check if any of the CardModel sub-classes 'match' the currently inserted card
1563 (by ATR or overriding the 'match' method). If so, call their 'add_files'
1564 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001565 for m in CardModel.__subclasses__():
1566 if m.match(scc):
1567 m.add_files(rs)