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 |
| 32 | |
| 33 | from pySim.ts_51_011 import EF, DF, EF_SST_map, EF_AD_mode_map |
| 34 | from pySim.ts_31_102 import EF_UST_map, EF_USIM_ADF_map |
| 35 | from pySim.ts_31_103 import EF_IST_map, EF_ISIM_ADF_map |
| 36 | |
| 37 | from pySim.exceptions import * |
| 38 | from pySim.commands import SimCardCommands |
| 39 | from pySim.cards import card_detect, Card |
| 40 | from pySim.utils import h2b, swap_nibbles, rpad, h2s |
Philipp Maier | 5d3e259 | 2021-02-22 17:22:16 +0100 | [diff] [blame] | 41 | from pySim.utils import dec_st, init_reader, sanitize_pin_adm, tabulate_str_list |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 42 | from pySim.card_handler import card_handler |
| 43 | |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 44 | from pySim.filesystem import CardMF, RuntimeState, CardDF, CardADF |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 45 | from pySim.ts_51_011 import CardProfileSIM, DF_TELECOM, DF_GSM |
| 46 | from pySim.ts_102_221 import CardProfileUICC |
| 47 | from pySim.ts_31_102 import ADF_USIM |
| 48 | from pySim.ts_31_103 import ADF_ISIM |
| 49 | |
| 50 | class PysimApp(cmd2.Cmd): |
| 51 | CUSTOM_CATEGORY = 'pySim Commands' |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 52 | def __init__(self, card, rs, script = None): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 53 | basic_commands = [Iso7816Commands(), UsimCommands()] |
| 54 | super().__init__(persistent_history_file='~/.pysim_shell_history', allow_cli_args=False, |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 55 | 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] | 56 | self.intro = style('Welcome to pySim-shell!', fg=fg.red) |
| 57 | self.default_category = 'pySim-shell built-in commands' |
| 58 | self.card = card |
| 59 | self.rs = rs |
| 60 | self.py_locals = { 'card': self.card, 'rs' : self.rs } |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 61 | self.numeric_path = False |
| 62 | self.add_settable(cmd2.Settable('numeric_path', bool, 'Print File IDs instead of names', |
| 63 | onchange_cb=self._onchange_numeric_path)) |
| 64 | self.update_prompt() |
| 65 | |
| 66 | def _onchange_numeric_path(self, param_name, old, new): |
| 67 | self.update_prompt() |
| 68 | |
| 69 | def update_prompt(self): |
| 70 | path_list = self.rs.selected_file.fully_qualified_path(not self.numeric_path) |
| 71 | self.prompt = 'pySIM-shell (%s)> ' % ('/'.join(path_list)) |
| 72 | |
| 73 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 74 | def do_intro(self, _): |
| 75 | """Display the intro banner""" |
| 76 | self.poutput(self.intro) |
| 77 | |
| 78 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 79 | def do_verify_adm(self, arg): |
| 80 | """VERIFY the ADM1 PIN""" |
| 81 | pin_adm = sanitize_pin_adm(arg) |
| 82 | self.card.verify_adm(h2b(pin_adm)) |
| 83 | |
Philipp Maier | 2558aa6 | 2021-03-10 16:20:02 +0100 | [diff] [blame] | 84 | @cmd2.with_category(CUSTOM_CATEGORY) |
| 85 | def do_desc(self, opts): |
| 86 | """Display human readable file description for the currently selected file""" |
| 87 | desc = self.rs.selected_file.desc |
| 88 | if desc: |
| 89 | self.poutput(desc) |
| 90 | else: |
| 91 | self.poutput("no description available") |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 92 | |
| 93 | |
| 94 | @with_default_category('ISO7816 Commands') |
| 95 | class Iso7816Commands(CommandSet): |
| 96 | def __init__(self): |
| 97 | super().__init__() |
| 98 | |
| 99 | def do_select(self, opts): |
| 100 | """SELECT a File (ADF/DF/EF)""" |
Philipp Maier | f62866f | 2021-03-10 17:13:15 +0100 | [diff] [blame] | 101 | if len(opts.arg_list) == 0: |
| 102 | path_list = self._cmd.rs.selected_file.fully_qualified_path(True) |
| 103 | path_list_fid = self._cmd.rs.selected_file.fully_qualified_path(False) |
| 104 | self._cmd.poutput("currently selected file: " + '/'.join(path_list) + " (" + '/'.join(path_list_fid) + ")") |
| 105 | return |
| 106 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 107 | path = opts.arg_list[0] |
| 108 | fcp_dec = self._cmd.rs.select(path, self._cmd) |
| 109 | self._cmd.update_prompt() |
| 110 | self._cmd.poutput(json.dumps(fcp_dec, indent=4)) |
| 111 | |
| 112 | def complete_select(self, text, line, begidx, endidx) -> List[str]: |
| 113 | """Command Line tab completion for SELECT""" |
| 114 | index_dict = { 1: self._cmd.rs.selected_file.get_selectable_names() } |
| 115 | return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict) |
| 116 | |
| 117 | verify_chv_parser = argparse.ArgumentParser() |
| 118 | verify_chv_parser.add_argument('--chv-nr', type=int, default=1, help='CHV Number') |
| 119 | verify_chv_parser.add_argument('code', help='CODE/PIN/PUK') |
| 120 | |
| 121 | @cmd2.with_argparser(verify_chv_parser) |
| 122 | def do_verify_chv(self, opts): |
| 123 | """Verify (authenticate) using specified CHV (PIN)""" |
| 124 | (data, sw) = self._cmd.card._scc.verify_chv(opts.chv_nr, opts.code) |
| 125 | self._cmd.poutput(data) |
| 126 | |
Philipp Maier | 5d3e259 | 2021-02-22 17:22:16 +0100 | [diff] [blame] | 127 | dir_parser = argparse.ArgumentParser() |
| 128 | dir_parser.add_argument('--fids', help='Show file identifiers', action='store_true') |
| 129 | dir_parser.add_argument('--names', help='Show file names', action='store_true') |
| 130 | dir_parser.add_argument('--apps', help='Show applications', action='store_true') |
| 131 | dir_parser.add_argument('--all', help='Show all selectable identifiers and names', action='store_true') |
| 132 | |
| 133 | @cmd2.with_argparser(dir_parser) |
| 134 | def do_dir(self, opts): |
| 135 | """Show a listing of files available in currently selected DF or MF""" |
| 136 | if opts.all: |
| 137 | flags = [] |
| 138 | elif opts.fids or opts.names or opts.apps: |
| 139 | flags = ['PARENT', 'SELF'] |
| 140 | if opts.fids: |
| 141 | flags += ['FIDS', 'AIDS'] |
| 142 | if opts.names: |
| 143 | flags += ['FNAMES', 'ANAMES'] |
| 144 | if opts.apps: |
| 145 | flags += ['ANAMES', 'AIDS'] |
| 146 | else: |
| 147 | flags = ['PARENT', 'SELF', 'FNAMES', 'ANAMES'] |
| 148 | selectables = list(self._cmd.rs.selected_file.get_selectable_names(flags = flags)) |
| 149 | directory_str = tabulate_str_list(selectables, width = 79, hspace = 2, lspace = 1, align_left = True) |
| 150 | path_list = self._cmd.rs.selected_file.fully_qualified_path(True) |
| 151 | self._cmd.poutput('/'.join(path_list)) |
| 152 | path_list = self._cmd.rs.selected_file.fully_qualified_path(False) |
| 153 | self._cmd.poutput('/'.join(path_list)) |
| 154 | self._cmd.poutput(directory_str) |
| 155 | self._cmd.poutput("%d files" % len(selectables)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 156 | |
Philipp Maier | ff9dae2 | 2021-02-25 17:03:21 +0100 | [diff] [blame] | 157 | def walk(self, indent = 0, action = None, context = None): |
| 158 | """Recursively walk through the file system, starting at the currently selected DF""" |
| 159 | files = self._cmd.rs.selected_file.get_selectables(flags = ['FNAMES', 'ANAMES']) |
| 160 | for f in files: |
| 161 | if not action: |
| 162 | output_str = " " * indent + str(f) + (" " * 250) |
| 163 | output_str = output_str[0:25] |
| 164 | if isinstance(files[f], CardADF): |
| 165 | output_str += " " + str(files[f].aid) |
| 166 | else: |
| 167 | output_str += " " + str(files[f].fid) |
| 168 | output_str += " " + str(files[f].desc) |
| 169 | self._cmd.poutput(output_str) |
| 170 | if isinstance(files[f], CardDF): |
| 171 | fcp_dec = self._cmd.rs.select(f, self._cmd) |
| 172 | self.walk(indent + 1, action, context) |
| 173 | fcp_dec = self._cmd.rs.select("..", self._cmd) |
| 174 | elif action: |
| 175 | action(f, context) |
| 176 | |
| 177 | def do_tree(self, opts): |
| 178 | """Display a filesystem-tree with all selectable files""" |
| 179 | self.walk() |
| 180 | |
Philipp Maier | 24f7bd3 | 2021-02-25 17:06:18 +0100 | [diff] [blame] | 181 | def export(self, filename, context): |
| 182 | context['COUNT'] += 1 |
| 183 | path_list = self._cmd.rs.selected_file.fully_qualified_path(True) |
| 184 | path_list_fid = self._cmd.rs.selected_file.fully_qualified_path(False) |
| 185 | |
| 186 | self._cmd.poutput("#" * 80) |
| 187 | file_str = '/'.join(path_list) + "/" + str(filename) + " " * 80 |
| 188 | self._cmd.poutput("# " + file_str[0:77] + "#") |
| 189 | self._cmd.poutput("#" * 80) |
| 190 | |
| 191 | self._cmd.poutput("# directory: %s (%s)" % ('/'.join(path_list), '/'.join(path_list_fid))) |
| 192 | try: |
| 193 | fcp_dec = self._cmd.rs.select(filename, self._cmd) |
| 194 | path_list = self._cmd.rs.selected_file.fully_qualified_path(True) |
| 195 | path_list_fid = self._cmd.rs.selected_file.fully_qualified_path(False) |
| 196 | self._cmd.poutput("# file: %s (%s)" % (path_list[-1], path_list_fid[-1])) |
| 197 | |
| 198 | fd = fcp_dec['file_descriptor'] |
| 199 | structure = fd['structure'] |
| 200 | self._cmd.poutput("# structure: %s" % str(structure)) |
| 201 | |
| 202 | for f in path_list: |
| 203 | self._cmd.poutput("select " + str(f)) |
| 204 | |
| 205 | if structure == 'transparent': |
| 206 | result = self._cmd.rs.read_binary() |
| 207 | self._cmd.poutput("update_binary " + str(result[0])) |
| 208 | if structure == 'cyclic' or structure == 'linear_fixed': |
| 209 | num_of_rec = fd['num_of_rec'] |
| 210 | for r in range(1, num_of_rec + 1): |
| 211 | result = self._cmd.rs.read_record(r) |
| 212 | self._cmd.poutput("update_record %d %s" % (r, str(result[0]))) |
| 213 | fcp_dec = self._cmd.rs.select("..", self._cmd) |
| 214 | except Exception as e: |
| 215 | bad_file_str = '/'.join(path_list) + "/" + str(filename) + ", " + str(e) |
| 216 | self._cmd.poutput("# bad file: %s" % bad_file_str) |
| 217 | context['ERR'] += 1 |
| 218 | context['BAD'].append(bad_file_str) |
| 219 | |
| 220 | self._cmd.poutput("#") |
| 221 | |
| 222 | export_parser = argparse.ArgumentParser() |
| 223 | export_parser.add_argument('--filename', type=str, default=None, help='only export specific file') |
| 224 | |
| 225 | @cmd2.with_argparser(export_parser) |
| 226 | def do_export(self, opts): |
| 227 | """Export files to script that can be imported back later""" |
| 228 | context = {'ERR':0, 'COUNT':0, 'BAD':[]} |
| 229 | if opts.filename: |
| 230 | self.export(opts.filename, context) |
| 231 | else: |
| 232 | self.walk(0, self.export, context) |
| 233 | self._cmd.poutput("# total files visited: %u" % context['COUNT']) |
| 234 | self._cmd.poutput("# bad files: %u" % context['ERR']) |
| 235 | for b in context['BAD']: |
| 236 | self._cmd.poutput("# " + b) |
| 237 | if context['ERR']: |
| 238 | raise RuntimeError("unable to export %i file(s)" % context['ERR']) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 239 | |
| 240 | |
| 241 | @with_default_category('USIM Commands') |
| 242 | class UsimCommands(CommandSet): |
| 243 | def __init__(self): |
| 244 | super().__init__() |
| 245 | |
| 246 | def do_read_ust(self, _): |
| 247 | """Read + Display the EF.UST""" |
| 248 | self._cmd.card.select_adf_by_aid(adf="usim") |
| 249 | (res, sw) = self._cmd.card.read_ust() |
| 250 | self._cmd.poutput(res[0]) |
| 251 | self._cmd.poutput(res[1]) |
| 252 | |
| 253 | def do_read_ehplmn(self, _): |
| 254 | """Read EF.EHPLMN""" |
| 255 | self._cmd.card.select_adf_by_aid(adf="usim") |
| 256 | (res, sw) = self._cmd.card.read_ehplmn() |
| 257 | self._cmd.poutput(res) |
| 258 | |
| 259 | def parse_options(): |
| 260 | |
| 261 | parser = OptionParser(usage="usage: %prog [options]") |
| 262 | |
| 263 | parser.add_option("-d", "--device", dest="device", metavar="DEV", |
| 264 | help="Serial Device for SIM access [default: %default]", |
| 265 | default="/dev/ttyUSB0", |
| 266 | ) |
| 267 | parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD", |
| 268 | help="Baudrate used for SIM access [default: %default]", |
| 269 | default=9600, |
| 270 | ) |
| 271 | parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC", |
| 272 | help="Which PC/SC reader number for SIM access", |
| 273 | default=None, |
| 274 | ) |
| 275 | parser.add_option("--modem-device", dest="modem_dev", metavar="DEV", |
| 276 | help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)", |
| 277 | default=None, |
| 278 | ) |
| 279 | parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD", |
| 280 | help="Baudrate used for modem's port [default: %default]", |
| 281 | default=115200, |
| 282 | ) |
| 283 | parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH", |
| 284 | help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)", |
| 285 | default=None, |
| 286 | ) |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 287 | parser.add_option("--script", dest="script", metavar="PATH", |
| 288 | help="script with shell commands to be executed automatically", |
| 289 | default=None, |
| 290 | ) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 291 | |
| 292 | parser.add_option("-a", "--pin-adm", dest="pin_adm", |
| 293 | help="ADM PIN used for provisioning (overwrites default)", |
| 294 | ) |
| 295 | parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex", |
| 296 | help="ADM PIN used for provisioning, as hex string (16 characters long", |
| 297 | ) |
| 298 | |
| 299 | (options, args) = parser.parse_args() |
| 300 | |
| 301 | if args: |
| 302 | parser.error("Extraneous arguments") |
| 303 | |
| 304 | return options |
| 305 | |
| 306 | |
| 307 | |
| 308 | if __name__ == '__main__': |
| 309 | |
| 310 | # Parse options |
| 311 | opts = parse_options() |
| 312 | |
| 313 | # Init card reader driver |
| 314 | sl = init_reader(opts) |
| 315 | if (sl == None): |
| 316 | exit(1) |
| 317 | |
| 318 | # Create command layer |
| 319 | scc = SimCardCommands(transport=sl) |
| 320 | |
| 321 | sl.wait_for_card(); |
| 322 | |
| 323 | card_handler = card_handler(sl) |
| 324 | |
| 325 | card = card_detect("auto", scc) |
| 326 | if card is None: |
| 327 | print("No card detected!") |
| 328 | sys.exit(2) |
| 329 | |
| 330 | profile = CardProfileUICC() |
Philipp Maier | 1e896f3 | 2021-03-10 17:02:53 +0100 | [diff] [blame] | 331 | profile.add_application(ADF_USIM()) |
| 332 | profile.add_application(ADF_ISIM()) |
| 333 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 334 | rs = RuntimeState(card, profile) |
| 335 | |
| 336 | # FIXME: do this dynamically |
| 337 | rs.mf.add_file(DF_TELECOM()) |
| 338 | rs.mf.add_file(DF_GSM()) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 339 | |
Philipp Maier | 681bc7b | 2021-03-10 19:52:41 +0100 | [diff] [blame] | 340 | app = PysimApp(card, rs, opts.script) |
Philipp Maier | 9c1a4ec | 2021-03-10 12:38:15 +0100 | [diff] [blame] | 341 | rs.select('MF', app) |
Philipp Maier | 228c98e | 2021-03-10 20:14:06 +0100 | [diff] [blame^] | 342 | |
| 343 | # If the user supplies an ADM PIN at via commandline args authenticate |
| 344 | # immediatley so that the user does not have to use the shell commands |
| 345 | pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex) |
| 346 | if pin_adm: |
| 347 | try: |
| 348 | card.verify_adm(h2b(pin_adm)) |
| 349 | except Exception as e: |
| 350 | print(e) |
| 351 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 352 | app.cmdloop() |