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