blob: ab66392394952c5e1eb6b28d59e84101d99aea12 [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- 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 Weltefdb187d2023-07-09 17:03:17 +02008# Copyright (C) 2010-2023 Harald Welte <laforge@gnumonks.org>
Sylvain Munaut76504e02010-12-07 00:24:32 +01009#
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 Weltefdb187d2023-07-09 17:03:17 +020024from typing import List, Optional, Tuple
25import typing # construct also has a Union, so we do typing.Union below
26
Harald Welte15fae982021-04-10 10:22:27 +020027from construct import *
28from pySim.construct import LV
Philipp Maier40ea4a42022-06-02 14:45:41 +020029from pySim.utils import rpad, b2h, h2b, sw_match, bertlv_encode_len, Hexstr, h2i, str_sanitize, expand_hex
Harald Weltefdb187d2023-07-09 17:03:17 +020030from pySim.utils import Hexstr, SwHexstr, ResTuple
Philipp Maier46f09af2021-03-25 20:24:27 +010031from pySim.exceptions import SwMatchError
Harald Weltefdb187d2023-07-09 17:03:17 +020032from pySim.transport import LinkBase
Sylvain Munaut76504e02010-12-07 00:24:32 +010033
Harald Weltefdb187d2023-07-09 17:03:17 +020034# A path can be either just a FID or a list of FID
35Path = typing.Union[Hexstr, List[Hexstr]]
Harald Weltec91085e2022-02-10 18:05:45 +010036
Vadim Yanitskiy04b5d9d2022-07-07 03:05:30 +070037class SimCardCommands:
Harald Weltefdb187d2023-07-09 17:03:17 +020038 def __init__(self, transport: LinkBase):
Harald Weltec91085e2022-02-10 18:05:45 +010039 self._tp = transport
40 self.cla_byte = "a0"
41 self.sel_ctrl = "0000"
Jan Balke14b350f2015-01-26 11:15:25 +010042
Harald Weltec91085e2022-02-10 18:05:45 +010043 # Extract a single FCP item from TLV
Harald Weltefdb187d2023-07-09 17:03:17 +020044 def __parse_fcp(self, fcp: Hexstr):
Harald Weltec91085e2022-02-10 18:05:45 +010045 # 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 Maier0e3fcaa2018-06-13 12:34:03 +020050
Harald Weltec91085e2022-02-10 18:05:45 +010051 # pytlv is case sensitive!
52 fcp = fcp.lower()
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020053
Harald Weltec91085e2022-02-10 18:05:45 +010054 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 Maier0e3fcaa2018-06-13 12:34:03 +020057
Harald Weltec91085e2022-02-10 18:05:45 +010058 # 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 Maier0e3fcaa2018-06-13 12:34:03 +020070
Harald Weltec91085e2022-02-10 18:05:45 +010071 # Skip FCP tag and length
72 tlv = fcp[skip:]
73 return tlvparser.parse(tlv)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020074
Harald Weltec91085e2022-02-10 18:05:45 +010075 # 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 Maier0e3fcaa2018-06-13 12:34:03 +020088
Harald Weltec91085e2022-02-10 18:05:45 +010089 # 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 Maier0e3fcaa2018-06-13 12:34:03 +020097
Harald Weltefdb187d2023-07-09 17:03:17 +020098 def get_atr(self) -> Hexstr:
Harald Weltec91085e2022-02-10 18:05:45 +010099 """Return the ATR of the currently inserted card."""
100 return self._tp.get_atr()
Alexander Chemerisd2d660a2017-07-18 16:52:25 +0300101
Harald Weltefdb187d2023-07-09 17:03:17 +0200102 def try_select_path(self, dir_list: List[Hexstr]) -> List[ResTuple]:
Harald Weltec91085e2022-02-10 18:05:45 +0100103 """ Try to select a specified path
Philipp Maier712251a2021-11-04 17:09:37 +0100104
Harald Weltec91085e2022-02-10 18:05:45 +0100105 Args:
106 dir_list : list of hex-string FIDs
107 """
Philipp Maier712251a2021-11-04 17:09:37 +0100108
Harald Weltec91085e2022-02-10 18:05:45 +0100109 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 Welteca673942020-06-03 15:19:40 +0200119
Harald Weltefdb187d2023-07-09 17:03:17 +0200120 def select_path(self, dir_list: Path) -> List[Hexstr]:
Harald Weltec91085e2022-02-10 18:05:45 +0100121 """Execute SELECT for an entire list/path of FIDs.
Harald Welteee3501f2021-04-02 13:00:18 +0200122
Harald Weltec91085e2022-02-10 18:05:45 +0100123 Args:
124 dir_list: list of FIDs representing the path to select
Harald Welteee3501f2021-04-02 13:00:18 +0200125
Harald Weltec91085e2022-02-10 18:05:45 +0100126 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 Munaut76504e02010-12-07 00:24:32 +0100136
Harald Weltefdb187d2023-07-09 17:03:17 +0200137 def select_file(self, fid: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100138 """Execute SELECT a given file by FID.
Philipp Maier712251a2021-11-04 17:09:37 +0100139
Harald Weltec91085e2022-02-10 18:05:45 +0100140 Args:
141 fid : file identifier as hex string
142 """
Philipp Maier712251a2021-11-04 17:09:37 +0100143
Harald Weltec91085e2022-02-10 18:05:45 +0100144 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
Harald Welte85484a92021-01-21 16:08:56 +0100145
Harald Weltefdb187d2023-07-09 17:03:17 +0200146 def select_parent_df(self) -> ResTuple:
Harald Welte3729c472022-02-12 14:36:37 +0100147 """Execute SELECT to switch to the parent DF """
148 return self._tp.send_apdu_checksw(self.cla_byte + "a4030400")
149
Harald Weltefdb187d2023-07-09 17:03:17 +0200150 def select_adf(self, aid: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100151 """Execute SELECT a given Applicaiton ADF.
Philipp Maier712251a2021-11-04 17:09:37 +0100152
Harald Weltec91085e2022-02-10 18:05:45 +0100153 Args:
154 aid : application identifier as hex string
155 """
Philipp Maier712251a2021-11-04 17:09:37 +0100156
Harald Weltec91085e2022-02-10 18:05:45 +0100157 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
158 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100159
Harald Weltefdb187d2023-07-09 17:03:17 +0200160 def read_binary(self, ef: Path, length: int = None, offset: int = 0) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100161 """Execute READD BINARY.
Harald Welteee3501f2021-04-02 13:00:18 +0200162
Harald Weltec91085e2022-02-10 18:05:45 +0100163 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 Maiere087f902021-11-03 11:46:05 +0100175
Harald Weltec91085e2022-02-10 18:05:45 +0100176 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 Munaut76504e02010-12-07 00:24:32 +0100190
Harald Weltefdb187d2023-07-09 17:03:17 +0200191 def update_binary(self, ef: Path, data: Hexstr, offset: int = 0, verify: bool = False,
192 conserve: bool = False) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100193 """Execute UPDATE BINARY.
Harald Welteee3501f2021-04-02 13:00:18 +0200194
Harald Weltec91085e2022-02-10 18:05:45 +0100195 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 Maier40ea4a42022-06-02 14:45:41 +0200201
202 file_len = self.binary_size(ef)
203 data = expand_hex(data, file_len)
204
Harald Weltec91085e2022-02-10 18:05:45 +0100205 data_length = len(data) // 2
Philipp Maier38c74f62021-03-17 17:19:52 +0100206
Harald Weltec91085e2022-02-10 18:05:45 +0100207 # 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 Maier38c74f62021-03-17 17:19:52 +0100212
Harald Weltec91085e2022-02-10 18:05:45 +0100213 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 Maier30eb8ca2020-05-11 22:51:37 +0200232
Harald Weltec91085e2022-02-10 18:05:45 +0100233 def verify_binary(self, ef, data: str, offset: int = 0):
234 """Verify contents of transparent EF.
Harald Welteee3501f2021-04-02 13:00:18 +0200235
Harald Weltec91085e2022-02-10 18:05:45 +0100236 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 Munaut76504e02010-12-07 00:24:32 +0100245
Harald Weltefdb187d2023-07-09 17:03:17 +0200246 def read_record(self, ef: Path, rec_no: int) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100247 """Execute READ RECORD.
Harald Welteee3501f2021-04-02 13:00:18 +0200248
Harald Weltec91085e2022-02-10 18:05:45 +0100249 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 Munaut76504e02010-12-07 00:24:32 +0100257
Harald Weltefdb187d2023-07-09 17:03:17 +0200258 def update_record(self, ef: Path, rec_no: int, data: Hexstr, force_len: bool = False,
259 verify: bool = False, conserve: bool = False) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100260 """Execute UPDATE RECORD.
Philipp Maier712251a2021-11-04 17:09:37 +0100261
Harald Weltec91085e2022-02-10 18:05:45 +0100262 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 Maier40ea4a42022-06-02 14:45:41 +0200270
Harald Weltec91085e2022-02-10 18:05:45 +0100271 res = self.select_path(ef)
Philipp Maier40ea4a42022-06-02 14:45:41 +0200272 rec_length = self.__record_len(res)
273 data = expand_hex(data, rec_length)
Philipp Maier42804d72021-04-30 11:56:23 +0200274
Harald Weltec91085e2022-02-10 18:05:45 +0100275 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 Maier40ea4a42022-06-02 14:45:41 +0200279 # 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 Weltec91085e2022-02-10 18:05:45 +0100281 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 Maier38c74f62021-03-17 17:19:52 +0100286
Harald Weltec91085e2022-02-10 18:05:45 +0100287 # 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 Maier38c74f62021-03-17 17:19:52 +0100293
Harald Weltec91085e2022-02-10 18:05:45 +0100294 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 Maier30eb8ca2020-05-11 22:51:37 +0200299
Harald Weltefdb187d2023-07-09 17:03:17 +0200300 def verify_record(self, ef: Path, rec_no: int, data: str):
Harald Weltec91085e2022-02-10 18:05:45 +0100301 """Verify record against given data
Philipp Maier712251a2021-11-04 17:09:37 +0100302
Harald Weltec91085e2022-02-10 18:05:45 +0100303 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 Munaut76504e02010-12-07 00:24:32 +0100312
Harald Weltefdb187d2023-07-09 17:03:17 +0200313 def record_size(self, ef: Path) -> int:
Harald Weltec91085e2022-02-10 18:05:45 +0100314 """Determine the record size of given file.
Harald Welteee3501f2021-04-02 13:00:18 +0200315
Harald Weltec91085e2022-02-10 18:05:45 +0100316 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 Munaut76504e02010-12-07 00:24:32 +0100321
Harald Weltefdb187d2023-07-09 17:03:17 +0200322 def record_count(self, ef: Path) -> int:
Harald Weltec91085e2022-02-10 18:05:45 +0100323 """Determine the number of records in given file.
Harald Welteee3501f2021-04-02 13:00:18 +0200324
Harald Weltec91085e2022-02-10 18:05:45 +0100325 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 Munaut76504e02010-12-07 00:24:32 +0100330
Harald Weltefdb187d2023-07-09 17:03:17 +0200331 def binary_size(self, ef: Path) -> int:
Harald Weltec91085e2022-02-10 18:05:45 +0100332 """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 Welteee3501f2021-04-02 13:00:18 +0200339
Harald Weltec91085e2022-02-10 18:05:45 +0100340 # TS 102 221 Section 11.3.1 low-level helper
Harald Weltefdb187d2023-07-09 17:03:17 +0200341 def _retrieve_data(self, tag: int, first: bool = True) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100342 if first:
343 pdu = '80cb008001%02x' % (tag)
344 else:
345 pdu = '80cb000000'
346 return self._tp.send_apdu_checksw(pdu)
Philipp Maier32daaf52020-05-11 21:48:33 +0200347
Harald Weltefdb187d2023-07-09 17:03:17 +0200348 def retrieve_data(self, ef: Path, tag: int) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100349 """Execute RETRIEVE DATA, see also TS 102 221 Section 11.3.1.
Harald Welte917d98c2021-04-21 11:51:25 +0200350
Harald Weltec91085e2022-02-10 18:05:45 +0100351 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 Welte917d98c2021-04-21 11:51:25 +0200366
Harald Weltec91085e2022-02-10 18:05:45 +0100367 # TS 102 221 Section 11.3.2 low-level helper
Harald Weltefdb187d2023-07-09 17:03:17 +0200368 def _set_data(self, data: Hexstr, first: bool = True) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100369 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 Welte917d98c2021-04-21 11:51:25 +0200377
Harald Weltefdb187d2023-07-09 17:03:17 +0200378 def set_data(self, ef, tag: int, value: str, verify: bool = False, conserve: bool = False) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100379 """Execute SET DATA.
Harald Welte917d98c2021-04-21 11:51:25 +0200380
Harald Weltec91085e2022-02-10 18:05:45 +0100381 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 Welte917d98c2021-04-21 11:51:25 +0200389
Harald Weltec91085e2022-02-10 18:05:45 +0100390 # 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 Welte917d98c2021-04-21 11:51:25 +0200393
Harald Weltec91085e2022-02-10 18:05:45 +0100394 # 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 Welte917d98c2021-04-21 11:51:25 +0200398
Harald Weltec91085e2022-02-10 18:05:45 +0100399 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 Welte917d98c2021-04-21 11:51:25 +0200408
Harald Weltefdb187d2023-07-09 17:03:17 +0200409 def run_gsm(self, rand: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100410 """Execute RUN GSM ALGORITHM.
Harald Welte917d98c2021-04-21 11:51:25 +0200411
Harald Weltec91085e2022-02-10 18:05:45 +0100412 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 Yanitskiy9970f592022-04-22 00:29:10 +0300418 return self._tp.send_apdu_checksw('a0' + '88000010' + rand, sw='9000')
Philipp Maier712251a2021-11-04 17:09:37 +0100419
Harald Weltefdb187d2023-07-09 17:03:17 +0200420 def authenticate(self, rand: Hexstr, autn: Hexstr, context: str = '3g') -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100421 """Execute AUTHENTICATE (USIM/ISIM).
Sylvain Munaut76504e02010-12-07 00:24:32 +0100422
Harald Weltec91085e2022-02-10 18:05:45 +0100423 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 Maier712251a2021-11-04 17:09:37 +0100447
Harald Weltefdb187d2023-07-09 17:03:17 +0200448 def status(self) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100449 """Execute a STATUS command as per TS 102 221 Section 11.1.2."""
450 return self._tp.send_apdu_checksw('80F20000ff')
Harald Welte15fae982021-04-10 10:22:27 +0200451
Harald Weltefdb187d2023-07-09 17:03:17 +0200452 def deactivate_file(self) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100453 """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 Welte34b05d32021-05-25 22:03:13 +0200455
Harald Weltefdb187d2023-07-09 17:03:17 +0200456 def activate_file(self, fid: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100457 """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15.
Harald Weltea4631612021-04-10 18:17:55 +0200458
Harald Weltec91085e2022-02-10 18:05:45 +0100459 Args:
460 fid : file identifier as hex string
461 """
462 return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid)
Philipp Maier712251a2021-11-04 17:09:37 +0100463
Harald Weltefdb187d2023-07-09 17:03:17 +0200464 def create_file(self, payload: Hexstr) -> ResTuple:
Harald Welte3c9b7842021-10-19 21:44:24 +0200465 """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 Weltefdb187d2023-07-09 17:03:17 +0200468 def resize_file(self, payload: Hexstr) -> ResTuple:
Harald Welte0707b802023-03-07 11:43:37 +0100469 """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 Weltefdb187d2023-07-09 17:03:17 +0200472 def delete_file(self, fid: Hexstr) -> ResTuple:
Harald Welte3c9b7842021-10-19 21:44:24 +0200473 """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 Weltefdb187d2023-07-09 17:03:17 +0200476 def terminate_df(self, fid: Hexstr) -> ResTuple:
Harald Welte3c9b7842021-10-19 21:44:24 +0200477 """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 Weltefdb187d2023-07-09 17:03:17 +0200480 def terminate_ef(self, fid: Hexstr) -> ResTuple:
Harald Welte3c9b7842021-10-19 21:44:24 +0200481 """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 Weltefdb187d2023-07-09 17:03:17 +0200484 def terminate_card_usage(self) -> ResTuple:
Harald Welte3c9b7842021-10-19 21:44:24 +0200485 """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 Weltefdb187d2023-07-09 17:03:17 +0200488 def manage_channel(self, mode: str = 'open', lchan_nr: int =0) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100489 """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17.
Harald Weltea4631612021-04-10 18:17:55 +0200490
Harald Weltec91085e2022-02-10 18:05:45 +0100491 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 Maier712251a2021-11-04 17:09:37 +0100501
Harald Weltefdb187d2023-07-09 17:03:17 +0200502 def reset_card(self) -> Hexstr:
Harald Weltec91085e2022-02-10 18:05:45 +0100503 """Physically reset the card"""
504 return self._tp.reset_card()
Harald Welte703f9332021-04-10 18:39:32 +0200505
Harald Weltefdb187d2023-07-09 17:03:17 +0200506 def _chv_process_sw(self, op_name: str, chv_no: int, pin_code: Hexstr, sw: SwHexstr):
Harald Weltec91085e2022-02-10 18:05:45 +0100507 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 Munaut76504e02010-12-07 00:24:32 +0100512
Harald Weltefdb187d2023-07-09 17:03:17 +0200513 def verify_chv(self, chv_no: int, code: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100514 """Verify a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100515
Harald Weltec91085e2022-02-10 18:05:45 +0100516 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 Maier712251a2021-11-04 17:09:37 +0100525
Harald Weltec91085e2022-02-10 18:05:45 +0100526 def unblock_chv(self, chv_no: int, puk_code: str, pin_code: str):
527 """Unblock a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100528
Harald Weltec91085e2022-02-10 18:05:45 +0100529 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 Maier712251a2021-11-04 17:09:37 +0100539
Harald Weltefdb187d2023-07-09 17:03:17 +0200540 def change_chv(self, chv_no: int, pin_code: Hexstr, new_pin_code: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100541 """Change a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100542
Harald Weltec91085e2022-02-10 18:05:45 +0100543 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 Maier712251a2021-11-04 17:09:37 +0100553
Harald Weltefdb187d2023-07-09 17:03:17 +0200554 def disable_chv(self, chv_no: int, pin_code: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100555 """Disable a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100556
Harald Weltec91085e2022-02-10 18:05:45 +0100557 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 Maier712251a2021-11-04 17:09:37 +0100567
Harald Weltefdb187d2023-07-09 17:03:17 +0200568 def enable_chv(self, chv_no: int, pin_code: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100569 """Enable a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100570
Harald Weltec91085e2022-02-10 18:05:45 +0100571 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 Maier712251a2021-11-04 17:09:37 +0100580
Harald Weltefdb187d2023-07-09 17:03:17 +0200581 def envelope(self, payload: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100582 """Send one ENVELOPE command to the SIM
Harald Weltef2011662021-05-24 23:19:30 +0200583
Harald Weltec91085e2022-02-10 18:05:45 +0100584 Args:
585 payload : payload as hex string
586 """
587 return self._tp.send_apdu_checksw('80c20000%02x%s' % (len(payload)//2, payload))
Philipp Maier712251a2021-11-04 17:09:37 +0100588
Harald Weltefdb187d2023-07-09 17:03:17 +0200589 def terminal_profile(self, payload: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100590 """Send TERMINAL PROFILE to card
Harald Welte846a8982021-10-08 15:47:16 +0200591
Harald Weltec91085e2022-02-10 18:05:45 +0100592 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 Maier712251a2021-11-04 17:09:37 +0100598
Harald Weltec91085e2022-02-10 18:05:45 +0100599 # ETSI TS 102 221 11.1.22
Harald Weltefdb187d2023-07-09 17:03:17 +0200600 def suspend_uicc(self, min_len_secs: int = 60, max_len_secs: int = 43200) -> Tuple[int, Hexstr, SwHexstr]:
Harald Weltec91085e2022-02-10 18:05:45 +0100601 """Send SUSPEND UICC to the card.
Harald Welteec950532021-10-20 13:09:00 +0200602
Harald Weltec91085e2022-02-10 18:05:45 +0100603 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 Maier712251a2021-11-04 17:09:37 +0100618
Harald Weltec91085e2022-02-10 18:05:45 +0100619 def decode_duration(enc: Hexstr) -> int:
620 time_unit = enc[:2]
Harald Weltec85ae412023-06-06 09:03:27 +0200621 length = h2i(enc[2:4])[0]
Harald Weltec91085e2022-02-10 18:05:45 +0100622 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 Welte34eb5042022-02-21 17:19:28 +0100641
Harald Welteb0e0dce2023-06-06 17:21:13 +0200642 # ETSI TS 102 221 11.1.22
Harald Weltefdb187d2023-07-09 17:03:17 +0200643 def resume_uicc(self, token: Hexstr) -> ResTuple:
Harald Welteb0e0dce2023-06-06 17:21:13 +0200644 """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 Weltefdb187d2023-07-09 17:03:17 +0200648 return (data, sw)
Harald Welteb0e0dce2023-06-06 17:21:13 +0200649
Harald Welte34eb5042022-02-21 17:19:28 +0100650 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 Welte7ec82232023-06-06 18:15:52 +0200653
654 # TS 31.102 Section 7.5.2
Harald Weltefdb187d2023-07-09 17:03:17 +0200655 def get_identity(self, context: int) -> Tuple[Hexstr, SwHexstr]:
Harald Welte7ec82232023-06-06 18:15:52 +0200656 data, sw = self._tp.send_apdu_checksw('807800%02x00' % (context))
657 return (data, sw)