Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | # Interactive shell for working with SIM / UICC / USIM / ISIM cards |
| 4 | # |
Harald Welte | 8fab463 | 2023-11-03 01:03:28 +0100 | [diff] [blame] | 5 | # (C) 2021-2023 by Harald Welte <laforge@osmocom.org> |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 6 | # |
| 7 | # This program is free software: you can redistribute it and/or modify |
| 8 | # it under the terms of the GNU General Public License as published by |
| 9 | # the Free Software Foundation, either version 2 of the License, or |
| 10 | # (at your option) any later version. |
| 11 | # |
| 12 | # This program is distributed in the hope that it will be useful, |
| 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | # GNU General Public License for more details. |
| 16 | # |
| 17 | # You should have received a copy of the GNU General Public License |
| 18 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 | |
Harald Welte | e126872 | 2023-06-24 07:57:08 +0200 | [diff] [blame] | 20 | from typing import List, Optional |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 21 | |
| 22 | import json |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 23 | import traceback |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 24 | |
| 25 | import cmd2 |
Harald Welte | 93aac3a | 2023-04-27 15:18:13 +0200 | [diff] [blame] | 26 | from packaging import version |
Harald Welte | 961b803 | 2023-04-27 17:30:22 +0200 | [diff] [blame] | 27 | from cmd2 import style |
| 28 | # cmd2 >= 2.3.0 has deprecated the bg/fg in favor of Bg/Fg :( |
| 29 | if version.parse(cmd2.__version__) < version.parse("2.3.0"): |
Oliver Smith | e47ea5f | 2023-05-23 12:54:15 +0200 | [diff] [blame] | 30 | from cmd2 import fg, bg # pylint: disable=no-name-in-module |
Harald Welte | 961b803 | 2023-04-27 17:30:22 +0200 | [diff] [blame] | 31 | RED = fg.red |
| 32 | LIGHT_RED = fg.bright_red |
| 33 | LIGHT_GREEN = fg.bright_green |
| 34 | else: |
| 35 | from cmd2 import Fg, Bg # pylint: disable=no-name-in-module |
| 36 | RED = Fg.RED |
| 37 | LIGHT_RED = Fg.LIGHT_RED |
| 38 | LIGHT_GREEN = Fg.LIGHT_GREEN |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 39 | from cmd2 import CommandSet, with_default_category, with_argparser |
| 40 | import argparse |
| 41 | |
| 42 | import os |
| 43 | import sys |
Harald Welte | 6ad9a24 | 2023-07-11 18:55:29 +0200 | [diff] [blame] | 44 | import inspect |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 45 | from pathlib import Path |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 46 | from io import StringIO |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 47 | |
Harald Welte | cab26c7 | 2022-08-06 16:12:30 +0200 | [diff] [blame] | 48 | from pprint import pprint as pp |
| 49 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 50 | from pySim.exceptions import * |
Harald Welte | cab26c7 | 2022-08-06 16:12:30 +0200 | [diff] [blame] | 51 | from pySim.transport import init_reader, ApduTracer, argparse_add_reader_args, ProactiveHandler |
Philipp Maier | e345e11 | 2023-06-09 15:19:56 +0200 | [diff] [blame] | 52 | from pySim.utils import h2b, b2h, i2h, swap_nibbles, rpad, JsonEncoder, bertlv_parse_one, sw_match |
Philipp Maier | a42ee6f | 2023-08-16 10:44:57 +0200 | [diff] [blame] | 53 | from pySim.utils import sanitize_pin_adm, tabulate_str_list, boxed_heading_str, Hexstr, dec_iccid |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 54 | from pySim.utils import is_hexstr_or_decimal, is_hexstr, is_decimal |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 55 | from pySim.card_handler import CardHandler, CardHandlerAuto |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 56 | |
Philipp Maier | 5482737 | 2023-10-24 16:18:30 +0200 | [diff] [blame] | 57 | from pySim.filesystem import CardMF, CardDF, CardADF |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 58 | from pySim.ts_102_222 import Ts102222Commands |
Harald Welte | 2a33ad2 | 2021-10-20 10:14:18 +0200 | [diff] [blame] | 59 | from pySim.gsm_r import DF_EIRENE |
Harald Welte | cab26c7 | 2022-08-06 16:12:30 +0200 | [diff] [blame] | 60 | from pySim.cat import ProactiveCommand |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 61 | |
Harald Welte | 4442b3d | 2021-04-03 09:00:16 +0200 | [diff] [blame] | 62 | from pySim.card_key_provider import CardKeyProviderCsv, card_key_provider_register, card_key_provider_get_field |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 63 | |
Harald Welte | 8fab463 | 2023-11-03 01:03:28 +0100 | [diff] [blame] | 64 | from pySim.app import init_card |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 65 | |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 66 | |
Harald Welte | e126872 | 2023-06-24 07:57:08 +0200 | [diff] [blame] | 67 | class Cmd2Compat(cmd2.Cmd): |
| 68 | """Backwards-compatibility wrapper around cmd2.Cmd to support older and newer |
| 69 | releases. See https://github.com/python-cmd2/cmd2/blob/master/CHANGELOG.md""" |
| 70 | def run_editor(self, file_path: Optional[str] = None) -> None: |
| 71 | if version.parse(cmd2.__version__) < version.parse("2.0.0"): |
Harald Welte | 0ec0150 | 2023-06-24 10:00:12 +0200 | [diff] [blame] | 72 | return self._run_editor(file_path) # pylint: disable=no-member |
Harald Welte | e126872 | 2023-06-24 07:57:08 +0200 | [diff] [blame] | 73 | else: |
Harald Welte | 0ec0150 | 2023-06-24 10:00:12 +0200 | [diff] [blame] | 74 | return super().run_editor(file_path) # pylint: disable=no-member |
| 75 | |
| 76 | class Settable2Compat(cmd2.Settable): |
| 77 | """Backwards-compatibility wrapper around cmd2.Settable to support older and newer |
| 78 | releases. See https://github.com/python-cmd2/cmd2/blob/master/CHANGELOG.md""" |
| 79 | def __init__(self, name, val_type, description, settable_object, **kwargs): |
| 80 | if version.parse(cmd2.__version__) < version.parse("2.0.0"): |
| 81 | super().__init__(name, val_type, description, **kwargs) # pylint: disable=no-value-for-parameter |
| 82 | else: |
| 83 | super().__init__(name, val_type, description, settable_object, **kwargs) # pylint: disable=too-many-function-args |
Harald Welte | e126872 | 2023-06-24 07:57:08 +0200 | [diff] [blame] | 84 | |
| 85 | class PysimApp(Cmd2Compat): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 86 | CUSTOM_CATEGORY = 'pySim Commands' |
Harald Welte | 0ba3fd9 | 2023-11-01 19:18:24 +0100 | [diff] [blame] | 87 | BANNER = """Welcome to pySim-shell! |
| 88 | (C) 2021-2023 by Harald Welte, sysmocom - s.f.m.c. GmbH and contributors |
| 89 | Online manual available at https://downloads.osmocom.org/docs/pysim/master/html/shell.html """ |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 90 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 91 | def __init__(self, card, rs, sl, ch, script=None): |
Harald Welte | c85d406 | 2023-04-27 17:10:17 +0200 | [diff] [blame] | 92 | if version.parse(cmd2.__version__) < version.parse("2.0.0"): |
| 93 | kwargs = {'use_ipython': True} |
| 94 | else: |
| 95 | kwargs = {'include_ipy': True} |
| 96 | |
Oliver Smith | e47ea5f | 2023-05-23 12:54:15 +0200 | [diff] [blame] | 97 | # pylint: disable=unexpected-keyword-arg |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 98 | super().__init__(persistent_history_file='~/.pysim_shell_history', allow_cli_args=False, |
Harald Welte | c85d406 | 2023-04-27 17:10:17 +0200 | [diff] [blame] | 99 | auto_load_commands=False, startup_script=script, **kwargs) |
Harald Welte | 0ba3fd9 | 2023-11-01 19:18:24 +0100 | [diff] [blame] | 100 | self.intro = style(self.BANNER, fg=RED) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 101 | self.default_category = 'pySim-shell built-in commands' |
| 102 | self.card = None |
| 103 | self.rs = None |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 104 | self.lchan = None |
| 105 | self.py_locals = {'card': self.card, 'rs': self.rs, 'lchan': self.lchan} |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 106 | self.sl = sl |
| 107 | self.ch = ch |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 108 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 109 | self.numeric_path = False |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 110 | self.conserve_write = True |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 111 | self.json_pretty_print = True |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 112 | self.apdu_trace = False |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 113 | |
Harald Welte | 0ec0150 | 2023-06-24 10:00:12 +0200 | [diff] [blame] | 114 | self.add_settable(Settable2Compat('numeric_path', bool, 'Print File IDs instead of names', self, |
| 115 | onchange_cb=self._onchange_numeric_path)) |
| 116 | self.add_settable(Settable2Compat('conserve_write', bool, 'Read and compare before write', self, |
| 117 | onchange_cb=self._onchange_conserve_write)) |
| 118 | self.add_settable(Settable2Compat('json_pretty_print', bool, 'Pretty-Print JSON output', self)) |
| 119 | self.add_settable(Settable2Compat('apdu_trace', bool, 'Trace and display APDUs exchanged with card', self, |
| 120 | onchange_cb=self._onchange_apdu_trace)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 121 | self.equip(card, rs) |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 122 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 123 | def equip(self, card, rs): |
| 124 | """ |
| 125 | Equip pySim-shell with the supplied card and runtime state, add (or remove) all required settables and |
| 126 | and commands to enable card operations. |
| 127 | """ |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 128 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 129 | rc = False |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 130 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 131 | # Unequip everything from pySim-shell that would not work in unequipped state |
| 132 | if self.rs: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 133 | lchan = self.rs.lchan[0] |
| 134 | lchan.unregister_cmds(self) |
iw0 | f818acd | 2023-06-19 10:27:04 +0200 | [diff] [blame] | 135 | if self.rs.profile: |
| 136 | for cmd_set in self.rs.profile.shell_cmdsets: |
| 137 | self.unregister_command_set(cmd_set) |
| 138 | |
Harald Welte | 892526f | 2023-06-06 17:09:50 +0200 | [diff] [blame] | 139 | for cmds in [Iso7816Commands, Ts102222Commands, PySimCommands]: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 140 | cmd_set = self.find_commandsets(cmds) |
| 141 | if cmd_set: |
| 142 | self.unregister_command_set(cmd_set[0]) |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 143 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 144 | self.card = card |
| 145 | self.rs = rs |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 146 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 147 | # When a card object and a runtime state is present, (re)equip pySim-shell with everything that is |
| 148 | # needed to operate on cards. |
| 149 | if self.card and self.rs: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 150 | self.lchan = self.rs.lchan[0] |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 151 | self._onchange_conserve_write( |
| 152 | 'conserve_write', False, self.conserve_write) |
| 153 | self._onchange_apdu_trace('apdu_trace', False, self.apdu_trace) |
Harald Welte | 659781c | 2023-06-06 17:00:51 +0200 | [diff] [blame] | 154 | if self.rs.profile: |
| 155 | for cmd_set in self.rs.profile.shell_cmdsets: |
| 156 | self.register_command_set(cmd_set) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 157 | self.register_command_set(Iso7816Commands()) |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 158 | self.register_command_set(Ts102222Commands()) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 159 | self.register_command_set(PySimCommands()) |
Philipp Maier | a42ee6f | 2023-08-16 10:44:57 +0200 | [diff] [blame] | 160 | |
Philipp Maier | 7c0cd0a | 2023-10-16 15:02:07 +0200 | [diff] [blame] | 161 | try: |
| 162 | self.lchan.select('MF/EF.ICCID', self) |
| 163 | self.iccid = dec_iccid(self.lchan.read_binary()[0]) |
| 164 | except: |
| 165 | self.iccid = None |
Philipp Maier | a42ee6f | 2023-08-16 10:44:57 +0200 | [diff] [blame] | 166 | |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 167 | self.lchan.select('MF', self) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 168 | rc = True |
| 169 | else: |
| 170 | self.poutput("pySim-shell not equipped!") |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 171 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 172 | self.update_prompt() |
| 173 | return rc |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 174 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 175 | def poutput_json(self, data, force_no_pretty=False): |
| 176 | """like cmd2.poutput() but for a JSON serializable dict.""" |
| 177 | if force_no_pretty or self.json_pretty_print == False: |
| 178 | output = json.dumps(data, cls=JsonEncoder) |
| 179 | else: |
| 180 | output = json.dumps(data, cls=JsonEncoder, indent=4) |
| 181 | self.poutput(output) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 182 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 183 | def _onchange_numeric_path(self, param_name, old, new): |
| 184 | self.update_prompt() |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 185 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 186 | def _onchange_conserve_write(self, param_name, old, new): |
| 187 | if self.rs: |
| 188 | self.rs.conserve_write = new |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 189 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 190 | def _onchange_apdu_trace(self, param_name, old, new): |
| 191 | if self.card: |
| 192 | if new == True: |
| 193 | self.card._scc._tp.apdu_tracer = self.Cmd2ApduTracer(self) |
| 194 | else: |
| 195 | self.card._scc._tp.apdu_tracer = None |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 196 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 197 | class Cmd2ApduTracer(ApduTracer): |
| 198 | def __init__(self, cmd2_app): |
Philipp Maier | 91c971b | 2023-10-09 10:48:46 +0200 | [diff] [blame] | 199 | self.cmd2 = cmd2_app |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 200 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 201 | def trace_response(self, cmd, sw, resp): |
| 202 | self.cmd2.poutput("-> %s %s" % (cmd[:10], cmd[10:])) |
| 203 | self.cmd2.poutput("<- %s: %s" % (sw, resp)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 204 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 205 | def update_prompt(self): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 206 | if self.lchan: |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 207 | path_str = self.lchan.selected_file.fully_qualified_path_str(not self.numeric_path) |
Harald Welte | 41a7379 | 2023-12-28 20:51:52 +0100 | [diff] [blame] | 208 | scp = self.lchan.scc.scp |
| 209 | if scp: |
| 210 | self.prompt = 'pySIM-shell (%s:%02u:%s)> ' % (str(scp), self.lchan.lchan_nr, path_str) |
| 211 | else: |
| 212 | self.prompt = 'pySIM-shell (%02u:%s)> ' % (self.lchan.lchan_nr, path_str) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 213 | else: |
Philipp Maier | 7226c09 | 2022-06-01 17:58:38 +0200 | [diff] [blame] | 214 | if self.card: |
| 215 | self.prompt = 'pySIM-shell (no card profile)> ' |
| 216 | else: |
| 217 | self.prompt = 'pySIM-shell (no card)> ' |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 218 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 219 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 220 | def do_intro(self, _): |
| 221 | """Display the intro banner""" |
| 222 | self.poutput(self.intro) |
Philipp Maier | 9764de2 | 2021-11-03 10:44:39 +0100 | [diff] [blame] | 223 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 224 | def do_eof(self, _: argparse.Namespace) -> bool: |
| 225 | self.poutput("") |
| 226 | return self.do_quit('') |
Philipp Maier | 5d698e5 | 2021-09-16 13:18:01 +0200 | [diff] [blame] | 227 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 228 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 229 | def do_equip(self, opts): |
| 230 | """Equip pySim-shell with card""" |
Philipp Maier | e6cba76 | 2023-08-11 11:23:17 +0200 | [diff] [blame] | 231 | if self.rs and self.rs.profile: |
Harald Welte | 659781c | 2023-06-06 17:00:51 +0200 | [diff] [blame] | 232 | for cmd_set in self.rs.profile.shell_cmdsets: |
| 233 | self.unregister_command_set(cmd_set) |
Philipp Maier | 91c971b | 2023-10-09 10:48:46 +0200 | [diff] [blame] | 234 | rs, card = init_card(self.sl) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 235 | self.equip(card, rs) |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 236 | |
Philipp Maier | 7226c09 | 2022-06-01 17:58:38 +0200 | [diff] [blame] | 237 | apdu_cmd_parser = argparse.ArgumentParser() |
Harald Welte | 4e59d89 | 2023-11-01 23:40:07 +0100 | [diff] [blame] | 238 | apdu_cmd_parser.add_argument('APDU', type=is_hexstr, help='APDU as hex string') |
Philipp Maier | e7d1b67 | 2022-06-01 18:05:34 +0200 | [diff] [blame] | 239 | apdu_cmd_parser.add_argument('--expect-sw', help='expect a specified status word', type=str, default=None) |
Harald Welte | 321973a | 2024-02-01 18:43:48 +0100 | [diff] [blame^] | 240 | apdu_cmd_parser.add_argument('--raw', help='Bypass the logical channel (and secure channel)', action='store_true') |
Philipp Maier | 7226c09 | 2022-06-01 17:58:38 +0200 | [diff] [blame] | 241 | |
| 242 | @cmd2.with_argparser(apdu_cmd_parser) |
| 243 | def do_apdu(self, opts): |
| 244 | """Send a raw APDU to the card, and print SW + Response. |
Philipp Maier | 1c207a2 | 2023-11-29 13:04:09 +0100 | [diff] [blame] | 245 | CAUTION: this command bypasses the logical channel handling of pySim-shell and card state changes are not |
| 246 | tracked. Dpending on the raw APDU sent, pySim-shell may not continue to work as expected if you e.g. select |
| 247 | a different file.""" |
| 248 | |
| 249 | # When sending raw APDUs we access the scc object through _scc member of the card object. It should also be |
| 250 | # noted that the apdu command plays an exceptional role since it is the only card accessing command that |
| 251 | # can be executed without the presence of a runtime state (self.rs) object. However, this also means that |
| 252 | # self.lchan is also not present (see method equip). |
Harald Welte | 321973a | 2024-02-01 18:43:48 +0100 | [diff] [blame^] | 253 | if opts.raw: |
| 254 | data, sw = self.card._scc.send_apdu(opts.APDU) |
| 255 | else: |
| 256 | data, sw = self.lchan.scc.send_apdu(opts.APDU) |
Philipp Maier | 7226c09 | 2022-06-01 17:58:38 +0200 | [diff] [blame] | 257 | if data: |
| 258 | self.poutput("SW: %s, RESP: %s" % (sw, data)) |
| 259 | else: |
| 260 | self.poutput("SW: %s" % sw) |
Philipp Maier | e7d1b67 | 2022-06-01 18:05:34 +0200 | [diff] [blame] | 261 | if opts.expect_sw: |
| 262 | if not sw_match(sw, opts.expect_sw): |
| 263 | raise SwMatchError(sw, opts.expect_sw) |
Philipp Maier | 7226c09 | 2022-06-01 17:58:38 +0200 | [diff] [blame] | 264 | |
Harald Welte | 66b3370 | 2024-01-16 18:59:43 +0100 | [diff] [blame] | 265 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 266 | def do_reset(self, opts): |
| 267 | """Reset the Card.""" |
| 268 | atr = self.card.reset() |
Harald Welte | 41a7379 | 2023-12-28 20:51:52 +0100 | [diff] [blame] | 269 | if self.lchan and self.lchan.scc.scp: |
| 270 | self.lchan.scc.scp = None |
Harald Welte | 66b3370 | 2024-01-16 18:59:43 +0100 | [diff] [blame] | 271 | self.poutput('Card ATR: %s' % i2h(atr)) |
| 272 | self.update_prompt() |
| 273 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 274 | class InterceptStderr(list): |
| 275 | def __init__(self): |
| 276 | self._stderr_backup = sys.stderr |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 277 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 278 | def __enter__(self): |
| 279 | self._stringio_stderr = StringIO() |
| 280 | sys.stderr = self._stringio_stderr |
| 281 | return self |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 282 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 283 | def __exit__(self, *args): |
| 284 | self.stderr = self._stringio_stderr.getvalue().strip() |
| 285 | del self._stringio_stderr |
| 286 | sys.stderr = self._stderr_backup |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 287 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 288 | def _show_failure_sign(self): |
Harald Welte | 961b803 | 2023-04-27 17:30:22 +0200 | [diff] [blame] | 289 | self.poutput(style(" +-------------+", fg=LIGHT_RED)) |
| 290 | self.poutput(style(" + ## ## +", fg=LIGHT_RED)) |
| 291 | self.poutput(style(" + ## ## +", fg=LIGHT_RED)) |
| 292 | self.poutput(style(" + ### +", fg=LIGHT_RED)) |
| 293 | self.poutput(style(" + ## ## +", fg=LIGHT_RED)) |
| 294 | self.poutput(style(" + ## ## +", fg=LIGHT_RED)) |
| 295 | self.poutput(style(" +-------------+", fg=LIGHT_RED)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 296 | self.poutput("") |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 297 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 298 | def _show_success_sign(self): |
Harald Welte | 961b803 | 2023-04-27 17:30:22 +0200 | [diff] [blame] | 299 | self.poutput(style(" +-------------+", fg=LIGHT_GREEN)) |
| 300 | self.poutput(style(" + ## +", fg=LIGHT_GREEN)) |
| 301 | self.poutput(style(" + ## +", fg=LIGHT_GREEN)) |
| 302 | self.poutput(style(" + # ## +", fg=LIGHT_GREEN)) |
| 303 | self.poutput(style(" + ## # +", fg=LIGHT_GREEN)) |
| 304 | self.poutput(style(" + ## +", fg=LIGHT_GREEN)) |
| 305 | self.poutput(style(" +-------------+", fg=LIGHT_GREEN)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 306 | self.poutput("") |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 307 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 308 | def _process_card(self, first, script_path): |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 309 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 310 | # Early phase of card initialzation (this part may fail with an exception) |
| 311 | try: |
| 312 | rs, card = init_card(self.sl) |
| 313 | rc = self.equip(card, rs) |
| 314 | except: |
| 315 | self.poutput("") |
Philipp Maier | 6bfa8a8 | 2023-10-09 13:32:49 +0200 | [diff] [blame] | 316 | self.poutput("Card initialization (%s) failed with an exception:" % str(self.sl)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 317 | self.poutput("---------------------8<---------------------") |
| 318 | traceback.print_exc() |
| 319 | self.poutput("---------------------8<---------------------") |
| 320 | self.poutput("") |
| 321 | return -1 |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 322 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 323 | # Actual card processing step. This part should never fail with an exception since the cmd2 |
| 324 | # do_run_script method will catch any exception that might occur during script execution. |
| 325 | if rc: |
| 326 | self.poutput("") |
| 327 | self.poutput("Transcript stdout:") |
| 328 | self.poutput("---------------------8<---------------------") |
| 329 | with self.InterceptStderr() as logged: |
| 330 | self.do_run_script(script_path) |
| 331 | self.poutput("---------------------8<---------------------") |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 332 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 333 | self.poutput("") |
| 334 | self.poutput("Transcript stderr:") |
| 335 | if logged.stderr: |
| 336 | self.poutput("---------------------8<---------------------") |
| 337 | self.poutput(logged.stderr) |
| 338 | self.poutput("---------------------8<---------------------") |
| 339 | else: |
| 340 | self.poutput("(none)") |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 341 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 342 | # Check for exceptions |
| 343 | self.poutput("") |
| 344 | if "EXCEPTION of type" not in logged.stderr: |
| 345 | return 0 |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 346 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 347 | return -1 |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 348 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 349 | bulk_script_parser = argparse.ArgumentParser() |
| 350 | bulk_script_parser.add_argument( |
| 351 | 'script_path', help="path to the script file") |
| 352 | bulk_script_parser.add_argument('--halt_on_error', help='stop card handling if an exeption occurs', |
| 353 | action='store_true') |
| 354 | bulk_script_parser.add_argument('--tries', type=int, default=2, |
| 355 | help='how many tries before trying the next card') |
| 356 | bulk_script_parser.add_argument('--on_stop_action', type=str, default=None, |
| 357 | help='commandline to execute when card handling has stopped') |
| 358 | bulk_script_parser.add_argument('--pre_card_action', type=str, default=None, |
| 359 | help='commandline to execute before actually talking to the card') |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 360 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 361 | @cmd2.with_argparser(bulk_script_parser) |
| 362 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 363 | def do_bulk_script(self, opts): |
| 364 | """Run script on multiple cards (bulk provisioning)""" |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 365 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 366 | # Make sure that the script file exists and that it is readable. |
| 367 | if not os.access(opts.script_path, os.R_OK): |
| 368 | self.poutput("Invalid script file!") |
| 369 | return |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 370 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 371 | success_count = 0 |
| 372 | fail_count = 0 |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 373 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 374 | first = True |
| 375 | while 1: |
| 376 | # TODO: Count consecutive failures, if more than N consecutive failures occur, then stop. |
| 377 | # The ratinale is: There may be a problem with the device, we do want to prevent that |
| 378 | # all remaining cards are fired to the error bin. This is only relevant for situations |
| 379 | # with large stacks, probably we do not need this feature right now. |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 380 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 381 | try: |
| 382 | # In case of failure, try multiple times. |
| 383 | for i in range(opts.tries): |
| 384 | # fetch card into reader bay |
Philipp Maier | 91c971b | 2023-10-09 10:48:46 +0200 | [diff] [blame] | 385 | self.ch.get(first) |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 386 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 387 | # if necessary execute an action before we start processing the card |
| 388 | if(opts.pre_card_action): |
| 389 | os.system(opts.pre_card_action) |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 390 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 391 | # process the card |
| 392 | rc = self._process_card(first, opts.script_path) |
| 393 | if rc == 0: |
| 394 | success_count = success_count + 1 |
| 395 | self._show_success_sign() |
| 396 | self.poutput("Statistics: success :%i, failure: %i" % ( |
| 397 | success_count, fail_count)) |
| 398 | break |
| 399 | else: |
| 400 | fail_count = fail_count + 1 |
| 401 | self._show_failure_sign() |
| 402 | self.poutput("Statistics: success :%i, failure: %i" % ( |
| 403 | success_count, fail_count)) |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 404 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 405 | # Depending on success or failure, the card goes either in the "error" bin or in the |
| 406 | # "done" bin. |
| 407 | if rc < 0: |
Philipp Maier | 91c971b | 2023-10-09 10:48:46 +0200 | [diff] [blame] | 408 | self.ch.error() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 409 | else: |
Philipp Maier | 91c971b | 2023-10-09 10:48:46 +0200 | [diff] [blame] | 410 | self.ch.done() |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 411 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 412 | # In most cases it is possible to proceed with the next card, but the |
| 413 | # user may decide to halt immediately when an error occurs |
| 414 | if opts.halt_on_error and rc < 0: |
| 415 | return |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 416 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 417 | except (KeyboardInterrupt): |
| 418 | self.poutput("") |
| 419 | self.poutput("Terminated by user!") |
| 420 | return |
| 421 | except (SystemExit): |
| 422 | # When all cards are processed the card handler device will throw a SystemExit |
| 423 | # exception. Also Errors that are not recoverable (cards stuck etc.) will end up here. |
| 424 | # The user has the option to execute some action to make aware that the card handler |
| 425 | # needs service. |
| 426 | if(opts.on_stop_action): |
| 427 | os.system(opts.on_stop_action) |
| 428 | return |
| 429 | except: |
| 430 | self.poutput("") |
Philipp Maier | 6bfa8a8 | 2023-10-09 13:32:49 +0200 | [diff] [blame] | 431 | self.poutput("Card handling (%s) failed with an exception:" % str(self.sl)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 432 | self.poutput("---------------------8<---------------------") |
| 433 | traceback.print_exc() |
| 434 | self.poutput("---------------------8<---------------------") |
| 435 | self.poutput("") |
| 436 | fail_count = fail_count + 1 |
| 437 | self._show_failure_sign() |
| 438 | self.poutput("Statistics: success :%i, failure: %i" % |
| 439 | (success_count, fail_count)) |
Philipp Maier | b52feed | 2021-09-22 16:43:13 +0200 | [diff] [blame] | 440 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 441 | first = False |
| 442 | |
| 443 | echo_parser = argparse.ArgumentParser() |
Harald Welte | 977c592 | 2023-11-01 23:42:55 +0100 | [diff] [blame] | 444 | echo_parser.add_argument('string', help="string to echo on the shell", nargs='+') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 445 | |
| 446 | @cmd2.with_argparser(echo_parser) |
| 447 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 448 | def do_echo(self, opts): |
| 449 | """Echo (print) a string on the console""" |
Harald Welte | 977c592 | 2023-11-01 23:42:55 +0100 | [diff] [blame] | 450 | self.poutput(' '.join(opts.string)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 451 | |
Harald Welte | fc31548 | 2022-07-23 12:49:14 +0200 | [diff] [blame] | 452 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 453 | def do_version(self, opts): |
| 454 | """Print the pySim software version.""" |
| 455 | import pkg_resources |
| 456 | self.poutput(pkg_resources.get_distribution('pySim')) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 457 | |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 458 | @with_default_category('pySim Commands') |
| 459 | class PySimCommands(CommandSet): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 460 | def __init__(self): |
| 461 | super().__init__() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 462 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 463 | dir_parser = argparse.ArgumentParser() |
| 464 | dir_parser.add_argument( |
| 465 | '--fids', help='Show file identifiers', action='store_true') |
| 466 | dir_parser.add_argument( |
| 467 | '--names', help='Show file names', action='store_true') |
| 468 | dir_parser.add_argument( |
| 469 | '--apps', help='Show applications', action='store_true') |
| 470 | dir_parser.add_argument( |
| 471 | '--all', help='Show all selectable identifiers and names', action='store_true') |
Philipp Maier | 5d3e259 | 2021-02-22 17:22:16 +0100 | [diff] [blame] | 472 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 473 | @cmd2.with_argparser(dir_parser) |
| 474 | def do_dir(self, opts): |
| 475 | """Show a listing of files available in currently selected DF or MF""" |
| 476 | if opts.all: |
| 477 | flags = [] |
| 478 | elif opts.fids or opts.names or opts.apps: |
| 479 | flags = ['PARENT', 'SELF'] |
| 480 | if opts.fids: |
| 481 | flags += ['FIDS', 'AIDS'] |
| 482 | if opts.names: |
| 483 | flags += ['FNAMES', 'ANAMES'] |
| 484 | if opts.apps: |
| 485 | flags += ['ANAMES', 'AIDS'] |
| 486 | else: |
| 487 | flags = ['PARENT', 'SELF', 'FNAMES', 'ANAMES'] |
| 488 | selectables = list( |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 489 | self._cmd.lchan.selected_file.get_selectable_names(flags=flags)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 490 | directory_str = tabulate_str_list( |
| 491 | selectables, width=79, hspace=2, lspace=1, align_left=True) |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 492 | path = self._cmd.lchan.selected_file.fully_qualified_path_str(True) |
| 493 | self._cmd.poutput(path) |
| 494 | path = self._cmd.lchan.selected_file.fully_qualified_path_str(False) |
| 495 | self._cmd.poutput(path) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 496 | self._cmd.poutput(directory_str) |
| 497 | self._cmd.poutput("%d files" % len(selectables)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 498 | |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 499 | def walk(self, indent=0, action_ef=None, action_df=None, context=None, **kwargs): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 500 | """Recursively walk through the file system, starting at the currently selected DF""" |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 501 | |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 502 | if isinstance(self._cmd.lchan.selected_file, CardDF): |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 503 | if action_df: |
Philipp Maier | 91c971b | 2023-10-09 10:48:46 +0200 | [diff] [blame] | 504 | action_df(context, **kwargs) |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 505 | |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 506 | files = self._cmd.lchan.selected_file.get_selectables( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 507 | flags=['FNAMES', 'ANAMES']) |
| 508 | for f in files: |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 509 | # special case: When no action is performed, just output a directory |
| 510 | if not action_ef and not action_df: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 511 | output_str = " " * indent + str(f) + (" " * 250) |
| 512 | output_str = output_str[0:25] |
| 513 | if isinstance(files[f], CardADF): |
| 514 | output_str += " " + str(files[f].aid) |
| 515 | else: |
| 516 | output_str += " " + str(files[f].fid) |
| 517 | output_str += " " + str(files[f].desc) |
| 518 | self._cmd.poutput(output_str) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 519 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 520 | if isinstance(files[f], CardDF): |
| 521 | skip_df = False |
| 522 | try: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 523 | fcp_dec = self._cmd.lchan.select(f, self._cmd) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 524 | except Exception as e: |
| 525 | skip_df = True |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 526 | df = self._cmd.lchan.selected_file |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 527 | df_path = df.fully_qualified_path_str(True) |
| 528 | df_skip_reason_str = df_path + \ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 529 | "/" + str(f) + ", " + str(e) |
| 530 | if context: |
| 531 | context['DF_SKIP'] += 1 |
| 532 | context['DF_SKIP_REASON'].append(df_skip_reason_str) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 533 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 534 | # If the DF was skipped, we never have entered the directory |
| 535 | # below, so we must not move up. |
| 536 | if skip_df == False: |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 537 | self.walk(indent + 1, action_ef, action_df, context, **kwargs) |
Philipp Maier | 5482737 | 2023-10-24 16:18:30 +0200 | [diff] [blame] | 538 | |
| 539 | parent = self._cmd.lchan.selected_file.parent |
| 540 | df = self._cmd.lchan.selected_file |
| 541 | adf = self._cmd.lchan.selected_adf |
| 542 | if isinstance(parent, CardMF) and (adf and adf.has_fs == False): |
| 543 | # Not every application that may be present on a GlobalPlatform card will support the SELECT |
| 544 | # command as we know it from ETSI TS 102 221, section 11.1.1. In fact the only subset of |
| 545 | # SELECT we may rely on is the OPEN SELECT command as specified in GlobalPlatform Card |
| 546 | # Specification, section 11.9. Unfortunately the OPEN SELECT command only supports the |
| 547 | # "select by name" method, which means we can only select an application and not a file. |
| 548 | # The consequence of this is that we may get trapped in an application that does not have |
| 549 | # ISIM/USIM like file system support and the only way to leave that application is to select |
| 550 | # an ISIM/USIM application in order to get the file system access back. |
| 551 | # |
| 552 | # To automate this escape-route while traversing the file system we will check whether |
| 553 | # the parent file is the MF. When this is the case and the selected ADF has no file system |
| 554 | # support, we will select an arbitrary ADF that has file system support first and from there |
| 555 | # we will then select the MF. |
| 556 | for selectable in parent.get_selectables().items(): |
| 557 | if isinstance(selectable[1], CardADF) and selectable[1].has_fs == True: |
| 558 | self._cmd.lchan.select(selectable[1].name, self._cmd) |
| 559 | break |
| 560 | self._cmd.lchan.select(df.get_mf().name, self._cmd) |
| 561 | else: |
| 562 | # Normal DF/ADF selection |
| 563 | fcp_dec = self._cmd.lchan.select("..", self._cmd) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 564 | |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 565 | elif action_ef: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 566 | df_before_action = self._cmd.lchan.selected_file |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 567 | action_ef(f, context, **kwargs) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 568 | # When walking through the file system tree the action must not |
| 569 | # always restore the currently selected file to the file that |
| 570 | # was selected before executing the action() callback. |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 571 | if df_before_action != self._cmd.lchan.selected_file: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 572 | raise RuntimeError("inconsistent walk, %s is currently selected but expecting %s to be selected" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 573 | % (str(self._cmd.lchan.selected_file), str(df_before_action))) |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 574 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 575 | def do_tree(self, opts): |
| 576 | """Display a filesystem-tree with all selectable files""" |
| 577 | self.walk() |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 578 | |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 579 | def export_ef(self, filename, context, as_json): |
| 580 | """ Select and export a single elementary file (EF) """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 581 | context['COUNT'] += 1 |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 582 | df = self._cmd.lchan.selected_file |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 583 | |
Philipp Maier | ea81f75 | 2022-05-19 10:13:30 +0200 | [diff] [blame] | 584 | # The currently selected file (not the file we are going to export) |
| 585 | # must always be an ADF or DF. From this starting point we select |
| 586 | # the EF we want to export. To maintain consistency we will then |
| 587 | # select the current DF again (see comment below). |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 588 | if not isinstance(df, CardDF): |
| 589 | raise RuntimeError( |
| 590 | "currently selected file %s is not a DF or ADF" % str(df)) |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 591 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 592 | df_path_list = df.fully_qualified_path(True) |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 593 | df_path = df.fully_qualified_path_str(True) |
| 594 | df_path_fid = df.fully_qualified_path_str(False) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 595 | |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 596 | file_str = df_path + "/" + str(filename) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 597 | self._cmd.poutput(boxed_heading_str(file_str)) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 598 | |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 599 | self._cmd.poutput("# directory: %s (%s)" % (df_path, df_path_fid)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 600 | try: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 601 | fcp_dec = self._cmd.lchan.select(filename, self._cmd) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 602 | self._cmd.poutput("# file: %s (%s)" % ( |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 603 | self._cmd.lchan.selected_file.name, self._cmd.lchan.selected_file.fid)) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 604 | |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 605 | structure = self._cmd.lchan.selected_file_structure() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 606 | self._cmd.poutput("# structure: %s" % str(structure)) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 607 | self._cmd.poutput("# RAW FCP Template: %s" % str(self._cmd.lchan.selected_file_fcp_hex)) |
| 608 | self._cmd.poutput("# Decoded FCP Template: %s" % str(self._cmd.lchan.selected_file_fcp)) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 609 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 610 | for f in df_path_list: |
| 611 | self._cmd.poutput("select " + str(f)) |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 612 | self._cmd.poutput("select " + self._cmd.lchan.selected_file.name) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 613 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 614 | if structure == 'transparent': |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 615 | if as_json: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 616 | result = self._cmd.lchan.read_binary_dec() |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 617 | self._cmd.poutput("update_binary_decoded '%s'" % json.dumps(result[0], cls=JsonEncoder)) |
| 618 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 619 | result = self._cmd.lchan.read_binary() |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 620 | self._cmd.poutput("update_binary " + str(result[0])) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 621 | elif structure == 'cyclic' or structure == 'linear_fixed': |
| 622 | # Use number of records specified in select response |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 623 | num_of_rec = self._cmd.lchan.selected_file_num_of_rec() |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 624 | if num_of_rec: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 625 | for r in range(1, num_of_rec + 1): |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 626 | if as_json: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 627 | result = self._cmd.lchan.read_record_dec(r) |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 628 | self._cmd.poutput("update_record_decoded %d '%s'" % (r, json.dumps(result[0], cls=JsonEncoder))) |
| 629 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 630 | result = self._cmd.lchan.read_record(r) |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 631 | self._cmd.poutput("update_record %d %s" % (r, str(result[0]))) |
| 632 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 633 | # When the select response does not return the number of records, read until we hit the |
| 634 | # first record that cannot be read. |
| 635 | else: |
| 636 | r = 1 |
| 637 | while True: |
| 638 | try: |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 639 | if as_json: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 640 | result = self._cmd.lchan.read_record_dec(r) |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 641 | self._cmd.poutput("update_record_decoded %d '%s'" % (r, json.dumps(result[0], cls=JsonEncoder))) |
| 642 | else: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 643 | result = self._cmd.lchan.read_record(r) |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 644 | self._cmd.poutput("update_record %d %s" % (r, str(result[0]))) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 645 | except SwMatchError as e: |
| 646 | # We are past the last valid record - stop |
| 647 | if e.sw_actual == "9402": |
| 648 | break |
| 649 | # Some other problem occurred |
| 650 | else: |
| 651 | raise e |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 652 | r = r + 1 |
| 653 | elif structure == 'ber_tlv': |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 654 | tags = self._cmd.lchan.retrieve_tags() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 655 | for t in tags: |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 656 | result = self._cmd.lchan.retrieve_data(t) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 657 | (tag, l, val, remainer) = bertlv_parse_one(h2b(result[0])) |
| 658 | self._cmd.poutput("set_data 0x%02x %s" % (t, b2h(val))) |
| 659 | else: |
| 660 | raise RuntimeError( |
| 661 | 'Unsupported structure "%s" of file "%s"' % (structure, filename)) |
| 662 | except Exception as e: |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 663 | bad_file_str = df_path + "/" + str(filename) + ", " + str(e) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 664 | self._cmd.poutput("# bad file: %s" % bad_file_str) |
| 665 | context['ERR'] += 1 |
| 666 | context['BAD'].append(bad_file_str) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 667 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 668 | # When reading the file is done, make sure the parent file is |
| 669 | # selected again. This will be the usual case, however we need |
| 670 | # to check before since we must not select the same DF twice |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 671 | if df != self._cmd.lchan.selected_file: |
| 672 | self._cmd.lchan.select(df.fid or df.aid, self._cmd) |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 673 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 674 | self._cmd.poutput("#") |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 675 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 676 | export_parser = argparse.ArgumentParser() |
| 677 | export_parser.add_argument( |
| 678 | '--filename', type=str, default=None, help='only export specific file') |
Harald Welte | 08b11ab | 2022-02-10 18:56:41 +0100 | [diff] [blame] | 679 | export_parser.add_argument( |
| 680 | '--json', action='store_true', help='export as JSON (less reliable)') |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 681 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 682 | @cmd2.with_argparser(export_parser) |
| 683 | def do_export(self, opts): |
| 684 | """Export files to script that can be imported back later""" |
| 685 | context = {'ERR': 0, 'COUNT': 0, 'BAD': [], |
| 686 | 'DF_SKIP': 0, 'DF_SKIP_REASON': []} |
Philipp Maier | 9a4091d | 2022-05-19 10:20:30 +0200 | [diff] [blame] | 687 | kwargs_export = {'as_json': opts.json} |
Philipp Maier | f16ac6a | 2022-05-31 14:08:47 +0200 | [diff] [blame] | 688 | exception_str_add = "" |
| 689 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 690 | if opts.filename: |
Philipp Maier | 7b138b0 | 2022-05-31 13:42:56 +0200 | [diff] [blame] | 691 | self.export_ef(opts.filename, context, **kwargs_export) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 692 | else: |
Philipp Maier | f16ac6a | 2022-05-31 14:08:47 +0200 | [diff] [blame] | 693 | try: |
| 694 | self.walk(0, self.export_ef, None, context, **kwargs_export) |
| 695 | except Exception as e: |
| 696 | print("# Stopping early here due to exception: " + str(e)) |
| 697 | print("#") |
| 698 | exception_str_add = ", also had to stop early due to exception:" + str(e) |
Philipp Maier | 80ce71f | 2021-04-19 21:24:23 +0200 | [diff] [blame] | 699 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 700 | self._cmd.poutput(boxed_heading_str("Export summary")) |
Philipp Maier | 80ce71f | 2021-04-19 21:24:23 +0200 | [diff] [blame] | 701 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 702 | self._cmd.poutput("# total files visited: %u" % context['COUNT']) |
| 703 | self._cmd.poutput("# bad files: %u" % context['ERR']) |
| 704 | for b in context['BAD']: |
| 705 | self._cmd.poutput("# " + b) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 706 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 707 | self._cmd.poutput("# skipped dedicated files(s): %u" % |
| 708 | context['DF_SKIP']) |
| 709 | for b in context['DF_SKIP_REASON']: |
| 710 | self._cmd.poutput("# " + b) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 711 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 712 | if context['ERR'] and context['DF_SKIP']: |
Philipp Maier | f16ac6a | 2022-05-31 14:08:47 +0200 | [diff] [blame] | 713 | raise RuntimeError("unable to export %i elementary file(s) and %i dedicated file(s)%s" % ( |
| 714 | context['ERR'], context['DF_SKIP'], exception_str_add)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 715 | elif context['ERR']: |
| 716 | raise RuntimeError( |
Philipp Maier | f16ac6a | 2022-05-31 14:08:47 +0200 | [diff] [blame] | 717 | "unable to export %i elementary file(s)%s" % (context['ERR'], exception_str_add)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 718 | elif context['DF_SKIP']: |
| 719 | raise RuntimeError( |
Philipp Maier | f16ac6a | 2022-05-31 14:08:47 +0200 | [diff] [blame] | 720 | "unable to export %i dedicated files(s)%s" % (context['ERR'], exception_str_add)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 721 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 722 | def do_desc(self, opts): |
| 723 | """Display human readable file description for the currently selected file""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 724 | desc = self._cmd.lchan.selected_file.desc |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 725 | if desc: |
| 726 | self._cmd.poutput(desc) |
| 727 | else: |
| 728 | self._cmd.poutput("no description available") |
Philipp Maier | a8c9ea9 | 2021-09-16 12:51:46 +0200 | [diff] [blame] | 729 | |
Harald Welte | 469db93 | 2023-11-01 23:17:06 +0100 | [diff] [blame] | 730 | verify_adm_parser = argparse.ArgumentParser() |
Harald Welte | f9ea63e | 2023-11-01 23:35:31 +0100 | [diff] [blame] | 731 | verify_adm_parser.add_argument('ADM1', nargs='?', type=is_hexstr_or_decimal, |
Harald Welte | 469db93 | 2023-11-01 23:17:06 +0100 | [diff] [blame] | 732 | help='ADM1 pin value. If none given, CSV file will be queried') |
| 733 | |
| 734 | @cmd2.with_argparser(verify_adm_parser) |
| 735 | def do_verify_adm(self, opts): |
| 736 | """Verify the ADM (Administrator) PIN specified as argument. This is typically needed in order |
| 737 | to get write/update permissions to most of the files on SIM cards. |
| 738 | |
| 739 | Currently only ADM1 is supported.""" |
| 740 | if opts.ADM1: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 741 | # use specified ADM-PIN |
Harald Welte | 469db93 | 2023-11-01 23:17:06 +0100 | [diff] [blame] | 742 | pin_adm = sanitize_pin_adm(opts.ADM1) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 743 | else: |
| 744 | # try to find an ADM-PIN if none is specified |
| 745 | result = card_key_provider_get_field( |
| 746 | 'ADM1', key='ICCID', value=self._cmd.iccid) |
| 747 | pin_adm = sanitize_pin_adm(result) |
| 748 | if pin_adm: |
| 749 | self._cmd.poutput( |
| 750 | "found ADM-PIN '%s' for ICCID '%s'" % (result, self._cmd.iccid)) |
| 751 | else: |
| 752 | raise ValueError( |
| 753 | "cannot find ADM-PIN for ICCID '%s'" % (self._cmd.iccid)) |
Philipp Maier | a8c9ea9 | 2021-09-16 12:51:46 +0200 | [diff] [blame] | 754 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 755 | if pin_adm: |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 756 | self._cmd.lchan.scc.verify_chv(self._cmd.card._adm_chv_num, h2b(pin_adm)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 757 | else: |
| 758 | raise ValueError("error: cannot authenticate, no adm-pin!") |
| 759 | |
Philipp Maier | 7b9e244 | 2023-03-22 15:19:54 +0100 | [diff] [blame] | 760 | def do_cardinfo(self, opts): |
| 761 | """Display information about the currently inserted card""" |
| 762 | self._cmd.poutput("Card info:") |
| 763 | self._cmd.poutput(" Name: %s" % self._cmd.card.name) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 764 | self._cmd.poutput(" ATR: %s" % b2h(self._cmd.lchan.scc.get_atr())) |
Philipp Maier | 7b9e244 | 2023-03-22 15:19:54 +0100 | [diff] [blame] | 765 | self._cmd.poutput(" ICCID: %s" % self._cmd.iccid) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 766 | self._cmd.poutput(" Class-Byte: %s" % self._cmd.lchan.scc.cla_byte) |
| 767 | self._cmd.poutput(" Select-Ctrl: %s" % self._cmd.lchan.scc.sel_ctrl) |
Philipp Maier | 7b9e244 | 2023-03-22 15:19:54 +0100 | [diff] [blame] | 768 | self._cmd.poutput(" AIDs:") |
| 769 | for a in self._cmd.rs.mf.applications: |
| 770 | self._cmd.poutput(" %s" % a) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 771 | |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 772 | @with_default_category('ISO7816 Commands') |
| 773 | class Iso7816Commands(CommandSet): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 774 | def __init__(self): |
| 775 | super().__init__() |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 776 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 777 | def do_select(self, opts): |
| 778 | """SELECT a File (ADF/DF/EF)""" |
| 779 | if len(opts.arg_list) == 0: |
Harald Welte | b2e4b4a | 2022-07-19 23:48:45 +0200 | [diff] [blame] | 780 | path = self._cmd.lchan.selected_file.fully_qualified_path_str(True) |
| 781 | path_fid = self._cmd.lchan.selected_file.fully_qualified_path_str(False) |
| 782 | self._cmd.poutput("currently selected file: %s (%s)" % (path, path_fid)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 783 | return |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 784 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 785 | path = opts.arg_list[0] |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 786 | fcp_dec = self._cmd.lchan.select(path, self._cmd) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 787 | self._cmd.update_prompt() |
| 788 | self._cmd.poutput_json(fcp_dec) |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 789 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 790 | def complete_select(self, text, line, begidx, endidx) -> List[str]: |
| 791 | """Command Line tab completion for SELECT""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 792 | index_dict = {1: self._cmd.lchan.selected_file.get_selectable_names()} |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 793 | return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict) |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 794 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 795 | def get_code(self, code): |
| 796 | """Use code either directly or try to get it from external data source""" |
| 797 | auto = ('PIN1', 'PIN2', 'PUK1', 'PUK2') |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 798 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 799 | if str(code).upper() not in auto: |
| 800 | return sanitize_pin_adm(code) |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 801 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 802 | result = card_key_provider_get_field( |
| 803 | str(code), key='ICCID', value=self._cmd.iccid) |
| 804 | result = sanitize_pin_adm(result) |
| 805 | if result: |
| 806 | self._cmd.poutput("found %s '%s' for ICCID '%s'" % |
| 807 | (code.upper(), result, self._cmd.iccid)) |
| 808 | else: |
| 809 | self._cmd.poutput("cannot find %s for ICCID '%s'" % |
| 810 | (code.upper(), self._cmd.iccid)) |
| 811 | return result |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 812 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 813 | verify_chv_parser = argparse.ArgumentParser() |
| 814 | verify_chv_parser.add_argument( |
| 815 | '--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 816 | verify_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 817 | 'pin_code', type=is_decimal, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 818 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 819 | @cmd2.with_argparser(verify_chv_parser) |
| 820 | def do_verify_chv(self, opts): |
Harald Welte | 12af793 | 2022-02-15 16:39:08 +0100 | [diff] [blame] | 821 | """Verify (authenticate) using specified CHV (PIN) code, which is how the specifications |
| 822 | call it if you authenticate yourself using the specified PIN. There usually is at least PIN1 and |
| 823 | PIN2.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 824 | pin = self.get_code(opts.pin_code) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 825 | (data, sw) = self._cmd.lchan.scc.verify_chv(opts.pin_nr, h2b(pin)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 826 | self._cmd.poutput("CHV verification successful") |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 827 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 828 | unblock_chv_parser = argparse.ArgumentParser() |
| 829 | unblock_chv_parser.add_argument( |
| 830 | '--pin-nr', type=int, default=1, help='PUK Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 831 | unblock_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 832 | 'puk_code', type=is_decimal, help='PUK code digits \"PUK1\" or \"PUK2\" to get PUK code from external data source') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 833 | unblock_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 834 | 'new_pin_code', type=is_decimal, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 835 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 836 | @cmd2.with_argparser(unblock_chv_parser) |
| 837 | def do_unblock_chv(self, opts): |
| 838 | """Unblock PIN code using specified PUK code""" |
| 839 | new_pin = self.get_code(opts.new_pin_code) |
| 840 | puk = self.get_code(opts.puk_code) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 841 | (data, sw) = self._cmd.lchan.scc.unblock_chv( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 842 | opts.pin_nr, h2b(puk), h2b(new_pin)) |
| 843 | self._cmd.poutput("CHV unblock successful") |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 844 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 845 | change_chv_parser = argparse.ArgumentParser() |
| 846 | change_chv_parser.add_argument( |
| 847 | '--pin-nr', type=int, default=1, help='PUK Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 848 | change_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 849 | 'pin_code', type=is_decimal, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 850 | change_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 851 | 'new_pin_code', type=is_decimal, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 852 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 853 | @cmd2.with_argparser(change_chv_parser) |
| 854 | def do_change_chv(self, opts): |
| 855 | """Change PIN code to a new PIN code""" |
| 856 | new_pin = self.get_code(opts.new_pin_code) |
| 857 | pin = self.get_code(opts.pin_code) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 858 | (data, sw) = self._cmd.lchan.scc.change_chv( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 859 | opts.pin_nr, h2b(pin), h2b(new_pin)) |
| 860 | self._cmd.poutput("CHV change successful") |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 861 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 862 | disable_chv_parser = argparse.ArgumentParser() |
| 863 | disable_chv_parser.add_argument( |
| 864 | '--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 865 | disable_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 866 | 'pin_code', type=is_decimal, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 867 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 868 | @cmd2.with_argparser(disable_chv_parser) |
| 869 | def do_disable_chv(self, opts): |
| 870 | """Disable PIN code using specified PIN code""" |
| 871 | pin = self.get_code(opts.pin_code) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 872 | (data, sw) = self._cmd.lchan.scc.disable_chv(opts.pin_nr, h2b(pin)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 873 | self._cmd.poutput("CHV disable successful") |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 874 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 875 | enable_chv_parser = argparse.ArgumentParser() |
| 876 | enable_chv_parser.add_argument( |
| 877 | '--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 878 | enable_chv_parser.add_argument( |
Harald Welte | 1c849f8 | 2023-11-01 23:48:28 +0100 | [diff] [blame] | 879 | 'pin_code', type=is_decimal, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 880 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 881 | @cmd2.with_argparser(enable_chv_parser) |
| 882 | def do_enable_chv(self, opts): |
| 883 | """Enable PIN code using specified PIN code""" |
| 884 | pin = self.get_code(opts.pin_code) |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 885 | (data, sw) = self._cmd.lchan.scc.enable_chv(opts.pin_nr, h2b(pin)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 886 | self._cmd.poutput("CHV enable successful") |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 887 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 888 | def do_deactivate_file(self, opts): |
Harald Welte | 799c354 | 2022-02-15 15:56:28 +0100 | [diff] [blame] | 889 | """Deactivate the currently selected EF""" |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 890 | (data, sw) = self._cmd.lchan.scc.deactivate_file() |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 891 | |
Harald Welte | 799c354 | 2022-02-15 15:56:28 +0100 | [diff] [blame] | 892 | activate_file_parser = argparse.ArgumentParser() |
| 893 | activate_file_parser.add_argument('NAME', type=str, help='File name or FID of file to activate') |
| 894 | @cmd2.with_argparser(activate_file_parser) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 895 | def do_activate_file(self, opts): |
Harald Welte | cd18ed0 | 2024-01-15 09:21:03 +0100 | [diff] [blame] | 896 | """Activate the specified EF by sending an ACTIVATE FILE apdu command (used to be called REHABILITATE |
| 897 | in TS 11.11 for classic SIM). |
| 898 | |
| 899 | This command is used to (re-)activate a file that is currently in deactivated (sometimes also called |
| 900 | "invalidated") state. You need to call this from the DF above the to-be-activated EF and specify the name or |
| 901 | FID of the file to activate. |
| 902 | |
| 903 | Note that for *deactivation* the to-be-deactivated EF must be selected, but for *activation*, the DF |
| 904 | above the to-be-activated EF must be selected!""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 905 | (data, sw) = self._cmd.lchan.activate_file(opts.NAME) |
Harald Welte | 485692b | 2021-05-25 22:21:44 +0200 | [diff] [blame] | 906 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 907 | def complete_activate_file(self, text, line, begidx, endidx) -> List[str]: |
| 908 | """Command Line tab completion for ACTIVATE FILE""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 909 | index_dict = {1: self._cmd.lchan.selected_file.get_selectable_names()} |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 910 | return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict) |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 911 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 912 | open_chan_parser = argparse.ArgumentParser() |
| 913 | open_chan_parser.add_argument( |
| 914 | 'chan_nr', type=int, default=0, help='Channel Number') |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 915 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 916 | @cmd2.with_argparser(open_chan_parser) |
| 917 | def do_open_channel(self, opts): |
| 918 | """Open a logical channel.""" |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 919 | (data, sw) = self._cmd.lchan.scc.manage_channel( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 920 | mode='open', lchan_nr=opts.chan_nr) |
Harald Welte | bdf5957 | 2023-10-21 20:06:19 +0200 | [diff] [blame] | 921 | # this is executed only in successful case, as unsuccessful raises exception |
| 922 | self._cmd.lchan.add_lchan(opts.chan_nr) |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 923 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 924 | close_chan_parser = argparse.ArgumentParser() |
| 925 | close_chan_parser.add_argument( |
| 926 | 'chan_nr', type=int, default=0, help='Channel Number') |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 927 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 928 | @cmd2.with_argparser(close_chan_parser) |
| 929 | def do_close_channel(self, opts): |
| 930 | """Close a logical channel.""" |
Harald Welte | 4625512 | 2023-10-21 23:40:42 +0200 | [diff] [blame] | 931 | (data, sw) = self._cmd.lchan.scc.manage_channel( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 932 | mode='close', lchan_nr=opts.chan_nr) |
Harald Welte | bdf5957 | 2023-10-21 20:06:19 +0200 | [diff] [blame] | 933 | # this is executed only in successful case, as unsuccessful raises exception |
| 934 | self._cmd.rs.del_lchan(opts.chan_nr) |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 935 | |
Harald Welte | 2065099 | 2023-10-21 23:47:02 +0200 | [diff] [blame] | 936 | switch_chan_parser = argparse.ArgumentParser() |
| 937 | switch_chan_parser.add_argument( |
| 938 | 'chan_nr', type=int, default=0, help='Channel Number') |
| 939 | |
| 940 | @cmd2.with_argparser(switch_chan_parser) |
| 941 | def do_switch_channel(self, opts): |
| 942 | """Switch currently active logical channel.""" |
| 943 | self._cmd.lchan._select_pre(self._cmd) |
| 944 | self._cmd.lchan = self._cmd.rs.lchan[opts.chan_nr] |
| 945 | self._cmd.lchan._select_post(self._cmd) |
| 946 | self._cmd.update_prompt() |
| 947 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 948 | def do_status(self, opts): |
| 949 | """Perform the STATUS command.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 950 | fcp_dec = self._cmd.lchan.status() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 951 | self._cmd.poutput_json(fcp_dec) |
Harald Welte | 34b05d3 | 2021-05-25 22:03:13 +0200 | [diff] [blame] | 952 | |
Harald Welte | ec95053 | 2021-10-20 13:09:00 +0200 | [diff] [blame] | 953 | |
Harald Welte | cab26c7 | 2022-08-06 16:12:30 +0200 | [diff] [blame] | 954 | class Proact(ProactiveHandler): |
| 955 | def receive_fetch(self, pcmd: ProactiveCommand): |
| 956 | # print its parsed representation |
| 957 | print(pcmd.decoded) |
| 958 | # TODO: implement the basics, such as SMS Sending, ... |
| 959 | |
| 960 | |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 961 | |
Harald Welte | f422eb1 | 2023-06-09 11:15:09 +0200 | [diff] [blame] | 962 | option_parser = argparse.ArgumentParser(description='interactive SIM card shell', |
Harald Welte | f2e761c | 2021-04-11 11:56:44 +0200 | [diff] [blame] | 963 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
Harald Welte | 28c2431 | 2021-04-11 12:19:36 +0200 | [diff] [blame] | 964 | argparse_add_reader_args(option_parser) |
Harald Welte | c8ff026 | 2021-04-11 12:06:13 +0200 | [diff] [blame] | 965 | |
| 966 | global_group = option_parser.add_argument_group('General Options') |
| 967 | global_group.add_argument('--script', metavar='PATH', default=None, |
Harald Welte | 28c2431 | 2021-04-11 12:19:36 +0200 | [diff] [blame] | 968 | help='script with pySim-shell commands to be executed automatically at start-up') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 969 | global_group.add_argument('--csv', metavar='FILE', |
| 970 | default=None, help='Read card data from CSV file') |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 971 | global_group.add_argument("--card_handler", dest="card_handler_config", metavar="FILE", |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 972 | help="Use automatic card handling machine") |
Harald Welte | c8ff026 | 2021-04-11 12:06:13 +0200 | [diff] [blame] | 973 | |
| 974 | adm_group = global_group.add_mutually_exclusive_group() |
| 975 | adm_group.add_argument('-a', '--pin-adm', metavar='PIN_ADM1', dest='pin_adm', default=None, |
| 976 | help='ADM PIN used for provisioning (overwrites default)') |
| 977 | adm_group.add_argument('-A', '--pin-adm-hex', metavar='PIN_ADM1_HEX', dest='pin_adm_hex', default=None, |
| 978 | help='ADM PIN used for provisioning, as hex string (16 characters long)') |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 979 | |
Harald Welte | 38306df | 2023-07-11 21:17:55 +0200 | [diff] [blame] | 980 | option_parser.add_argument("command", nargs='?', |
| 981 | help="A pySim-shell command that would optionally be executed at startup") |
| 982 | option_parser.add_argument('command_args', nargs=argparse.REMAINDER, |
| 983 | help="Optional Arguments for command") |
| 984 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 985 | |
| 986 | if __name__ == '__main__': |
| 987 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 988 | # Parse options |
| 989 | opts = option_parser.parse_args() |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 990 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 991 | # If a script file is specified, be sure that it actually exists |
| 992 | if opts.script: |
| 993 | if not os.access(opts.script, os.R_OK): |
| 994 | print("Invalid script file!") |
| 995 | sys.exit(2) |
Philipp Maier | 13e258d | 2021-04-08 17:48:49 +0200 | [diff] [blame] | 996 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 997 | # Register csv-file as card data provider, either from specified CSV |
| 998 | # or from CSV file in home directory |
| 999 | csv_default = str(Path.home()) + "/.osmocom/pysim/card_data.csv" |
| 1000 | if opts.csv: |
| 1001 | card_key_provider_register(CardKeyProviderCsv(opts.csv)) |
| 1002 | if os.path.isfile(csv_default): |
| 1003 | card_key_provider_register(CardKeyProviderCsv(csv_default)) |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 1004 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1005 | # Init card reader driver |
Harald Welte | cab26c7 | 2022-08-06 16:12:30 +0200 | [diff] [blame] | 1006 | sl = init_reader(opts, proactive_handler = Proact()) |
Philipp Maier | ea95c39 | 2021-09-16 13:10:19 +0200 | [diff] [blame] | 1007 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1008 | # Create a card handler (for bulk provisioning) |
| 1009 | if opts.card_handler_config: |
| 1010 | ch = CardHandlerAuto(None, opts.card_handler_config) |
| 1011 | else: |
| 1012 | ch = CardHandler(sl) |
Philipp Maier | 7666764 | 2021-09-22 16:53:22 +0200 | [diff] [blame] | 1013 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1014 | # Detect and initialize the card in the reader. This may fail when there |
| 1015 | # is no card in the reader or the card is unresponsive. PysimApp is |
| 1016 | # able to tolerate and recover from that. |
| 1017 | try: |
| 1018 | rs, card = init_card(sl) |
| 1019 | app = PysimApp(card, rs, sl, ch, opts.script) |
| 1020 | except: |
Philipp Maier | 6bfa8a8 | 2023-10-09 13:32:49 +0200 | [diff] [blame] | 1021 | print("Card initialization (%s) failed with an exception:" % str(sl)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1022 | print("---------------------8<---------------------") |
| 1023 | traceback.print_exc() |
| 1024 | print("---------------------8<---------------------") |
| 1025 | print("(you may still try to recover from this manually by using the 'equip' command.)") |
| 1026 | print( |
| 1027 | " it should also be noted that some readers may behave strangely when no card") |
| 1028 | print(" is inserted.)") |
| 1029 | print("") |
Philipp Maier | eb3b0dd | 2023-11-23 11:46:39 +0100 | [diff] [blame] | 1030 | if opts.script: |
| 1031 | print("will not execute startup script due to card initialization errors!") |
| 1032 | app = PysimApp(None, None, sl, ch) |
Philipp Maier | ea95c39 | 2021-09-16 13:10:19 +0200 | [diff] [blame] | 1033 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1034 | # If the user supplies an ADM PIN at via commandline args authenticate |
| 1035 | # immediately so that the user does not have to use the shell commands |
| 1036 | pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex) |
| 1037 | if pin_adm: |
| 1038 | if not card: |
| 1039 | print("Card error, cannot do ADM verification with supplied ADM pin now.") |
| 1040 | try: |
Philipp Maier | 4840d4d | 2023-09-06 14:54:14 +0200 | [diff] [blame] | 1041 | card._scc.verify_chv(card._adm_chv_num, h2b(pin_adm)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1042 | except Exception as e: |
| 1043 | print(e) |
Philipp Maier | 228c98e | 2021-03-10 20:14:06 +0100 | [diff] [blame] | 1044 | |
Harald Welte | 38306df | 2023-07-11 21:17:55 +0200 | [diff] [blame] | 1045 | if opts.command: |
| 1046 | app.onecmd_plus_hooks('{} {}'.format(opts.command, ' '.join(opts.command_args))) |
| 1047 | else: |
| 1048 | app.cmdloop() |