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