blob: ce9630a52ac16c614b39a15979d49515f56185cf [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
41from pySim.utils import dec_st, init_reader, sanitize_pin_adm
42from pySim.card_handler import card_handler
43
44from pySim.filesystem import CardMF, RuntimeState
45from 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
115
116
117
118@with_default_category('USIM Commands')
119class UsimCommands(CommandSet):
120 def __init__(self):
121 super().__init__()
122
123 def do_read_ust(self, _):
124 """Read + Display the EF.UST"""
125 self._cmd.card.select_adf_by_aid(adf="usim")
126 (res, sw) = self._cmd.card.read_ust()
127 self._cmd.poutput(res[0])
128 self._cmd.poutput(res[1])
129
130 def do_read_ehplmn(self, _):
131 """Read EF.EHPLMN"""
132 self._cmd.card.select_adf_by_aid(adf="usim")
133 (res, sw) = self._cmd.card.read_ehplmn()
134 self._cmd.poutput(res)
135
136def parse_options():
137
138 parser = OptionParser(usage="usage: %prog [options]")
139
140 parser.add_option("-d", "--device", dest="device", metavar="DEV",
141 help="Serial Device for SIM access [default: %default]",
142 default="/dev/ttyUSB0",
143 )
144 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
145 help="Baudrate used for SIM access [default: %default]",
146 default=9600,
147 )
148 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
149 help="Which PC/SC reader number for SIM access",
150 default=None,
151 )
152 parser.add_option("--modem-device", dest="modem_dev", metavar="DEV",
153 help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)",
154 default=None,
155 )
156 parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD",
157 help="Baudrate used for modem's port [default: %default]",
158 default=115200,
159 )
160 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
161 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
162 default=None,
163 )
164
165 parser.add_option("-a", "--pin-adm", dest="pin_adm",
166 help="ADM PIN used for provisioning (overwrites default)",
167 )
168 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
169 help="ADM PIN used for provisioning, as hex string (16 characters long",
170 )
171
172 (options, args) = parser.parse_args()
173
174 if args:
175 parser.error("Extraneous arguments")
176
177 return options
178
179
180
181if __name__ == '__main__':
182
183 # Parse options
184 opts = parse_options()
185
186 # Init card reader driver
187 sl = init_reader(opts)
188 if (sl == None):
189 exit(1)
190
191 # Create command layer
192 scc = SimCardCommands(transport=sl)
193
194 sl.wait_for_card();
195
196 card_handler = card_handler(sl)
197
198 card = card_detect("auto", scc)
199 if card is None:
200 print("No card detected!")
201 sys.exit(2)
202
203 profile = CardProfileUICC()
204 rs = RuntimeState(card, profile)
205
206 # FIXME: do this dynamically
207 rs.mf.add_file(DF_TELECOM())
208 rs.mf.add_file(DF_GSM())
209 rs.mf.add_application(ADF_USIM())
210 rs.mf.add_application(ADF_ISIM())
211
212 app = PysimApp(card, rs)
213 app.cmdloop()