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 | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 29 | from pySim.utils import rpad, 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 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 191 | def update_binary(self, ef: Path, data: Hexstr, offset: int = 0, verify: bool = False, |
| 192 | conserve: bool = False) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 193 | """Execute UPDATE BINARY. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 194 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 195 | Args: |
| 196 | ef : string or list of strings indicating name or path of transparent EF |
| 197 | data : hex string of data to be written |
| 198 | offset : byte offset in file from which to start writing |
| 199 | verify : Whether or not to verify data after write |
| 200 | """ |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 201 | |
| 202 | file_len = self.binary_size(ef) |
| 203 | data = expand_hex(data, file_len) |
| 204 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 205 | data_length = len(data) // 2 |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 206 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 207 | # Save write cycles by reading+comparing before write |
| 208 | if conserve: |
| 209 | data_current, sw = self.read_binary(ef, data_length, offset) |
| 210 | if data_current == data: |
| 211 | return None, sw |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 212 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 213 | self.select_path(ef) |
| 214 | total_data = '' |
| 215 | chunk_offset = 0 |
| 216 | while chunk_offset < data_length: |
| 217 | chunk_len = min(255, data_length - chunk_offset) |
| 218 | # chunk_offset is bytes, but data slicing is hex chars, so we need to multiply by 2 |
| 219 | pdu = self.cla_byte + \ |
| 220 | 'd6%04x%02x' % (offset + chunk_offset, chunk_len) + \ |
| 221 | data[chunk_offset*2: (chunk_offset+chunk_len)*2] |
| 222 | try: |
| 223 | chunk_data, chunk_sw = self._tp.send_apdu_checksw(pdu) |
| 224 | except Exception as e: |
| 225 | raise ValueError('%s, failed to write chunk (chunk_offset %d, chunk_len %d)' % |
| 226 | (str_sanitize(str(e)), chunk_offset, chunk_len)) |
| 227 | total_data += data |
| 228 | chunk_offset += chunk_len |
| 229 | if verify: |
| 230 | self.verify_binary(ef, data, offset) |
| 231 | return total_data, chunk_sw |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 232 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 233 | def verify_binary(self, ef, data: str, offset: int = 0): |
| 234 | """Verify contents of transparent EF. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 235 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 236 | Args: |
| 237 | ef : string or list of strings indicating name or path of transparent EF |
| 238 | data : hex string of expected data |
| 239 | offset : byte offset in file from which to start verifying |
| 240 | """ |
| 241 | res = self.read_binary(ef, len(data) // 2, offset) |
| 242 | if res[0].lower() != data.lower(): |
| 243 | raise ValueError('Binary verification failed (expected %s, got %s)' % ( |
| 244 | data.lower(), res[0].lower())) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [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 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 258 | def update_record(self, ef: Path, rec_no: int, data: Hexstr, force_len: bool = False, |
| 259 | verify: bool = False, conserve: bool = False) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 260 | """Execute UPDATE RECORD. |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 261 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 262 | Args: |
| 263 | ef : string or list of strings indicating name or path of linear fixed EF |
| 264 | rec_no : record number to read |
| 265 | data : hex string of data to be written |
| 266 | force_len : enforce record length by using the actual data length |
| 267 | verify : verify data by re-reading the record |
| 268 | conserve : read record and compare it with data, skip write on match |
| 269 | """ |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 270 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 271 | res = self.select_path(ef) |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 272 | rec_length = self.__record_len(res) |
| 273 | data = expand_hex(data, rec_length) |
Philipp Maier | 42804d7 | 2021-04-30 11:56:23 +0200 | [diff] [blame] | 274 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 275 | if force_len: |
| 276 | # enforce the record length by the actual length of the given data input |
| 277 | rec_length = len(data) // 2 |
| 278 | else: |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 279 | # make sure the input data is padded to the record length using 0xFF. |
| 280 | # In cases where the input data exceed we throw an exception. |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 281 | if (len(data) // 2 > rec_length): |
| 282 | raise ValueError('Data length exceeds record length (expected max %d, got %d)' % ( |
| 283 | rec_length, len(data) // 2)) |
| 284 | elif (len(data) // 2 < rec_length): |
| 285 | data = rpad(data, rec_length * 2) |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 286 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 287 | # Save write cycles by reading+comparing before write |
| 288 | if conserve: |
| 289 | data_current, sw = self.read_record(ef, rec_no) |
| 290 | data_current = data_current[0:rec_length*2] |
| 291 | if data_current == data: |
| 292 | return None, sw |
Philipp Maier | 38c74f6 | 2021-03-17 17:19:52 +0100 | [diff] [blame] | 293 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 294 | pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data |
| 295 | res = self._tp.send_apdu_checksw(pdu) |
| 296 | if verify: |
| 297 | self.verify_record(ef, rec_no, data) |
| 298 | return res |
Philipp Maier | 30eb8ca | 2020-05-11 22:51:37 +0200 | [diff] [blame] | 299 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 300 | def verify_record(self, ef: Path, rec_no: int, data: str): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 301 | """Verify record against given data |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 302 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 303 | Args: |
| 304 | ef : string or list of strings indicating name or path of linear fixed EF |
| 305 | rec_no : record number to read |
| 306 | data : hex string of data to be verified |
| 307 | """ |
| 308 | res = self.read_record(ef, rec_no) |
| 309 | if res[0].lower() != data.lower(): |
| 310 | raise ValueError('Record verification failed (expected %s, got %s)' % ( |
| 311 | data.lower(), res[0].lower())) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 312 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 313 | def record_size(self, ef: Path) -> int: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 314 | """Determine the record size of given file. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 315 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 316 | Args: |
| 317 | ef : string or list of strings indicating name or path of linear fixed EF |
| 318 | """ |
| 319 | r = self.select_path(ef) |
| 320 | return self.__record_len(r) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 321 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 322 | def record_count(self, ef: Path) -> int: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 323 | """Determine the number of records in given file. |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 324 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 325 | Args: |
| 326 | ef : string or list of strings indicating name or path of linear fixed EF |
| 327 | """ |
| 328 | r = self.select_path(ef) |
| 329 | return self.__len(r) // self.__record_len(r) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 330 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 331 | def binary_size(self, ef: Path) -> int: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 332 | """Determine the size of given transparent file. |
| 333 | |
| 334 | Args: |
| 335 | ef : string or list of strings indicating name or path of transparent EF |
| 336 | """ |
| 337 | r = self.select_path(ef) |
| 338 | return self.__len(r) |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 339 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 340 | # TS 102 221 Section 11.3.1 low-level helper |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 341 | def _retrieve_data(self, tag: int, first: bool = True) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 342 | if first: |
| 343 | pdu = '80cb008001%02x' % (tag) |
| 344 | else: |
| 345 | pdu = '80cb000000' |
| 346 | return self._tp.send_apdu_checksw(pdu) |
Philipp Maier | 32daaf5 | 2020-05-11 21:48:33 +0200 | [diff] [blame] | 347 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 348 | def retrieve_data(self, ef: Path, tag: int) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 349 | """Execute RETRIEVE DATA, see also TS 102 221 Section 11.3.1. |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 350 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 351 | Args |
| 352 | ef : string or list of strings indicating name or path of transparent EF |
| 353 | tag : BER-TLV Tag of value to be retrieved |
| 354 | """ |
| 355 | r = self.select_path(ef) |
| 356 | if len(r[-1]) == 0: |
| 357 | return (None, None) |
| 358 | total_data = '' |
| 359 | # retrieve first block |
| 360 | data, sw = self._retrieve_data(tag, first=True) |
| 361 | total_data += data |
| 362 | while sw == '62f1' or sw == '62f2': |
| 363 | data, sw = self._retrieve_data(tag, first=False) |
| 364 | total_data += data |
| 365 | return total_data, sw |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 366 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 367 | # TS 102 221 Section 11.3.2 low-level helper |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 368 | def _set_data(self, data: Hexstr, first: bool = True) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 369 | if first: |
| 370 | p1 = 0x80 |
| 371 | else: |
| 372 | p1 = 0x00 |
| 373 | if isinstance(data, bytes) or isinstance(data, bytearray): |
| 374 | data = b2h(data) |
| 375 | pdu = '80db00%02x%02x%s' % (p1, len(data)//2, data) |
| 376 | return self._tp.send_apdu_checksw(pdu) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 377 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 378 | 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] | 379 | """Execute SET DATA. |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 380 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 381 | Args |
| 382 | ef : string or list of strings indicating name or path of transparent EF |
| 383 | tag : BER-TLV Tag of value to be stored |
| 384 | value : BER-TLV value to be stored |
| 385 | """ |
| 386 | r = self.select_path(ef) |
| 387 | if len(r[-1]) == 0: |
| 388 | return (None, None) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 389 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 390 | # in case of deleting the data, we only have 'tag' but no 'value' |
| 391 | if not value: |
| 392 | return self._set_data('%02x' % tag, first=True) |
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 | # FIXME: proper BER-TLV encode |
| 395 | tl = '%02x%s' % (tag, b2h(bertlv_encode_len(len(value)//2))) |
| 396 | tlv = tl + value |
| 397 | tlv_bin = h2b(tlv) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 398 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 399 | first = True |
| 400 | total_len = len(tlv_bin) |
| 401 | remaining = tlv_bin |
| 402 | while len(remaining) > 0: |
| 403 | fragment = remaining[:255] |
| 404 | rdata, sw = self._set_data(fragment, first=first) |
| 405 | first = False |
| 406 | remaining = remaining[255:] |
| 407 | return rdata, sw |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 408 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 409 | def run_gsm(self, rand: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 410 | """Execute RUN GSM ALGORITHM. |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 411 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 412 | Args: |
| 413 | rand : 16 byte random data as hex string (RAND) |
| 414 | """ |
| 415 | if len(rand) != 32: |
| 416 | raise ValueError('Invalid rand') |
| 417 | self.select_path(['3f00', '7f20']) |
Vadim Yanitskiy | 9970f59 | 2022-04-22 00:29:10 +0300 | [diff] [blame] | 418 | return self._tp.send_apdu_checksw('a0' + '88000010' + rand, sw='9000') |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 419 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 420 | def authenticate(self, rand: Hexstr, autn: Hexstr, context: str = '3g') -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 421 | """Execute AUTHENTICATE (USIM/ISIM). |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 422 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 423 | Args: |
| 424 | rand : 16 byte random data as hex string (RAND) |
| 425 | autn : 8 byte Autentication Token (AUTN) |
| 426 | context : 16 byte random data ('3g' or 'gsm') |
| 427 | """ |
| 428 | # 3GPP TS 31.102 Section 7.1.2.1 |
| 429 | AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV)) |
| 430 | AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV) |
| 431 | AuthResp3GSuccess = Struct( |
| 432 | Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV)) |
| 433 | AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess) |
| 434 | # build parameters |
| 435 | cmd_data = {'rand': rand, 'autn': autn} |
| 436 | if context == '3g': |
| 437 | p2 = '81' |
| 438 | elif context == 'gsm': |
| 439 | p2 = '80' |
| 440 | (data, sw) = self._tp.send_apdu_constr_checksw( |
| 441 | self.cla_byte, '88', '00', p2, AuthCmd3G, cmd_data, AuthResp3G) |
| 442 | if 'auts' in data: |
| 443 | ret = {'synchronisation_failure': data} |
| 444 | else: |
| 445 | ret = {'successful_3g_authentication': data} |
| 446 | return (ret, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 447 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 448 | def status(self) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 449 | """Execute a STATUS command as per TS 102 221 Section 11.1.2.""" |
| 450 | return self._tp.send_apdu_checksw('80F20000ff') |
Harald Welte | 15fae98 | 2021-04-10 10:22:27 +0200 | [diff] [blame] | 451 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 452 | def deactivate_file(self) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 453 | """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14.""" |
| 454 | 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] | 455 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 456 | def activate_file(self, fid: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 457 | """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] | 458 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 459 | Args: |
| 460 | fid : file identifier as hex string |
| 461 | """ |
| 462 | return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 463 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 464 | def create_file(self, payload: Hexstr) -> ResTuple: |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 465 | """Execute CREEATE FILE command as per TS 102 222 Section 6.3""" |
| 466 | return self._tp.send_apdu_checksw(self.cla_byte + 'e00000%02x%s' % (len(payload)//2, payload)) |
| 467 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 468 | def resize_file(self, payload: Hexstr) -> ResTuple: |
Harald Welte | 0707b80 | 2023-03-07 11:43:37 +0100 | [diff] [blame] | 469 | """Execute RESIZE FILE command as per TS 102 222 Section 6.10""" |
| 470 | return self._tp.send_apdu_checksw('80d40000%02x%s' % (len(payload)//2, payload)) |
| 471 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 472 | def delete_file(self, fid: Hexstr) -> ResTuple: |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 473 | """Execute DELETE FILE command as per TS 102 222 Section 6.4""" |
| 474 | return self._tp.send_apdu_checksw(self.cla_byte + 'e4000002' + fid) |
| 475 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 476 | def terminate_df(self, fid: Hexstr) -> ResTuple: |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 477 | """Execute TERMINATE DF command as per TS 102 222 Section 6.7""" |
| 478 | return self._tp.send_apdu_checksw(self.cla_byte + 'e6000002' + fid) |
| 479 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 480 | def terminate_ef(self, fid: Hexstr) -> ResTuple: |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 481 | """Execute TERMINATE EF command as per TS 102 222 Section 6.8""" |
| 482 | return self._tp.send_apdu_checksw(self.cla_byte + 'e8000002' + fid) |
| 483 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 484 | def terminate_card_usage(self) -> ResTuple: |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 485 | """Execute TERMINATE CARD USAGE command as per TS 102 222 Section 6.9""" |
| 486 | return self._tp.send_apdu_checksw(self.cla_byte + 'fe000000') |
| 487 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 488 | def manage_channel(self, mode: str = 'open', lchan_nr: int =0) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 489 | """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] | 490 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 491 | Args: |
| 492 | mode : logical channel operation code ('open' or 'close') |
| 493 | lchan_nr : logical channel number (1-19, 0=assigned by UICC) |
| 494 | """ |
| 495 | if mode == 'close': |
| 496 | p1 = 0x80 |
| 497 | else: |
| 498 | p1 = 0x00 |
| 499 | pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr) |
| 500 | return self._tp.send_apdu_checksw(pdu) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 501 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 502 | def reset_card(self) -> Hexstr: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 503 | """Physically reset the card""" |
| 504 | return self._tp.reset_card() |
Harald Welte | 703f933 | 2021-04-10 18:39:32 +0200 | [diff] [blame] | 505 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 506 | 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] | 507 | if sw_match(sw, '63cx'): |
| 508 | raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' % |
| 509 | (op_name, chv_no, b2h(pin_code).upper(), int(sw[3]))) |
| 510 | elif (sw != '9000'): |
| 511 | raise SwMatchError(sw, '9000') |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 512 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 513 | def verify_chv(self, chv_no: int, code: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 514 | """Verify a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 515 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 516 | Args: |
| 517 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 518 | code : chv code as hex string |
| 519 | """ |
| 520 | fc = rpad(b2h(code), 16) |
| 521 | data, sw = self._tp.send_apdu( |
| 522 | self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc) |
| 523 | self._chv_process_sw('verify', chv_no, code, sw) |
| 524 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 525 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 526 | def unblock_chv(self, chv_no: int, puk_code: str, pin_code: str): |
| 527 | """Unblock a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 528 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 529 | Args: |
| 530 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 531 | puk_code : puk code as hex string |
| 532 | pin_code : new chv code as hex string |
| 533 | """ |
| 534 | fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16) |
| 535 | data, sw = self._tp.send_apdu( |
| 536 | self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc) |
| 537 | self._chv_process_sw('unblock', chv_no, pin_code, sw) |
| 538 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 539 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 540 | 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] | 541 | """Change a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 542 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 543 | Args: |
| 544 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 545 | pin_code : current chv code as hex string |
| 546 | new_pin_code : new chv code as hex string |
| 547 | """ |
| 548 | fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16) |
| 549 | data, sw = self._tp.send_apdu( |
| 550 | self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc) |
| 551 | self._chv_process_sw('change', chv_no, pin_code, sw) |
| 552 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 553 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 554 | def disable_chv(self, chv_no: int, pin_code: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 555 | """Disable a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 556 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 557 | Args: |
| 558 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 559 | pin_code : current chv code as hex string |
| 560 | new_pin_code : new chv code as hex string |
| 561 | """ |
| 562 | fc = rpad(b2h(pin_code), 16) |
| 563 | data, sw = self._tp.send_apdu( |
| 564 | self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc) |
| 565 | self._chv_process_sw('disable', chv_no, pin_code, sw) |
| 566 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 567 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 568 | def enable_chv(self, chv_no: int, pin_code: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 569 | """Enable a given CHV (Card Holder Verification == PIN) |
Philipp Maier | 46f09af | 2021-03-25 20:24:27 +0100 | [diff] [blame] | 570 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 571 | Args: |
| 572 | chv_no : chv number (1=CHV1, 2=CHV2, ...) |
| 573 | pin_code : chv code as hex string |
| 574 | """ |
| 575 | fc = rpad(b2h(pin_code), 16) |
| 576 | data, sw = self._tp.send_apdu( |
| 577 | self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc) |
| 578 | self._chv_process_sw('enable', chv_no, pin_code, sw) |
| 579 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 580 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 581 | def envelope(self, payload: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 582 | """Send one ENVELOPE command to the SIM |
Harald Welte | f201166 | 2021-05-24 23:19:30 +0200 | [diff] [blame] | 583 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 584 | Args: |
| 585 | payload : payload as hex string |
| 586 | """ |
| 587 | 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] | 588 | |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 589 | def terminal_profile(self, payload: Hexstr) -> ResTuple: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 590 | """Send TERMINAL PROFILE to card |
Harald Welte | 846a898 | 2021-10-08 15:47:16 +0200 | [diff] [blame] | 591 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 592 | Args: |
| 593 | payload : payload as hex string |
| 594 | """ |
| 595 | data_length = len(payload) // 2 |
| 596 | data, sw = self._tp.send_apdu(('80100000%02x' % data_length) + payload) |
| 597 | return (data, sw) |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 598 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 599 | # ETSI TS 102 221 11.1.22 |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 600 | 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] | 601 | """Send SUSPEND UICC to the card. |
Harald Welte | ec95053 | 2021-10-20 13:09:00 +0200 | [diff] [blame] | 602 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 603 | Args: |
| 604 | min_len_secs : mimumum suspend time seconds |
| 605 | max_len_secs : maximum suspend time seconds |
| 606 | """ |
| 607 | def encode_duration(secs: int) -> Hexstr: |
| 608 | if secs >= 10*24*60*60: |
| 609 | return '04%02x' % (secs // (10*24*60*60)) |
| 610 | elif secs >= 24*60*60: |
| 611 | return '03%02x' % (secs // (24*60*60)) |
| 612 | elif secs >= 60*60: |
| 613 | return '02%02x' % (secs // (60*60)) |
| 614 | elif secs >= 60: |
| 615 | return '01%02x' % (secs // 60) |
| 616 | else: |
| 617 | return '00%02x' % secs |
Philipp Maier | 712251a | 2021-11-04 17:09:37 +0100 | [diff] [blame] | 618 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 619 | def decode_duration(enc: Hexstr) -> int: |
| 620 | time_unit = enc[:2] |
Harald Welte | c85ae41 | 2023-06-06 09:03:27 +0200 | [diff] [blame] | 621 | length = h2i(enc[2:4])[0] |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 622 | if time_unit == '04': |
| 623 | return length * 10*24*60*60 |
| 624 | elif time_unit == '03': |
| 625 | return length * 24*60*60 |
| 626 | elif time_unit == '02': |
| 627 | return length * 60*60 |
| 628 | elif time_unit == '01': |
| 629 | return length * 60 |
| 630 | elif time_unit == '00': |
| 631 | return length |
| 632 | else: |
| 633 | raise ValueError('Time unit must be 0x00..0x04') |
| 634 | min_dur_enc = encode_duration(min_len_secs) |
| 635 | max_dur_enc = encode_duration(max_len_secs) |
| 636 | data, sw = self._tp.send_apdu_checksw( |
| 637 | '8076000004' + min_dur_enc + max_dur_enc) |
| 638 | negotiated_duration_secs = decode_duration(data[:4]) |
| 639 | resume_token = data[4:] |
| 640 | return (negotiated_duration_secs, resume_token, sw) |
Harald Welte | 34eb504 | 2022-02-21 17:19:28 +0100 | [diff] [blame] | 641 | |
Harald Welte | b0e0dce | 2023-06-06 17:21:13 +0200 | [diff] [blame] | 642 | # ETSI TS 102 221 11.1.22 |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 643 | def resume_uicc(self, token: Hexstr) -> ResTuple: |
Harald Welte | b0e0dce | 2023-06-06 17:21:13 +0200 | [diff] [blame] | 644 | """Send SUSPEND UICC (resume) to the card.""" |
| 645 | if len(h2b(token)) != 8: |
| 646 | raise ValueError("Token must be 8 bytes long") |
| 647 | data, sw = self._tp.send_apdu_checksw('8076010008' + token) |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 648 | return (data, sw) |
Harald Welte | b0e0dce | 2023-06-06 17:21:13 +0200 | [diff] [blame] | 649 | |
Harald Welte | 34eb504 | 2022-02-21 17:19:28 +0100 | [diff] [blame] | 650 | def get_data(self, tag: int, cla: int = 0x00): |
| 651 | data, sw = self._tp.send_apdu('%02xca%04x00' % (cla, tag)) |
| 652 | return (data, sw) |
Harald Welte | 7ec8223 | 2023-06-06 18:15:52 +0200 | [diff] [blame] | 653 | |
| 654 | # TS 31.102 Section 7.5.2 |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 655 | def get_identity(self, context: int) -> Tuple[Hexstr, SwHexstr]: |
Harald Welte | 7ec8223 | 2023-06-06 18:15:52 +0200 | [diff] [blame] | 656 | data, sw = self._tp.send_apdu_checksw('807800%02x00' % (context)) |
| 657 | return (data, sw) |