Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 1 | # -*- 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> |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 8 | # Copyright (C) 2010-2021 Harald Welte <laforge@gnumonks.org> |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 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 Welte | 15fae98 | 2021-04-10 10:22:27 +0200 | [diff] [blame] | 24 | from construct import * |
| 25 | from pySim.construct import LV |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 26 | from pySim.utils import rpad, b2h, h2b, sw_match, bertlv_encode_len |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 27 | from pySim.exceptions import SwMatchError |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 28 | |
| 29 | class SimCardCommands(object): |
| 30 | def __init__(self, transport): |
Daniel Willmann | 677d41b | 2020-10-19 10:34:31 +0200 | [diff] [blame] | 31 | self._tp = transport |
Harald Welte | 0f96c02 | 2021-05-23 14:07:23 +0200 | [diff] [blame] | 32 | self.cla_byte = "a0" |
Philipp Maier | 4146086 | 2017-03-21 12:05:30 +0100 | [diff] [blame] | 33 | self.sel_ctrl = "0000" |
Jan Balke | 14b350f | 2015-01-26 11:15:25 +0100 | [diff] [blame] | 34 | |
Philipp Maier | cdfdd41 | 2019-12-20 13:39:24 +0100 | [diff] [blame] | 35 | # Extract a single FCP item from TLV |
| 36 | def __parse_fcp(self, fcp): |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 37 | # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF, |
| 38 | # DF or ADF |
Denis 'GNUtoo' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 39 | from pytlv.TLV import TLV |
Philipp Maier | 91f26d7 | 2019-03-20 12:12:51 +0100 | [diff] [blame] | 40 | tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b', '8c', '80', 'ab', 'c6', '81', '88']) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 41 | |
| 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 Yanitskiy | 99affe1 | 2020-02-15 05:03:09 +0700 | [diff] [blame] | 54 | if len(fcp[4:]) // 2 == exp_tlv_len: |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 55 | skip = 4 |
| 56 | else: |
| 57 | exp_tlv_len = int(fcp[2:6], 16) |
Vadim Yanitskiy | 99affe1 | 2020-02-15 05:03:09 +0700 | [diff] [blame] | 58 | if len(fcp[4:]) // 2 == exp_tlv_len: |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 59 | skip = 6 |
| 60 | |
| 61 | # Skip FCP tag and length |
| 62 | tlv = fcp[skip:] |
Philipp Maier | cdfdd41 | 2019-12-20 13:39:24 +0100 | [diff] [blame] | 63 | return tlvparser.parse(tlv) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 64 | |
Denis 'GNUtoo' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 65 | # 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 Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 70 | def __record_len(self, r) -> int: |
Denis 'GNUtoo' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 71 | if self.sel_ctrl == "0004": |
Philipp Maier | cdfdd41 | 2019-12-20 13:39:24 +0100 | [diff] [blame] | 72 | 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' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 76 | else: |
| 77 | return int(r[-1][28:30], 16) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 78 | |
Denis 'GNUtoo' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 79 | # Tell the length of a binary file. See also comment |
| 80 | # above. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 81 | def __len(self, r) -> int: |
Denis 'GNUtoo' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 82 | if self.sel_ctrl == "0004": |
Philipp Maier | cdfdd41 | 2019-12-20 13:39:24 +0100 | [diff] [blame] | 83 | tlv_parsed = self.__parse_fcp(r[-1]) |
| 84 | return int(tlv_parsed['80'], 16) |
Denis 'GNUtoo' Carikli | 84d2cb3 | 2019-09-12 01:46:25 +0200 | [diff] [blame] | 85 | else: |
| 86 | return int(r[-1][4:8], 16) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 87 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 88 | def get_atr(self) -> str: |
| 89 | """Return the ATR of the currently inserted card.""" |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 90 | return self._tp.get_atr() |
| 91 | |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 92 | def try_select_path(self, dir_list): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 93 | """ Try to select a specified path given as list of hex-string FIDs""" |
Harald Welte | ca67394 | 2020-06-03 15:19:40 +0200 | [diff] [blame] | 94 | rv = [] |
| 95 | if type(dir_list) is not list: |
| 96 | dir_list = [dir_list] |
| 97 | for i in dir_list: |
| 98 | data, sw = self._tp.send_apdu(self.cla_byte + "a4" + self.sel_ctrl + "02" + i) |
| 99 | rv.append((data, sw)) |
| 100 | if sw != '9000': |
| 101 | return rv |
| 102 | return rv |
| 103 | |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 104 | def select_path(self, dir_list): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 105 | """Execute SELECT for an entire list/path of FIDs. |
| 106 | |
| 107 | Args: |
| 108 | dir_list: list of FIDs representing the path to select |
| 109 | |
| 110 | Returns: |
| 111 | list of return values (FCP in hex encoding) for each element of the path |
| 112 | """ |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 113 | rv = [] |
Vadim Yanitskiy | edf873d | 2020-02-27 01:40:14 +0700 | [diff] [blame] | 114 | if type(dir_list) is not list: |
| 115 | dir_list = [dir_list] |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 116 | for i in dir_list: |
Harald Welte | 85484a9 | 2021-01-21 16:08:56 +0100 | [diff] [blame] | 117 | data, sw = self.select_file(i) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 118 | rv.append(data) |
| 119 | return rv |
| 120 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 121 | def select_file(self, fid:str): |
| 122 | """Execute SELECT a given file by FID.""" |
Harald Welte | 85484a9 | 2021-01-21 16:08:56 +0100 | [diff] [blame] | 123 | return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid) |
| 124 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 125 | def select_adf(self, aid:str): |
| 126 | """Execute SELECT a given Applicaiton ADF.""" |
Vadim Yanitskiy | 99affe1 | 2020-02-15 05:03:09 +0700 | [diff] [blame] | 127 | aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:] |
Philipp Maier | 0ad5bcf | 2019-12-31 17:55:47 +0100 | [diff] [blame] | 128 | return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid) |
| 129 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 130 | def read_binary(self, ef, length:int=None, offset:int=0): |
| 131 | """Execute READD BINARY. |
| 132 | |
| 133 | Args: |
| 134 | ef : string or list of strings indicating name or path of transparent EF |
| 135 | length : number of bytes to read |
| 136 | offset : byte offset in file from which to start reading |
| 137 | """ |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 138 | r = self.select_path(ef) |
Max | 5491c48 | 2019-01-03 11:29:25 +0100 | [diff] [blame] | 139 | if len(r[-1]) == 0: |
| 140 | return (None, None) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 141 | if length is None: |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 142 | length = self.__len(r) - offset |
Sebastian Viviani | 0e9f93f | 2020-04-17 16:42:09 +0100 | [diff] [blame] | 143 | total_data = '' |
| 144 | while offset < length: |
| 145 | chunk_len = min(255, length-offset) |
| 146 | pdu = self.cla_byte + 'b0%04x%02x' % (offset, chunk_len) |
| 147 | data,sw = self._tp.send_apdu(pdu) |
| 148 | if sw == '9000': |
| 149 | total_data += data |
| 150 | offset += chunk_len |
| 151 | else: |
| 152 | raise ValueError('Failed to read (offset %d)' % (offset)) |
| 153 | return total_data, sw |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 154 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 155 | def update_binary(self, ef, data:str, offset:int=0, verify:bool=False, conserve:bool=False): |
| 156 | """Execute UPDATE BINARY. |
| 157 | |
| 158 | Args: |
| 159 | ef : string or list of strings indicating name or path of transparent EF |
| 160 | data : hex string of data to be written |
| 161 | offset : byte offset in file from which to start writing |
| 162 | verify : Whether or not to verify data after write |
| 163 | """ |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 164 | data_length = len(data) // 2 |
| 165 | |
| 166 | # Save write cycles by reading+comparing before write |
| 167 | if conserve: |
| 168 | data_current, sw = self.read_binary(ef, data_length, offset) |
| 169 | if data_current == data: |
| 170 | return None, sw |
| 171 | |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 172 | self.select_path(ef) |
andrew-ma | 2e6dc03 | 2021-07-31 22:18:24 -0700 | [diff] [blame] | 173 | total_data = '' |
| 174 | total_sw = "9000" |
| 175 | chunk_offset = offset |
| 176 | while chunk_offset < data_length: |
| 177 | chunk_len = min(255, data_length - chunk_offset) |
| 178 | # chunk_offset is bytes, but data slicing is hex chars, so we need to multiply by 2 |
| 179 | pdu = self.cla_byte + 'd6%04x%02x' % (chunk_offset, chunk_len) + data[chunk_offset*2 : (chunk_offset+chunk_len)*2] |
| 180 | chunk_data, chunk_sw = self._tp.send_apdu(pdu) |
| 181 | if chunk_sw == total_sw: |
| 182 | total_data += chunk_data |
| 183 | chunk_offset += chunk_len |
| 184 | else: |
| 185 | total_sw = chunk_sw |
| 186 | raise ValueError('Failed to write chunk (chunk_offset %d, chunk_len %d)' % (chunk_offset, chunk_len)) |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 187 | if verify: |
| 188 | self.verify_binary(ef, data, offset) |
andrew-ma | 2e6dc03 | 2021-07-31 22:18:24 -0700 | [diff] [blame] | 189 | return total_data, total_sw |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 190 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 191 | def verify_binary(self, ef, data:str, offset:int=0): |
| 192 | """Verify contents of transparent EF. |
| 193 | |
| 194 | Args: |
| 195 | ef : string or list of strings indicating name or path of transparent EF |
| 196 | data : hex string of expected data |
| 197 | offset : byte offset in file from which to start verifying |
| 198 | """ |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 199 | res = self.read_binary(ef, len(data) // 2, offset) |
| 200 | if res[0].lower() != data.lower(): |
| 201 | raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower())) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 202 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 203 | def read_record(self, ef, rec_no:int): |
| 204 | """Execute READ RECORD. |
| 205 | |
| 206 | Args: |
| 207 | ef : string or list of strings indicating name or path of linear fixed EF |
| 208 | rec_no : record number to read |
| 209 | """ |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 210 | r = self.select_path(ef) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 211 | rec_length = self.__record_len(r) |
Jan Balke | 14b350f | 2015-01-26 11:15:25 +0100 | [diff] [blame] | 212 | pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 213 | return self._tp.send_apdu(pdu) |
| 214 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 215 | def update_record(self, ef, rec_no:int, data:str, force_len:bool=False, verify:bool=False, |
| 216 | conserve:bool=False): |
Philipp Maier | 42804d7 | 2021-04-30 11:56:23 +0200 | [diff] [blame] | 217 | res = self.select_path(ef) |
| 218 | |
| 219 | if force_len: |
| 220 | # enforce the record length by the actual length of the given data input |
Vadim Yanitskiy | 99affe1 | 2020-02-15 05:03:09 +0700 | [diff] [blame] | 221 | rec_length = len(data) // 2 |
Philipp Maier | 42804d7 | 2021-04-30 11:56:23 +0200 | [diff] [blame] | 222 | else: |
| 223 | # determine the record length from the select response of the file and pad |
| 224 | # the input data with 0xFF if necessary. In cases where the input data |
| 225 | # exceed we throw an exception. |
| 226 | rec_length = self.__record_len(res) |
| 227 | if (len(data) // 2 > rec_length): |
| 228 | raise ValueError('Data length exceeds record length (expected max %d, got %d)' % (rec_length, len(data) // 2)) |
| 229 | elif (len(data) // 2 < rec_length): |
| 230 | data = rpad(data, rec_length * 2) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 231 | |
| 232 | # Save write cycles by reading+comparing before write |
| 233 | if conserve: |
| 234 | data_current, sw = self.read_record(ef, rec_no) |
| 235 | data_current = data_current[0:rec_length*2] |
| 236 | if data_current == data: |
| 237 | return None, sw |
| 238 | |
Jan Balke | 14b350f | 2015-01-26 11:15:25 +0100 | [diff] [blame] | 239 | pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 240 | res = self._tp.send_apdu_checksw(pdu) |
| 241 | if verify: |
| 242 | self.verify_record(ef, rec_no, data) |
| 243 | return res |
| 244 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 245 | def verify_record(self, ef, rec_no:int, data:str): |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 246 | res = self.read_record(ef, rec_no) |
| 247 | if res[0].lower() != data.lower(): |
| 248 | raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower())) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 249 | |
| 250 | def record_size(self, ef): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 251 | """Determine the record size of given file. |
| 252 | |
| 253 | Args: |
| 254 | ef : string or list of strings indicating name or path of linear fixed EF |
| 255 | """ |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 256 | r = self.select_path(ef) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 257 | return self.__record_len(r) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 258 | |
| 259 | def record_count(self, ef): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 260 | """Determine the number of records in given file. |
| 261 | |
| 262 | Args: |
| 263 | ef : string or list of strings indicating name or path of linear fixed EF |
| 264 | """ |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 265 | r = self.select_path(ef) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 266 | return self.__len(r) // self.__record_len(r) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 267 | |
Philipp Maier | 32daaf5 | 2020-05-11 21:48:33 +0200 | [diff] [blame] | 268 | def binary_size(self, ef): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 269 | """Determine the size of given transparent file. |
| 270 | |
| 271 | Args: |
| 272 | ef : string or list of strings indicating name or path of transparent EF |
| 273 | """ |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 274 | r = self.select_path(ef) |
Philipp Maier | 32daaf5 | 2020-05-11 21:48:33 +0200 | [diff] [blame] | 275 | return self.__len(r) |
| 276 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 277 | # TS 102 221 Section 11.3.1 low-level helper |
| 278 | def _retrieve_data(self, tag:int, first:bool=True): |
| 279 | if first: |
| 280 | pdu = '80cb008001%02x' % (tag) |
| 281 | else: |
| 282 | pdu = '80cb000000' |
| 283 | return self._tp.send_apdu_checksw(pdu) |
| 284 | |
| 285 | # TS 102 221 Section 11.3.1 |
| 286 | def retrieve_data(self, ef, tag:int): |
| 287 | """Execute RETRIEVE DATA. |
| 288 | |
| 289 | Args |
| 290 | ef : string or list of strings indicating name or path of transparent EF |
| 291 | tag : BER-TLV Tag of value to be retrieved |
| 292 | """ |
| 293 | r = self.select_path(ef) |
| 294 | if len(r[-1]) == 0: |
| 295 | return (None, None) |
| 296 | total_data = '' |
| 297 | # retrieve first block |
| 298 | data, sw = self._retrieve_data(tag, first=True) |
| 299 | total_data += data |
| 300 | while sw == '62f1' or sw == '62f2': |
| 301 | data, sw = self._retrieve_data(tag, first=False) |
| 302 | total_data += data |
| 303 | return total_data, sw |
| 304 | |
| 305 | # TS 102 221 Section 11.3.2 low-level helper |
| 306 | def _set_data(self, data:str, first:bool=True): |
| 307 | if first: |
| 308 | p1 = 0x80 |
| 309 | else: |
| 310 | p1 = 0x00 |
| 311 | if isinstance(data, bytes) or isinstance(data, bytearray): |
| 312 | data = b2h(data) |
| 313 | pdu = '80db00%02x%02x%s' % (p1, len(data)//2, data) |
| 314 | return self._tp.send_apdu_checksw(pdu) |
| 315 | |
| 316 | def set_data(self, ef, tag:int, value:str, verify:bool=False, conserve:bool=False): |
| 317 | """Execute SET DATA. |
| 318 | |
| 319 | Args |
| 320 | ef : string or list of strings indicating name or path of transparent EF |
| 321 | tag : BER-TLV Tag of value to be stored |
| 322 | value : BER-TLV value to be stored |
| 323 | """ |
| 324 | r = self.select_path(ef) |
| 325 | if len(r[-1]) == 0: |
| 326 | return (None, None) |
| 327 | |
| 328 | # in case of deleting the data, we only have 'tag' but no 'value' |
| 329 | if not value: |
| 330 | return self._set_data('%02x' % tag, first=True) |
| 331 | |
| 332 | # FIXME: proper BER-TLV encode |
| 333 | tl = '%02x%s' % (tag, b2h(bertlv_encode_len(len(value)//2))) |
| 334 | tlv = tl + value |
| 335 | tlv_bin = h2b(tlv) |
| 336 | |
| 337 | first = True |
| 338 | total_len = len(tlv_bin) |
| 339 | remaining = tlv_bin |
| 340 | while len(remaining) > 0: |
| 341 | fragment = remaining[:255] |
| 342 | rdata, sw = self._set_data(fragment, first=first) |
| 343 | first = False |
| 344 | remaining = remaining[255:] |
| 345 | return rdata, sw |
| 346 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 347 | def run_gsm(self, rand:str): |
| 348 | """Execute RUN GSM ALGORITHM.""" |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 349 | if len(rand) != 32: |
| 350 | raise ValueError('Invalid rand') |
Harald Welte | c0499c8 | 2021-01-21 16:06:50 +0100 | [diff] [blame] | 351 | self.select_path(['3f00', '7f20']) |
Jan Balke | 14b350f | 2015-01-26 11:15:25 +0100 | [diff] [blame] | 352 | return self._tp.send_apdu(self.cla_byte + '88000010' + rand) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 353 | |
Harald Welte | 15fae98 | 2021-04-10 10:22:27 +0200 | [diff] [blame] | 354 | def authenticate(self, rand:str, autn:str, context='3g'): |
| 355 | """Execute AUTHENTICATE (USIM/ISIM).""" |
| 356 | # 3GPP TS 31.102 Section 7.1.2.1 |
| 357 | AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV)) |
| 358 | AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV) |
| 359 | AuthResp3GSuccess = Struct(Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV)) |
| 360 | AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess) |
| 361 | # build parameters |
| 362 | cmd_data = {'rand': rand, 'autn': autn} |
| 363 | if context == '3g': |
| 364 | p2 = '81' |
| 365 | elif context == 'gsm': |
| 366 | p2 = '80' |
Harald Welte | 59f9a38 | 2021-05-22 00:17:26 +0200 | [diff] [blame] | 367 | (data, sw) = self._tp.send_apdu_constr_checksw(self.cla_byte, '88', '00', p2, AuthCmd3G, cmd_data, AuthResp3G) |
Harald Welte | 15fae98 | 2021-04-10 10:22:27 +0200 | [diff] [blame] | 368 | if 'auts' in data: |
| 369 | ret = {'synchronisation_failure': data} |
| 370 | else: |
| 371 | ret = {'successful_3g_authentication': data} |
| 372 | return (ret, sw) |
| 373 | |
Harald Welte | 34b05d3 | 2021-05-25 22:03:13 +0200 | [diff] [blame] | 374 | def status(self): |
| 375 | """Execute a STATUS command as per TS 102 221 Section 11.1.2.""" |
| 376 | return self._tp.send_apdu_checksw('80F20000ff') |
| 377 | |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 378 | def deactivate_file(self): |
| 379 | """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14.""" |
| 380 | return self._tp.send_apdu_constr_checksw(self.cla_byte, '04', '00', '00', None, None, None) |
| 381 | |
Harald Welte | 485692b | 2021-05-25 22:21:44 +0200 | [diff] [blame] | 382 | def activate_file(self, fid): |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 383 | """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15.""" |
Harald Welte | 485692b | 2021-05-25 22:21:44 +0200 | [diff] [blame] | 384 | return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid) |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 385 | |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 386 | def manage_channel(self, mode='open', lchan_nr=0): |
| 387 | """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17.""" |
| 388 | if mode == 'close': |
| 389 | p1 = 0x80 |
| 390 | else: |
| 391 | p1 = 0x00 |
| 392 | pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr) |
| 393 | return self._tp.send_apdu_checksw(pdu) |
| 394 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 395 | def reset_card(self): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 396 | """Physically reset the card""" |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 397 | return self._tp.reset_card() |
| 398 | |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 399 | def _chv_process_sw(self, op_name, chv_no, pin_code, sw): |
| 400 | if sw_match(sw, '63cx'): |
| 401 | raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' % |
| 402 | (op_name, chv_no, b2h(pin_code).upper(), int(sw[3]))) |
| 403 | elif (sw != '9000'): |
| 404 | raise SwMatchError(sw, '9000') |
| 405 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 406 | def verify_chv(self, chv_no:int, code:str): |
| 407 | """Verify a given CHV (Card Holder Verification == PIN)""" |
| 408 | fc = rpad(b2h(code), 16) |
Philipp Maier | a31e9a9 | 2021-03-11 13:46:32 +0100 | [diff] [blame] | 409 | data, sw = self._tp.send_apdu(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 410 | self._chv_process_sw('verify', chv_no, code, sw) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 411 | return (data, sw) |
| 412 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 413 | def unblock_chv(self, chv_no:int, puk_code:str, pin_code:str): |
| 414 | """Unblock a given CHV (Card Holder Verification == PIN)""" |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 415 | fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16) |
| 416 | data, sw = self._tp.send_apdu(self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc) |
| 417 | self._chv_process_sw('unblock', chv_no, pin_code, sw) |
| 418 | return (data, sw) |
| 419 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 420 | def change_chv(self, chv_no:int, pin_code:str, new_pin_code:str): |
| 421 | """Change a given CHV (Card Holder Verification == PIN)""" |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 422 | fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16) |
| 423 | data, sw = self._tp.send_apdu(self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc) |
| 424 | self._chv_process_sw('change', chv_no, pin_code, sw) |
| 425 | return (data, sw) |
| 426 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 427 | def disable_chv(self, chv_no:int, pin_code:str): |
| 428 | """Disable a given CHV (Card Holder Verification == PIN)""" |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 429 | fc = rpad(b2h(pin_code), 16) |
| 430 | data, sw = self._tp.send_apdu(self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc) |
| 431 | self._chv_process_sw('disable', chv_no, pin_code, sw) |
| 432 | return (data, sw) |
| 433 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 434 | def enable_chv(self, chv_no:int, pin_code:str): |
| 435 | """Enable a given CHV (Card Holder Verification == PIN)""" |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 436 | fc = rpad(b2h(pin_code), 16) |
| 437 | data, sw = self._tp.send_apdu(self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc) |
| 438 | self._chv_process_sw('enable', chv_no, pin_code, sw) |
| 439 | return (data, sw) |
Harald Welte | f201166 | 2021-05-24 23:19:30 +0200 | [diff] [blame] | 440 | |
| 441 | def envelope(self, payload:str): |
| 442 | """Send one ENVELOPE command to the SIM""" |
| 443 | return self._tp.send_apdu_checksw('80c20000%02x%s' % (len(payload)//2, payload)) |
Harald Welte | 846a898 | 2021-10-08 15:47:16 +0200 | [diff] [blame] | 444 | |
| 445 | def terminal_profile(self, payload:str): |
| 446 | """Send TERMINAL PROFILE to card""" |
| 447 | data_length = len(payload) // 2 |
| 448 | data, sw = self._tp.send_apdu(('80100000%02x' % data_length) + payload) |
| 449 | return (data, sw) |