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 | # |
| 5 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 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 | |
| 20 | from typing import List |
| 21 | |
| 22 | import json |
| 23 | |
| 24 | import cmd2 |
| 25 | from cmd2 import style, fg, bg |
| 26 | from cmd2 import CommandSet, with_default_category, with_argparser |
| 27 | import argparse |
| 28 | |
| 29 | import os |
| 30 | import sys |
| 31 | from optparse import OptionParser |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 32 | from pathlib import Path |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 33 | |
| 34 | from pySim.ts_51_011 import EF, DF, EF_SST_map, EF_AD_mode_map |
| 35 | from pySim.ts_31_102 import EF_UST_map, EF_USIM_ADF_map |
| 36 | from pySim.ts_31_103 import EF_IST_map, EF_ISIM_ADF_map |
| 37 | |
| 38 | from pySim.exceptions import * |
| 39 | from pySim.commands import SimCardCommands |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 40 | from pySim.transport import init_reader, ApduTracer |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 41 | from pySim.cards import card_detect, Card |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 42 | from pySim.utils import h2b, swap_nibbles, rpad, h2s, JsonEncoder |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 43 | from pySim.utils import dec_st, sanitize_pin_adm, tabulate_str_list, is_hex |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 44 | from pySim.card_handler import card_handler |
| 45 | |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 46 | from pySim.filesystem import CardMF, RuntimeState, CardDF, CardADF |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 47 | from pySim.ts_51_011 import CardProfileSIM, DF_TELECOM, DF_GSM |
| 48 | from pySim.ts_102_221 import CardProfileUICC |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 49 | from pySim.ts_31_102 import CardApplicationUSIM |
| 50 | from pySim.ts_31_103 import CardApplicationISIM |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 51 | |
Harald Welte | 4442b3d | 2021-04-03 09:00:16 +0200 | [diff] [blame] | 52 | 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] | 53 | |
| 54 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 55 | class PysimApp(cmd2.Cmd): |
| 56 | CUSTOM_CATEGORY = 'pySim Commands' |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 57 | def __init__(self, card, rs, script = None): |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 58 | basic_commands = [Iso7816Commands(), PySimCommands()] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 59 | super().__init__(persistent_history_file='~/.pysim_shell_history', allow_cli_args=False, |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 60 | use_ipython=True, auto_load_commands=False, command_sets=basic_commands, startup_script=script) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 61 | self.intro = style('Welcome to pySim-shell!', fg=fg.red) |
| 62 | self.default_category = 'pySim-shell built-in commands' |
| 63 | self.card = card |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 64 | iccid, sw = self.card.read_iccid() |
| 65 | self.iccid = iccid |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 66 | self.rs = rs |
| 67 | self.py_locals = { 'card': self.card, 'rs' : self.rs } |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 68 | self.numeric_path = False |
| 69 | self.add_settable(cmd2.Settable('numeric_path', bool, 'Print File IDs instead of names', |
| 70 | onchange_cb=self._onchange_numeric_path)) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 71 | self.conserve_write = True |
| 72 | self.add_settable(cmd2.Settable('conserve_write', bool, 'Read and compare before write', |
| 73 | onchange_cb=self._onchange_conserve_write)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 74 | self.update_prompt() |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 75 | self.json_pretty_print = True |
| 76 | self.add_settable(cmd2.Settable('json_pretty_print', bool, 'Pretty-Print JSON output')) |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 77 | self.apdu_trace = False |
| 78 | self.add_settable(cmd2.Settable('apdu_trace', bool, 'Trace and display APDUs exchanged with card', |
| 79 | onchange_cb=self._onchange_apdu_trace)) |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 80 | |
| 81 | def poutput_json(self, data, force_no_pretty = False): |
| 82 | """line cmd2.putput() but for a json serializable dict.""" |
| 83 | if force_no_pretty or self.json_pretty_print == False: |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 84 | output = json.dumps(data, cls=JsonEncoder) |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 85 | else: |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 86 | output = json.dumps(data, cls=JsonEncoder, indent=4) |
Harald Welte | 1748b93 | 2021-04-06 21:12:25 +0200 | [diff] [blame] | 87 | self.poutput(output) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 88 | |
| 89 | def _onchange_numeric_path(self, param_name, old, new): |
| 90 | self.update_prompt() |
| 91 | |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 92 | def _onchange_conserve_write(self, param_name, old, new): |
| 93 | self.rs.conserve_write = new |
| 94 | |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 95 | def _onchange_apdu_trace(self, param_name, old, new): |
| 96 | if new == True: |
| 97 | self.card._scc._tp.apdu_tracer = self.Cmd2ApduTracer(self) |
| 98 | else: |
| 99 | self.card._scc._tp.apdu_tracer = None |
| 100 | |
| 101 | class Cmd2ApduTracer(ApduTracer): |
| 102 | def __init__(self, cmd2_app): |
| 103 | self.cmd2 = app |
| 104 | |
| 105 | def trace_response(self, cmd, sw, resp): |
| 106 | self.cmd2.poutput("-> %s %s" % (cmd[:10], cmd[10:])) |
| 107 | self.cmd2.poutput("<- %s: %s" % (sw, resp)) |
| 108 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 109 | def update_prompt(self): |
| 110 | path_list = self.rs.selected_file.fully_qualified_path(not self.numeric_path) |
| 111 | self.prompt = 'pySIM-shell (%s)> ' % ('/'.join(path_list)) |
| 112 | |
| 113 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 114 | def do_intro(self, _): |
| 115 | """Display the intro banner""" |
| 116 | self.poutput(self.intro) |
| 117 | |
| 118 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 119 | def do_verify_adm(self, arg): |
| 120 | """VERIFY the ADM1 PIN""" |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 121 | if arg: |
| 122 | # use specified ADM-PIN |
| 123 | pin_adm = sanitize_pin_adm(arg) |
| 124 | else: |
| 125 | # try to find an ADM-PIN if none is specified |
Harald Welte | 4442b3d | 2021-04-03 09:00:16 +0200 | [diff] [blame] | 126 | result = card_key_provider_get_field('ADM1', key='ICCID', value=self.iccid) |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 127 | pin_adm = sanitize_pin_adm(result) |
| 128 | if pin_adm: |
Philipp Maier | b63766b | 2021-03-26 11:50:21 +0100 | [diff] [blame] | 129 | self.poutput("found ADM-PIN '%s' for ICCID '%s'" % (result, self.iccid)) |
| 130 | else: |
Philipp Maier | dc4402e | 2021-04-07 14:16:13 +0200 | [diff] [blame] | 131 | self.poutput("cannot find ADM-PIN for ICCID '%s'" % (self.iccid)) |
Philipp Maier | b63766b | 2021-03-26 11:50:21 +0100 | [diff] [blame] | 132 | return |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 133 | |
| 134 | if pin_adm: |
| 135 | self.card.verify_adm(h2b(pin_adm)) |
| 136 | else: |
| 137 | self.poutput("error: cannot authenticate, no adm-pin!") |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 138 | |
Philipp Maier | 2558aa6 | 2021-03-10 16:20:02 +0100 | [diff] [blame] | 139 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 140 | def do_desc(self, opts): |
| 141 | """Display human readable file description for the currently selected file""" |
| 142 | desc = self.rs.selected_file.desc |
| 143 | if desc: |
| 144 | self.poutput(desc) |
| 145 | else: |
| 146 | self.poutput("no description available") |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 147 | |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 148 | @with_default_category('pySim Commands') |
| 149 | class PySimCommands(CommandSet): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 150 | def __init__(self): |
| 151 | super().__init__() |
| 152 | |
Philipp Maier | 5d3e259 | 2021-02-22 17:22:16 +0100 | [diff] [blame] | 153 | dir_parser = argparse.ArgumentParser() |
| 154 | dir_parser.add_argument('--fids', help='Show file identifiers', action='store_true') |
| 155 | dir_parser.add_argument('--names', help='Show file names', action='store_true') |
| 156 | dir_parser.add_argument('--apps', help='Show applications', action='store_true') |
| 157 | dir_parser.add_argument('--all', help='Show all selectable identifiers and names', action='store_true') |
| 158 | |
| 159 | @cmd2.with_argparser(dir_parser) |
| 160 | def do_dir(self, opts): |
| 161 | """Show a listing of files available in currently selected DF or MF""" |
| 162 | if opts.all: |
| 163 | flags = [] |
| 164 | elif opts.fids or opts.names or opts.apps: |
| 165 | flags = ['PARENT', 'SELF'] |
| 166 | if opts.fids: |
| 167 | flags += ['FIDS', 'AIDS'] |
| 168 | if opts.names: |
| 169 | flags += ['FNAMES', 'ANAMES'] |
| 170 | if opts.apps: |
| 171 | flags += ['ANAMES', 'AIDS'] |
| 172 | else: |
| 173 | flags = ['PARENT', 'SELF', 'FNAMES', 'ANAMES'] |
| 174 | selectables = list(self._cmd.rs.selected_file.get_selectable_names(flags = flags)) |
| 175 | directory_str = tabulate_str_list(selectables, width = 79, hspace = 2, lspace = 1, align_left = True) |
| 176 | path_list = self._cmd.rs.selected_file.fully_qualified_path(True) |
| 177 | self._cmd.poutput('/'.join(path_list)) |
| 178 | path_list = self._cmd.rs.selected_file.fully_qualified_path(False) |
| 179 | self._cmd.poutput('/'.join(path_list)) |
| 180 | self._cmd.poutput(directory_str) |
| 181 | self._cmd.poutput("%d files" % len(selectables)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 182 | |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 183 | def walk(self, indent = 0, action = None, context = None): |
| 184 | """Recursively walk through the file system, starting at the currently selected DF""" |
| 185 | files = self._cmd.rs.selected_file.get_selectables(flags = ['FNAMES', 'ANAMES']) |
| 186 | for f in files: |
| 187 | if not action: |
| 188 | output_str = " " * indent + str(f) + (" " * 250) |
| 189 | output_str = output_str[0:25] |
| 190 | if isinstance(files[f], CardADF): |
| 191 | output_str += " " + str(files[f].aid) |
| 192 | else: |
| 193 | output_str += " " + str(files[f].fid) |
| 194 | output_str += " " + str(files[f].desc) |
| 195 | self._cmd.poutput(output_str) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 196 | |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 197 | if isinstance(files[f], CardDF): |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 198 | skip_df=False |
| 199 | try: |
| 200 | fcp_dec = self._cmd.rs.select(f, self._cmd) |
| 201 | except Exception as e: |
| 202 | skip_df=True |
| 203 | df = self._cmd.rs.selected_file |
| 204 | df_path_list = df.fully_qualified_path(True) |
| 205 | df_skip_reason_str = '/'.join(df_path_list) + "/" + str(f) + ", " + str(e) |
| 206 | if context: |
| 207 | context['DF_SKIP'] += 1 |
| 208 | context['DF_SKIP_REASON'].append(df_skip_reason_str) |
| 209 | |
| 210 | # If the DF was skipped, we never have entered the directory |
| 211 | # below, so we must not move up. |
| 212 | if skip_df == False: |
| 213 | self.walk(indent + 1, action, context) |
| 214 | fcp_dec = self._cmd.rs.select("..", self._cmd) |
| 215 | |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 216 | elif action: |
Philipp Maier | b152a9e | 2021-04-01 17:13:03 +0200 | [diff] [blame] | 217 | df_before_action = self._cmd.rs.selected_file |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 218 | action(f, context) |
Philipp Maier | b152a9e | 2021-04-01 17:13:03 +0200 | [diff] [blame] | 219 | # When walking through the file system tree the action must not |
| 220 | # always restore the currently selected file to the file that |
| 221 | # was selected before executing the action() callback. |
| 222 | if df_before_action != self._cmd.rs.selected_file: |
| 223 | raise RuntimeError("inconsistant walk, %s is currently selected but expecting %s to be selected" |
| 224 | % (str(self._cmd.rs.selected_file), str(df_before_action))) |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 225 | |
| 226 | def do_tree(self, opts): |
| 227 | """Display a filesystem-tree with all selectable files""" |
| 228 | self.walk() |
| 229 | |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 230 | def export(self, filename, context): |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 231 | """ Select and export a single file """ |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 232 | context['COUNT'] += 1 |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 233 | df = self._cmd.rs.selected_file |
| 234 | |
| 235 | if not isinstance(df, CardDF): |
| 236 | raise RuntimeError("currently selected file %s is not a DF or ADF" % str(df)) |
| 237 | |
| 238 | df_path_list = df.fully_qualified_path(True) |
| 239 | df_path_list_fid = df.fully_qualified_path(False) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 240 | |
| 241 | self._cmd.poutput("#" * 80) |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 242 | file_str = '/'.join(df_path_list) + "/" + str(filename) + " " * 80 |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 243 | self._cmd.poutput("# " + file_str[0:77] + "#") |
| 244 | self._cmd.poutput("#" * 80) |
| 245 | |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 246 | self._cmd.poutput("# directory: %s (%s)" % ('/'.join(df_path_list), '/'.join(df_path_list_fid))) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 247 | try: |
| 248 | fcp_dec = self._cmd.rs.select(filename, self._cmd) |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 249 | self._cmd.poutput("# file: %s (%s)" % (self._cmd.rs.selected_file.name, self._cmd.rs.selected_file.fid)) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 250 | |
| 251 | fd = fcp_dec['file_descriptor'] |
| 252 | structure = fd['structure'] |
| 253 | self._cmd.poutput("# structure: %s" % str(structure)) |
| 254 | |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 255 | for f in df_path_list: |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 256 | self._cmd.poutput("select " + str(f)) |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 257 | self._cmd.poutput("select " + self._cmd.rs.selected_file.name) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 258 | |
| 259 | if structure == 'transparent': |
| 260 | result = self._cmd.rs.read_binary() |
| 261 | self._cmd.poutput("update_binary " + str(result[0])) |
| 262 | if structure == 'cyclic' or structure == 'linear_fixed': |
| 263 | num_of_rec = fd['num_of_rec'] |
| 264 | for r in range(1, num_of_rec + 1): |
| 265 | result = self._cmd.rs.read_record(r) |
| 266 | self._cmd.poutput("update_record %d %s" % (r, str(result[0]))) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 267 | except Exception as e: |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 268 | bad_file_str = '/'.join(df_path_list) + "/" + str(filename) + ", " + str(e) |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 269 | self._cmd.poutput("# bad file: %s" % bad_file_str) |
| 270 | context['ERR'] += 1 |
| 271 | context['BAD'].append(bad_file_str) |
| 272 | |
Philipp Maier | ac34dcc | 2021-04-01 17:19:05 +0200 | [diff] [blame] | 273 | # When reading the file is done, make sure the parent file is |
| 274 | # selected again. This will be the usual case, however we need |
| 275 | # to check before since we must not select the same DF twice |
| 276 | if df != self._cmd.rs.selected_file: |
| 277 | self._cmd.rs.select(df.fid or df.aid, self._cmd) |
| 278 | |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 279 | self._cmd.poutput("#") |
| 280 | |
| 281 | export_parser = argparse.ArgumentParser() |
| 282 | export_parser.add_argument('--filename', type=str, default=None, help='only export specific file') |
| 283 | |
| 284 | @cmd2.with_argparser(export_parser) |
| 285 | def do_export(self, opts): |
| 286 | """Export files to script that can be imported back later""" |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 287 | context = {'ERR':0, 'COUNT':0, 'BAD':[], 'DF_SKIP':0, 'DF_SKIP_REASON':[]} |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 288 | if opts.filename: |
| 289 | self.export(opts.filename, context) |
| 290 | else: |
| 291 | self.walk(0, self.export, context) |
| 292 | self._cmd.poutput("# total files visited: %u" % context['COUNT']) |
| 293 | self._cmd.poutput("# bad files: %u" % context['ERR']) |
| 294 | for b in context['BAD']: |
| 295 | self._cmd.poutput("# " + b) |
Philipp Maier | f408a40 | 2021-04-09 21:16:12 +0200 | [diff] [blame] | 296 | |
| 297 | self._cmd.poutput("# skipped dedicated files(s): %u" % context['DF_SKIP']) |
| 298 | for b in context['DF_SKIP_REASON']: |
| 299 | self._cmd.poutput("# " + b) |
| 300 | |
| 301 | if context['ERR'] and context['DF_SKIP']: |
| 302 | raise RuntimeError("unable to export %i elementry file(s) and %i dedicated file(s)" % (context['ERR'], context['DF_SKIP'])) |
| 303 | elif context['ERR']: |
| 304 | raise RuntimeError("unable to export %i elementry file(s)" % context['ERR']) |
| 305 | elif context['DF_SKIP']: |
| 306 | raise RuntimeError("unable to export %i dedicated files(s)" % context['ERR']) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 307 | |
| 308 | |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 309 | @with_default_category('ISO7816 Commands') |
| 310 | class Iso7816Commands(CommandSet): |
| 311 | def __init__(self): |
| 312 | super().__init__() |
| 313 | |
| 314 | def do_select(self, opts): |
| 315 | """SELECT a File (ADF/DF/EF)""" |
| 316 | if len(opts.arg_list) == 0: |
| 317 | path_list = self._cmd.rs.selected_file.fully_qualified_path(True) |
| 318 | path_list_fid = self._cmd.rs.selected_file.fully_qualified_path(False) |
| 319 | self._cmd.poutput("currently selected file: " + '/'.join(path_list) + " (" + '/'.join(path_list_fid) + ")") |
| 320 | return |
| 321 | |
| 322 | path = opts.arg_list[0] |
| 323 | fcp_dec = self._cmd.rs.select(path, self._cmd) |
| 324 | self._cmd.update_prompt() |
Harald Welte | b00e893 | 2021-04-10 17:19:13 +0200 | [diff] [blame] | 325 | self._cmd.poutput_json(fcp_dec) |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 326 | |
| 327 | def complete_select(self, text, line, begidx, endidx) -> List[str]: |
| 328 | """Command Line tab completion for SELECT""" |
| 329 | index_dict = { 1: self._cmd.rs.selected_file.get_selectable_names() } |
| 330 | return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict) |
| 331 | |
| 332 | def get_code(self, code): |
| 333 | """Use code either directly or try to get it from external data source""" |
| 334 | auto = ('PIN1', 'PIN2', 'PUK1', 'PUK2') |
| 335 | |
| 336 | if str(code).upper() not in auto: |
| 337 | return sanitize_pin_adm(code) |
| 338 | |
| 339 | result = card_key_provider_get_field(str(code), key='ICCID', value=self._cmd.iccid) |
| 340 | result = sanitize_pin_adm(result) |
| 341 | if result: |
| 342 | self._cmd.poutput("found %s '%s' for ICCID '%s'" % (code.upper(), result, self._cmd.iccid)) |
| 343 | else: |
| 344 | self._cmd.poutput("cannot find %s for ICCID '%s'" % (code.upper(), self._cmd.iccid)) |
| 345 | return result |
| 346 | |
| 347 | verify_chv_parser = argparse.ArgumentParser() |
| 348 | verify_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 349 | verify_chv_parser.add_argument('pin_code', type=str, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
| 350 | |
| 351 | @cmd2.with_argparser(verify_chv_parser) |
| 352 | def do_verify_chv(self, opts): |
| 353 | """Verify (authenticate) using specified PIN code""" |
| 354 | pin = self.get_code(opts.pin_code) |
| 355 | (data, sw) = self._cmd.card._scc.verify_chv(opts.pin_nr, h2b(pin)) |
| 356 | self._cmd.poutput("CHV verfication successful") |
| 357 | |
| 358 | unblock_chv_parser = argparse.ArgumentParser() |
| 359 | unblock_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PUK Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 360 | unblock_chv_parser.add_argument('puk_code', type=str, help='PUK code digits \"PUK1\" or \"PUK2\" to get PUK code from external data source') |
| 361 | unblock_chv_parser.add_argument('new_pin_code', type=str, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
| 362 | |
| 363 | @cmd2.with_argparser(unblock_chv_parser) |
| 364 | def do_unblock_chv(self, opts): |
| 365 | """Unblock PIN code using specified PUK code""" |
| 366 | new_pin = self.get_code(opts.new_pin_code) |
| 367 | puk = self.get_code(opts.puk_code) |
| 368 | (data, sw) = self._cmd.card._scc.unblock_chv(opts.pin_nr, h2b(puk), h2b(new_pin)) |
| 369 | self._cmd.poutput("CHV unblock successful") |
| 370 | |
| 371 | change_chv_parser = argparse.ArgumentParser() |
| 372 | change_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PUK Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 373 | change_chv_parser.add_argument('pin_code', type=str, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
| 374 | change_chv_parser.add_argument('new_pin_code', type=str, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
| 375 | |
| 376 | @cmd2.with_argparser(change_chv_parser) |
| 377 | def do_change_chv(self, opts): |
| 378 | """Change PIN code to a new PIN code""" |
| 379 | new_pin = self.get_code(opts.new_pin_code) |
| 380 | pin = self.get_code(opts.pin_code) |
| 381 | (data, sw) = self._cmd.card._scc.change_chv(opts.pin_nr, h2b(pin), h2b(new_pin)) |
| 382 | self._cmd.poutput("CHV change successful") |
| 383 | |
| 384 | disable_chv_parser = argparse.ArgumentParser() |
| 385 | disable_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 386 | disable_chv_parser.add_argument('pin_code', type=str, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
| 387 | |
| 388 | @cmd2.with_argparser(disable_chv_parser) |
| 389 | def do_disable_chv(self, opts): |
| 390 | """Disable PIN code using specified PIN code""" |
| 391 | pin = self.get_code(opts.pin_code) |
| 392 | (data, sw) = self._cmd.card._scc.disable_chv(opts.pin_nr, h2b(pin)) |
| 393 | self._cmd.poutput("CHV disable successful") |
| 394 | |
| 395 | enable_chv_parser = argparse.ArgumentParser() |
| 396 | enable_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)') |
| 397 | enable_chv_parser.add_argument('pin_code', type=str, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source') |
| 398 | |
| 399 | @cmd2.with_argparser(enable_chv_parser) |
| 400 | def do_enable_chv(self, opts): |
| 401 | """Enable PIN code using specified PIN code""" |
| 402 | pin = self.get_code(opts.pin_code) |
| 403 | (data, sw) = self._cmd.card._scc.enable_chv(opts.pin_nr, h2b(pin)) |
| 404 | self._cmd.poutput("CHV enable successful") |
| 405 | |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 406 | def do_deactivate_file(self, opts): |
| 407 | """Deactivate the current EF""" |
| 408 | fid = self._cmd.rs.selected_file.fid |
| 409 | (data, sw) = self._cmd.card._scc.deactivate_file(fid) |
| 410 | |
| 411 | def do_activate_file(self, opts): |
| 412 | """Activate the current EF""" |
| 413 | fid = self._cmd.rs.selected_file.fid |
| 414 | (data, sw) = self._cmd.card._scc.activate_file(fid) |
Harald Welte | 31d2cf0 | 2021-04-03 10:47:29 +0200 | [diff] [blame] | 415 | |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 416 | open_chan_parser = argparse.ArgumentParser() |
| 417 | open_chan_parser.add_argument('chan_nr', type=int, default=0, help='Channel Number') |
| 418 | |
| 419 | @cmd2.with_argparser(open_chan_parser) |
| 420 | def do_open_channel(self, opts): |
| 421 | """Open a logical channel.""" |
| 422 | (data, sw) = self._cmd.card._scc.manage_channel(mode='open', lchan_nr=opts.chan_nr) |
| 423 | |
| 424 | close_chan_parser = argparse.ArgumentParser() |
| 425 | close_chan_parser.add_argument('chan_nr', type=int, default=0, help='Channel Number') |
| 426 | |
| 427 | @cmd2.with_argparser(close_chan_parser) |
| 428 | def do_close_channel(self, opts): |
| 429 | """Close a logical channel.""" |
| 430 | (data, sw) = self._cmd.card._scc.manage_channel(mode='close', lchan_nr=opts.chan_nr) |
| 431 | |
| 432 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 433 | def parse_options(): |
| 434 | |
| 435 | parser = OptionParser(usage="usage: %prog [options]") |
| 436 | |
| 437 | parser.add_option("-d", "--device", dest="device", metavar="DEV", |
| 438 | help="Serial Device for SIM access [default: %default]", |
| 439 | default="/dev/ttyUSB0", |
| 440 | ) |
| 441 | parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD", |
| 442 | help="Baudrate used for SIM access [default: %default]", |
| 443 | default=9600, |
| 444 | ) |
| 445 | parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC", |
| 446 | help="Which PC/SC reader number for SIM access", |
| 447 | default=None, |
| 448 | ) |
| 449 | parser.add_option("--modem-device", dest="modem_dev", metavar="DEV", |
| 450 | help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)", |
| 451 | default=None, |
| 452 | ) |
| 453 | parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD", |
| 454 | help="Baudrate used for modem's port [default: %default]", |
| 455 | default=115200, |
| 456 | ) |
| 457 | parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH", |
| 458 | help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)", |
| 459 | default=None, |
| 460 | ) |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 461 | parser.add_option("--script", dest="script", metavar="PATH", |
| 462 | help="script with shell commands to be executed automatically", |
| 463 | default=None, |
| 464 | ) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 465 | |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 466 | parser.add_option("--csv", dest="csv", metavar="FILE", |
| 467 | help="Read card data from CSV file", |
| 468 | default=None, |
| 469 | ) |
| 470 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 471 | parser.add_option("-a", "--pin-adm", dest="pin_adm", |
| 472 | help="ADM PIN used for provisioning (overwrites default)", |
| 473 | ) |
| 474 | parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex", |
| 475 | help="ADM PIN used for provisioning, as hex string (16 characters long", |
| 476 | ) |
| 477 | |
| 478 | (options, args) = parser.parse_args() |
| 479 | |
| 480 | if args: |
| 481 | parser.error("Extraneous arguments") |
| 482 | |
| 483 | return options |
| 484 | |
| 485 | |
| 486 | |
| 487 | if __name__ == '__main__': |
| 488 | |
| 489 | # Parse options |
| 490 | opts = parse_options() |
| 491 | |
| 492 | # Init card reader driver |
| 493 | sl = init_reader(opts) |
| 494 | if (sl == None): |
| 495 | exit(1) |
| 496 | |
| 497 | # Create command layer |
| 498 | scc = SimCardCommands(transport=sl) |
| 499 | |
| 500 | sl.wait_for_card(); |
| 501 | |
| 502 | card_handler = card_handler(sl) |
| 503 | |
| 504 | card = card_detect("auto", scc) |
| 505 | if card is None: |
| 506 | print("No card detected!") |
| 507 | sys.exit(2) |
| 508 | |
| 509 | profile = CardProfileUICC() |
Harald Welte | 5ce3524 | 2021-04-02 20:27:05 +0200 | [diff] [blame] | 510 | profile.add_application(CardApplicationUSIM) |
| 511 | profile.add_application(CardApplicationISIM) |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 512 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 513 | rs = RuntimeState(card, profile) |
Harald Welte | 4f2c546 | 2021-04-03 11:48:22 +0200 | [diff] [blame] | 514 | # inform the transport that we can do context-specific SW interpretation |
| 515 | sl.set_sw_interpreter(rs) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 516 | |
| 517 | # FIXME: do this dynamically |
| 518 | rs.mf.add_file(DF_TELECOM()) |
| 519 | rs.mf.add_file(DF_GSM()) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 520 | |
Philipp Maier | 13e258d | 2021-04-08 17:48:49 +0200 | [diff] [blame] | 521 | # If a script file is specified, be sure that it actually exists |
| 522 | if opts.script: |
| 523 | if not os.access(opts.script, os.R_OK): |
| 524 | print("Invalid script file!") |
| 525 | sys.exit(2) |
| 526 | |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 527 | app = PysimApp(card, rs, opts.script) |
Philipp Maier | 9c1a4ec | 2021-03-10 12:38:15 +0100 | [diff] [blame] | 528 | rs.select('MF', app) |
Philipp Maier | 228c98e | 2021-03-10 20:14:06 +0100 | [diff] [blame] | 529 | |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 530 | # Register csv-file as card data provider, either from specified CSV |
| 531 | # or from CSV file in home directory |
| 532 | csv_default = str(Path.home()) + "/.osmocom/pysim/card_data.csv" |
| 533 | if opts.csv: |
Harald Welte | 4442b3d | 2021-04-03 09:00:16 +0200 | [diff] [blame] | 534 | card_key_provider_register(CardKeyProviderCsv(opts.csv)) |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 535 | if os.path.isfile(csv_default): |
Harald Welte | 4442b3d | 2021-04-03 09:00:16 +0200 | [diff] [blame] | 536 | card_key_provider_register(CardKeyProviderCsv(csv_default)) |
Philipp Maier | 2b11c32 | 2021-03-17 12:37:39 +0100 | [diff] [blame] | 537 | |
Philipp Maier | 228c98e | 2021-03-10 20:14:06 +0100 | [diff] [blame] | 538 | # If the user supplies an ADM PIN at via commandline args authenticate |
| 539 | # immediatley so that the user does not have to use the shell commands |
| 540 | pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex) |
| 541 | if pin_adm: |
| 542 | try: |
| 543 | card.verify_adm(h2b(pin_adm)) |
| 544 | except Exception as e: |
| 545 | print(e) |
| 546 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 547 | app.cmdloop() |