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