blob: 33aec125fc7459293205b8c7d37d253365e90097 [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- coding: utf-8 -*-
2
3""" pySim: SIM Card commands according to ISO 7816-4 and TS 11.11
4"""
5
6#
7# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
8# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
9#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.
22#
23
Harald Welte15fae982021-04-10 10:22:27 +020024from construct import *
25from pySim.construct import LV
Philipp Maier46f09af2021-03-25 20:24:27 +010026from pySim.utils import rpad, b2h, sw_match
27from pySim.exceptions import SwMatchError
Sylvain Munaut76504e02010-12-07 00:24:32 +010028
29class SimCardCommands(object):
30 def __init__(self, transport):
Daniel Willmann677d41b2020-10-19 10:34:31 +020031 self._tp = transport
Jan Balke14b350f2015-01-26 11:15:25 +010032 self._cla_byte = "a0"
Philipp Maier41460862017-03-21 12:05:30 +010033 self.sel_ctrl = "0000"
Jan Balke14b350f2015-01-26 11:15:25 +010034
Philipp Maiercdfdd412019-12-20 13:39:24 +010035 # Extract a single FCP item from TLV
36 def __parse_fcp(self, fcp):
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020037 # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF,
38 # DF or ADF
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020039 from pytlv.TLV import TLV
Philipp Maier91f26d72019-03-20 12:12:51 +010040 tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b', '8c', '80', 'ab', 'c6', '81', '88'])
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020041
42 # pytlv is case sensitive!
43 fcp = fcp.lower()
44
45 if fcp[0:2] != '62':
46 raise ValueError('Tag of the FCP template does not match, expected 62 but got %s'%fcp[0:2])
47
48 # Unfortunately the spec is not very clear if the FCP length is
49 # coded as one or two byte vale, so we have to try it out by
50 # checking if the length of the remaining TLV string matches
51 # what we get in the length field.
52 # See also ETSI TS 102 221, chapter 11.1.1.3.0 Base coding.
53 exp_tlv_len = int(fcp[2:4], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070054 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020055 skip = 4
56 else:
57 exp_tlv_len = int(fcp[2:6], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070058 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020059 skip = 6
60
61 # Skip FCP tag and length
62 tlv = fcp[skip:]
Philipp Maiercdfdd412019-12-20 13:39:24 +010063 return tlvparser.parse(tlv)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020064
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020065 # Tell the length of a record by the card response
66 # USIMs respond with an FCP template, which is different
67 # from what SIMs responds. See also:
68 # USIM: ETSI TS 102 221, chapter 11.1.1.3 Response Data
69 # SIM: GSM 11.11, chapter 9.2.1 SELECT
Harald Welteee3501f2021-04-02 13:00:18 +020070 def __record_len(self, r) -> int:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020071 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010072 tlv_parsed = self.__parse_fcp(r[-1])
73 file_descriptor = tlv_parsed['82']
74 # See also ETSI TS 102 221, chapter 11.1.1.4.3 File Descriptor
75 return int(file_descriptor[4:8], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020076 else:
77 return int(r[-1][28:30], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020078
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020079 # Tell the length of a binary file. See also comment
80 # above.
Harald Welteee3501f2021-04-02 13:00:18 +020081 def __len(self, r) -> int:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020082 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010083 tlv_parsed = self.__parse_fcp(r[-1])
84 return int(tlv_parsed['80'], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020085 else:
86 return int(r[-1][4:8], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020087
Harald Welteee3501f2021-04-02 13:00:18 +020088 def get_atr(self) -> str:
89 """Return the ATR of the currently inserted card."""
Alexander Chemerisd2d660a2017-07-18 16:52:25 +030090 return self._tp.get_atr()
91
Jan Balke14b350f2015-01-26 11:15:25 +010092 @property
93 def cla_byte(self):
94 return self._cla_byte
95 @cla_byte.setter
96 def cla_byte(self, value):
97 self._cla_byte = value
98
Philipp Maier41460862017-03-21 12:05:30 +010099 @property
100 def sel_ctrl(self):
101 return self._sel_ctrl
102 @sel_ctrl.setter
103 def sel_ctrl(self, value):
104 self._sel_ctrl = value
Sylvain Munaut76504e02010-12-07 00:24:32 +0100105
Harald Weltec0499c82021-01-21 16:06:50 +0100106 def try_select_path(self, dir_list):
Harald Welteee3501f2021-04-02 13:00:18 +0200107 """ Try to select a specified path given as list of hex-string FIDs"""
Harald Welteca673942020-06-03 15:19:40 +0200108 rv = []
109 if type(dir_list) is not list:
110 dir_list = [dir_list]
111 for i in dir_list:
112 data, sw = self._tp.send_apdu(self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
113 rv.append((data, sw))
114 if sw != '9000':
115 return rv
116 return rv
117
Harald Weltec0499c82021-01-21 16:06:50 +0100118 def select_path(self, dir_list):
Harald Welteee3501f2021-04-02 13:00:18 +0200119 """Execute SELECT for an entire list/path of FIDs.
120
121 Args:
122 dir_list: list of FIDs representing the path to select
123
124 Returns:
125 list of return values (FCP in hex encoding) for each element of the path
126 """
Sylvain Munaut76504e02010-12-07 00:24:32 +0100127 rv = []
Vadim Yanitskiyedf873d2020-02-27 01:40:14 +0700128 if type(dir_list) is not list:
129 dir_list = [dir_list]
Sylvain Munaut76504e02010-12-07 00:24:32 +0100130 for i in dir_list:
Harald Welte85484a92021-01-21 16:08:56 +0100131 data, sw = self.select_file(i)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100132 rv.append(data)
133 return rv
134
Harald Welteee3501f2021-04-02 13:00:18 +0200135 def select_file(self, fid:str):
136 """Execute SELECT a given file by FID."""
Harald Welte85484a92021-01-21 16:08:56 +0100137 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
138
Harald Welteee3501f2021-04-02 13:00:18 +0200139 def select_adf(self, aid:str):
140 """Execute SELECT a given Applicaiton ADF."""
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700141 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100142 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
143
Harald Welteee3501f2021-04-02 13:00:18 +0200144 def read_binary(self, ef, length:int=None, offset:int=0):
145 """Execute READD BINARY.
146
147 Args:
148 ef : string or list of strings indicating name or path of transparent EF
149 length : number of bytes to read
150 offset : byte offset in file from which to start reading
151 """
Harald Weltec0499c82021-01-21 16:06:50 +0100152 r = self.select_path(ef)
Max5491c482019-01-03 11:29:25 +0100153 if len(r[-1]) == 0:
154 return (None, None)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100155 if length is None:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200156 length = self.__len(r) - offset
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100157 total_data = ''
158 while offset < length:
159 chunk_len = min(255, length-offset)
160 pdu = self.cla_byte + 'b0%04x%02x' % (offset, chunk_len)
161 data,sw = self._tp.send_apdu(pdu)
162 if sw == '9000':
163 total_data += data
164 offset += chunk_len
165 else:
166 raise ValueError('Failed to read (offset %d)' % (offset))
167 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100168
Harald Welteee3501f2021-04-02 13:00:18 +0200169 def update_binary(self, ef, data:str, offset:int=0, verify:bool=False, conserve:bool=False):
170 """Execute UPDATE BINARY.
171
172 Args:
173 ef : string or list of strings indicating name or path of transparent EF
174 data : hex string of data to be written
175 offset : byte offset in file from which to start writing
176 verify : Whether or not to verify data after write
177 """
Philipp Maier38c74f62021-03-17 17:19:52 +0100178 data_length = len(data) // 2
179
180 # Save write cycles by reading+comparing before write
181 if conserve:
182 data_current, sw = self.read_binary(ef, data_length, offset)
183 if data_current == data:
184 return None, sw
185
Harald Weltec0499c82021-01-21 16:06:50 +0100186 self.select_path(ef)
Philipp Maier38c74f62021-03-17 17:19:52 +0100187 pdu = self.cla_byte + 'd6%04x%02x' % (offset, data_length) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200188 res = self._tp.send_apdu_checksw(pdu)
189 if verify:
190 self.verify_binary(ef, data, offset)
191 return res
192
Harald Welteee3501f2021-04-02 13:00:18 +0200193 def verify_binary(self, ef, data:str, offset:int=0):
194 """Verify contents of transparent EF.
195
196 Args:
197 ef : string or list of strings indicating name or path of transparent EF
198 data : hex string of expected data
199 offset : byte offset in file from which to start verifying
200 """
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200201 res = self.read_binary(ef, len(data) // 2, offset)
202 if res[0].lower() != data.lower():
203 raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100204
Harald Welteee3501f2021-04-02 13:00:18 +0200205 def read_record(self, ef, rec_no:int):
206 """Execute READ RECORD.
207
208 Args:
209 ef : string or list of strings indicating name or path of linear fixed EF
210 rec_no : record number to read
211 """
Harald Weltec0499c82021-01-21 16:06:50 +0100212 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200213 rec_length = self.__record_len(r)
Jan Balke14b350f2015-01-26 11:15:25 +0100214 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100215 return self._tp.send_apdu(pdu)
216
Harald Welteee3501f2021-04-02 13:00:18 +0200217 def update_record(self, ef, rec_no:int, data:str, force_len:bool=False, verify:bool=False,
218 conserve:bool=False):
Harald Weltec0499c82021-01-21 16:06:50 +0100219 r = self.select_path(ef)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100220 if not force_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200221 rec_length = self.__record_len(r)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700222 if (len(data) // 2 != rec_length):
223 raise ValueError('Invalid data length (expected %d, got %d)' % (rec_length, len(data) // 2))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100224 else:
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700225 rec_length = len(data) // 2
Philipp Maier38c74f62021-03-17 17:19:52 +0100226
227 # Save write cycles by reading+comparing before write
228 if conserve:
229 data_current, sw = self.read_record(ef, rec_no)
230 data_current = data_current[0:rec_length*2]
231 if data_current == data:
232 return None, sw
233
Jan Balke14b350f2015-01-26 11:15:25 +0100234 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200235 res = self._tp.send_apdu_checksw(pdu)
236 if verify:
237 self.verify_record(ef, rec_no, data)
238 return res
239
Harald Welteee3501f2021-04-02 13:00:18 +0200240 def verify_record(self, ef, rec_no:int, data:str):
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200241 res = self.read_record(ef, rec_no)
242 if res[0].lower() != data.lower():
243 raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100244
245 def record_size(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200246 """Determine the record size of given file.
247
248 Args:
249 ef : string or list of strings indicating name or path of linear fixed EF
250 """
Harald Weltec0499c82021-01-21 16:06:50 +0100251 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200252 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100253
254 def record_count(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200255 """Determine the number of records in given file.
256
257 Args:
258 ef : string or list of strings indicating name or path of linear fixed EF
259 """
Harald Weltec0499c82021-01-21 16:06:50 +0100260 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200261 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100262
Philipp Maier32daaf52020-05-11 21:48:33 +0200263 def binary_size(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200264 """Determine the size of given transparent file.
265
266 Args:
267 ef : string or list of strings indicating name or path of transparent EF
268 """
Harald Weltec0499c82021-01-21 16:06:50 +0100269 r = self.select_path(ef)
Philipp Maier32daaf52020-05-11 21:48:33 +0200270 return self.__len(r)
271
Harald Welteee3501f2021-04-02 13:00:18 +0200272 def run_gsm(self, rand:str):
273 """Execute RUN GSM ALGORITHM."""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100274 if len(rand) != 32:
275 raise ValueError('Invalid rand')
Harald Weltec0499c82021-01-21 16:06:50 +0100276 self.select_path(['3f00', '7f20'])
Jan Balke14b350f2015-01-26 11:15:25 +0100277 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100278
Harald Welte15fae982021-04-10 10:22:27 +0200279 def authenticate(self, rand:str, autn:str, context='3g'):
280 """Execute AUTHENTICATE (USIM/ISIM)."""
281 # 3GPP TS 31.102 Section 7.1.2.1
282 AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV))
283 AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV)
284 AuthResp3GSuccess = Struct(Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV))
285 AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess)
286 # build parameters
287 cmd_data = {'rand': rand, 'autn': autn}
288 if context == '3g':
289 p2 = '81'
290 elif context == 'gsm':
291 p2 = '80'
292 (data, sw) = self._tp.send_apdu_constr(self.cla_byte, '88', '00', p2, AuthCmd3G, cmd_data, AuthResp3G)
293 if 'auts' in data:
294 ret = {'synchronisation_failure': data}
295 else:
296 ret = {'successful_3g_authentication': data}
297 return (ret, sw)
298
Harald Weltea4631612021-04-10 18:17:55 +0200299 def deactivate_file(self):
300 """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14."""
301 return self._tp.send_apdu_constr_checksw(self.cla_byte, '04', '00', '00', None, None, None)
302
303 def activate_file(self):
304 """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15."""
305 return self._tp.send_apdu_constr_checksw(self.cla_byte, '44', '00', '00', None, None, None)
306
Harald Welte703f9332021-04-10 18:39:32 +0200307 def manage_channel(self, mode='open', lchan_nr=0):
308 """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17."""
309 if mode == 'close':
310 p1 = 0x80
311 else:
312 p1 = 0x00
313 pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr)
314 return self._tp.send_apdu_checksw(pdu)
315
Sylvain Munaut76504e02010-12-07 00:24:32 +0100316 def reset_card(self):
Harald Welteee3501f2021-04-02 13:00:18 +0200317 """Physically reset the card"""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100318 return self._tp.reset_card()
319
Philipp Maier46f09af2021-03-25 20:24:27 +0100320 def _chv_process_sw(self, op_name, chv_no, pin_code, sw):
321 if sw_match(sw, '63cx'):
322 raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' %
323 (op_name, chv_no, b2h(pin_code).upper(), int(sw[3])))
324 elif (sw != '9000'):
325 raise SwMatchError(sw, '9000')
326
Harald Welteee3501f2021-04-02 13:00:18 +0200327 def verify_chv(self, chv_no:int, code:str):
328 """Verify a given CHV (Card Holder Verification == PIN)"""
329 fc = rpad(b2h(code), 16)
Philipp Maiera31e9a92021-03-11 13:46:32 +0100330 data, sw = self._tp.send_apdu(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
Harald Welteee3501f2021-04-02 13:00:18 +0200331 self._chv_process_sw('verify', chv_no, code, sw)
Philipp Maier46f09af2021-03-25 20:24:27 +0100332 return (data, sw)
333
Harald Welteee3501f2021-04-02 13:00:18 +0200334 def unblock_chv(self, chv_no:int, puk_code:str, pin_code:str):
335 """Unblock a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100336 fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16)
337 data, sw = self._tp.send_apdu(self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc)
338 self._chv_process_sw('unblock', chv_no, pin_code, sw)
339 return (data, sw)
340
Harald Welteee3501f2021-04-02 13:00:18 +0200341 def change_chv(self, chv_no:int, pin_code:str, new_pin_code:str):
342 """Change a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100343 fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16)
344 data, sw = self._tp.send_apdu(self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc)
345 self._chv_process_sw('change', chv_no, pin_code, sw)
346 return (data, sw)
347
Harald Welteee3501f2021-04-02 13:00:18 +0200348 def disable_chv(self, chv_no:int, pin_code:str):
349 """Disable a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100350 fc = rpad(b2h(pin_code), 16)
351 data, sw = self._tp.send_apdu(self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc)
352 self._chv_process_sw('disable', chv_no, pin_code, sw)
353 return (data, sw)
354
Harald Welteee3501f2021-04-02 13:00:18 +0200355 def enable_chv(self, chv_no:int, pin_code:str):
356 """Enable a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100357 fc = rpad(b2h(pin_code), 16)
358 data, sw = self._tp.send_apdu(self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc)
359 self._chv_process_sw('enable', chv_no, pin_code, sw)
360 return (data, sw)