blob: 946b3e5772fd8f74e49fc13015e2370719edc8a8 [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
31from optparse import OptionParser
32
33from pySim.ts_51_011 import EF, DF, EF_SST_map, EF_AD_mode_map
34from 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
39from pySim.cards import card_detect, Card
40from pySim.utils import h2b, swap_nibbles, rpad, h2s
Philipp Maier5d3e2592021-02-22 17:22:16 +010041from pySim.utils import dec_st, init_reader, sanitize_pin_adm, tabulate_str_list
Harald Welteb2edd142021-01-08 23:29:35 +010042from pySim.card_handler import card_handler
43
Philipp Maierff9dae22021-02-25 17:03:21 +010044from pySim.filesystem import CardMF, RuntimeState, CardDF, CardADF
Harald Welteb2edd142021-01-08 23:29:35 +010045from pySim.ts_51_011 import CardProfileSIM, DF_TELECOM, DF_GSM
46from pySim.ts_102_221 import CardProfileUICC
47from pySim.ts_31_102 import ADF_USIM
48from pySim.ts_31_103 import ADF_ISIM
49
50class PysimApp(cmd2.Cmd):
51 CUSTOM_CATEGORY = 'pySim Commands'
52 def __init__(self, card, rs):
53 basic_commands = [Iso7816Commands(), UsimCommands()]
54 super().__init__(persistent_history_file='~/.pysim_shell_history', allow_cli_args=False,
55 use_ipython=True, auto_load_commands=False, command_sets=basic_commands)
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 }
61 self.card.read_aids()
62 self.poutput('AIDs on card: %s' % (self.card._aids))
63 self.numeric_path = False
64 self.add_settable(cmd2.Settable('numeric_path', bool, 'Print File IDs instead of names',
65 onchange_cb=self._onchange_numeric_path))
66 self.update_prompt()
67
68 def _onchange_numeric_path(self, param_name, old, new):
69 self.update_prompt()
70
71 def update_prompt(self):
72 path_list = self.rs.selected_file.fully_qualified_path(not self.numeric_path)
73 self.prompt = 'pySIM-shell (%s)> ' % ('/'.join(path_list))
74
75 @cmd2.with_category(CUSTOM_CATEGORY)
76 def do_intro(self, _):
77 """Display the intro banner"""
78 self.poutput(self.intro)
79
80 @cmd2.with_category(CUSTOM_CATEGORY)
81 def do_verify_adm(self, arg):
82 """VERIFY the ADM1 PIN"""
83 pin_adm = sanitize_pin_adm(arg)
84 self.card.verify_adm(h2b(pin_adm))
85
86
87
88@with_default_category('ISO7816 Commands')
89class Iso7816Commands(CommandSet):
90 def __init__(self):
91 super().__init__()
92
93 def do_select(self, opts):
94 """SELECT a File (ADF/DF/EF)"""
95 path = opts.arg_list[0]
96 fcp_dec = self._cmd.rs.select(path, self._cmd)
97 self._cmd.update_prompt()
98 self._cmd.poutput(json.dumps(fcp_dec, indent=4))
99
100 def complete_select(self, text, line, begidx, endidx) -> List[str]:
101 """Command Line tab completion for SELECT"""
102 index_dict = { 1: self._cmd.rs.selected_file.get_selectable_names() }
103 return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict)
104
105 verify_chv_parser = argparse.ArgumentParser()
106 verify_chv_parser.add_argument('--chv-nr', type=int, default=1, help='CHV Number')
107 verify_chv_parser.add_argument('code', help='CODE/PIN/PUK')
108
109 @cmd2.with_argparser(verify_chv_parser)
110 def do_verify_chv(self, opts):
111 """Verify (authenticate) using specified CHV (PIN)"""
112 (data, sw) = self._cmd.card._scc.verify_chv(opts.chv_nr, opts.code)
113 self._cmd.poutput(data)
114
Philipp Maier5d3e2592021-02-22 17:22:16 +0100115 dir_parser = argparse.ArgumentParser()
116 dir_parser.add_argument('--fids', help='Show file identifiers', action='store_true')
117 dir_parser.add_argument('--names', help='Show file names', action='store_true')
118 dir_parser.add_argument('--apps', help='Show applications', action='store_true')
119 dir_parser.add_argument('--all', help='Show all selectable identifiers and names', action='store_true')
120
121 @cmd2.with_argparser(dir_parser)
122 def do_dir(self, opts):
123 """Show a listing of files available in currently selected DF or MF"""
124 if opts.all:
125 flags = []
126 elif opts.fids or opts.names or opts.apps:
127 flags = ['PARENT', 'SELF']
128 if opts.fids:
129 flags += ['FIDS', 'AIDS']
130 if opts.names:
131 flags += ['FNAMES', 'ANAMES']
132 if opts.apps:
133 flags += ['ANAMES', 'AIDS']
134 else:
135 flags = ['PARENT', 'SELF', 'FNAMES', 'ANAMES']
136 selectables = list(self._cmd.rs.selected_file.get_selectable_names(flags = flags))
137 directory_str = tabulate_str_list(selectables, width = 79, hspace = 2, lspace = 1, align_left = True)
138 path_list = self._cmd.rs.selected_file.fully_qualified_path(True)
139 self._cmd.poutput('/'.join(path_list))
140 path_list = self._cmd.rs.selected_file.fully_qualified_path(False)
141 self._cmd.poutput('/'.join(path_list))
142 self._cmd.poutput(directory_str)
143 self._cmd.poutput("%d files" % len(selectables))
Harald Welteb2edd142021-01-08 23:29:35 +0100144
Philipp Maierff9dae22021-02-25 17:03:21 +0100145 def walk(self, indent = 0, action = None, context = None):
146 """Recursively walk through the file system, starting at the currently selected DF"""
147 files = self._cmd.rs.selected_file.get_selectables(flags = ['FNAMES', 'ANAMES'])
148 for f in files:
149 if not action:
150 output_str = " " * indent + str(f) + (" " * 250)
151 output_str = output_str[0:25]
152 if isinstance(files[f], CardADF):
153 output_str += " " + str(files[f].aid)
154 else:
155 output_str += " " + str(files[f].fid)
156 output_str += " " + str(files[f].desc)
157 self._cmd.poutput(output_str)
158 if isinstance(files[f], CardDF):
159 fcp_dec = self._cmd.rs.select(f, self._cmd)
160 self.walk(indent + 1, action, context)
161 fcp_dec = self._cmd.rs.select("..", self._cmd)
162 elif action:
163 action(f, context)
164
165 def do_tree(self, opts):
166 """Display a filesystem-tree with all selectable files"""
167 self.walk()
168
Harald Welteb2edd142021-01-08 23:29:35 +0100169
170
171@with_default_category('USIM Commands')
172class UsimCommands(CommandSet):
173 def __init__(self):
174 super().__init__()
175
176 def do_read_ust(self, _):
177 """Read + Display the EF.UST"""
178 self._cmd.card.select_adf_by_aid(adf="usim")
179 (res, sw) = self._cmd.card.read_ust()
180 self._cmd.poutput(res[0])
181 self._cmd.poutput(res[1])
182
183 def do_read_ehplmn(self, _):
184 """Read EF.EHPLMN"""
185 self._cmd.card.select_adf_by_aid(adf="usim")
186 (res, sw) = self._cmd.card.read_ehplmn()
187 self._cmd.poutput(res)
188
189def parse_options():
190
191 parser = OptionParser(usage="usage: %prog [options]")
192
193 parser.add_option("-d", "--device", dest="device", metavar="DEV",
194 help="Serial Device for SIM access [default: %default]",
195 default="/dev/ttyUSB0",
196 )
197 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
198 help="Baudrate used for SIM access [default: %default]",
199 default=9600,
200 )
201 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
202 help="Which PC/SC reader number for SIM access",
203 default=None,
204 )
205 parser.add_option("--modem-device", dest="modem_dev", metavar="DEV",
206 help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)",
207 default=None,
208 )
209 parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD",
210 help="Baudrate used for modem's port [default: %default]",
211 default=115200,
212 )
213 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
214 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
215 default=None,
216 )
217
218 parser.add_option("-a", "--pin-adm", dest="pin_adm",
219 help="ADM PIN used for provisioning (overwrites default)",
220 )
221 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
222 help="ADM PIN used for provisioning, as hex string (16 characters long",
223 )
224
225 (options, args) = parser.parse_args()
226
227 if args:
228 parser.error("Extraneous arguments")
229
230 return options
231
232
233
234if __name__ == '__main__':
235
236 # Parse options
237 opts = parse_options()
238
239 # Init card reader driver
240 sl = init_reader(opts)
241 if (sl == None):
242 exit(1)
243
244 # Create command layer
245 scc = SimCardCommands(transport=sl)
246
247 sl.wait_for_card();
248
249 card_handler = card_handler(sl)
250
251 card = card_detect("auto", scc)
252 if card is None:
253 print("No card detected!")
254 sys.exit(2)
255
256 profile = CardProfileUICC()
257 rs = RuntimeState(card, profile)
258
259 # FIXME: do this dynamically
260 rs.mf.add_file(DF_TELECOM())
261 rs.mf.add_file(DF_GSM())
262 rs.mf.add_application(ADF_USIM())
263 rs.mf.add_application(ADF_ISIM())
264
265 app = PysimApp(card, rs)
Philipp Maier9c1a4ec2021-03-10 12:38:15 +0100266 rs.select('MF', app)
Harald Welteb2edd142021-01-08 23:29:35 +0100267 app.cmdloop()