blob: 2c1d600e8399c569fa86f1f95d9342670c1526c4 [file] [log] [blame]
Harald Welte3c9b7842021-10-19 21:44:24 +02001#!/usr/bin/env python3
2
3# Interactive shell for working with SIM / UICC / USIM / ISIM cards
4#
5# (C) 2022 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 cmd2
23from cmd2 import style, fg, bg
24from cmd2 import CommandSet, with_default_category, with_argparser
25import argparse
26
27from pySim.ts_31_102 import EF_UST_map, EF_USIM_ADF_map
28from pySim.ts_31_103 import EF_IST_map, EF_ISIM_ADF_map
29
30from pySim.exceptions import *
31from pySim.utils import h2b, swap_nibbles, b2h, JsonEncoder
32
33from pySim.ts_102_221 import *
34
35@with_default_category('TS 102 222 Administrative Commands')
36class Ts102222Commands(CommandSet):
37 """Administrative commands for telecommunication applications."""
38
39 def __init__(self):
40 super().__init__()
41
42 delfile_parser = argparse.ArgumentParser()
43 delfile_parser.add_argument('--force-delete', action='store_true',
44 help='I really want to permanently delete the file. I know pySim cannot re-create it yet!')
45 delfile_parser.add_argument('NAME', type=str, help='File name or FID to delete')
46
47 @cmd2.with_argparser(delfile_parser)
48 def do_delete_file(self, opts):
49 """Delete the specified file. DANGEROUS! See TS 102 222 Section 6.4.
50 This will permanently delete the specified file from the card.
51 pySim has no support to re-create files yet, and even if it did, your card may not allow it!"""
52 if not opts.force_delete:
53 self._cmd.perror("Refusing to permanently delete the file, please read the help text.")
54 return
55 f = self._cmd.rs.get_file_for_selectable(opts.NAME)
56 (data, sw) = self._cmd.card._scc.delete_file(f.fid)
57
58 def complete_delete_file(self, text, line, begidx, endidx) -> List[str]:
59 """Command Line tab completion for DELETE FILE"""
60 index_dict = {1: self._cmd.rs.selected_file.get_selectable_names()}
61 return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict)
62
63 termdf_parser = argparse.ArgumentParser()
64 termdf_parser.add_argument('--force', action='store_true',
65 help='I really want to terminate the file. I know I can not recover from it!')
66 termdf_parser.add_argument('NAME', type=str, help='File name or FID')
67
68 @cmd2.with_argparser(termdf_parser)
69 def do_terminate_df(self, opts):
70 """Terminate the specified DF. DANGEROUS! See TS 102 222 6.7.
71 This is a permanent, one-way operation on the card. There is no undo, you can not recover
72 a terminated DF. The only permitted command for a terminated DF is the DLETE FILE command."""
73 if not opts.force:
74 self._cmd.perror("Refusing to terminate the file, please read the help text.")
75 return
76 f = self._cmd.rs.get_file_for_selectable(opts.NAME)
77 (data, sw) = self._cmd.card._scc.terminate_df(f.fid)
78
79 def complete_terminate_df(self, text, line, begidx, endidx) -> List[str]:
80 """Command Line tab completion for TERMINATE DF"""
81 index_dict = {1: self._cmd.rs.selected_file.get_selectable_names()}
82 return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict)
83
84 @cmd2.with_argparser(termdf_parser)
85 def do_terminate_ef(self, opts):
86 """Terminate the specified EF. DANGEROUS! See TS 102 222 6.8.
87 This is a permanent, one-way operation on the card. There is no undo, you can not recover
88 a terminated EF. The only permitted command for a terminated EF is the DLETE FILE command."""
89 if not opts.force:
90 self._cmd.perror("Refusing to terminate the file, please read the help text.")
91 return
92 f = self._cmd.rs.get_file_for_selectable(opts.NAME)
93 (data, sw) = self._cmd.card._scc.terminate_ef(f.fid)
94
95 def complete_terminate_ef(self, text, line, begidx, endidx) -> List[str]:
96 """Command Line tab completion for TERMINATE EF"""
97 index_dict = {1: self._cmd.rs.selected_file.get_selectable_names()}
98 return self._cmd.index_based_complete(text, line, begidx, endidx, index_dict=index_dict)
99
100 tcard_parser = argparse.ArgumentParser()
101 tcard_parser.add_argument('--force-terminate-card', action='store_true',
102 help='I really want to permanently terminate the card. It will not be usable afterwards!')
103
104 @cmd2.with_argparser(tcard_parser)
105 def do_terminate_card_usage(self, opts):
106 """Terminate the Card. SUPER DANGEROUS! See TS 102 222 Section 6.9.
107 This will permanently brick the card and can NOT be recovered from!"""
108 if not opts.force_terminate_card:
109 self._cmd.perror("Refusing to permanently terminate the card, please read the help text.")
110 return
111 (data, sw) = self._cmd.card._scc.terminate_card_usage()
112
113 create_parser = argparse.ArgumentParser()
114 create_parser.add_argument('FILE_ID', type=str, help='File Identifier as 4-character hex string')
115 create_parser._action_groups.pop()
116 create_required = create_parser.add_argument_group('required arguments')
117 create_optional = create_parser.add_argument_group('optional arguments')
118 create_required.add_argument('--ef-arr-file-id', required=True, type=str, help='Referenced Security: File Identifier of EF.ARR')
119 create_required.add_argument('--ef-arr-record-nr', required=True, type=int, help='Referenced Security: Record Number within EF.ARR')
120 create_required.add_argument('--file-size', required=True, type=int, help='Size of file in octets')
121 create_required.add_argument('--structure', required=True, type=str, choices=['transparent', 'linear_fixed', 'ber_tlv'],
122 help='Structure of the to-be-created EF')
123 create_optional.add_argument('--short-file-id', type=str, help='Short File Identifier as 2-digit hex string')
124 create_optional.add_argument('--shareable', action='store_true', help='Should the file be shareable?')
125 create_optional.add_argument('--record-length', type=int, help='Length of each record in octets')
126
127 @cmd2.with_argparser(create_parser)
128 def do_create_ef(self, opts):
129 """Create a new EF below the currently selected DF. Requires related privileges."""
130 file_descriptor = {
131 'file_descriptor_byte': {
132 'shareable': opts.shareable,
133 'file_type': 'working_ef',
134 'structure': opts.structure,
135 }
136 }
137 if opts.structure == 'linear_fixed':
138 if not opts.record_length:
139 self._cmd.perror("you must specify the --record-length for linear fixed EF")
140 return
141 file_descriptor['record_len'] = opts.record_length
142 elif opts.structure == 'ber_tlv':
143 self._cmd.perror("BER-TLV creation not yet fully supported, sorry")
144 return
145 ies = [FileDescriptor(decoded=file_descriptor), FileIdentifier(decoded=opts.FILE_ID),
146 LifeCycleStatusInteger(decoded='operational_activated'),
147 SecurityAttribReferenced(decoded={'ef_arr_file_id': opts.ef_arr_file_id,
148 'ef_arr_record_nr': opts.ef_arr_record_nr }),
149 FileSize(decoded=opts.file_size),
150 ShortFileIdentifier(decoded=opts.short_file_id),
151 ]
152 fcp = FcpTemplate(children=ies)
153 (data, sw) = self._cmd.card._scc.create_file(b2h(fcp.to_tlv()))
154 # the newly-created file is automatically selected but our runtime state knows nothing of it
155 self._cmd.rs.select_file(self._cmd.rs.selected_file)
156
157 createdf_parser = argparse.ArgumentParser()
158 createdf_parser.add_argument('FILE_ID', type=str, help='File Identifier as 4-character hex string')
159 createdf_parser._action_groups.pop()
160 createdf_required = createdf_parser.add_argument_group('required arguments')
161 createdf_optional = createdf_parser.add_argument_group('optional arguments')
162 createdf_sja_optional = createdf_parser.add_argument_group('sysmoISIM-SJA optional arguments')
163 createdf_required.add_argument('--ef-arr-file-id', required=True, type=str, help='Referenced Security: File Identifier of EF.ARR')
164 createdf_required.add_argument('--ef-arr-record-nr', required=True, type=int, help='Referenced Security: Record Number within EF.ARR')
165 createdf_optional.add_argument('--shareable', action='store_true', help='Should the file be shareable?')
166 createdf_optional.add_argument('--aid', type=str, help='Application ID (creates an ADF, instead of a DF)')
167 # mandatory by spec, but ignored by several OS, so don't force the user
168 createdf_optional.add_argument('--total-file-size', type=int, help='Physical memory allocated for DF/ADi in octets')
169 createdf_sja_optional.add_argument('--permit-rfm-create', action='store_true')
170 createdf_sja_optional.add_argument('--permit-rfm-delete-terminate', action='store_true')
171 createdf_sja_optional.add_argument('--permit-other-applet-create', action='store_true')
172 createdf_sja_optional.add_argument('--permit-other-applet-delete-terminate', action='store_true')
173
174 @cmd2.with_argparser(createdf_parser)
175 def do_create_df(self, opts):
176 """Create a new DF below the currently selected DF. Requires related privileges."""
177 file_descriptor = {
178 'file_descriptor_byte': {
179 'shareable': opts.shareable,
180 'file_type': 'df',
181 'structure': 'no_info_given',
182 }
183 }
184 ies = []
185 ies.append(FileDescriptor(decoded=file_descriptor))
186 ies.append(FileIdentifier(decoded=opts.FILE_ID))
187 if opts.aid:
188 ies.append(DfName(decoded=opts.aid))
189 ies.append(LifeCycleStatusInteger(decoded='operational_activated'))
190 ies.append(SecurityAttribReferenced(decoded={'ef_arr_file_id': opts.ef_arr_file_id,
191 'ef_arr_record_nr': opts.ef_arr_record_nr }))
192 if opts.total_file_size:
193 ies.append(TotalFileSize(decoded=opts.total_file_size))
194 # TODO: Spec states PIN Status Template DO is mandatory
195 if opts.permit_rfm_create or opts.permit_rfm_delete_terminate or opts.permit_other_applet_create or opts.permit_other_applet_delete_terminate:
196 toolkit_ac = {
197 'rfm_create': opts.permit_rfm_create,
198 'rfm_delete_terminate': opts.permit_rfm_delete_terminate,
199 'other_applet_create': opts.permit_other_applet_create,
200 'other_applet_delete_terminate': opts.permit_other_applet_delete_terminate,
201 }
202 ies.append(ProprietaryInformation(children=[ToolkitAccessConditions(decoded=toolkit_ac)]))
203 fcp = FcpTemplate(children=ies)
204 (data, sw) = self._cmd.card._scc.create_file(b2h(fcp.to_tlv()))
205 # the newly-created file is automatically selected but our runtime state knows nothing of it
206 self._cmd.rs.select_file(self._cmd.rs.selected_file)