blob: d52a16e474f0b10116866d7393c194f33d5fcd4e [file] [log] [blame]
Harald Welteb2edd142021-01-08 23:29:35 +01001# coding=utf-8
2"""Representation of the ISO7816-4 filesystem model.
3
4The File (and its derived classes) represent the structure / hierarchy
5of the ISO7816-4 smart card file system with the MF, DF, EF and ADF
6entries, further sub-divided into the EF sub-types Transparent, Linear Fixed, etc.
7
8The classes are intended to represent the *specification* of the filesystem,
9not the actual contents / runtime state of interacting with a given smart card.
Harald Welteb2edd142021-01-08 23:29:35 +010010"""
11
Harald Welte5a4fd522021-04-02 16:05:26 +020012# (C) 2021 by Harald Welte <laforge@osmocom.org>
13#
14# This program is free software: you can redistribute it and/or modify
15# it under the terms of the GNU General Public License as published by
16# the Free Software Foundation, either version 2 of the License, or
17# (at your option) any later version.
18#
19# This program is distributed in the hope that it will be useful,
20# but WITHOUT ANY WARRANTY; without even the implied warranty of
21# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22# GNU General Public License for more details.
23#
24# You should have received a copy of the GNU General Public License
25# along with this program. If not, see <http://www.gnu.org/licenses/>.
26
Harald Welteb2edd142021-01-08 23:29:35 +010027import code
Harald Welte4145d3c2021-04-08 20:34:13 +020028import tempfile
Harald Welteb2edd142021-01-08 23:29:35 +010029import json
Harald Weltef44256c2021-10-14 15:53:39 +020030import abc
31import inspect
Harald Welteb2edd142021-01-08 23:29:35 +010032
33import cmd2
34from cmd2 import CommandSet, with_default_category, with_argparser
35import argparse
36
Harald Welte9170fbf2022-02-11 21:54:37 +010037from typing import cast, Optional, Iterable, List, Dict, Tuple, Union
Harald Welteee3501f2021-04-02 13:00:18 +020038
Harald Weltef44256c2021-10-14 15:53:39 +020039from smartcard.util import toBytes
40
Harald Weltedaf2b392021-05-03 23:17:29 +020041from pySim.utils import sw_match, h2b, b2h, i2h, is_hex, auto_int, bertlv_parse_one, Hexstr
Harald Welte07c7b1f2021-05-28 22:01:29 +020042from pySim.construct import filter_dict, parse_construct
Harald Welteb2edd142021-01-08 23:29:35 +010043from pySim.exceptions import *
Harald Welte0d4e98a2021-04-07 00:14:40 +020044from pySim.jsonpath import js_path_find, js_path_modify
Harald Weltef44256c2021-10-14 15:53:39 +020045from pySim.commands import SimCardCommands
Harald Welteb2edd142021-01-08 23:29:35 +010046
Harald Welte9170fbf2022-02-11 21:54:37 +010047# int: a single service is associated with this file
48# list: any of the listed services requires this file
49# tuple: logical-and of the listed services requires this file
50CardFileService = Union[int, List[int], Tuple[int, ...]]
Harald Weltec91085e2022-02-10 18:05:45 +010051
Harald Welteb2edd142021-01-08 23:29:35 +010052class CardFile(object):
53 """Base class for all objects in the smart card filesystem.
54 Serve as a common ancestor to all other file types; rarely used directly.
55 """
56 RESERVED_NAMES = ['..', '.', '/', 'MF']
57 RESERVED_FIDS = ['3f00']
58
Harald Weltec91085e2022-02-10 18:05:45 +010059 def __init__(self, fid: str = None, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +010060 parent: Optional['CardDF'] = None, profile: Optional['CardProfile'] = None,
61 service: Optional[CardFileService] = None):
Harald Welteee3501f2021-04-02 13:00:18 +020062 """
63 Args:
64 fid : File Identifier (4 hex digits)
65 sfid : Short File Identifier (2 hex digits, optional)
66 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +020067 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +020068 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier5af7bdf2021-11-04 12:48:41 +010069 profile : Card profile that this file should be part of
Harald Welte9170fbf2022-02-11 21:54:37 +010070 service : Service (SST/UST/IST) associated with the file
Harald Welteee3501f2021-04-02 13:00:18 +020071 """
Harald Welteb2edd142021-01-08 23:29:35 +010072 if not isinstance(self, CardADF) and fid == None:
73 raise ValueError("fid is mandatory")
74 if fid:
75 fid = fid.lower()
76 self.fid = fid # file identifier
77 self.sfid = sfid # short file identifier
78 self.name = name # human readable name
79 self.desc = desc # human readable description
80 self.parent = parent
81 if self.parent and self.parent != self and self.fid:
82 self.parent.add_file(self)
Philipp Maier5af7bdf2021-11-04 12:48:41 +010083 self.profile = profile
Harald Welte9170fbf2022-02-11 21:54:37 +010084 self.service = service
Harald Weltec91085e2022-02-10 18:05:45 +010085 self.shell_commands = [] # type: List[CommandSet]
Harald Welteb2edd142021-01-08 23:29:35 +010086
Harald Weltec91085e2022-02-10 18:05:45 +010087 # Note: the basic properties (fid, name, ect.) are verified when
88 # the file is attached to a parent file. See method add_file() in
89 # class Card DF
Philipp Maier66061582021-03-09 21:57:57 +010090
Harald Welteb2edd142021-01-08 23:29:35 +010091 def __str__(self):
92 if self.name:
93 return self.name
94 else:
95 return self.fid
96
Harald Weltec91085e2022-02-10 18:05:45 +010097 def _path_element(self, prefer_name: bool) -> Optional[str]:
Harald Welteb2edd142021-01-08 23:29:35 +010098 if prefer_name and self.name:
99 return self.name
100 else:
101 return self.fid
102
Harald Weltec91085e2022-02-10 18:05:45 +0100103 def fully_qualified_path(self, prefer_name: bool = True) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200104 """Return fully qualified path to file as list of FID or name strings.
105
106 Args:
107 prefer_name : Preferably build path of names; fall-back to FIDs as required
108 """
Harald Welte1e456572021-04-02 17:16:30 +0200109 if self.parent and self.parent != self:
Harald Welteb2edd142021-01-08 23:29:35 +0100110 ret = self.parent.fully_qualified_path(prefer_name)
111 else:
112 ret = []
Harald Welte1e456572021-04-02 17:16:30 +0200113 elem = self._path_element(prefer_name)
114 if elem:
115 ret.append(elem)
Harald Welteb2edd142021-01-08 23:29:35 +0100116 return ret
117
Harald Welteee3501f2021-04-02 13:00:18 +0200118 def get_mf(self) -> Optional['CardMF']:
Harald Welteb2edd142021-01-08 23:29:35 +0100119 """Return the MF (root) of the file system."""
120 if self.parent == None:
121 return None
122 # iterate towards the top. MF has parent == self
123 node = self
Harald Welte1e456572021-04-02 17:16:30 +0200124 while node.parent and node.parent != node:
Harald Welteb2edd142021-01-08 23:29:35 +0100125 node = node.parent
Harald Welte1e456572021-04-02 17:16:30 +0200126 return cast(CardMF, node)
Harald Welteb2edd142021-01-08 23:29:35 +0100127
Harald Weltec91085e2022-02-10 18:05:45 +0100128 def _get_self_selectables(self, alias: str = None, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200129 """Return a dict of {'identifier': self} tuples.
130
131 Args:
132 alias : Add an alias with given name to 'self'
133 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
134 If not specified, all selectables will be returned.
135 Returns:
136 dict containing reference to 'self' for all identifiers.
137 """
Harald Welteb2edd142021-01-08 23:29:35 +0100138 sels = {}
139 if alias:
140 sels.update({alias: self})
Philipp Maier786f7812021-02-25 16:48:10 +0100141 if self.fid and (flags == [] or 'FIDS' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100142 sels.update({self.fid: self})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100143 if self.name and (flags == [] or 'FNAMES' in flags):
Harald Welteb2edd142021-01-08 23:29:35 +0100144 sels.update({self.name: self})
145 return sels
146
Harald Weltec91085e2022-02-10 18:05:45 +0100147 def get_selectables(self, flags=[]) -> Dict[str, 'CardFile']:
Harald Welteee3501f2021-04-02 13:00:18 +0200148 """Return a dict of {'identifier': File} that is selectable from the current file.
149
150 Args:
151 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
152 If not specified, all selectables will be returned.
153 Returns:
154 dict containing all selectable items. Key is identifier (string), value
155 a reference to a CardFile (or derived class) instance.
156 """
Philipp Maier786f7812021-02-25 16:48:10 +0100157 sels = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100158 # we can always select ourself
Philipp Maier786f7812021-02-25 16:48:10 +0100159 if flags == [] or 'SELF' in flags:
160 sels = self._get_self_selectables('.', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100161 # we can always select our parent
Philipp Maier786f7812021-02-25 16:48:10 +0100162 if flags == [] or 'PARENT' in flags:
Harald Welte1e456572021-04-02 17:16:30 +0200163 if self.parent:
164 sels = self.parent._get_self_selectables('..', flags)
Harald Welteb2edd142021-01-08 23:29:35 +0100165 # if we have a MF, we can always select its applications
Philipp Maier786f7812021-02-25 16:48:10 +0100166 if flags == [] or 'MF' in flags:
167 mf = self.get_mf()
168 if mf:
Harald Weltec91085e2022-02-10 18:05:45 +0100169 sels.update(mf._get_self_selectables(flags=flags))
170 sels.update(mf.get_app_selectables(flags=flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100171 return sels
172
Harald Weltec91085e2022-02-10 18:05:45 +0100173 def get_selectable_names(self, flags=[]) -> List[str]:
Harald Welteee3501f2021-04-02 13:00:18 +0200174 """Return a dict of {'identifier': File} that is selectable from the current file.
175
176 Args:
177 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
178 If not specified, all selectables will be returned.
179 Returns:
Harald Welte1e456572021-04-02 17:16:30 +0200180 list containing all selectable names.
Harald Welteee3501f2021-04-02 13:00:18 +0200181 """
Philipp Maier786f7812021-02-25 16:48:10 +0100182 sels = self.get_selectables(flags)
Harald Welteb3d68c02022-01-21 15:31:29 +0100183 sel_keys = list(sels.keys())
184 sel_keys.sort()
185 return sel_keys
Harald Welteb2edd142021-01-08 23:29:35 +0100186
Harald Weltec91085e2022-02-10 18:05:45 +0100187 def decode_select_response(self, data_hex: str):
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100188 """Decode the response to a SELECT command.
189
190 Args:
Harald Weltec91085e2022-02-10 18:05:45 +0100191 data_hex: Hex string of the select response
192 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100193
Harald Weltec91085e2022-02-10 18:05:45 +0100194 # When the current file does not implement a custom select response decoder,
195 # we just ask the parent file to decode the select response. If this method
196 # is not overloaded by the current file we will again ask the parent file.
197 # This way we recursively travel up the file system tree until we hit a file
198 # that does implement a concrete decoder.
Harald Welte1e456572021-04-02 17:16:30 +0200199 if self.parent:
200 return self.parent.decode_select_response(data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +0100201
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100202 def get_profile(self):
203 """Get the profile associated with this file. If this file does not have any
204 profile assigned, try to find a file above (usually the MF) in the filesystem
205 hirarchy that has a profile assigned
206 """
207
208 # If we have a profile set, return it
209 if self.profile:
210 return self.profile
211
212 # Walk up recursively until we hit a parent that has a profile set
213 if self.parent:
214 return self.parent.get_profile()
215 return None
Harald Welteb2edd142021-01-08 23:29:35 +0100216
Harald Welte9170fbf2022-02-11 21:54:37 +0100217 def should_exist_for_services(self, services: List[int]):
218 """Assuming the provided list of activated services, should this file exist and be activated?."""
219 if self.service is None:
220 return None
221 elif isinstance(self.service, int):
222 # a single service determines the result
223 return self.service in services
224 elif isinstance(self.service, list):
225 # any of the services active -> true
226 for s in self.service:
227 if s in services:
228 return True
229 return False
230 elif isinstance(self.service, tuple):
231 # all of the services active -> true
232 for s in self.service:
233 if not s in services:
234 return False
235 return True
236 else:
237 raise ValueError("self.service must be either int or list or tuple")
238
Harald Weltec91085e2022-02-10 18:05:45 +0100239
Harald Welteb2edd142021-01-08 23:29:35 +0100240class CardDF(CardFile):
241 """DF (Dedicated File) in the smart card filesystem. Those are basically sub-directories."""
Philipp Maier63f572d2021-03-09 22:42:47 +0100242
243 @with_default_category('DF/ADF Commands')
244 class ShellCommands(CommandSet):
245 def __init__(self):
246 super().__init__()
247
Harald Welteb2edd142021-01-08 23:29:35 +0100248 def __init__(self, **kwargs):
249 if not isinstance(self, CardADF):
250 if not 'fid' in kwargs:
251 raise TypeError('fid is mandatory for all DF')
252 super().__init__(**kwargs)
253 self.children = dict()
Philipp Maier63f572d2021-03-09 22:42:47 +0100254 self.shell_commands = [self.ShellCommands()]
Harald Welte9170fbf2022-02-11 21:54:37 +0100255 # dict of CardFile affected by service(int), indexed by service
256 self.files_by_service = {}
Harald Welteb2edd142021-01-08 23:29:35 +0100257
258 def __str__(self):
259 return "DF(%s)" % (super().__str__())
260
Harald Welte9170fbf2022-02-11 21:54:37 +0100261 def _add_file_services(self, child):
262 """Add a child (DF/EF) to the files_by_services of the parent."""
263 if not child.service:
264 return
265 if isinstance(child.service, int):
266 self.files_by_service.setdefault(child.service, []).append(child)
267 elif isinstance(child.service, list):
268 for service in child.service:
269 self.files_by_service.setdefault(service, []).append(child)
270 elif isinstance(child.service, tuple):
271 for service in child.service:
272 self.files_by_service.setdefault(service, []).append(child)
273 else:
274 raise ValueError
275
Harald Weltec91085e2022-02-10 18:05:45 +0100276 def add_file(self, child: CardFile, ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200277 """Add a child (DF/EF) to this DF.
278 Args:
279 child: The new DF/EF to be added
280 ignore_existing: Ignore, if file with given FID already exists. Old one will be kept.
281 """
Harald Welteb2edd142021-01-08 23:29:35 +0100282 if not isinstance(child, CardFile):
283 raise TypeError("Expected a File instance")
Harald Weltec91085e2022-02-10 18:05:45 +0100284 if not is_hex(child.fid, minlen=4, maxlen=4):
Philipp Maier3aec8712021-03-09 21:49:01 +0100285 raise ValueError("File name %s is not a valid fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100286 if child.name in CardFile.RESERVED_NAMES:
287 raise ValueError("File name %s is a reserved name" % (child.name))
288 if child.fid in CardFile.RESERVED_FIDS:
Philipp Maiere8bc1b42021-03-09 20:33:41 +0100289 raise ValueError("File fid %s is a reserved fid" % (child.fid))
Harald Welteb2edd142021-01-08 23:29:35 +0100290 if child.fid in self.children:
291 if ignore_existing:
292 return
Harald Weltec91085e2022-02-10 18:05:45 +0100293 raise ValueError(
294 "File with given fid %s already exists in %s" % (child.fid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100295 if self.lookup_file_by_sfid(child.sfid):
Harald Weltec91085e2022-02-10 18:05:45 +0100296 raise ValueError(
297 "File with given sfid %s already exists in %s" % (child.sfid, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100298 if self.lookup_file_by_name(child.name):
299 if ignore_existing:
300 return
Harald Weltec91085e2022-02-10 18:05:45 +0100301 raise ValueError(
302 "File with given name %s already exists in %s" % (child.name, self))
Harald Welteb2edd142021-01-08 23:29:35 +0100303 self.children[child.fid] = child
304 child.parent = self
Harald Welte9170fbf2022-02-11 21:54:37 +0100305 self._add_file_services(child)
Harald Welteb2edd142021-01-08 23:29:35 +0100306
Harald Weltec91085e2022-02-10 18:05:45 +0100307 def add_files(self, children: Iterable[CardFile], ignore_existing: bool = False):
Harald Welteee3501f2021-04-02 13:00:18 +0200308 """Add a list of child (DF/EF) to this DF
309
310 Args:
311 children: List of new DF/EFs to be added
312 ignore_existing: Ignore, if file[s] with given FID already exists. Old one[s] will be kept.
313 """
Harald Welteb2edd142021-01-08 23:29:35 +0100314 for child in children:
315 self.add_file(child, ignore_existing)
316
Harald Weltec91085e2022-02-10 18:05:45 +0100317 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200318 """Return a dict of {'identifier': File} that is selectable from the current DF.
319
320 Args:
321 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
322 If not specified, all selectables will be returned.
323 Returns:
324 dict containing all selectable items. Key is identifier (string), value
325 a reference to a CardFile (or derived class) instance.
326 """
Harald Welteb2edd142021-01-08 23:29:35 +0100327 # global selectables + our children
Philipp Maier786f7812021-02-25 16:48:10 +0100328 sels = super().get_selectables(flags)
329 if flags == [] or 'FIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100330 sels.update({x.fid: x for x in self.children.values() if x.fid})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100331 if flags == [] or 'FNAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100332 sels.update({x.name: x for x in self.children.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100333 return sels
334
Harald Weltec91085e2022-02-10 18:05:45 +0100335 def lookup_file_by_name(self, name: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200336 """Find a file with given name within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100337 if name == None:
338 return None
339 for i in self.children.values():
340 if i.name and i.name == name:
341 return i
342 return None
343
Harald Weltec91085e2022-02-10 18:05:45 +0100344 def lookup_file_by_sfid(self, sfid: Optional[str]) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200345 """Find a file with given short file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100346 if sfid == None:
347 return None
348 for i in self.children.values():
Harald Welte1e456572021-04-02 17:16:30 +0200349 if i.sfid == int(str(sfid)):
Harald Welteb2edd142021-01-08 23:29:35 +0100350 return i
351 return None
352
Harald Weltec91085e2022-02-10 18:05:45 +0100353 def lookup_file_by_fid(self, fid: str) -> Optional[CardFile]:
Harald Welteee3501f2021-04-02 13:00:18 +0200354 """Find a file with given file ID within current DF."""
Harald Welteb2edd142021-01-08 23:29:35 +0100355 if fid in self.children:
356 return self.children[fid]
357 return None
358
359
360class CardMF(CardDF):
361 """MF (Master File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100362
Harald Welteb2edd142021-01-08 23:29:35 +0100363 def __init__(self, **kwargs):
364 # can be overridden; use setdefault
365 kwargs.setdefault('fid', '3f00')
366 kwargs.setdefault('name', 'MF')
367 kwargs.setdefault('desc', 'Master File (directory root)')
368 # cannot be overridden; use assignment
369 kwargs['parent'] = self
370 super().__init__(**kwargs)
371 self.applications = dict()
372
373 def __str__(self):
374 return "MF(%s)" % (self.fid)
375
Harald Weltec91085e2022-02-10 18:05:45 +0100376 def add_application_df(self, app: 'CardADF'):
Harald Welte5ce35242021-04-02 20:27:05 +0200377 """Add an Application to the MF"""
Harald Welteb2edd142021-01-08 23:29:35 +0100378 if not isinstance(app, CardADF):
379 raise TypeError("Expected an ADF instance")
380 if app.aid in self.applications:
381 raise ValueError("AID %s already exists" % (app.aid))
382 self.applications[app.aid] = app
Harald Weltec91085e2022-02-10 18:05:45 +0100383 app.parent = self
Harald Welteb2edd142021-01-08 23:29:35 +0100384
385 def get_app_names(self):
386 """Get list of completions (AID names)"""
387 return [x.name for x in self.applications]
388
Harald Weltec91085e2022-02-10 18:05:45 +0100389 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200390 """Return a dict of {'identifier': File} that is selectable from the current DF.
391
392 Args:
393 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
394 If not specified, all selectables will be returned.
395 Returns:
396 dict containing all selectable items. Key is identifier (string), value
397 a reference to a CardFile (or derived class) instance.
398 """
Philipp Maier786f7812021-02-25 16:48:10 +0100399 sels = super().get_selectables(flags)
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100400 sels.update(self.get_app_selectables(flags))
Harald Welteb2edd142021-01-08 23:29:35 +0100401 return sels
402
Harald Weltec91085e2022-02-10 18:05:45 +0100403 def get_app_selectables(self, flags=[]) -> dict:
Philipp Maier786f7812021-02-25 16:48:10 +0100404 """Get applications by AID + name"""
405 sels = {}
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100406 if flags == [] or 'AIDS' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100407 sels.update({x.aid: x for x in self.applications.values()})
Philipp Maierbd8ed2c2021-03-18 17:09:33 +0100408 if flags == [] or 'ANAMES' in flags:
Harald Weltec91085e2022-02-10 18:05:45 +0100409 sels.update(
410 {x.name: x for x in self.applications.values() if x.name})
Harald Welteb2edd142021-01-08 23:29:35 +0100411 return sels
412
Harald Weltec9752512022-02-11 16:31:15 +0100413 def decode_select_response(self, data_hex: Optional[str]) -> object:
Harald Welteee3501f2021-04-02 13:00:18 +0200414 """Decode the response to a SELECT command.
415
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100416 This is the fall-back method which automatically defers to the standard decoding
417 method defined by the card profile. When no profile is set, then no decoding is
Harald Weltec91085e2022-02-10 18:05:45 +0100418 performed. Specific derived classes (usually ADF) can overload this method to
419 install specific decoding.
Harald Welteee3501f2021-04-02 13:00:18 +0200420 """
Harald Welteb2edd142021-01-08 23:29:35 +0100421
Harald Weltec9752512022-02-11 16:31:15 +0100422 if not data_hex:
423 return data_hex
424
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100425 profile = self.get_profile()
Harald Welteb2edd142021-01-08 23:29:35 +0100426
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100427 if profile:
428 return profile.decode_select_response(data_hex)
429 else:
430 return data_hex
Harald Welteb2edd142021-01-08 23:29:35 +0100431
Harald Weltec91085e2022-02-10 18:05:45 +0100432
Harald Welteb2edd142021-01-08 23:29:35 +0100433class CardADF(CardDF):
434 """ADF (Application Dedicated File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100435
436 def __init__(self, aid: str, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100437 super().__init__(**kwargs)
Harald Welte5ce35242021-04-02 20:27:05 +0200438 # reference to CardApplication may be set from CardApplication constructor
Harald Weltefe8a7442021-04-10 11:51:54 +0200439 self.application = None # type: Optional[CardApplication]
Harald Welteb2edd142021-01-08 23:29:35 +0100440 self.aid = aid # Application Identifier
Harald Welte1e456572021-04-02 17:16:30 +0200441 mf = self.get_mf()
442 if mf:
Harald Welte5ce35242021-04-02 20:27:05 +0200443 mf.add_application_df(self)
Harald Welteb2edd142021-01-08 23:29:35 +0100444
445 def __str__(self):
446 return "ADF(%s)" % (self.aid)
447
Harald Weltec91085e2022-02-10 18:05:45 +0100448 def _path_element(self, prefer_name: bool):
Harald Welteb2edd142021-01-08 23:29:35 +0100449 if self.name and prefer_name:
450 return self.name
451 else:
452 return self.aid
453
454
455class CardEF(CardFile):
456 """EF (Entry File) in the smart card filesystem"""
Harald Weltec91085e2022-02-10 18:05:45 +0100457
Harald Welteb2edd142021-01-08 23:29:35 +0100458 def __init__(self, *, fid, **kwargs):
459 kwargs['fid'] = fid
460 super().__init__(**kwargs)
461
462 def __str__(self):
463 return "EF(%s)" % (super().__str__())
464
Harald Weltec91085e2022-02-10 18:05:45 +0100465 def get_selectables(self, flags=[]) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200466 """Return a dict of {'identifier': File} that is selectable from the current DF.
467
468 Args:
469 flags : Specify which selectables to return 'FIDS' and/or 'NAMES';
470 If not specified, all selectables will be returned.
471 Returns:
472 dict containing all selectable items. Key is identifier (string), value
473 a reference to a CardFile (or derived class) instance.
474 """
Harald Weltec91085e2022-02-10 18:05:45 +0100475 # global selectable names + those of the parent DF
Philipp Maier786f7812021-02-25 16:48:10 +0100476 sels = super().get_selectables(flags)
Harald Weltec91085e2022-02-10 18:05:45 +0100477 sels.update(
478 {x.name: x for x in self.parent.children.values() if x != self})
Harald Welteb2edd142021-01-08 23:29:35 +0100479 return sels
480
481
482class TransparentEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200483 """Transparent EF (Entry File) in the smart card filesystem.
484
485 A Transparent EF is a binary file with no formal structure. This is contrary to
486 Record based EFs which have [fixed size] records that can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100487
488 @with_default_category('Transparent EF Commands')
489 class ShellCommands(CommandSet):
Harald Weltec9cdce32021-04-11 10:28:28 +0200490 """Shell commands specific for transparent EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100491
Harald Welteb2edd142021-01-08 23:29:35 +0100492 def __init__(self):
493 super().__init__()
494
495 read_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100496 read_bin_parser.add_argument(
497 '--offset', type=int, default=0, help='Byte offset for start of read')
498 read_bin_parser.add_argument(
499 '--length', type=int, help='Number of bytes to read')
500
Harald Welteb2edd142021-01-08 23:29:35 +0100501 @cmd2.with_argparser(read_bin_parser)
502 def do_read_binary(self, opts):
503 """Read binary data from a transparent EF"""
504 (data, sw) = self._cmd.rs.read_binary(opts.length, opts.offset)
505 self._cmd.poutput(data)
506
Harald Weltebcad86c2021-04-06 20:08:39 +0200507 read_bin_dec_parser = argparse.ArgumentParser()
508 read_bin_dec_parser.add_argument('--oneline', action='store_true',
509 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100510
Harald Weltebcad86c2021-04-06 20:08:39 +0200511 @cmd2.with_argparser(read_bin_dec_parser)
Harald Welteb2edd142021-01-08 23:29:35 +0100512 def do_read_binary_decoded(self, opts):
513 """Read + decode data from a transparent EF"""
514 (data, sw) = self._cmd.rs.read_binary_dec()
Harald Welte1748b932021-04-06 21:12:25 +0200515 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100516
517 upd_bin_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100518 upd_bin_parser.add_argument(
519 '--offset', type=int, default=0, help='Byte offset for start of read')
520 upd_bin_parser.add_argument(
521 'data', help='Data bytes (hex format) to write')
522
Harald Welteb2edd142021-01-08 23:29:35 +0100523 @cmd2.with_argparser(upd_bin_parser)
524 def do_update_binary(self, opts):
525 """Update (Write) data of a transparent EF"""
526 (data, sw) = self._cmd.rs.update_binary(opts.data, opts.offset)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100527 if data:
528 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100529
530 upd_bin_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100531 upd_bin_dec_parser.add_argument(
532 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200533 upd_bin_dec_parser.add_argument('--json-path', type=str,
534 help='JSON path to modify specific element of file only')
Harald Weltec91085e2022-02-10 18:05:45 +0100535
Harald Welteb2edd142021-01-08 23:29:35 +0100536 @cmd2.with_argparser(upd_bin_dec_parser)
537 def do_update_binary_decoded(self, opts):
538 """Encode + Update (Write) data of a transparent EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200539 if opts.json_path:
540 (data_json, sw) = self._cmd.rs.read_binary_dec()
Harald Weltec91085e2022-02-10 18:05:45 +0100541 js_path_modify(data_json, opts.json_path,
542 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200543 else:
544 data_json = json.loads(opts.data)
Harald Welteb2edd142021-01-08 23:29:35 +0100545 (data, sw) = self._cmd.rs.update_binary_dec(data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100546 if data:
Harald Welte1748b932021-04-06 21:12:25 +0200547 self._cmd.poutput_json(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100548
Harald Welte4145d3c2021-04-08 20:34:13 +0200549 def do_edit_binary_decoded(self, opts):
550 """Edit the JSON representation of the EF contents in an editor."""
551 (orig_json, sw) = self._cmd.rs.read_binary_dec()
552 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
553 filename = '%s/file' % dirname
554 # write existing data as JSON to file
555 with open(filename, 'w') as text_file:
556 json.dump(orig_json, text_file, indent=4)
557 # run a text editor
558 self._cmd._run_editor(filename)
559 with open(filename, 'r') as text_file:
560 edited_json = json.load(text_file)
561 if edited_json == orig_json:
562 self._cmd.poutput("Data not modified, skipping write")
563 else:
564 (data, sw) = self._cmd.rs.update_binary_dec(edited_json)
565 if data:
566 self._cmd.poutput_json(data)
567
Harald Weltec91085e2022-02-10 18:05:45 +0100568 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100569 size={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200570 """
571 Args:
572 fid : File Identifier (4 hex digits)
573 sfid : Short File Identifier (2 hex digits, optional)
574 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200575 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200576 parent : Parent CardFile object within filesystem hierarchy
577 size : tuple of (minimum_size, recommended_size)
578 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100579 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200580 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200581 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100582 self.size = size
583 self.shell_commands = [self.ShellCommands()]
584
Harald Weltec91085e2022-02-10 18:05:45 +0100585 def decode_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200586 """Decode raw (binary) data into abstract representation.
587
588 A derived class would typically provide a _decode_bin() or _decode_hex() method
589 for implementing this specifically for the given file. This function checks which
590 of the method exists, add calls them (with conversion, as needed).
591
592 Args:
593 raw_bin_data : binary encoded data
594 Returns:
595 abstract_data; dict representing the decoded data
596 """
Harald Welteb2edd142021-01-08 23:29:35 +0100597 method = getattr(self, '_decode_bin', None)
598 if callable(method):
599 return method(raw_bin_data)
600 method = getattr(self, '_decode_hex', None)
601 if callable(method):
602 return method(b2h(raw_bin_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200603 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200604 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200605 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100606 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100607 t.from_tlv(raw_bin_data)
608 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100609 return {'raw': raw_bin_data.hex()}
610
Harald Weltec91085e2022-02-10 18:05:45 +0100611 def decode_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200612 """Decode raw (hex string) data into abstract representation.
613
614 A derived class would typically provide a _decode_bin() or _decode_hex() method
615 for implementing this specifically for the given file. This function checks which
616 of the method exists, add calls them (with conversion, as needed).
617
618 Args:
619 raw_hex_data : hex-encoded data
620 Returns:
621 abstract_data; dict representing the decoded data
622 """
Harald Welteb2edd142021-01-08 23:29:35 +0100623 method = getattr(self, '_decode_hex', None)
624 if callable(method):
625 return method(raw_hex_data)
626 raw_bin_data = h2b(raw_hex_data)
627 method = getattr(self, '_decode_bin', None)
628 if callable(method):
629 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200630 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200631 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200632 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100633 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100634 t.from_tlv(raw_bin_data)
635 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100636 return {'raw': raw_bin_data.hex()}
637
Harald Weltec91085e2022-02-10 18:05:45 +0100638 def encode_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200639 """Encode abstract representation into raw (binary) data.
640
641 A derived class would typically provide an _encode_bin() or _encode_hex() method
642 for implementing this specifically for the given file. This function checks which
643 of the method exists, add calls them (with conversion, as needed).
644
645 Args:
646 abstract_data : dict representing the decoded data
647 Returns:
648 binary encoded data
649 """
Harald Welteb2edd142021-01-08 23:29:35 +0100650 method = getattr(self, '_encode_bin', None)
651 if callable(method):
652 return method(abstract_data)
653 method = getattr(self, '_encode_hex', None)
654 if callable(method):
655 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200656 if self._construct:
657 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200658 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100659 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100660 t.from_dict(abstract_data)
661 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100662 raise NotImplementedError(
663 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100664
Harald Weltec91085e2022-02-10 18:05:45 +0100665 def encode_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200666 """Encode abstract representation into raw (hex string) data.
667
668 A derived class would typically provide an _encode_bin() or _encode_hex() method
669 for implementing this specifically for the given file. This function checks which
670 of the method exists, add calls them (with conversion, as needed).
671
672 Args:
673 abstract_data : dict representing the decoded data
674 Returns:
675 hex string encoded data
676 """
Harald Welteb2edd142021-01-08 23:29:35 +0100677 method = getattr(self, '_encode_hex', None)
678 if callable(method):
679 return method(abstract_data)
680 method = getattr(self, '_encode_bin', None)
681 if callable(method):
682 raw_bin_data = method(abstract_data)
683 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200684 if self._construct:
685 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200686 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100687 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100688 t.from_dict(abstract_data)
689 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100690 raise NotImplementedError(
691 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100692
693
694class LinFixedEF(CardEF):
Harald Welteee3501f2021-04-02 13:00:18 +0200695 """Linear Fixed EF (Entry File) in the smart card filesystem.
696
697 Linear Fixed EFs are record oriented files. They consist of a number of fixed-size
698 records. The records can be individually read/updated."""
Harald Welteb2edd142021-01-08 23:29:35 +0100699
700 @with_default_category('Linear Fixed EF Commands')
701 class ShellCommands(CommandSet):
Harald Welteee3501f2021-04-02 13:00:18 +0200702 """Shell commands specific for Linear Fixed EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +0100703
Harald Welte9170fbf2022-02-11 21:54:37 +0100704 def __init__(self, **kwargs):
705 super().__init__(**kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100706
707 read_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100708 read_rec_parser.add_argument(
709 'record_nr', type=int, help='Number of record to be read')
710 read_rec_parser.add_argument(
711 '--count', type=int, default=1, help='Number of records to be read, beginning at record_nr')
712
Harald Welteb2edd142021-01-08 23:29:35 +0100713 @cmd2.with_argparser(read_rec_parser)
714 def do_read_record(self, opts):
Philipp Maier41555732021-02-25 16:52:08 +0100715 """Read one or multiple records from a record-oriented EF"""
716 for r in range(opts.count):
717 recnr = opts.record_nr + r
718 (data, sw) = self._cmd.rs.read_record(recnr)
719 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100720 recstr = str(data)
Philipp Maier41555732021-02-25 16:52:08 +0100721 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100722 recstr = "(empty)"
Philipp Maier41555732021-02-25 16:52:08 +0100723 self._cmd.poutput("%03d %s" % (recnr, recstr))
Harald Welteb2edd142021-01-08 23:29:35 +0100724
725 read_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100726 read_rec_dec_parser.add_argument(
727 'record_nr', type=int, help='Number of record to be read')
Harald Weltebcad86c2021-04-06 20:08:39 +0200728 read_rec_dec_parser.add_argument('--oneline', action='store_true',
729 help='No JSON pretty-printing, dump as a single line')
Harald Weltec91085e2022-02-10 18:05:45 +0100730
Harald Welteb2edd142021-01-08 23:29:35 +0100731 @cmd2.with_argparser(read_rec_dec_parser)
732 def do_read_record_decoded(self, opts):
733 """Read + decode a record from a record-oriented EF"""
734 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Welte1748b932021-04-06 21:12:25 +0200735 self._cmd.poutput_json(data, opts.oneline)
Harald Welteb2edd142021-01-08 23:29:35 +0100736
Harald Welte850b72a2021-04-07 09:33:03 +0200737 read_recs_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100738
Harald Welte850b72a2021-04-07 09:33:03 +0200739 @cmd2.with_argparser(read_recs_parser)
740 def do_read_records(self, opts):
741 """Read all records from a record-oriented EF"""
742 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
743 for recnr in range(1, 1 + num_of_rec):
744 (data, sw) = self._cmd.rs.read_record(recnr)
745 if (len(data) > 0):
Harald Weltec91085e2022-02-10 18:05:45 +0100746 recstr = str(data)
Harald Welte850b72a2021-04-07 09:33:03 +0200747 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100748 recstr = "(empty)"
Harald Welte850b72a2021-04-07 09:33:03 +0200749 self._cmd.poutput("%03d %s" % (recnr, recstr))
750
751 read_recs_dec_parser = argparse.ArgumentParser()
752 read_recs_dec_parser.add_argument('--oneline', action='store_true',
Harald Weltec91085e2022-02-10 18:05:45 +0100753 help='No JSON pretty-printing, dump as a single line')
754
Harald Welte850b72a2021-04-07 09:33:03 +0200755 @cmd2.with_argparser(read_recs_dec_parser)
756 def do_read_records_decoded(self, opts):
757 """Read + decode all records from a record-oriented EF"""
758 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
759 # collect all results in list so they are rendered as JSON list when printing
760 data_list = []
761 for recnr in range(1, 1 + num_of_rec):
762 (data, sw) = self._cmd.rs.read_record_dec(recnr)
763 data_list.append(data)
764 self._cmd.poutput_json(data_list, opts.oneline)
765
Harald Welteb2edd142021-01-08 23:29:35 +0100766 upd_rec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100767 upd_rec_parser.add_argument(
768 'record_nr', type=int, help='Number of record to be read')
769 upd_rec_parser.add_argument(
770 'data', help='Data bytes (hex format) to write')
771
Harald Welteb2edd142021-01-08 23:29:35 +0100772 @cmd2.with_argparser(upd_rec_parser)
773 def do_update_record(self, opts):
774 """Update (write) data to a record-oriented EF"""
775 (data, sw) = self._cmd.rs.update_record(opts.record_nr, opts.data)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100776 if data:
777 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100778
779 upd_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100780 upd_rec_dec_parser.add_argument(
781 'record_nr', type=int, help='Number of record to be read')
782 upd_rec_dec_parser.add_argument(
783 'data', help='Abstract data (JSON format) to write')
Harald Welte0d4e98a2021-04-07 00:14:40 +0200784 upd_rec_dec_parser.add_argument('--json-path', type=str,
785 help='JSON path to modify specific element of record only')
Harald Weltec91085e2022-02-10 18:05:45 +0100786
Harald Welteb2edd142021-01-08 23:29:35 +0100787 @cmd2.with_argparser(upd_rec_dec_parser)
788 def do_update_record_decoded(self, opts):
789 """Encode + Update (write) data to a record-oriented EF"""
Harald Welte0d4e98a2021-04-07 00:14:40 +0200790 if opts.json_path:
791 (data_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Harald Weltec91085e2022-02-10 18:05:45 +0100792 js_path_modify(data_json, opts.json_path,
793 json.loads(opts.data))
Harald Welte0d4e98a2021-04-07 00:14:40 +0200794 else:
795 data_json = json.loads(opts.data)
Harald Weltec91085e2022-02-10 18:05:45 +0100796 (data, sw) = self._cmd.rs.update_record_dec(
797 opts.record_nr, data_json)
Philipp Maiere6bc4f92021-03-11 17:13:46 +0100798 if data:
799 self._cmd.poutput(data)
Harald Welteb2edd142021-01-08 23:29:35 +0100800
Harald Welte4145d3c2021-04-08 20:34:13 +0200801 edit_rec_dec_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +0100802 edit_rec_dec_parser.add_argument(
803 'record_nr', type=int, help='Number of record to be edited')
804
Harald Welte4145d3c2021-04-08 20:34:13 +0200805 @cmd2.with_argparser(edit_rec_dec_parser)
806 def do_edit_record_decoded(self, opts):
807 """Edit the JSON representation of one record in an editor."""
808 (orig_json, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
Vadim Yanitskiy895fa6f2021-05-02 02:36:44 +0200809 with tempfile.TemporaryDirectory(prefix='pysim_') as dirname:
Harald Welte4145d3c2021-04-08 20:34:13 +0200810 filename = '%s/file' % dirname
811 # write existing data as JSON to file
812 with open(filename, 'w') as text_file:
813 json.dump(orig_json, text_file, indent=4)
814 # run a text editor
815 self._cmd._run_editor(filename)
816 with open(filename, 'r') as text_file:
817 edited_json = json.load(text_file)
818 if edited_json == orig_json:
819 self._cmd.poutput("Data not modified, skipping write")
820 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100821 (data, sw) = self._cmd.rs.update_record_dec(
822 opts.record_nr, edited_json)
Harald Welte4145d3c2021-04-08 20:34:13 +0200823 if data:
824 self._cmd.poutput_json(data)
Harald Welte4145d3c2021-04-08 20:34:13 +0200825
Harald Weltec91085e2022-02-10 18:05:45 +0100826 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100827 parent: Optional[CardDF] = None, rec_len={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200828 """
829 Args:
830 fid : File Identifier (4 hex digits)
831 sfid : Short File Identifier (2 hex digits, optional)
832 name : Brief name of the file, lik EF_ICCID
Harald Weltec9cdce32021-04-11 10:28:28 +0200833 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200834 parent : Parent CardFile object within filesystem hierarchy
Philipp Maier0adabf62021-04-20 22:36:41 +0200835 rec_len : set of {minimum_length, recommended_length}
Harald Welteee3501f2021-04-02 13:00:18 +0200836 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100837 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100838 self.rec_len = rec_len
839 self.shell_commands = [self.ShellCommands()]
Harald Welte2db5cfb2021-04-10 19:05:37 +0200840 self._construct = None
Harald Weltefb506212021-05-29 21:28:24 +0200841 self._tlv = None
Harald Welteb2edd142021-01-08 23:29:35 +0100842
Harald Weltec91085e2022-02-10 18:05:45 +0100843 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200844 """Decode raw (hex string) data into abstract representation.
845
846 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
847 method for implementing this specifically for the given file. This function checks which
848 of the method exists, add calls them (with conversion, as needed).
849
850 Args:
851 raw_hex_data : hex-encoded data
852 Returns:
853 abstract_data; dict representing the decoded data
854 """
Harald Welteb2edd142021-01-08 23:29:35 +0100855 method = getattr(self, '_decode_record_hex', None)
856 if callable(method):
857 return method(raw_hex_data)
858 raw_bin_data = h2b(raw_hex_data)
859 method = getattr(self, '_decode_record_bin', None)
860 if callable(method):
861 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200862 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200863 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200864 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100865 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100866 t.from_tlv(raw_bin_data)
867 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100868 return {'raw': raw_bin_data.hex()}
869
Harald Weltec91085e2022-02-10 18:05:45 +0100870 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200871 """Decode raw (binary) data into abstract representation.
872
873 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
874 method for implementing this specifically for the given file. This function checks which
875 of the method exists, add calls them (with conversion, as needed).
876
877 Args:
878 raw_bin_data : binary encoded data
879 Returns:
880 abstract_data; dict representing the decoded data
881 """
Harald Welteb2edd142021-01-08 23:29:35 +0100882 method = getattr(self, '_decode_record_bin', None)
883 if callable(method):
884 return method(raw_bin_data)
885 raw_hex_data = b2h(raw_bin_data)
886 method = getattr(self, '_decode_record_hex', None)
887 if callable(method):
888 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200889 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +0200890 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +0200891 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100892 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100893 t.from_tlv(raw_bin_data)
894 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +0100895 return {'raw': raw_hex_data}
896
Harald Weltec91085e2022-02-10 18:05:45 +0100897 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +0200898 """Encode abstract representation into raw (hex string) data.
899
900 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
901 method for implementing this specifically for the given file. This function checks which
902 of the method exists, add calls them (with conversion, as needed).
903
904 Args:
905 abstract_data : dict representing the decoded data
906 Returns:
907 hex string encoded data
908 """
Harald Welteb2edd142021-01-08 23:29:35 +0100909 method = getattr(self, '_encode_record_hex', None)
910 if callable(method):
911 return method(abstract_data)
912 method = getattr(self, '_encode_record_bin', None)
913 if callable(method):
914 raw_bin_data = method(abstract_data)
Harald Welte1e456572021-04-02 17:16:30 +0200915 return b2h(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +0200916 if self._construct:
917 return b2h(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +0200918 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100919 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100920 t.from_dict(abstract_data)
921 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +0100922 raise NotImplementedError(
923 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +0100924
Harald Weltec91085e2022-02-10 18:05:45 +0100925 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +0200926 """Encode abstract representation into raw (binary) data.
927
928 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
929 method for implementing this specifically for the given file. This function checks which
930 of the method exists, add calls them (with conversion, as needed).
931
932 Args:
933 abstract_data : dict representing the decoded data
934 Returns:
935 binary encoded data
936 """
Harald Welteb2edd142021-01-08 23:29:35 +0100937 method = getattr(self, '_encode_record_bin', None)
938 if callable(method):
939 return method(abstract_data)
940 method = getattr(self, '_encode_record_hex', None)
941 if callable(method):
Harald Welteee3501f2021-04-02 13:00:18 +0200942 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +0200943 if self._construct:
944 return self._construct.build(abstract_data)
Harald Weltefb506212021-05-29 21:28:24 +0200945 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +0100946 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +0100947 t.from_dict(abstract_data)
948 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +0100949 raise NotImplementedError(
950 "%s encoder not yet implemented. Patches welcome." % self)
951
Harald Welteb2edd142021-01-08 23:29:35 +0100952
953class CyclicEF(LinFixedEF):
954 """Cyclic EF (Entry File) in the smart card filesystem"""
955 # we don't really have any special support for those; just recycling LinFixedEF here
Harald Weltec91085e2022-02-10 18:05:45 +0100956
957 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100958 rec_len={1, None}, **kwargs):
959 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100960
Harald Welteb2edd142021-01-08 23:29:35 +0100961
962class TransRecEF(TransparentEF):
963 """Transparent EF (Entry File) containing fixed-size records.
Harald Welteee3501f2021-04-02 13:00:18 +0200964
Harald Welteb2edd142021-01-08 23:29:35 +0100965 These are the real odd-balls and mostly look like mistakes in the specification:
966 Specified as 'transparent' EF, but actually containing several fixed-length records
967 inside.
968 We add a special class for those, so the user only has to provide encoder/decoder functions
969 for a record, while this class takes care of split / merge of records.
970 """
Harald Weltec91085e2022-02-10 18:05:45 +0100971
972 def __init__(self, fid: str, rec_len: int, sfid: str = None, name: str = None, desc: str = None,
Harald Welte9170fbf2022-02-11 21:54:37 +0100973 parent: Optional[CardDF] = None, size={1, None}, **kwargs):
Harald Welteee3501f2021-04-02 13:00:18 +0200974 """
975 Args:
976 fid : File Identifier (4 hex digits)
977 sfid : Short File Identifier (2 hex digits, optional)
Harald Weltec9cdce32021-04-11 10:28:28 +0200978 name : Brief name of the file, like EF_ICCID
979 desc : Description of the file
Harald Welteee3501f2021-04-02 13:00:18 +0200980 parent : Parent CardFile object within filesystem hierarchy
981 rec_len : Length of the fixed-length records within transparent EF
982 size : tuple of (minimum_size, recommended_size)
983 """
Harald Welte9170fbf2022-02-11 21:54:37 +0100984 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, size=size, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100985 self.rec_len = rec_len
986
Harald Weltec91085e2022-02-10 18:05:45 +0100987 def decode_record_hex(self, raw_hex_data: str) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +0200988 """Decode raw (hex string) data into abstract representation.
989
990 A derived class would typically provide a _decode_record_bin() or _decode_record_hex()
991 method for implementing this specifically for the given file. This function checks which
992 of the method exists, add calls them (with conversion, as needed).
993
994 Args:
995 raw_hex_data : hex-encoded data
996 Returns:
997 abstract_data; dict representing the decoded data
998 """
Harald Welteb2edd142021-01-08 23:29:35 +0100999 method = getattr(self, '_decode_record_hex', None)
1000 if callable(method):
1001 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001002 raw_bin_data = h2b(raw_hex_data)
Harald Welteb2edd142021-01-08 23:29:35 +01001003 method = getattr(self, '_decode_record_bin', None)
1004 if callable(method):
Harald Welteb2edd142021-01-08 23:29:35 +01001005 return method(raw_bin_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001006 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +02001007 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +02001008 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001009 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001010 t.from_tlv(raw_bin_data)
1011 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001012 return {'raw': raw_hex_data}
1013
Harald Weltec91085e2022-02-10 18:05:45 +01001014 def decode_record_bin(self, raw_bin_data: bytearray) -> dict:
Harald Welteee3501f2021-04-02 13:00:18 +02001015 """Decode raw (binary) data into abstract representation.
1016
1017 A derived class would typically provide a _decode_record_bin() or _decode_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 raw_bin_data : binary encoded data
1023 Returns:
1024 abstract_data; dict representing the decoded data
1025 """
Harald Welteb2edd142021-01-08 23:29:35 +01001026 method = getattr(self, '_decode_record_bin', None)
1027 if callable(method):
1028 return method(raw_bin_data)
1029 raw_hex_data = b2h(raw_bin_data)
1030 method = getattr(self, '_decode_record_hex', None)
1031 if callable(method):
1032 return method(raw_hex_data)
Harald Welte2db5cfb2021-04-10 19:05:37 +02001033 if self._construct:
Harald Welte07c7b1f2021-05-28 22:01:29 +02001034 return parse_construct(self._construct, raw_bin_data)
Harald Weltefb506212021-05-29 21:28:24 +02001035 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001036 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001037 t.from_tlv(raw_bin_data)
1038 return t.to_dict()
Harald Welteb2edd142021-01-08 23:29:35 +01001039 return {'raw': raw_hex_data}
1040
Harald Weltec91085e2022-02-10 18:05:45 +01001041 def encode_record_hex(self, abstract_data: dict) -> str:
Harald Welteee3501f2021-04-02 13:00:18 +02001042 """Encode abstract representation into raw (hex string) data.
1043
1044 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1045 method for implementing this specifically for the given file. This function checks which
1046 of the method exists, add calls them (with conversion, as needed).
1047
1048 Args:
1049 abstract_data : dict representing the decoded data
1050 Returns:
1051 hex string encoded data
1052 """
Harald Welteb2edd142021-01-08 23:29:35 +01001053 method = getattr(self, '_encode_record_hex', None)
1054 if callable(method):
1055 return method(abstract_data)
1056 method = getattr(self, '_encode_record_bin', None)
1057 if callable(method):
Harald Welte1e456572021-04-02 17:16:30 +02001058 return b2h(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001059 if self._construct:
1060 return b2h(filter_dict(self._construct.build(abstract_data)))
Harald Weltefb506212021-05-29 21:28:24 +02001061 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001062 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001063 t.from_dict(abstract_data)
1064 return b2h(t.to_tlv())
Harald Weltec91085e2022-02-10 18:05:45 +01001065 raise NotImplementedError(
1066 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001067
Harald Weltec91085e2022-02-10 18:05:45 +01001068 def encode_record_bin(self, abstract_data: dict) -> bytearray:
Harald Welteee3501f2021-04-02 13:00:18 +02001069 """Encode abstract representation into raw (binary) data.
1070
1071 A derived class would typically provide an _encode_record_bin() or _encode_record_hex()
1072 method for implementing this specifically for the given file. This function checks which
1073 of the method exists, add calls them (with conversion, as needed).
1074
1075 Args:
1076 abstract_data : dict representing the decoded data
1077 Returns:
1078 binary encoded data
1079 """
Harald Welteb2edd142021-01-08 23:29:35 +01001080 method = getattr(self, '_encode_record_bin', None)
1081 if callable(method):
1082 return method(abstract_data)
1083 method = getattr(self, '_encode_record_hex', None)
1084 if callable(method):
1085 return h2b(method(abstract_data))
Harald Welte2db5cfb2021-04-10 19:05:37 +02001086 if self._construct:
1087 return filter_dict(self._construct.build(abstract_data))
Harald Weltefb506212021-05-29 21:28:24 +02001088 elif self._tlv:
Harald Welteca60ac22022-02-10 18:01:02 +01001089 t = self._tlv() if inspect.isclass(self._tlv) else self._tlv
Harald Welte944cd2f2022-01-21 16:01:29 +01001090 t.from_dict(abstract_data)
1091 return t.to_tlv()
Harald Weltec91085e2022-02-10 18:05:45 +01001092 raise NotImplementedError(
1093 "%s encoder not yet implemented. Patches welcome." % self)
Harald Welteb2edd142021-01-08 23:29:35 +01001094
Harald Weltec91085e2022-02-10 18:05:45 +01001095 def _decode_bin(self, raw_bin_data: bytearray):
1096 chunks = [raw_bin_data[i:i+self.rec_len]
1097 for i in range(0, len(raw_bin_data), self.rec_len)]
Harald Welteb2edd142021-01-08 23:29:35 +01001098 return [self.decode_record_bin(x) for x in chunks]
1099
Harald Welteee3501f2021-04-02 13:00:18 +02001100 def _encode_bin(self, abstract_data) -> bytes:
Harald Welteb2edd142021-01-08 23:29:35 +01001101 chunks = [self.encode_record_bin(x) for x in abstract_data]
1102 # FIXME: pad to file size
1103 return b''.join(chunks)
1104
1105
Harald Welte917d98c2021-04-21 11:51:25 +02001106class BerTlvEF(CardEF):
Harald Welte27881622021-04-21 11:16:31 +02001107 """BER-TLV EF (Entry File) in the smart card filesystem.
1108 A BER-TLV EF is a binary file with a BER (Basic Encoding Rules) TLV structure
Harald Welteb2edd142021-01-08 23:29:35 +01001109
Harald Welte27881622021-04-21 11:16:31 +02001110 NOTE: We currently don't really support those, this class is simply a wrapper
1111 around TransparentEF as a place-holder, so we can already define EFs of BER-TLV
1112 type without fully supporting them."""
Harald Welteb2edd142021-01-08 23:29:35 +01001113
Harald Welte917d98c2021-04-21 11:51:25 +02001114 @with_default_category('BER-TLV EF Commands')
1115 class ShellCommands(CommandSet):
1116 """Shell commands specific for BER-TLV EFs."""
Harald Weltec91085e2022-02-10 18:05:45 +01001117
Harald Welte917d98c2021-04-21 11:51:25 +02001118 def __init__(self):
1119 super().__init__()
1120
1121 retrieve_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001122 retrieve_data_parser.add_argument(
1123 'tag', type=auto_int, help='BER-TLV Tag of value to retrieve')
1124
Harald Welte917d98c2021-04-21 11:51:25 +02001125 @cmd2.with_argparser(retrieve_data_parser)
1126 def do_retrieve_data(self, opts):
1127 """Retrieve (Read) data from a BER-TLV EF"""
1128 (data, sw) = self._cmd.rs.retrieve_data(opts.tag)
1129 self._cmd.poutput(data)
1130
1131 def do_retrieve_tags(self, opts):
1132 """List tags available in a given BER-TLV EF"""
1133 tags = self._cmd.rs.retrieve_tags()
1134 self._cmd.poutput(tags)
1135
1136 set_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001137 set_data_parser.add_argument(
1138 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1139 set_data_parser.add_argument(
1140 'data', help='Data bytes (hex format) to write')
1141
Harald Welte917d98c2021-04-21 11:51:25 +02001142 @cmd2.with_argparser(set_data_parser)
1143 def do_set_data(self, opts):
1144 """Set (Write) data for a given tag in a BER-TLV EF"""
1145 (data, sw) = self._cmd.rs.set_data(opts.tag, opts.data)
1146 if data:
1147 self._cmd.poutput(data)
1148
1149 del_data_parser = argparse.ArgumentParser()
Harald Weltec91085e2022-02-10 18:05:45 +01001150 del_data_parser.add_argument(
1151 'tag', type=auto_int, help='BER-TLV Tag of value to set')
1152
Harald Welte917d98c2021-04-21 11:51:25 +02001153 @cmd2.with_argparser(del_data_parser)
1154 def do_delete_data(self, opts):
1155 """Delete data for a given tag in a BER-TLV EF"""
1156 (data, sw) = self._cmd.rs.set_data(opts.tag, None)
1157 if data:
1158 self._cmd.poutput(data)
1159
Harald Weltec91085e2022-02-10 18:05:45 +01001160 def __init__(self, fid: str, sfid: str = None, name: str = None, desc: str = None, parent: CardDF = None,
Harald Welte9170fbf2022-02-11 21:54:37 +01001161 size={1, None}, **kwargs):
Harald Welte917d98c2021-04-21 11:51:25 +02001162 """
1163 Args:
1164 fid : File Identifier (4 hex digits)
1165 sfid : Short File Identifier (2 hex digits, optional)
1166 name : Brief name of the file, lik EF_ICCID
1167 desc : Description of the file
1168 parent : Parent CardFile object within filesystem hierarchy
1169 size : tuple of (minimum_size, recommended_size)
1170 """
Harald Welte9170fbf2022-02-11 21:54:37 +01001171 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, parent=parent, **kwargs)
Harald Welte917d98c2021-04-21 11:51:25 +02001172 self._construct = None
1173 self.size = size
1174 self.shell_commands = [self.ShellCommands()]
1175
Harald Welteb2edd142021-01-08 23:29:35 +01001176
1177class RuntimeState(object):
1178 """Represent the runtime state of a session with a card."""
Harald Weltec91085e2022-02-10 18:05:45 +01001179
1180 def __init__(self, card, profile: 'CardProfile'):
Harald Welteee3501f2021-04-02 13:00:18 +02001181 """
1182 Args:
1183 card : pysim.cards.Card instance
1184 profile : CardProfile instance
1185 """
Philipp Maier5af7bdf2021-11-04 12:48:41 +01001186 self.mf = CardMF(profile=profile)
Harald Welteb2edd142021-01-08 23:29:35 +01001187 self.card = card
Harald Weltec91085e2022-02-10 18:05:45 +01001188 self.selected_file = self.mf # type: CardDF
Harald Welteb2edd142021-01-08 23:29:35 +01001189 self.profile = profile
Philipp Maier51cad0d2021-11-08 15:45:10 +01001190
1191 # make sure the class and selection control bytes, which are specified
1192 # by the card profile are used
Harald Weltec91085e2022-02-10 18:05:45 +01001193 self.card.set_apdu_parameter(
1194 cla=self.profile.cla, sel_ctrl=self.profile.sel_ctrl)
Philipp Maier51cad0d2021-11-08 15:45:10 +01001195
Harald Welte5ce35242021-04-02 20:27:05 +02001196 # add application ADFs + MF-files from profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001197 apps = self._match_applications()
1198 for a in apps:
Harald Welte5ce35242021-04-02 20:27:05 +02001199 if a.adf:
1200 self.mf.add_application_df(a.adf)
Harald Welteb2edd142021-01-08 23:29:35 +01001201 for f in self.profile.files_in_mf:
1202 self.mf.add_file(f)
Philipp Maier38c74f62021-03-17 17:19:52 +01001203 self.conserve_write = True
Harald Welteb2edd142021-01-08 23:29:35 +01001204
Philipp Maier4e2e1d92021-11-08 15:36:01 +01001205 # make sure that when the runtime state is created, the card is also
1206 # in a defined state.
1207 self.reset()
1208
Philipp Maier1e896f32021-03-10 17:02:53 +01001209 def _match_applications(self):
1210 """match the applications from the profile with applications on the card"""
1211 apps_profile = self.profile.applications
Philipp Maierd454fe72021-11-08 15:32:23 +01001212
1213 # When the profile does not feature any applications, then we are done already
1214 if not apps_profile:
1215 return []
1216
1217 # Read AIDs from card and match them against the applications defined by the
1218 # card profile
Philipp Maier1e896f32021-03-10 17:02:53 +01001219 aids_card = self.card.read_aids()
1220 apps_taken = []
1221 if aids_card:
1222 aids_taken = []
1223 print("AIDs on card:")
1224 for a in aids_card:
1225 for f in apps_profile:
1226 if f.aid in a:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001227 print(" %s: %s (EF.DIR)" % (f.name, a))
Philipp Maier1e896f32021-03-10 17:02:53 +01001228 aids_taken.append(a)
1229 apps_taken.append(f)
1230 aids_unknown = set(aids_card) - set(aids_taken)
1231 for a in aids_unknown:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001232 print(" unknown: %s (EF.DIR)" % a)
Philipp Maier1e896f32021-03-10 17:02:53 +01001233 else:
Philipp Maier8d8bdef2021-12-01 11:48:27 +01001234 print("warning: EF.DIR seems to be empty!")
1235
1236 # Some card applications may not be registered in EF.DIR, we will actively
1237 # probe for those applications
1238 for f in set(apps_profile) - set(apps_taken):
Bjoern Riemerda57ef12022-01-18 15:38:14 +01001239 try:
1240 data, sw = self.card.select_adf_by_aid(f.aid)
1241 if sw == "9000":
1242 print(" %s: %s" % (f.name, f.aid))
1243 apps_taken.append(f)
1244 except SwMatchError:
1245 pass
Philipp Maier1e896f32021-03-10 17:02:53 +01001246 return apps_taken
1247
Harald Weltedaf2b392021-05-03 23:17:29 +02001248 def reset(self, cmd_app=None) -> Hexstr:
1249 """Perform physical card reset and obtain ATR.
1250 Args:
1251 cmd_app : Command Application State (for unregistering old file commands)
1252 """
Philipp Maier946226a2021-10-29 18:31:03 +02001253 atr = i2h(self.card.reset())
Harald Weltedaf2b392021-05-03 23:17:29 +02001254 # select MF to reset internal state and to verify card really works
1255 self.select('MF', cmd_app)
1256 return atr
1257
Harald Welteee3501f2021-04-02 13:00:18 +02001258 def get_cwd(self) -> CardDF:
1259 """Obtain the current working directory.
1260
1261 Returns:
1262 CardDF instance
1263 """
Harald Welteb2edd142021-01-08 23:29:35 +01001264 if isinstance(self.selected_file, CardDF):
1265 return self.selected_file
1266 else:
1267 return self.selected_file.parent
1268
Harald Welte5ce35242021-04-02 20:27:05 +02001269 def get_application_df(self) -> Optional[CardADF]:
1270 """Obtain the currently selected application DF (if any).
Harald Welteee3501f2021-04-02 13:00:18 +02001271
1272 Returns:
1273 CardADF() instance or None"""
Harald Welteb2edd142021-01-08 23:29:35 +01001274 # iterate upwards from selected file; check if any is an ADF
1275 node = self.selected_file
1276 while node.parent != node:
1277 if isinstance(node, CardADF):
1278 return node
1279 node = node.parent
1280 return None
1281
Harald Weltec91085e2022-02-10 18:05:45 +01001282 def interpret_sw(self, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001283 """Interpret a given status word relative to the currently selected application
1284 or the underlying card profile.
1285
1286 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001287 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001288
1289 Returns:
1290 Tuple of two strings
1291 """
Harald Welte86fbd392021-04-02 22:13:09 +02001292 res = None
Harald Welte5ce35242021-04-02 20:27:05 +02001293 adf = self.get_application_df()
1294 if adf:
1295 app = adf.application
Harald Welteb2edd142021-01-08 23:29:35 +01001296 # The application either comes with its own interpret_sw
1297 # method or we will use the interpret_sw method from the
1298 # card profile.
Harald Welte5ce35242021-04-02 20:27:05 +02001299 if app and hasattr(app, "interpret_sw"):
Harald Welte86fbd392021-04-02 22:13:09 +02001300 res = app.interpret_sw(sw)
1301 return res or self.profile.interpret_sw(sw)
Harald Welteb2edd142021-01-08 23:29:35 +01001302
Harald Weltec91085e2022-02-10 18:05:45 +01001303 def probe_file(self, fid: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001304 """Blindly try to select a file and automatically add a matching file
Harald Weltec91085e2022-02-10 18:05:45 +01001305 object if the file actually exists."""
Philipp Maier63f572d2021-03-09 22:42:47 +01001306 if not is_hex(fid, 4, 4):
Harald Weltec91085e2022-02-10 18:05:45 +01001307 raise ValueError(
1308 "Cannot select unknown file by name %s, only hexadecimal 4 digit FID is allowed" % fid)
Philipp Maier63f572d2021-03-09 22:42:47 +01001309
1310 try:
1311 (data, sw) = self.card._scc.select_file(fid)
1312 except SwMatchError as swm:
1313 k = self.interpret_sw(swm.sw_actual)
1314 if not k:
1315 raise(swm)
1316 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
1317
1318 select_resp = self.selected_file.decode_select_response(data)
1319 if (select_resp['file_descriptor']['file_type'] == 'df'):
Harald Weltec91085e2022-02-10 18:05:45 +01001320 f = CardDF(fid=fid, sfid=None, name="DF." + str(fid).upper(),
1321 desc="dedicated file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001322 else:
1323 if (select_resp['file_descriptor']['structure'] == 'transparent'):
Harald Weltec91085e2022-02-10 18:05:45 +01001324 f = TransparentEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1325 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001326 else:
Harald Weltec91085e2022-02-10 18:05:45 +01001327 f = LinFixedEF(fid=fid, sfid=None, name="EF." + str(fid).upper(),
1328 desc="elementary file, manually added at runtime")
Philipp Maier63f572d2021-03-09 22:42:47 +01001329
1330 self.selected_file.add_files([f])
1331 self.selected_file = f
1332 return select_resp
1333
Harald Weltec91085e2022-02-10 18:05:45 +01001334 def select(self, name: str, cmd_app=None):
Harald Welteee3501f2021-04-02 13:00:18 +02001335 """Select a file (EF, DF, ADF, MF, ...).
1336
1337 Args:
1338 name : Name of file to select
1339 cmd_app : Command Application State (for unregistering old file commands)
1340 """
Harald Welteb2edd142021-01-08 23:29:35 +01001341 sels = self.selected_file.get_selectables()
Philipp Maier7744b6e2021-03-11 14:29:37 +01001342 if is_hex(name):
1343 name = name.lower()
Philipp Maier63f572d2021-03-09 22:42:47 +01001344
1345 # unregister commands of old file
1346 if cmd_app and self.selected_file.shell_commands:
1347 for c in self.selected_file.shell_commands:
1348 cmd_app.unregister_command_set(c)
1349
Harald Welteb2edd142021-01-08 23:29:35 +01001350 if name in sels:
1351 f = sels[name]
Harald Welteb2edd142021-01-08 23:29:35 +01001352 try:
1353 if isinstance(f, CardADF):
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001354 (data, sw) = self.card.select_adf_by_aid(f.aid)
Harald Welteb2edd142021-01-08 23:29:35 +01001355 else:
1356 (data, sw) = self.card._scc.select_file(f.fid)
1357 self.selected_file = f
1358 except SwMatchError as swm:
1359 k = self.interpret_sw(swm.sw_actual)
1360 if not k:
1361 raise(swm)
1362 raise RuntimeError("%s: %s - %s" % (swm.sw_actual, k[0], k[1]))
Philipp Maier63f572d2021-03-09 22:42:47 +01001363 select_resp = f.decode_select_response(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001364 else:
Philipp Maier63f572d2021-03-09 22:42:47 +01001365 select_resp = self.probe_file(name, cmd_app)
Harald Welte850b72a2021-04-07 09:33:03 +02001366 # store the decoded FCP for later reference
1367 self.selected_file_fcp = select_resp
Philipp Maier63f572d2021-03-09 22:42:47 +01001368
1369 # register commands of new file
1370 if cmd_app and self.selected_file.shell_commands:
1371 for c in self.selected_file.shell_commands:
1372 cmd_app.register_command_set(c)
1373
1374 return select_resp
Harald Welteb2edd142021-01-08 23:29:35 +01001375
Harald Welte34b05d32021-05-25 22:03:13 +02001376 def status(self):
1377 """Request STATUS (current selected file FCP) from card."""
1378 (data, sw) = self.card._scc.status()
1379 return self.selected_file.decode_select_response(data)
1380
Harald Weltec91085e2022-02-10 18:05:45 +01001381 def activate_file(self, name: str):
Harald Welte485692b2021-05-25 22:21:44 +02001382 """Request ACTIVATE FILE of specified file."""
1383 sels = self.selected_file.get_selectables()
1384 f = sels[name]
1385 data, sw = self.card._scc.activate_file(f.fid)
1386 return data, sw
1387
Harald Weltec91085e2022-02-10 18:05:45 +01001388 def read_binary(self, length: int = None, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001389 """Read [part of] a transparent EF binary data.
1390
1391 Args:
1392 length : Amount of data to read (None: as much as possible)
1393 offset : Offset into the file from which to read 'length' bytes
1394 Returns:
1395 binary data read from the file
1396 """
Harald Welteb2edd142021-01-08 23:29:35 +01001397 if not isinstance(self.selected_file, TransparentEF):
1398 raise TypeError("Only works with TransparentEF")
1399 return self.card._scc.read_binary(self.selected_file.fid, length, offset)
1400
Harald Welte2d4a64b2021-04-03 09:01:24 +02001401 def read_binary_dec(self) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001402 """Read [part of] a transparent EF binary data and decode it.
1403
1404 Args:
1405 length : Amount of data to read (None: as much as possible)
1406 offset : Offset into the file from which to read 'length' bytes
1407 Returns:
1408 abstract decode data read from the file
1409 """
Harald Welteb2edd142021-01-08 23:29:35 +01001410 (data, sw) = self.read_binary()
1411 dec_data = self.selected_file.decode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001412 return (dec_data, sw)
1413
Harald Weltec91085e2022-02-10 18:05:45 +01001414 def update_binary(self, data_hex: str, offset: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001415 """Update transparent EF binary data.
1416
1417 Args:
1418 data_hex : hex string of data to be written
1419 offset : Offset into the file from which to write 'data_hex'
1420 """
Harald Welteb2edd142021-01-08 23:29:35 +01001421 if not isinstance(self.selected_file, TransparentEF):
1422 raise TypeError("Only works with TransparentEF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001423 return self.card._scc.update_binary(self.selected_file.fid, data_hex, offset, conserve=self.conserve_write)
Harald Welteb2edd142021-01-08 23:29:35 +01001424
Harald Weltec91085e2022-02-10 18:05:45 +01001425 def update_binary_dec(self, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001426 """Update transparent EF from abstract data. Encodes the data to binary and
1427 then updates the EF with it.
1428
1429 Args:
1430 data : abstract data which is to be encoded and written
1431 """
Harald Welteb2edd142021-01-08 23:29:35 +01001432 data_hex = self.selected_file.encode_hex(data)
Harald Welteb2edd142021-01-08 23:29:35 +01001433 return self.update_binary(data_hex)
1434
Harald Weltec91085e2022-02-10 18:05:45 +01001435 def read_record(self, rec_nr: int = 0):
Harald Welteee3501f2021-04-02 13:00:18 +02001436 """Read a record as binary data.
1437
1438 Args:
1439 rec_nr : Record number to read
1440 Returns:
1441 hex string of binary data contained in record
1442 """
Harald Welteb2edd142021-01-08 23:29:35 +01001443 if not isinstance(self.selected_file, LinFixedEF):
1444 raise TypeError("Only works with Linear Fixed EF")
1445 # returns a string of hex nibbles
1446 return self.card._scc.read_record(self.selected_file.fid, rec_nr)
1447
Harald Weltec91085e2022-02-10 18:05:45 +01001448 def read_record_dec(self, rec_nr: int = 0) -> Tuple[dict, str]:
Harald Welteee3501f2021-04-02 13:00:18 +02001449 """Read a record and decode it to abstract data.
1450
1451 Args:
1452 rec_nr : Record number to read
1453 Returns:
1454 abstract data contained in record
1455 """
Harald Welteb2edd142021-01-08 23:29:35 +01001456 (data, sw) = self.read_record(rec_nr)
1457 return (self.selected_file.decode_record_hex(data), sw)
1458
Harald Weltec91085e2022-02-10 18:05:45 +01001459 def update_record(self, rec_nr: int, data_hex: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001460 """Update a record with given binary data
1461
1462 Args:
1463 rec_nr : Record number to read
1464 data_hex : Hex string binary data to be written
1465 """
Harald Welteb2edd142021-01-08 23:29:35 +01001466 if not isinstance(self.selected_file, LinFixedEF):
1467 raise TypeError("Only works with Linear Fixed EF")
Philipp Maier38c74f62021-03-17 17:19:52 +01001468 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 +01001469
Harald Weltec91085e2022-02-10 18:05:45 +01001470 def update_record_dec(self, rec_nr: int, data: dict):
Harald Welteee3501f2021-04-02 13:00:18 +02001471 """Update a record with given abstract data. Will encode abstract to binary data
1472 and then write it to the given record on the card.
1473
1474 Args:
1475 rec_nr : Record number to read
1476 data_hex : Abstract data to be written
1477 """
Harald Welte1e456572021-04-02 17:16:30 +02001478 data_hex = self.selected_file.encode_record_hex(data)
1479 return self.update_record(rec_nr, data_hex)
Harald Welteb2edd142021-01-08 23:29:35 +01001480
Harald Weltec91085e2022-02-10 18:05:45 +01001481 def retrieve_data(self, tag: int = 0):
Harald Welte917d98c2021-04-21 11:51:25 +02001482 """Read a DO/TLV as binary data.
1483
1484 Args:
1485 tag : Tag of TLV/DO to read
1486 Returns:
1487 hex string of full BER-TLV DO including Tag and Length
1488 """
1489 if not isinstance(self.selected_file, BerTlvEF):
1490 raise TypeError("Only works with BER-TLV EF")
1491 # returns a string of hex nibbles
1492 return self.card._scc.retrieve_data(self.selected_file.fid, tag)
1493
1494 def retrieve_tags(self):
1495 """Retrieve tags available on BER-TLV EF.
1496
1497 Returns:
1498 list of integer tags contained in EF
1499 """
1500 if not isinstance(self.selected_file, BerTlvEF):
1501 raise TypeError("Only works with BER-TLV EF")
1502 data, sw = self.card._scc.retrieve_data(self.selected_file.fid, 0x5c)
Harald Weltec1475302021-05-21 21:47:55 +02001503 tag, length, value, remainder = bertlv_parse_one(h2b(data))
Harald Welte917d98c2021-04-21 11:51:25 +02001504 return list(value)
1505
Harald Weltec91085e2022-02-10 18:05:45 +01001506 def set_data(self, tag: int, data_hex: str):
Harald Welte917d98c2021-04-21 11:51:25 +02001507 """Update a TLV/DO with given binary data
1508
1509 Args:
1510 tag : Tag of TLV/DO to be written
1511 data_hex : Hex string binary data to be written (value portion)
1512 """
1513 if not isinstance(self.selected_file, BerTlvEF):
1514 raise TypeError("Only works with BER-TLV EF")
1515 return self.card._scc.set_data(self.selected_file.fid, tag, data_hex, conserve=self.conserve_write)
1516
Philipp Maier5d698e52021-09-16 13:18:01 +02001517 def unregister_cmds(self, cmd_app=None):
1518 """Unregister all file specific commands."""
1519 if cmd_app and self.selected_file.shell_commands:
1520 for c in self.selected_file.shell_commands:
1521 cmd_app.unregister_command_set(c)
Harald Welte917d98c2021-04-21 11:51:25 +02001522
Harald Welteb2edd142021-01-08 23:29:35 +01001523
Harald Welteb2edd142021-01-08 23:29:35 +01001524class FileData(object):
1525 """Represent the runtime, on-card data."""
Harald Weltec91085e2022-02-10 18:05:45 +01001526
Harald Welteb2edd142021-01-08 23:29:35 +01001527 def __init__(self, fdesc):
1528 self.desc = fdesc
1529 self.fcp = None
1530
1531
Harald Weltec91085e2022-02-10 18:05:45 +01001532def interpret_sw(sw_data: dict, sw: str):
Harald Welteee3501f2021-04-02 13:00:18 +02001533 """Interpret a given status word.
1534
1535 Args:
1536 sw_data : Hierarchical dict of status word matches
1537 sw : status word to match (string of 4 hex digits)
1538 Returns:
1539 tuple of two strings (class_string, description)
1540 """
Harald Welteb2edd142021-01-08 23:29:35 +01001541 for class_str, swdict in sw_data.items():
1542 # first try direct match
1543 if sw in swdict:
1544 return (class_str, swdict[sw])
1545 # next try wildcard matches
1546 for pattern, descr in swdict.items():
1547 if sw_match(sw, pattern):
1548 return (class_str, descr)
1549 return None
1550
Harald Weltec91085e2022-02-10 18:05:45 +01001551
Harald Welteb2edd142021-01-08 23:29:35 +01001552class CardApplication(object):
1553 """A card application is represented by an ADF (with contained hierarchy) and optionally
1554 some SW definitions."""
Harald Weltec91085e2022-02-10 18:05:45 +01001555
1556 def __init__(self, name, adf: Optional[CardADF] = None, aid: str = None, sw: dict = None):
Harald Welteee3501f2021-04-02 13:00:18 +02001557 """
1558 Args:
1559 adf : ADF name
1560 sw : Dict of status word conversions
1561 """
Harald Welteb2edd142021-01-08 23:29:35 +01001562 self.name = name
1563 self.adf = adf
Vadim Yanitskiy98f872b2021-03-27 01:25:46 +01001564 self.sw = sw or dict()
Harald Welte5ce35242021-04-02 20:27:05 +02001565 # back-reference from ADF to Applicaiton
1566 if self.adf:
1567 self.aid = aid or self.adf.aid
1568 self.adf.application = self
1569 else:
1570 self.aid = aid
Harald Welteb2edd142021-01-08 23:29:35 +01001571
1572 def __str__(self):
1573 return "APP(%s)" % (self.name)
1574
1575 def interpret_sw(self, sw):
Harald Welteee3501f2021-04-02 13:00:18 +02001576 """Interpret a given status word within the application.
1577
1578 Args:
Harald Weltec9cdce32021-04-11 10:28:28 +02001579 sw : Status word as string of 4 hex digits
Harald Welteee3501f2021-04-02 13:00:18 +02001580
1581 Returns:
1582 Tuple of two strings
1583 """
Harald Welteb2edd142021-01-08 23:29:35 +01001584 return interpret_sw(self.sw, sw)
1585
Harald Weltef44256c2021-10-14 15:53:39 +02001586
1587class CardModel(abc.ABC):
Harald Welte4c1dca02021-10-14 17:48:25 +02001588 """A specific card model, typically having some additional vendor-specific files. All
1589 you need to do is to define a sub-class with a list of ATRs or an overridden match
1590 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001591 _atrs = []
1592
1593 @classmethod
1594 @abc.abstractmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001595 def add_files(cls, rs: RuntimeState):
Harald Weltef44256c2021-10-14 15:53:39 +02001596 """Add model specific files to given RuntimeState."""
1597
1598 @classmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001599 def match(cls, scc: SimCardCommands) -> bool:
Harald Weltef44256c2021-10-14 15:53:39 +02001600 """Test if given card matches this model."""
1601 card_atr = scc.get_atr()
1602 for atr in cls._atrs:
1603 atr_bin = toBytes(atr)
1604 if atr_bin == card_atr:
1605 print("Detected CardModel:", cls.__name__)
1606 return True
1607 return False
1608
1609 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001610 def apply_matching_models(scc: SimCardCommands, rs: RuntimeState):
Harald Welte4c1dca02021-10-14 17:48:25 +02001611 """Check if any of the CardModel sub-classes 'match' the currently inserted card
1612 (by ATR or overriding the 'match' method). If so, call their 'add_files'
1613 method."""
Harald Weltef44256c2021-10-14 15:53:39 +02001614 for m in CardModel.__subclasses__():
1615 if m.match(scc):
1616 m.add_files(rs)