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 |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 26 | from pySim.utils import rpad, b2h, h2b, sw_match, bertlv_encode_len, Hexstr, h2i, str_sanitize, expand_hex |
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 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 29 | |
Vadim Yanitskiy | 04b5d9d | 2022-07-07 03:05:30 +0700 | [diff] [blame] | 30 | class SimCardCommands: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 31 | def __init__(self, transport): |
| 32 | self._tp = transport |
| 33 | self.cla_byte = "a0" |
| 34 | self.sel_ctrl = "0000" |
Jan Balke | 14b350f | 2015-01-26 11:15:25 +0100 | [diff] [blame] | 35 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 36 | # Extract a single FCP item from TLV |
| 37 | def __parse_fcp(self, fcp): |
| 38 | # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF, |
| 39 | # DF or ADF |
| 40 | from pytlv.TLV import TLV |
| 41 | tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b', |
| 42 | '8c', '80', 'ab', 'c6', '81', '88']) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 43 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 44 | # pytlv is case sensitive! |
| 45 | fcp = fcp.lower() |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 46 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 47 | if fcp[0:2] != '62': |
| 48 | raise ValueError( |
| 49 | 'Tag of the FCP template does not match, expected 62 but got %s' % fcp[0:2]) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 50 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 51 | # Unfortunately the spec is not very clear if the FCP length is |
| 52 | # coded as one or two byte vale, so we have to try it out by |
| 53 | # checking if the length of the remaining TLV string matches |
| 54 | # what we get in the length field. |
| 55 | # See also ETSI TS 102 221, chapter 11.1.1.3.0 Base coding. |
| 56 | exp_tlv_len = int(fcp[2:4], 16) |
| 57 | if len(fcp[4:]) // 2 == exp_tlv_len: |
| 58 | skip = 4 |
| 59 | else: |
| 60 | exp_tlv_len = int(fcp[2:6], 16) |
| 61 | if len(fcp[4:]) // 2 == exp_tlv_len: |
| 62 | skip = 6 |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 63 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 64 | # Skip FCP tag and length |
| 65 | tlv = fcp[skip:] |
| 66 | return tlvparser.parse(tlv) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 67 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 68 | # Tell the length of a record by the card response |
| 69 | # USIMs respond with an FCP template, which is different |
| 70 | # from what SIMs responds. See also: |
| 71 | # USIM: ETSI TS 102 221, chapter 11.1.1.3 Response Data |
| 72 | # SIM: GSM 11.11, chapter 9.2.1 SELECT |
| 73 | def __record_len(self, r) -> int: |
| 74 | if self.sel_ctrl == "0004": |
| 75 | tlv_parsed = self.__parse_fcp(r[-1]) |
| 76 | file_descriptor = tlv_parsed['82'] |
| 77 | # See also ETSI TS 102 221, chapter 11.1.1.4.3 File Descriptor |
| 78 | return int(file_descriptor[4:8], 16) |
| 79 | else: |
| 80 | return int(r[-1][28:30], 16) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 81 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 82 | # Tell the length of a binary file. See also comment |
| 83 | # above. |
| 84 | def __len(self, r) -> int: |
| 85 | if self.sel_ctrl == "0004": |
| 86 | tlv_parsed = self.__parse_fcp(r[-1]) |
| 87 | return int(tlv_parsed['80'], 16) |
| 88 | else: |
| 89 | return int(r[-1][4:8], 16) |
Philipp Maier | 0e3fcaa | 2018-06-13 12:34:03 +0200 | [diff] [blame] | 90 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 91 | def get_atr(self) -> str: |
| 92 | """Return the ATR of the currently inserted card.""" |
| 93 | return self._tp.get_atr() |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 94 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 95 | def try_select_path(self, dir_list): |
| 96 | """ Try to select a specified path |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 97 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 98 | Args: |
| 99 | dir_list : list of hex-string FIDs |
| 100 | """ |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 101 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 102 | rv = [] |
| 103 | if type(dir_list) is not list: |
| 104 | dir_list = [dir_list] |
| 105 | for i in dir_list: |
| 106 | data, sw = self._tp.send_apdu( |
| 107 | self.cla_byte + "a4" + self.sel_ctrl + "02" + i) |
| 108 | rv.append((data, sw)) |
| 109 | if sw != '9000': |
| 110 | return rv |
| 111 | return rv |
Harald Welte | ca67394 | 2020-06-03 15:19:40 +0200 | [diff] [blame] | 112 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 113 | def select_path(self, dir_list): |
| 114 | """Execute SELECT for an entire list/path of FIDs. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 115 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 116 | Args: |
| 117 | dir_list: list of FIDs representing the path to select |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 118 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 119 | Returns: |
| 120 | list of return values (FCP in hex encoding) for each element of the path |
| 121 | """ |
| 122 | rv = [] |
| 123 | if type(dir_list) is not list: |
| 124 | dir_list = [dir_list] |
| 125 | for i in dir_list: |
| 126 | data, sw = self.select_file(i) |
| 127 | rv.append(data) |
| 128 | return rv |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 129 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 130 | def select_file(self, fid: str): |
| 131 | """Execute SELECT a given file by FID. |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 132 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 133 | Args: |
| 134 | fid : file identifier as hex string |
| 135 | """ |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 136 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 137 | return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid) |
Harald Welte | 85484a9 | 2021-01-21 16:08:56 +0100 | [diff] [blame] | 138 | |
Harald Welte | 3729c47 | 2022-02-12 14:36:37 +0100 | [diff] [blame] | 139 | def select_parent_df(self): |
| 140 | """Execute SELECT to switch to the parent DF """ |
| 141 | return self._tp.send_apdu_checksw(self.cla_byte + "a4030400") |
| 142 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 143 | def select_adf(self, aid: str): |
| 144 | """Execute SELECT a given Applicaiton ADF. |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 145 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 146 | Args: |
| 147 | aid : application identifier as hex string |
| 148 | """ |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 149 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 150 | aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:] |
| 151 | return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid) |
Philipp Maier | 0ad5bcf | 2019-12-31 17:55:47 +0100 | [diff] [blame] | 152 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 153 | def read_binary(self, ef, length: int = None, offset: int = 0): |
| 154 | """Execute READD BINARY. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 155 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 156 | Args: |
| 157 | ef : string or list of strings indicating name or path of transparent EF |
| 158 | length : number of bytes to read |
| 159 | offset : byte offset in file from which to start reading |
| 160 | """ |
| 161 | r = self.select_path(ef) |
| 162 | if len(r[-1]) == 0: |
| 163 | return (None, None) |
| 164 | if length is None: |
| 165 | length = self.__len(r) - offset |
| 166 | if length < 0: |
| 167 | return (None, None) |
Philipp Maier | e087f90 | 2021-11-03 11:46:05 +0100 | [diff] [blame] | 168 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 169 | total_data = '' |
| 170 | chunk_offset = 0 |
| 171 | while chunk_offset < length: |
| 172 | chunk_len = min(255, length-chunk_offset) |
| 173 | pdu = self.cla_byte + \ |
| 174 | 'b0%04x%02x' % (offset + chunk_offset, chunk_len) |
| 175 | try: |
| 176 | data, sw = self._tp.send_apdu_checksw(pdu) |
| 177 | except Exception as e: |
| 178 | raise ValueError('%s, failed to read (offset %d)' % |
| 179 | (str_sanitize(str(e)), offset)) |
| 180 | total_data += data |
| 181 | chunk_offset += chunk_len |
| 182 | return total_data, sw |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 183 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 184 | def update_binary(self, ef, data: str, offset: int = 0, verify: bool = False, conserve: bool = False): |
| 185 | """Execute UPDATE BINARY. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 186 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 187 | Args: |
| 188 | ef : string or list of strings indicating name or path of transparent EF |
| 189 | data : hex string of data to be written |
| 190 | offset : byte offset in file from which to start writing |
| 191 | verify : Whether or not to verify data after write |
| 192 | """ |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 193 | |
| 194 | file_len = self.binary_size(ef) |
| 195 | data = expand_hex(data, file_len) |
| 196 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 197 | data_length = len(data) // 2 |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 198 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 199 | # Save write cycles by reading+comparing before write |
| 200 | if conserve: |
| 201 | data_current, sw = self.read_binary(ef, data_length, offset) |
| 202 | if data_current == data: |
| 203 | return None, sw |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 204 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 205 | self.select_path(ef) |
| 206 | total_data = '' |
| 207 | chunk_offset = 0 |
| 208 | while chunk_offset < data_length: |
| 209 | chunk_len = min(255, data_length - chunk_offset) |
| 210 | # chunk_offset is bytes, but data slicing is hex chars, so we need to multiply by 2 |
| 211 | pdu = self.cla_byte + \ |
| 212 | 'd6%04x%02x' % (offset + chunk_offset, chunk_len) + \ |
| 213 | data[chunk_offset*2: (chunk_offset+chunk_len)*2] |
| 214 | try: |
| 215 | chunk_data, chunk_sw = self._tp.send_apdu_checksw(pdu) |
| 216 | except Exception as e: |
| 217 | raise ValueError('%s, failed to write chunk (chunk_offset %d, chunk_len %d)' % |
| 218 | (str_sanitize(str(e)), chunk_offset, chunk_len)) |
| 219 | total_data += data |
| 220 | chunk_offset += chunk_len |
| 221 | if verify: |
| 222 | self.verify_binary(ef, data, offset) |
| 223 | return total_data, chunk_sw |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 224 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 225 | def verify_binary(self, ef, data: str, offset: int = 0): |
| 226 | """Verify contents of transparent EF. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 227 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 228 | Args: |
| 229 | ef : string or list of strings indicating name or path of transparent EF |
| 230 | data : hex string of expected data |
| 231 | offset : byte offset in file from which to start verifying |
| 232 | """ |
| 233 | res = self.read_binary(ef, len(data) // 2, offset) |
| 234 | if res[0].lower() != data.lower(): |
| 235 | raise ValueError('Binary verification failed (expected %s, got %s)' % ( |
| 236 | data.lower(), res[0].lower())) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 237 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 238 | def read_record(self, ef, rec_no: int): |
| 239 | """Execute READ RECORD. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 240 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 241 | Args: |
| 242 | ef : string or list of strings indicating name or path of linear fixed EF |
| 243 | rec_no : record number to read |
| 244 | """ |
| 245 | r = self.select_path(ef) |
| 246 | rec_length = self.__record_len(r) |
| 247 | pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length) |
| 248 | return self._tp.send_apdu_checksw(pdu) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 249 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 250 | def update_record(self, ef, rec_no: int, data: str, force_len: bool = False, verify: bool = False, |
| 251 | conserve: bool = False): |
| 252 | """Execute UPDATE RECORD. |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 253 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 254 | Args: |
| 255 | ef : string or list of strings indicating name or path of linear fixed EF |
| 256 | rec_no : record number to read |
| 257 | data : hex string of data to be written |
| 258 | force_len : enforce record length by using the actual data length |
| 259 | verify : verify data by re-reading the record |
| 260 | conserve : read record and compare it with data, skip write on match |
| 261 | """ |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 262 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 263 | res = self.select_path(ef) |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 264 | rec_length = self.__record_len(res) |
| 265 | data = expand_hex(data, rec_length) |
Philipp Maier | 42804d7 | 2021-04-30 11:56:23 +0200 | [diff] [blame] | 266 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 267 | if force_len: |
| 268 | # enforce the record length by the actual length of the given data input |
| 269 | rec_length = len(data) // 2 |
| 270 | else: |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 271 | # make sure the input data is padded to the record length using 0xFF. |
| 272 | # In cases where the input data exceed we throw an exception. |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 273 | if (len(data) // 2 > rec_length): |
| 274 | raise ValueError('Data length exceeds record length (expected max %d, got %d)' % ( |
| 275 | rec_length, len(data) // 2)) |
| 276 | elif (len(data) // 2 < rec_length): |
| 277 | data = rpad(data, rec_length * 2) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 278 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 279 | # Save write cycles by reading+comparing before write |
| 280 | if conserve: |
| 281 | data_current, sw = self.read_record(ef, rec_no) |
| 282 | data_current = data_current[0:rec_length*2] |
| 283 | if data_current == data: |
| 284 | return None, sw |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 285 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 286 | pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data |
| 287 | res = self._tp.send_apdu_checksw(pdu) |
| 288 | if verify: |
| 289 | self.verify_record(ef, rec_no, data) |
| 290 | return res |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 291 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 292 | def verify_record(self, ef, rec_no: int, data: str): |
| 293 | """Verify record against given data |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 294 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 295 | Args: |
| 296 | ef : string or list of strings indicating name or path of linear fixed EF |
| 297 | rec_no : record number to read |
| 298 | data : hex string of data to be verified |
| 299 | """ |
| 300 | res = self.read_record(ef, rec_no) |
| 301 | if res[0].lower() != data.lower(): |
| 302 | raise ValueError('Record verification failed (expected %s, got %s)' % ( |
| 303 | data.lower(), res[0].lower())) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 304 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 305 | def record_size(self, ef): |
| 306 | """Determine the record size of given file. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 307 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 308 | Args: |
| 309 | ef : string or list of strings indicating name or path of linear fixed EF |
| 310 | """ |
| 311 | r = self.select_path(ef) |
| 312 | return self.__record_len(r) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 313 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 314 | def record_count(self, ef): |
| 315 | """Determine the number of records in given file. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 316 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 317 | Args: |
| 318 | ef : string or list of strings indicating name or path of linear fixed EF |
| 319 | """ |
| 320 | r = self.select_path(ef) |
| 321 | return self.__len(r) // self.__record_len(r) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 322 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 323 | def binary_size(self, ef): |
| 324 | """Determine the size of given transparent file. |
| 325 | |
| 326 | Args: |
| 327 | ef : string or list of strings indicating name or path of transparent EF |
| 328 | """ |
| 329 | r = self.select_path(ef) |
| 330 | return self.__len(r) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 331 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 332 | # TS 102 221 Section 11.3.1 low-level helper |
| 333 | def _retrieve_data(self, tag: int, first: bool = True): |
| 334 | if first: |
| 335 | pdu = '80cb008001%02x' % (tag) |
| 336 | else: |
| 337 | pdu = '80cb000000' |
| 338 | return self._tp.send_apdu_checksw(pdu) |
Philipp Maier | 32daaf5 | 2020-05-11 21:48:33 +0200 | [diff] [blame] | 339 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 340 | def retrieve_data(self, ef, tag: int): |
| 341 | """Execute RETRIEVE DATA, see also TS 102 221 Section 11.3.1. |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 342 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 343 | Args |
| 344 | ef : string or list of strings indicating name or path of transparent EF |
| 345 | tag : BER-TLV Tag of value to be retrieved |
| 346 | """ |
| 347 | r = self.select_path(ef) |
| 348 | if len(r[-1]) == 0: |
| 349 | return (None, None) |
| 350 | total_data = '' |
| 351 | # retrieve first block |
| 352 | data, sw = self._retrieve_data(tag, first=True) |
| 353 | total_data += data |
| 354 | while sw == '62f1' or sw == '62f2': |
| 355 | data, sw = self._retrieve_data(tag, first=False) |
| 356 | total_data += data |
| 357 | return total_data, sw |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 358 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 359 | # TS 102 221 Section 11.3.2 low-level helper |
| 360 | def _set_data(self, data: str, first: bool = True): |
| 361 | if first: |
| 362 | p1 = 0x80 |
| 363 | else: |
| 364 | p1 = 0x00 |
| 365 | if isinstance(data, bytes) or isinstance(data, bytearray): |
| 366 | data = b2h(data) |
| 367 | pdu = '80db00%02x%02x%s' % (p1, len(data)//2, data) |
| 368 | return self._tp.send_apdu_checksw(pdu) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 369 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 370 | def set_data(self, ef, tag: int, value: str, verify: bool = False, conserve: bool = False): |
| 371 | """Execute SET DATA. |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 372 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 373 | Args |
| 374 | ef : string or list of strings indicating name or path of transparent EF |
| 375 | tag : BER-TLV Tag of value to be stored |
| 376 | value : BER-TLV value to be stored |
| 377 | """ |
| 378 | r = self.select_path(ef) |
| 379 | if len(r[-1]) == 0: |
| 380 | return (None, None) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 381 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 382 | # in case of deleting the data, we only have 'tag' but no 'value' |
| 383 | if not value: |
| 384 | return self._set_data('%02x' % tag, first=True) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 385 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 386 | # FIXME: proper BER-TLV encode |
| 387 | tl = '%02x%s' % (tag, b2h(bertlv_encode_len(len(value)//2))) |
| 388 | tlv = tl + value |
| 389 | tlv_bin = h2b(tlv) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 390 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 391 | first = True |
| 392 | total_len = len(tlv_bin) |
| 393 | remaining = tlv_bin |
| 394 | while len(remaining) > 0: |
| 395 | fragment = remaining[:255] |
| 396 | rdata, sw = self._set_data(fragment, first=first) |
| 397 | first = False |
| 398 | remaining = remaining[255:] |
| 399 | return rdata, sw |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 400 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 401 | def run_gsm(self, rand: str): |
| 402 | """Execute RUN GSM ALGORITHM. |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 403 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 404 | Args: |
| 405 | rand : 16 byte random data as hex string (RAND) |
| 406 | """ |
| 407 | if len(rand) != 32: |
| 408 | raise ValueError('Invalid rand') |
| 409 | self.select_path(['3f00', '7f20']) |
| 410 | return self._tp.send_apdu(self.cla_byte + '88000010' + rand) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 411 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 412 | def authenticate(self, rand: str, autn: str, context='3g'): |
| 413 | """Execute AUTHENTICATE (USIM/ISIM). |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 414 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 415 | Args: |
| 416 | rand : 16 byte random data as hex string (RAND) |
| 417 | autn : 8 byte Autentication Token (AUTN) |
| 418 | context : 16 byte random data ('3g' or 'gsm') |
| 419 | """ |
| 420 | # 3GPP TS 31.102 Section 7.1.2.1 |
| 421 | AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV)) |
| 422 | AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV) |
| 423 | AuthResp3GSuccess = Struct( |
| 424 | Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV)) |
| 425 | AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess) |
| 426 | # build parameters |
| 427 | cmd_data = {'rand': rand, 'autn': autn} |
| 428 | if context == '3g': |
| 429 | p2 = '81' |
| 430 | elif context == 'gsm': |
| 431 | p2 = '80' |
| 432 | (data, sw) = self._tp.send_apdu_constr_checksw( |
| 433 | self.cla_byte, '88', '00', p2, AuthCmd3G, cmd_data, AuthResp3G) |
| 434 | if 'auts' in data: |
| 435 | ret = {'synchronisation_failure': data} |
| 436 | else: |
| 437 | ret = {'successful_3g_authentication': data} |
| 438 | return (ret, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 439 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 440 | def status(self): |
| 441 | """Execute a STATUS command as per TS 102 221 Section 11.1.2.""" |
| 442 | return self._tp.send_apdu_checksw('80F20000ff') |
Harald Welte | 15fae98 | 2021-04-10 10:22:27 +0200 | [diff] [blame] | 443 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 444 | def deactivate_file(self): |
| 445 | """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14.""" |
| 446 | return self._tp.send_apdu_constr_checksw(self.cla_byte, '04', '00', '00', None, None, None) |
Harald Welte | 34b05d3 | 2021-05-25 22:03:13 +0200 | [diff] [blame] | 447 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 448 | def activate_file(self, fid): |
| 449 | """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15. |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 450 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 451 | Args: |
| 452 | fid : file identifier as hex string |
| 453 | """ |
| 454 | return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 455 | |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 456 | def create_file(self, payload: Hexstr): |
| 457 | """Execute CREEATE FILE command as per TS 102 222 Section 6.3""" |
| 458 | return self._tp.send_apdu_checksw(self.cla_byte + 'e00000%02x%s' % (len(payload)//2, payload)) |
| 459 | |
| 460 | def delete_file(self, fid): |
| 461 | """Execute DELETE FILE command as per TS 102 222 Section 6.4""" |
| 462 | return self._tp.send_apdu_checksw(self.cla_byte + 'e4000002' + fid) |
| 463 | |
| 464 | def terminate_df(self, fid): |
| 465 | """Execute TERMINATE DF command as per TS 102 222 Section 6.7""" |
| 466 | return self._tp.send_apdu_checksw(self.cla_byte + 'e6000002' + fid) |
| 467 | |
| 468 | def terminate_ef(self, fid): |
| 469 | """Execute TERMINATE EF command as per TS 102 222 Section 6.8""" |
| 470 | return self._tp.send_apdu_checksw(self.cla_byte + 'e8000002' + fid) |
| 471 | |
| 472 | def terminate_card_usage(self): |
| 473 | """Execute TERMINATE CARD USAGE command as per TS 102 222 Section 6.9""" |
| 474 | return self._tp.send_apdu_checksw(self.cla_byte + 'fe000000') |
| 475 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 476 | def manage_channel(self, mode='open', lchan_nr=0): |
| 477 | """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17. |
Harald Welte | a463161 | 2021-04-10 18:17:55 +0200 | [diff] [blame] | 478 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 479 | Args: |
| 480 | mode : logical channel operation code ('open' or 'close') |
| 481 | lchan_nr : logical channel number (1-19, 0=assigned by UICC) |
| 482 | """ |
| 483 | if mode == 'close': |
| 484 | p1 = 0x80 |
| 485 | else: |
| 486 | p1 = 0x00 |
| 487 | pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr) |
| 488 | return self._tp.send_apdu_checksw(pdu) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 489 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 490 | def reset_card(self): |
| 491 | """Physically reset the card""" |
| 492 | return self._tp.reset_card() |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 493 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 494 | def _chv_process_sw(self, op_name, chv_no, pin_code, sw): |
| 495 | if sw_match(sw, '63cx'): |
| 496 | raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' % |
| 497 | (op_name, chv_no, b2h(pin_code).upper(), int(sw[3]))) |
| 498 | elif (sw != '9000'): |
| 499 | raise SwMatchError(sw, '9000') |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 500 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 501 | def verify_chv(self, chv_no: int, code: str): |
| 502 | """Verify a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 503 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 504 | Args: |
| 505 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 506 | code : chv code as hex string |
| 507 | """ |
| 508 | fc = rpad(b2h(code), 16) |
| 509 | data, sw = self._tp.send_apdu( |
| 510 | self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc) |
| 511 | self._chv_process_sw('verify', chv_no, code, sw) |
| 512 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 513 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 514 | def unblock_chv(self, chv_no: int, puk_code: str, pin_code: str): |
| 515 | """Unblock a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 516 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 517 | Args: |
| 518 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 519 | puk_code : puk code as hex string |
| 520 | pin_code : new chv code as hex string |
| 521 | """ |
| 522 | fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16) |
| 523 | data, sw = self._tp.send_apdu( |
| 524 | self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc) |
| 525 | self._chv_process_sw('unblock', chv_no, pin_code, sw) |
| 526 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 527 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 528 | def change_chv(self, chv_no: int, pin_code: str, new_pin_code: str): |
| 529 | """Change a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 530 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 531 | Args: |
| 532 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 533 | pin_code : current chv code as hex string |
| 534 | new_pin_code : new chv code as hex string |
| 535 | """ |
| 536 | fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16) |
| 537 | data, sw = self._tp.send_apdu( |
| 538 | self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc) |
| 539 | self._chv_process_sw('change', chv_no, pin_code, sw) |
| 540 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 541 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 542 | def disable_chv(self, chv_no: int, pin_code: str): |
| 543 | """Disable a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 544 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 545 | Args: |
| 546 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 547 | pin_code : current chv code as hex string |
| 548 | new_pin_code : new chv code as hex string |
| 549 | """ |
| 550 | fc = rpad(b2h(pin_code), 16) |
| 551 | data, sw = self._tp.send_apdu( |
| 552 | self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc) |
| 553 | self._chv_process_sw('disable', chv_no, pin_code, sw) |
| 554 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 555 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 556 | def enable_chv(self, chv_no: int, pin_code: str): |
| 557 | """Enable a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 558 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 559 | Args: |
| 560 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 561 | pin_code : chv code as hex string |
| 562 | """ |
| 563 | fc = rpad(b2h(pin_code), 16) |
| 564 | data, sw = self._tp.send_apdu( |
| 565 | self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc) |
| 566 | self._chv_process_sw('enable', chv_no, pin_code, sw) |
| 567 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 568 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 569 | def envelope(self, payload: str): |
| 570 | """Send one ENVELOPE command to the SIM |
Harald Welte | f201166 | 2021-05-24 23:19:30 +0200 | [diff] [blame] | 571 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 572 | Args: |
| 573 | payload : payload as hex string |
| 574 | """ |
| 575 | return self._tp.send_apdu_checksw('80c20000%02x%s' % (len(payload)//2, payload)) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 576 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 577 | def terminal_profile(self, payload: str): |
| 578 | """Send TERMINAL PROFILE to card |
Harald Welte | 846a898 | 2021-10-08 15:47:16 +0200 | [diff] [blame] | 579 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 580 | Args: |
| 581 | payload : payload as hex string |
| 582 | """ |
| 583 | data_length = len(payload) // 2 |
| 584 | data, sw = self._tp.send_apdu(('80100000%02x' % data_length) + payload) |
| 585 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 586 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 587 | # ETSI TS 102 221 11.1.22 |
| 588 | def suspend_uicc(self, min_len_secs: int = 60, max_len_secs: int = 43200): |
| 589 | """Send SUSPEND UICC to the card. |
Harald Welte | ec95053 | 2021-10-20 13:09:00 +0200 | [diff] [blame] | 590 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 591 | Args: |
| 592 | min_len_secs : mimumum suspend time seconds |
| 593 | max_len_secs : maximum suspend time seconds |
| 594 | """ |
| 595 | def encode_duration(secs: int) -> Hexstr: |
| 596 | if secs >= 10*24*60*60: |
| 597 | return '04%02x' % (secs // (10*24*60*60)) |
| 598 | elif secs >= 24*60*60: |
| 599 | return '03%02x' % (secs // (24*60*60)) |
| 600 | elif secs >= 60*60: |
| 601 | return '02%02x' % (secs // (60*60)) |
| 602 | elif secs >= 60: |
| 603 | return '01%02x' % (secs // 60) |
| 604 | else: |
| 605 | return '00%02x' % secs |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 606 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 607 | def decode_duration(enc: Hexstr) -> int: |
| 608 | time_unit = enc[:2] |
| 609 | length = h2i(enc[2:4]) |
| 610 | if time_unit == '04': |
| 611 | return length * 10*24*60*60 |
| 612 | elif time_unit == '03': |
| 613 | return length * 24*60*60 |
| 614 | elif time_unit == '02': |
| 615 | return length * 60*60 |
| 616 | elif time_unit == '01': |
| 617 | return length * 60 |
| 618 | elif time_unit == '00': |
| 619 | return length |
| 620 | else: |
| 621 | raise ValueError('Time unit must be 0x00..0x04') |
| 622 | min_dur_enc = encode_duration(min_len_secs) |
| 623 | max_dur_enc = encode_duration(max_len_secs) |
| 624 | data, sw = self._tp.send_apdu_checksw( |
| 625 | '8076000004' + min_dur_enc + max_dur_enc) |
| 626 | negotiated_duration_secs = decode_duration(data[:4]) |
| 627 | resume_token = data[4:] |
| 628 | return (negotiated_duration_secs, resume_token, sw) |
Harald Welte | 34eb504 | 2022-02-21 17:19:28 +0100 | [diff] [blame] | 629 | |
| 630 | def get_data(self, tag: int, cla: int = 0x00): |
| 631 | data, sw = self._tp.send_apdu('%02xca%04x00' % (cla, tag)) |
| 632 | return (data, sw) |