blob: bbfe7e9e393bf2f0e67e2cd636f0df3cb0ba39db [file] [log] [blame]
Harald Welteb2edd142021-01-08 23:29:35 +01001#!/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
20from typing import List
21
22import json
23
24import cmd2
25from cmd2 import style, fg, bg
26from cmd2 import CommandSet, with_default_category, with_argparser
27import argparse
28
29import os
30import sys
Philipp Maier2b11c322021-03-17 12:37:39 +010031from pathlib import Path
Harald Welteb2edd142021-01-08 23:29:35 +010032
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +020033from pySim.ts_51_011 import EF, DF, EF_SST_map
Harald Welteb2edd142021-01-08 23:29:35 +010034from pySim.ts_31_102 import EF_UST_map, EF_USIM_ADF_map
35from pySim.ts_31_103 import EF_IST_map, EF_ISIM_ADF_map
36
37from pySim.exceptions import *
38from pySim.commands import SimCardCommands
Harald Welte28c24312021-04-11 12:19:36 +020039from pySim.transport import init_reader, ApduTracer, argparse_add_reader_args
Harald Welteb2edd142021-01-08 23:29:35 +010040from pySim.cards import card_detect, Card
Harald Welte917d98c2021-04-21 11:51:25 +020041from pySim.utils import h2b, swap_nibbles, rpad, b2h, h2s, JsonEncoder, bertlv_parse_one
Philipp Maier80ce71f2021-04-19 21:24:23 +020042from pySim.utils import dec_st, sanitize_pin_adm, tabulate_str_list, is_hex, boxed_heading_str
Harald Welteb2edd142021-01-08 23:29:35 +010043from pySim.card_handler import card_handler
44
Philipp Maierff9dae22021-02-25 17:03:21 +010045from pySim.filesystem import CardMF, RuntimeState, CardDF, CardADF
Harald Welteb2edd142021-01-08 23:29:35 +010046from pySim.ts_51_011 import CardProfileSIM, DF_TELECOM, DF_GSM
47from pySim.ts_102_221 import CardProfileUICC
Harald Welte5ce35242021-04-02 20:27:05 +020048from pySim.ts_31_102 import CardApplicationUSIM
49from pySim.ts_31_103 import CardApplicationISIM
Harald Welteb2edd142021-01-08 23:29:35 +010050
Harald Welte4442b3d2021-04-03 09:00:16 +020051from pySim.card_key_provider import CardKeyProviderCsv, card_key_provider_register, card_key_provider_get_field
Philipp Maier2b11c322021-03-17 12:37:39 +010052
53
Harald Welteb2edd142021-01-08 23:29:35 +010054class PysimApp(cmd2.Cmd):
55 CUSTOM_CATEGORY = 'pySim Commands'
Philipp Maier681bc7b2021-03-10 19:52:41 +010056 def __init__(self, card, rs, script = None):
Harald Welte31d2cf02021-04-03 10:47:29 +020057 basic_commands = [Iso7816Commands(), PySimCommands()]
Harald Welteb2edd142021-01-08 23:29:35 +010058 super().__init__(persistent_history_file='~/.pysim_shell_history', allow_cli_args=False,
Philipp Maier681bc7b2021-03-10 19:52:41 +010059 use_ipython=True, auto_load_commands=False, command_sets=basic_commands, startup_script=script)
Harald Welteb2edd142021-01-08 23:29:35 +010060 self.intro = style('Welcome to pySim-shell!', fg=fg.red)
61 self.default_category = 'pySim-shell built-in commands'
62 self.card = card
Philipp Maier2b11c322021-03-17 12:37:39 +010063 iccid, sw = self.card.read_iccid()
64 self.iccid = iccid
Harald Welteb2edd142021-01-08 23:29:35 +010065 self.rs = rs
66 self.py_locals = { 'card': self.card, 'rs' : self.rs }
Harald Welteb2edd142021-01-08 23:29:35 +010067 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 Maier38c74f62021-03-17 17:19:52 +010070 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 Welteb2edd142021-01-08 23:29:35 +010073 self.update_prompt()
Harald Welte1748b932021-04-06 21:12:25 +020074 self.json_pretty_print = True
75 self.add_settable(cmd2.Settable('json_pretty_print', bool, 'Pretty-Print JSON output'))
Harald Welte7829d8a2021-04-10 11:28:53 +020076 self.apdu_trace = False
77 self.add_settable(cmd2.Settable('apdu_trace', bool, 'Trace and display APDUs exchanged with card',
78 onchange_cb=self._onchange_apdu_trace))
Harald Welte1748b932021-04-06 21:12:25 +020079
80 def poutput_json(self, data, force_no_pretty = False):
Harald Weltec9cdce32021-04-11 10:28:28 +020081 """like cmd2.poutput() but for a JSON serializable dict."""
Harald Welte1748b932021-04-06 21:12:25 +020082 if force_no_pretty or self.json_pretty_print == False:
Harald Welte5e749a72021-04-10 17:18:17 +020083 output = json.dumps(data, cls=JsonEncoder)
Harald Welte1748b932021-04-06 21:12:25 +020084 else:
Harald Welte5e749a72021-04-10 17:18:17 +020085 output = json.dumps(data, cls=JsonEncoder, indent=4)
Harald Welte1748b932021-04-06 21:12:25 +020086 self.poutput(output)
Harald Welteb2edd142021-01-08 23:29:35 +010087
88 def _onchange_numeric_path(self, param_name, old, new):
89 self.update_prompt()
90
Philipp Maier38c74f62021-03-17 17:19:52 +010091 def _onchange_conserve_write(self, param_name, old, new):
92 self.rs.conserve_write = new
93
Harald Welte7829d8a2021-04-10 11:28:53 +020094 def _onchange_apdu_trace(self, param_name, old, new):
95 if new == True:
96 self.card._scc._tp.apdu_tracer = self.Cmd2ApduTracer(self)
97 else:
98 self.card._scc._tp.apdu_tracer = None
99
100 class Cmd2ApduTracer(ApduTracer):
101 def __init__(self, cmd2_app):
102 self.cmd2 = app
103
104 def trace_response(self, cmd, sw, resp):
105 self.cmd2.poutput("-> %s %s" % (cmd[:10], cmd[10:]))
106 self.cmd2.poutput("<- %s: %s" % (sw, resp))
107
Harald Welteb2edd142021-01-08 23:29:35 +0100108 def update_prompt(self):
109 path_list = self.rs.selected_file.fully_qualified_path(not self.numeric_path)
110 self.prompt = 'pySIM-shell (%s)> ' % ('/'.join(path_list))
111
112 @cmd2.with_category(CUSTOM_CATEGORY)
113 def do_intro(self, _):
114 """Display the intro banner"""
115 self.poutput(self.intro)
116
117 @cmd2.with_category(CUSTOM_CATEGORY)
118 def do_verify_adm(self, arg):
119 """VERIFY the ADM1 PIN"""
Philipp Maier2b11c322021-03-17 12:37:39 +0100120 if arg:
121 # use specified ADM-PIN
122 pin_adm = sanitize_pin_adm(arg)
123 else:
124 # try to find an ADM-PIN if none is specified
Harald Welte4442b3d2021-04-03 09:00:16 +0200125 result = card_key_provider_get_field('ADM1', key='ICCID', value=self.iccid)
Philipp Maier2b11c322021-03-17 12:37:39 +0100126 pin_adm = sanitize_pin_adm(result)
127 if pin_adm:
Philipp Maierb63766b2021-03-26 11:50:21 +0100128 self.poutput("found ADM-PIN '%s' for ICCID '%s'" % (result, self.iccid))
129 else:
Philipp Maierdc4402e2021-04-07 14:16:13 +0200130 self.poutput("cannot find ADM-PIN for ICCID '%s'" % (self.iccid))
Philipp Maierb63766b2021-03-26 11:50:21 +0100131 return
Philipp Maier2b11c322021-03-17 12:37:39 +0100132
133 if pin_adm:
134 self.card.verify_adm(h2b(pin_adm))
135 else:
136 self.poutput("error: cannot authenticate, no adm-pin!")
Harald Welteb2edd142021-01-08 23:29:35 +0100137
Philipp Maier2558aa62021-03-10 16:20:02 +0100138 @cmd2.with_category(CUSTOM_CATEGORY)
139 def do_desc(self, opts):
140 """Display human readable file description for the currently selected file"""
141 desc = self.rs.selected_file.desc
142 if desc:
143 self.poutput(desc)
144 else:
145 self.poutput("no description available")
Harald Welteb2edd142021-01-08 23:29:35 +0100146
Harald Welte31d2cf02021-04-03 10:47:29 +0200147@with_default_category('pySim Commands')
148class PySimCommands(CommandSet):
Harald Welteb2edd142021-01-08 23:29:35 +0100149 def __init__(self):
150 super().__init__()
151
Philipp Maier5d3e2592021-02-22 17:22:16 +0100152 dir_parser = argparse.ArgumentParser()
153 dir_parser.add_argument('--fids', help='Show file identifiers', action='store_true')
154 dir_parser.add_argument('--names', help='Show file names', action='store_true')
155 dir_parser.add_argument('--apps', help='Show applications', action='store_true')
156 dir_parser.add_argument('--all', help='Show all selectable identifiers and names', action='store_true')
157
158 @cmd2.with_argparser(dir_parser)
159 def do_dir(self, opts):
160 """Show a listing of files available in currently selected DF or MF"""
161 if opts.all:
162 flags = []
163 elif opts.fids or opts.names or opts.apps:
164 flags = ['PARENT', 'SELF']
165 if opts.fids:
166 flags += ['FIDS', 'AIDS']
167 if opts.names:
168 flags += ['FNAMES', 'ANAMES']
169 if opts.apps:
170 flags += ['ANAMES', 'AIDS']
171 else:
172 flags = ['PARENT', 'SELF', 'FNAMES', 'ANAMES']
173 selectables = list(self._cmd.rs.selected_file.get_selectable_names(flags = flags))
174 directory_str = tabulate_str_list(selectables, width = 79, hspace = 2, lspace = 1, align_left = True)
175 path_list = self._cmd.rs.selected_file.fully_qualified_path(True)
176 self._cmd.poutput('/'.join(path_list))
177 path_list = self._cmd.rs.selected_file.fully_qualified_path(False)
178 self._cmd.poutput('/'.join(path_list))
179 self._cmd.poutput(directory_str)
180 self._cmd.poutput("%d files" % len(selectables))
Harald Welteb2edd142021-01-08 23:29:35 +0100181
Philipp Maierff9dae22021-02-25 17:03:21 +0100182 def walk(self, indent = 0, action = None, context = None):
183 """Recursively walk through the file system, starting at the currently selected DF"""
184 files = self._cmd.rs.selected_file.get_selectables(flags = ['FNAMES', 'ANAMES'])
185 for f in files:
186 if not action:
187 output_str = " " * indent + str(f) + (" " * 250)
188 output_str = output_str[0:25]
189 if isinstance(files[f], CardADF):
190 output_str += " " + str(files[f].aid)
191 else:
192 output_str += " " + str(files[f].fid)
193 output_str += " " + str(files[f].desc)
194 self._cmd.poutput(output_str)
Philipp Maierf408a402021-04-09 21:16:12 +0200195
Philipp Maierff9dae22021-02-25 17:03:21 +0100196 if isinstance(files[f], CardDF):
Philipp Maierf408a402021-04-09 21:16:12 +0200197 skip_df=False
198 try:
199 fcp_dec = self._cmd.rs.select(f, self._cmd)
200 except Exception as e:
201 skip_df=True
202 df = self._cmd.rs.selected_file
203 df_path_list = df.fully_qualified_path(True)
204 df_skip_reason_str = '/'.join(df_path_list) + "/" + str(f) + ", " + str(e)
205 if context:
206 context['DF_SKIP'] += 1
207 context['DF_SKIP_REASON'].append(df_skip_reason_str)
208
209 # If the DF was skipped, we never have entered the directory
210 # below, so we must not move up.
211 if skip_df == False:
212 self.walk(indent + 1, action, context)
213 fcp_dec = self._cmd.rs.select("..", self._cmd)
214
Philipp Maierff9dae22021-02-25 17:03:21 +0100215 elif action:
Philipp Maierb152a9e2021-04-01 17:13:03 +0200216 df_before_action = self._cmd.rs.selected_file
Philipp Maierff9dae22021-02-25 17:03:21 +0100217 action(f, context)
Philipp Maierb152a9e2021-04-01 17:13:03 +0200218 # When walking through the file system tree the action must not
219 # always restore the currently selected file to the file that
220 # was selected before executing the action() callback.
221 if df_before_action != self._cmd.rs.selected_file:
Harald Weltec9cdce32021-04-11 10:28:28 +0200222 raise RuntimeError("inconsistent walk, %s is currently selected but expecting %s to be selected"
Philipp Maierb152a9e2021-04-01 17:13:03 +0200223 % (str(self._cmd.rs.selected_file), str(df_before_action)))
Philipp Maierff9dae22021-02-25 17:03:21 +0100224
225 def do_tree(self, opts):
226 """Display a filesystem-tree with all selectable files"""
227 self.walk()
228
Philipp Maier24f7bd32021-02-25 17:06:18 +0100229 def export(self, filename, context):
Philipp Maierac34dcc2021-04-01 17:19:05 +0200230 """ Select and export a single file """
Philipp Maier24f7bd32021-02-25 17:06:18 +0100231 context['COUNT'] += 1
Philipp Maierac34dcc2021-04-01 17:19:05 +0200232 df = self._cmd.rs.selected_file
233
234 if not isinstance(df, CardDF):
235 raise RuntimeError("currently selected file %s is not a DF or ADF" % str(df))
236
237 df_path_list = df.fully_qualified_path(True)
238 df_path_list_fid = df.fully_qualified_path(False)
Philipp Maier24f7bd32021-02-25 17:06:18 +0100239
Philipp Maier80ce71f2021-04-19 21:24:23 +0200240 file_str = '/'.join(df_path_list) + "/" + str(filename)
241 self._cmd.poutput(boxed_heading_str(file_str))
Philipp Maier24f7bd32021-02-25 17:06:18 +0100242
Philipp Maierac34dcc2021-04-01 17:19:05 +0200243 self._cmd.poutput("# directory: %s (%s)" % ('/'.join(df_path_list), '/'.join(df_path_list_fid)))
Philipp Maier24f7bd32021-02-25 17:06:18 +0100244 try:
245 fcp_dec = self._cmd.rs.select(filename, self._cmd)
Philipp Maierac34dcc2021-04-01 17:19:05 +0200246 self._cmd.poutput("# file: %s (%s)" % (self._cmd.rs.selected_file.name, self._cmd.rs.selected_file.fid))
Philipp Maier24f7bd32021-02-25 17:06:18 +0100247
248 fd = fcp_dec['file_descriptor']
249 structure = fd['structure']
250 self._cmd.poutput("# structure: %s" % str(structure))
251
Philipp Maierac34dcc2021-04-01 17:19:05 +0200252 for f in df_path_list:
Philipp Maier24f7bd32021-02-25 17:06:18 +0100253 self._cmd.poutput("select " + str(f))
Philipp Maierac34dcc2021-04-01 17:19:05 +0200254 self._cmd.poutput("select " + self._cmd.rs.selected_file.name)
Philipp Maier24f7bd32021-02-25 17:06:18 +0100255
256 if structure == 'transparent':
257 result = self._cmd.rs.read_binary()
258 self._cmd.poutput("update_binary " + str(result[0]))
Harald Welte917d98c2021-04-21 11:51:25 +0200259 elif structure == 'cyclic' or structure == 'linear_fixed':
Philipp Maier24f7bd32021-02-25 17:06:18 +0100260 num_of_rec = fd['num_of_rec']
261 for r in range(1, num_of_rec + 1):
262 result = self._cmd.rs.read_record(r)
263 self._cmd.poutput("update_record %d %s" % (r, str(result[0])))
Harald Welte917d98c2021-04-21 11:51:25 +0200264 elif structure == 'ber_tlv':
265 tags = self._cmd.rs.retrieve_tags()
266 for t in tags:
267 result = self._cmd.rs.retrieve_data(t)
268 (tag, l, val) = bertlv_parse_one(h2b(result[0]))
269 self._cmd.poutput("set_data 0x%02x %s" % (t, b2h(val)))
270 else:
271 raise RuntimeError('Unsupported structure "%s" of file "%s"' % (structure, filename))
Philipp Maier24f7bd32021-02-25 17:06:18 +0100272 except Exception as e:
Philipp Maierac34dcc2021-04-01 17:19:05 +0200273 bad_file_str = '/'.join(df_path_list) + "/" + str(filename) + ", " + str(e)
Philipp Maier24f7bd32021-02-25 17:06:18 +0100274 self._cmd.poutput("# bad file: %s" % bad_file_str)
275 context['ERR'] += 1
276 context['BAD'].append(bad_file_str)
277
Philipp Maierac34dcc2021-04-01 17:19:05 +0200278 # When reading the file is done, make sure the parent file is
279 # selected again. This will be the usual case, however we need
280 # to check before since we must not select the same DF twice
281 if df != self._cmd.rs.selected_file:
282 self._cmd.rs.select(df.fid or df.aid, self._cmd)
283
Philipp Maier24f7bd32021-02-25 17:06:18 +0100284 self._cmd.poutput("#")
285
286 export_parser = argparse.ArgumentParser()
287 export_parser.add_argument('--filename', type=str, default=None, help='only export specific file')
288
289 @cmd2.with_argparser(export_parser)
290 def do_export(self, opts):
291 """Export files to script that can be imported back later"""
Philipp Maierf408a402021-04-09 21:16:12 +0200292 context = {'ERR':0, 'COUNT':0, 'BAD':[], 'DF_SKIP':0, 'DF_SKIP_REASON':[]}
Philipp Maier24f7bd32021-02-25 17:06:18 +0100293 if opts.filename:
294 self.export(opts.filename, context)
295 else:
296 self.walk(0, self.export, context)
Philipp Maier80ce71f2021-04-19 21:24:23 +0200297
298 self._cmd.poutput(boxed_heading_str("Export summary"))
299
Philipp Maier24f7bd32021-02-25 17:06:18 +0100300 self._cmd.poutput("# total files visited: %u" % context['COUNT'])
301 self._cmd.poutput("# bad files: %u" % context['ERR'])
302 for b in context['BAD']:
303 self._cmd.poutput("# " + b)
Philipp Maierf408a402021-04-09 21:16:12 +0200304
305 self._cmd.poutput("# skipped dedicated files(s): %u" % context['DF_SKIP'])
306 for b in context['DF_SKIP_REASON']:
307 self._cmd.poutput("# " + b)
308
309 if context['ERR'] and context['DF_SKIP']:
Harald Weltec9cdce32021-04-11 10:28:28 +0200310 raise RuntimeError("unable to export %i elementary file(s) and %i dedicated file(s)" % (context['ERR'], context['DF_SKIP']))
Philipp Maierf408a402021-04-09 21:16:12 +0200311 elif context['ERR']:
Harald Weltec9cdce32021-04-11 10:28:28 +0200312 raise RuntimeError("unable to export %i elementary file(s)" % context['ERR'])
Philipp Maierf408a402021-04-09 21:16:12 +0200313 elif context['DF_SKIP']:
314 raise RuntimeError("unable to export %i dedicated files(s)" % context['ERR'])
Harald Welteb2edd142021-01-08 23:29:35 +0100315
Harald Weltedaf2b392021-05-03 23:17:29 +0200316 def do_reset(self, opts):
317 """Reset the Card."""
318 atr = self._cmd.rs.reset(self._cmd)
319 self._cmd.poutput('Card ATR: %s' % atr)
320 self._cmd.update_prompt()
321
Harald Welteb2edd142021-01-08 23:29:35 +0100322
Harald Welte31d2cf02021-04-03 10:47:29 +0200323@with_default_category('ISO7816 Commands')
324class Iso7816Commands(CommandSet):
325 def __init__(self):
326 super().__init__()
327
328 def do_select(self, opts):
329 """SELECT a File (ADF/DF/EF)"""
330 if len(opts.arg_list) == 0:
331 path_list = self._cmd.rs.selected_file.fully_qualified_path(True)
332 path_list_fid = self._cmd.rs.selected_file.fully_qualified_path(False)
333 self._cmd.poutput("currently selected file: " + '/'.join(path_list) + " (" + '/'.join(path_list_fid) + ")")
334 return
335
336 path = opts.arg_list[0]
337 fcp_dec = self._cmd.rs.select(path, self._cmd)
338 self._cmd.update_prompt()
Harald Welteb00e8932021-04-10 17:19:13 +0200339 self._cmd.poutput_json(fcp_dec)
Harald Welte31d2cf02021-04-03 10:47:29 +0200340
341 def complete_select(self, text, line, begidx, endidx) -> List[str]:
342 """Command Line tab completion for SELECT"""
343 index_dict = { 1: self._cmd.rs.selected_file.get_selectable_names() }
344 return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict)
345
346 def get_code(self, code):
347 """Use code either directly or try to get it from external data source"""
348 auto = ('PIN1', 'PIN2', 'PUK1', 'PUK2')
349
350 if str(code).upper() not in auto:
351 return sanitize_pin_adm(code)
352
353 result = card_key_provider_get_field(str(code), key='ICCID', value=self._cmd.iccid)
354 result = sanitize_pin_adm(result)
355 if result:
356 self._cmd.poutput("found %s '%s' for ICCID '%s'" % (code.upper(), result, self._cmd.iccid))
357 else:
358 self._cmd.poutput("cannot find %s for ICCID '%s'" % (code.upper(), self._cmd.iccid))
359 return result
360
361 verify_chv_parser = argparse.ArgumentParser()
362 verify_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)')
363 verify_chv_parser.add_argument('pin_code', type=str, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source')
364
365 @cmd2.with_argparser(verify_chv_parser)
366 def do_verify_chv(self, opts):
367 """Verify (authenticate) using specified PIN code"""
368 pin = self.get_code(opts.pin_code)
369 (data, sw) = self._cmd.card._scc.verify_chv(opts.pin_nr, h2b(pin))
Harald Weltec9cdce32021-04-11 10:28:28 +0200370 self._cmd.poutput("CHV verification successful")
Harald Welte31d2cf02021-04-03 10:47:29 +0200371
372 unblock_chv_parser = argparse.ArgumentParser()
373 unblock_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PUK Number, 1=PIN1, 2=PIN2 or custom value (decimal)')
374 unblock_chv_parser.add_argument('puk_code', type=str, help='PUK code digits \"PUK1\" or \"PUK2\" to get PUK code from external data source')
375 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')
376
377 @cmd2.with_argparser(unblock_chv_parser)
378 def do_unblock_chv(self, opts):
379 """Unblock PIN code using specified PUK code"""
380 new_pin = self.get_code(opts.new_pin_code)
381 puk = self.get_code(opts.puk_code)
382 (data, sw) = self._cmd.card._scc.unblock_chv(opts.pin_nr, h2b(puk), h2b(new_pin))
383 self._cmd.poutput("CHV unblock successful")
384
385 change_chv_parser = argparse.ArgumentParser()
386 change_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PUK Number, 1=PIN1, 2=PIN2 or custom value (decimal)')
387 change_chv_parser.add_argument('pin_code', type=str, help='PIN code digits \"PIN1\" or \"PIN2\" to get PIN code from external data source')
388 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')
389
390 @cmd2.with_argparser(change_chv_parser)
391 def do_change_chv(self, opts):
392 """Change PIN code to a new PIN code"""
393 new_pin = self.get_code(opts.new_pin_code)
394 pin = self.get_code(opts.pin_code)
395 (data, sw) = self._cmd.card._scc.change_chv(opts.pin_nr, h2b(pin), h2b(new_pin))
396 self._cmd.poutput("CHV change successful")
397
398 disable_chv_parser = argparse.ArgumentParser()
399 disable_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)')
400 disable_chv_parser.add_argument('pin_code', type=str, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source')
401
402 @cmd2.with_argparser(disable_chv_parser)
403 def do_disable_chv(self, opts):
404 """Disable PIN code using specified PIN code"""
405 pin = self.get_code(opts.pin_code)
406 (data, sw) = self._cmd.card._scc.disable_chv(opts.pin_nr, h2b(pin))
407 self._cmd.poutput("CHV disable successful")
408
409 enable_chv_parser = argparse.ArgumentParser()
410 enable_chv_parser.add_argument('--pin-nr', type=int, default=1, help='PIN Number, 1=PIN1, 2=PIN2 or custom value (decimal)')
411 enable_chv_parser.add_argument('pin_code', type=str, help='PIN code digits, \"PIN1\" or \"PIN2\" to get PIN code from external data source')
412
413 @cmd2.with_argparser(enable_chv_parser)
414 def do_enable_chv(self, opts):
415 """Enable PIN code using specified PIN code"""
416 pin = self.get_code(opts.pin_code)
417 (data, sw) = self._cmd.card._scc.enable_chv(opts.pin_nr, h2b(pin))
418 self._cmd.poutput("CHV enable successful")
419
Harald Weltea4631612021-04-10 18:17:55 +0200420 def do_deactivate_file(self, opts):
421 """Deactivate the current EF"""
422 fid = self._cmd.rs.selected_file.fid
423 (data, sw) = self._cmd.card._scc.deactivate_file(fid)
424
425 def do_activate_file(self, opts):
426 """Activate the current EF"""
427 fid = self._cmd.rs.selected_file.fid
428 (data, sw) = self._cmd.card._scc.activate_file(fid)
Harald Welte31d2cf02021-04-03 10:47:29 +0200429
Harald Welte703f9332021-04-10 18:39:32 +0200430 open_chan_parser = argparse.ArgumentParser()
431 open_chan_parser.add_argument('chan_nr', type=int, default=0, help='Channel Number')
432
433 @cmd2.with_argparser(open_chan_parser)
434 def do_open_channel(self, opts):
435 """Open a logical channel."""
436 (data, sw) = self._cmd.card._scc.manage_channel(mode='open', lchan_nr=opts.chan_nr)
437
438 close_chan_parser = argparse.ArgumentParser()
439 close_chan_parser.add_argument('chan_nr', type=int, default=0, help='Channel Number')
440
441 @cmd2.with_argparser(close_chan_parser)
442 def do_close_channel(self, opts):
443 """Close a logical channel."""
444 (data, sw) = self._cmd.card._scc.manage_channel(mode='close', lchan_nr=opts.chan_nr)
445
446
Harald Weltef2e761c2021-04-11 11:56:44 +0200447option_parser = argparse.ArgumentParser(prog='pySim-shell', description='interactive SIM card shell',
448 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
Harald Welte28c24312021-04-11 12:19:36 +0200449argparse_add_reader_args(option_parser)
Harald Weltec8ff0262021-04-11 12:06:13 +0200450
451global_group = option_parser.add_argument_group('General Options')
452global_group.add_argument('--script', metavar='PATH', default=None,
Harald Welte28c24312021-04-11 12:19:36 +0200453 help='script with pySim-shell commands to be executed automatically at start-up')
454global_group.add_argument('--csv', metavar='FILE', default=None, help='Read card data from CSV file')
Harald Weltec8ff0262021-04-11 12:06:13 +0200455
456adm_group = global_group.add_mutually_exclusive_group()
457adm_group.add_argument('-a', '--pin-adm', metavar='PIN_ADM1', dest='pin_adm', default=None,
458 help='ADM PIN used for provisioning (overwrites default)')
459adm_group.add_argument('-A', '--pin-adm-hex', metavar='PIN_ADM1_HEX', dest='pin_adm_hex', default=None,
460 help='ADM PIN used for provisioning, as hex string (16 characters long)')
Harald Welteb2edd142021-01-08 23:29:35 +0100461
462
463if __name__ == '__main__':
464
465 # Parse options
Harald Weltef2e761c2021-04-11 11:56:44 +0200466 opts = option_parser.parse_args()
Harald Welteb2edd142021-01-08 23:29:35 +0100467
468 # Init card reader driver
469 sl = init_reader(opts)
470 if (sl == None):
471 exit(1)
472
473 # Create command layer
474 scc = SimCardCommands(transport=sl)
475
476 sl.wait_for_card();
477
478 card_handler = card_handler(sl)
479
480 card = card_detect("auto", scc)
481 if card is None:
482 print("No card detected!")
483 sys.exit(2)
484
485 profile = CardProfileUICC()
Harald Welte5ce35242021-04-02 20:27:05 +0200486 profile.add_application(CardApplicationUSIM)
487 profile.add_application(CardApplicationISIM)
Philipp Maier1e896f32021-03-10 17:02:53 +0100488
Harald Welteb2edd142021-01-08 23:29:35 +0100489 rs = RuntimeState(card, profile)
Harald Welte4f2c5462021-04-03 11:48:22 +0200490 # inform the transport that we can do context-specific SW interpretation
491 sl.set_sw_interpreter(rs)
Harald Welteb2edd142021-01-08 23:29:35 +0100492
493 # FIXME: do this dynamically
494 rs.mf.add_file(DF_TELECOM())
495 rs.mf.add_file(DF_GSM())
Harald Welteb2edd142021-01-08 23:29:35 +0100496
Philipp Maier13e258d2021-04-08 17:48:49 +0200497 # If a script file is specified, be sure that it actually exists
498 if opts.script:
499 if not os.access(opts.script, os.R_OK):
500 print("Invalid script file!")
501 sys.exit(2)
502
Philipp Maier681bc7b2021-03-10 19:52:41 +0100503 app = PysimApp(card, rs, opts.script)
Philipp Maier9c1a4ec2021-03-10 12:38:15 +0100504 rs.select('MF', app)
Philipp Maier228c98e2021-03-10 20:14:06 +0100505
Philipp Maier2b11c322021-03-17 12:37:39 +0100506 # Register csv-file as card data provider, either from specified CSV
507 # or from CSV file in home directory
508 csv_default = str(Path.home()) + "/.osmocom/pysim/card_data.csv"
509 if opts.csv:
Harald Welte4442b3d2021-04-03 09:00:16 +0200510 card_key_provider_register(CardKeyProviderCsv(opts.csv))
Philipp Maier2b11c322021-03-17 12:37:39 +0100511 if os.path.isfile(csv_default):
Harald Welte4442b3d2021-04-03 09:00:16 +0200512 card_key_provider_register(CardKeyProviderCsv(csv_default))
Philipp Maier2b11c322021-03-17 12:37:39 +0100513
Philipp Maier228c98e2021-03-10 20:14:06 +0100514 # If the user supplies an ADM PIN at via commandline args authenticate
Harald Weltec9cdce32021-04-11 10:28:28 +0200515 # immediately so that the user does not have to use the shell commands
Philipp Maier228c98e2021-03-10 20:14:06 +0100516 pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex)
517 if pin_adm:
518 try:
519 card.verify_adm(h2b(pin_adm))
520 except Exception as e:
521 print(e)
522
Harald Welteb2edd142021-01-08 23:29:35 +0100523 app.cmdloop()