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