blob: 20b9c44301f4253de372a16b1855124e429cf044 [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 Welte917d98c2021-04-21 11:51:25 +02008# Copyright (C) 2010-2021 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 Welte15fae982021-04-10 10:22:27 +020024from construct import *
25from pySim.construct import LV
Philipp Maier796ca3d2021-11-01 17:13:57 +010026from pySim.utils import rpad, b2h, h2b, sw_match, bertlv_encode_len, Hexstr, h2i, str_sanitize
Philipp Maier46f09af2021-03-25 20:24:27 +010027from pySim.exceptions import SwMatchError
Sylvain Munaut76504e02010-12-07 00:24:32 +010028
Harald Weltec91085e2022-02-10 18:05:45 +010029
Sylvain Munaut76504e02010-12-07 00:24:32 +010030class SimCardCommands(object):
Harald Weltec91085e2022-02-10 18:05:45 +010031 def __init__(self, transport):
32 self._tp = transport
33 self.cla_byte = "a0"
34 self.sel_ctrl = "0000"
Jan Balke14b350f2015-01-26 11:15:25 +010035
Harald Weltec91085e2022-02-10 18:05:45 +010036 # Extract a single FCP item from TLV
37 def __parse_fcp(self, fcp):
38 # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF,
39 # DF or ADF
40 from pytlv.TLV import TLV
41 tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b',
42 '8c', '80', 'ab', 'c6', '81', '88'])
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020043
Harald Weltec91085e2022-02-10 18:05:45 +010044 # pytlv is case sensitive!
45 fcp = fcp.lower()
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020046
Harald Weltec91085e2022-02-10 18:05:45 +010047 if fcp[0:2] != '62':
48 raise ValueError(
49 'Tag of the FCP template does not match, expected 62 but got %s' % fcp[0:2])
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020050
Harald Weltec91085e2022-02-10 18:05:45 +010051 # Unfortunately the spec is not very clear if the FCP length is
52 # coded as one or two byte vale, so we have to try it out by
53 # checking if the length of the remaining TLV string matches
54 # what we get in the length field.
55 # See also ETSI TS 102 221, chapter 11.1.1.3.0 Base coding.
56 exp_tlv_len = int(fcp[2:4], 16)
57 if len(fcp[4:]) // 2 == exp_tlv_len:
58 skip = 4
59 else:
60 exp_tlv_len = int(fcp[2:6], 16)
61 if len(fcp[4:]) // 2 == exp_tlv_len:
62 skip = 6
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020063
Harald Weltec91085e2022-02-10 18:05:45 +010064 # Skip FCP tag and length
65 tlv = fcp[skip:]
66 return tlvparser.parse(tlv)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020067
Harald Weltec91085e2022-02-10 18:05:45 +010068 # Tell the length of a record by the card response
69 # USIMs respond with an FCP template, which is different
70 # from what SIMs responds. See also:
71 # USIM: ETSI TS 102 221, chapter 11.1.1.3 Response Data
72 # SIM: GSM 11.11, chapter 9.2.1 SELECT
73 def __record_len(self, r) -> int:
74 if self.sel_ctrl == "0004":
75 tlv_parsed = self.__parse_fcp(r[-1])
76 file_descriptor = tlv_parsed['82']
77 # See also ETSI TS 102 221, chapter 11.1.1.4.3 File Descriptor
78 return int(file_descriptor[4:8], 16)
79 else:
80 return int(r[-1][28:30], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020081
Harald Weltec91085e2022-02-10 18:05:45 +010082 # Tell the length of a binary file. See also comment
83 # above.
84 def __len(self, r) -> int:
85 if self.sel_ctrl == "0004":
86 tlv_parsed = self.__parse_fcp(r[-1])
87 return int(tlv_parsed['80'], 16)
88 else:
89 return int(r[-1][4:8], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020090
Harald Weltec91085e2022-02-10 18:05:45 +010091 def get_atr(self) -> str:
92 """Return the ATR of the currently inserted card."""
93 return self._tp.get_atr()
Alexander Chemerisd2d660a2017-07-18 16:52:25 +030094
Harald Weltec91085e2022-02-10 18:05:45 +010095 def try_select_path(self, dir_list):
96 """ Try to select a specified path
Philipp Maier712251a2021-11-04 17:09:37 +010097
Harald Weltec91085e2022-02-10 18:05:45 +010098 Args:
99 dir_list : list of hex-string FIDs
100 """
Philipp Maier712251a2021-11-04 17:09:37 +0100101
Harald Weltec91085e2022-02-10 18:05:45 +0100102 rv = []
103 if type(dir_list) is not list:
104 dir_list = [dir_list]
105 for i in dir_list:
106 data, sw = self._tp.send_apdu(
107 self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
108 rv.append((data, sw))
109 if sw != '9000':
110 return rv
111 return rv
Harald Welteca673942020-06-03 15:19:40 +0200112
Harald Weltec91085e2022-02-10 18:05:45 +0100113 def select_path(self, dir_list):
114 """Execute SELECT for an entire list/path of FIDs.
Harald Welteee3501f2021-04-02 13:00:18 +0200115
Harald Weltec91085e2022-02-10 18:05:45 +0100116 Args:
117 dir_list: list of FIDs representing the path to select
Harald Welteee3501f2021-04-02 13:00:18 +0200118
Harald Weltec91085e2022-02-10 18:05:45 +0100119 Returns:
120 list of return values (FCP in hex encoding) for each element of the path
121 """
122 rv = []
123 if type(dir_list) is not list:
124 dir_list = [dir_list]
125 for i in dir_list:
126 data, sw = self.select_file(i)
127 rv.append(data)
128 return rv
Sylvain Munaut76504e02010-12-07 00:24:32 +0100129
Harald Weltec91085e2022-02-10 18:05:45 +0100130 def select_file(self, fid: str):
131 """Execute SELECT a given file by FID.
Philipp Maier712251a2021-11-04 17:09:37 +0100132
Harald Weltec91085e2022-02-10 18:05:45 +0100133 Args:
134 fid : file identifier as hex string
135 """
Philipp Maier712251a2021-11-04 17:09:37 +0100136
Harald Weltec91085e2022-02-10 18:05:45 +0100137 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
Harald Welte85484a92021-01-21 16:08:56 +0100138
Harald Weltec91085e2022-02-10 18:05:45 +0100139 def select_adf(self, aid: str):
140 """Execute SELECT a given Applicaiton ADF.
Philipp Maier712251a2021-11-04 17:09:37 +0100141
Harald Weltec91085e2022-02-10 18:05:45 +0100142 Args:
143 aid : application identifier as hex string
144 """
Philipp Maier712251a2021-11-04 17:09:37 +0100145
Harald Weltec91085e2022-02-10 18:05:45 +0100146 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
147 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100148
Harald Weltec91085e2022-02-10 18:05:45 +0100149 def read_binary(self, ef, length: int = None, offset: int = 0):
150 """Execute READD BINARY.
Harald Welteee3501f2021-04-02 13:00:18 +0200151
Harald Weltec91085e2022-02-10 18:05:45 +0100152 Args:
153 ef : string or list of strings indicating name or path of transparent EF
154 length : number of bytes to read
155 offset : byte offset in file from which to start reading
156 """
157 r = self.select_path(ef)
158 if len(r[-1]) == 0:
159 return (None, None)
160 if length is None:
161 length = self.__len(r) - offset
162 if length < 0:
163 return (None, None)
Philipp Maiere087f902021-11-03 11:46:05 +0100164
Harald Weltec91085e2022-02-10 18:05:45 +0100165 total_data = ''
166 chunk_offset = 0
167 while chunk_offset < length:
168 chunk_len = min(255, length-chunk_offset)
169 pdu = self.cla_byte + \
170 'b0%04x%02x' % (offset + chunk_offset, chunk_len)
171 try:
172 data, sw = self._tp.send_apdu_checksw(pdu)
173 except Exception as e:
174 raise ValueError('%s, failed to read (offset %d)' %
175 (str_sanitize(str(e)), offset))
176 total_data += data
177 chunk_offset += chunk_len
178 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100179
Harald Weltec91085e2022-02-10 18:05:45 +0100180 def update_binary(self, ef, data: str, offset: int = 0, verify: bool = False, conserve: bool = False):
181 """Execute UPDATE BINARY.
Harald Welteee3501f2021-04-02 13:00:18 +0200182
Harald Weltec91085e2022-02-10 18:05:45 +0100183 Args:
184 ef : string or list of strings indicating name or path of transparent EF
185 data : hex string of data to be written
186 offset : byte offset in file from which to start writing
187 verify : Whether or not to verify data after write
188 """
189 data_length = len(data) // 2
Philipp Maier38c74f62021-03-17 17:19:52 +0100190
Harald Weltec91085e2022-02-10 18:05:45 +0100191 # Save write cycles by reading+comparing before write
192 if conserve:
193 data_current, sw = self.read_binary(ef, data_length, offset)
194 if data_current == data:
195 return None, sw
Philipp Maier38c74f62021-03-17 17:19:52 +0100196
Harald Weltec91085e2022-02-10 18:05:45 +0100197 self.select_path(ef)
198 total_data = ''
199 chunk_offset = 0
200 while chunk_offset < data_length:
201 chunk_len = min(255, data_length - chunk_offset)
202 # chunk_offset is bytes, but data slicing is hex chars, so we need to multiply by 2
203 pdu = self.cla_byte + \
204 'd6%04x%02x' % (offset + chunk_offset, chunk_len) + \
205 data[chunk_offset*2: (chunk_offset+chunk_len)*2]
206 try:
207 chunk_data, chunk_sw = self._tp.send_apdu_checksw(pdu)
208 except Exception as e:
209 raise ValueError('%s, failed to write chunk (chunk_offset %d, chunk_len %d)' %
210 (str_sanitize(str(e)), chunk_offset, chunk_len))
211 total_data += data
212 chunk_offset += chunk_len
213 if verify:
214 self.verify_binary(ef, data, offset)
215 return total_data, chunk_sw
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200216
Harald Weltec91085e2022-02-10 18:05:45 +0100217 def verify_binary(self, ef, data: str, offset: int = 0):
218 """Verify contents of transparent EF.
Harald Welteee3501f2021-04-02 13:00:18 +0200219
Harald Weltec91085e2022-02-10 18:05:45 +0100220 Args:
221 ef : string or list of strings indicating name or path of transparent EF
222 data : hex string of expected data
223 offset : byte offset in file from which to start verifying
224 """
225 res = self.read_binary(ef, len(data) // 2, offset)
226 if res[0].lower() != data.lower():
227 raise ValueError('Binary verification failed (expected %s, got %s)' % (
228 data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100229
Harald Weltec91085e2022-02-10 18:05:45 +0100230 def read_record(self, ef, rec_no: int):
231 """Execute READ RECORD.
Harald Welteee3501f2021-04-02 13:00:18 +0200232
Harald Weltec91085e2022-02-10 18:05:45 +0100233 Args:
234 ef : string or list of strings indicating name or path of linear fixed EF
235 rec_no : record number to read
236 """
237 r = self.select_path(ef)
238 rec_length = self.__record_len(r)
239 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
240 return self._tp.send_apdu_checksw(pdu)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100241
Harald Weltec91085e2022-02-10 18:05:45 +0100242 def update_record(self, ef, rec_no: int, data: str, force_len: bool = False, verify: bool = False,
243 conserve: bool = False):
244 """Execute UPDATE RECORD.
Philipp Maier712251a2021-11-04 17:09:37 +0100245
Harald Weltec91085e2022-02-10 18:05:45 +0100246 Args:
247 ef : string or list of strings indicating name or path of linear fixed EF
248 rec_no : record number to read
249 data : hex string of data to be written
250 force_len : enforce record length by using the actual data length
251 verify : verify data by re-reading the record
252 conserve : read record and compare it with data, skip write on match
253 """
254 res = self.select_path(ef)
Philipp Maier42804d72021-04-30 11:56:23 +0200255
Harald Weltec91085e2022-02-10 18:05:45 +0100256 if force_len:
257 # enforce the record length by the actual length of the given data input
258 rec_length = len(data) // 2
259 else:
260 # determine the record length from the select response of the file and pad
261 # the input data with 0xFF if necessary. In cases where the input data
262 # exceed we throw an exception.
263 rec_length = self.__record_len(res)
264 if (len(data) // 2 > rec_length):
265 raise ValueError('Data length exceeds record length (expected max %d, got %d)' % (
266 rec_length, len(data) // 2))
267 elif (len(data) // 2 < rec_length):
268 data = rpad(data, rec_length * 2)
Philipp Maier38c74f62021-03-17 17:19:52 +0100269
Harald Weltec91085e2022-02-10 18:05:45 +0100270 # Save write cycles by reading+comparing before write
271 if conserve:
272 data_current, sw = self.read_record(ef, rec_no)
273 data_current = data_current[0:rec_length*2]
274 if data_current == data:
275 return None, sw
Philipp Maier38c74f62021-03-17 17:19:52 +0100276
Harald Weltec91085e2022-02-10 18:05:45 +0100277 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
278 res = self._tp.send_apdu_checksw(pdu)
279 if verify:
280 self.verify_record(ef, rec_no, data)
281 return res
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200282
Harald Weltec91085e2022-02-10 18:05:45 +0100283 def verify_record(self, ef, rec_no: int, data: str):
284 """Verify record against given data
Philipp Maier712251a2021-11-04 17:09:37 +0100285
Harald Weltec91085e2022-02-10 18:05:45 +0100286 Args:
287 ef : string or list of strings indicating name or path of linear fixed EF
288 rec_no : record number to read
289 data : hex string of data to be verified
290 """
291 res = self.read_record(ef, rec_no)
292 if res[0].lower() != data.lower():
293 raise ValueError('Record verification failed (expected %s, got %s)' % (
294 data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100295
Harald Weltec91085e2022-02-10 18:05:45 +0100296 def record_size(self, ef):
297 """Determine the record size of given file.
Harald Welteee3501f2021-04-02 13:00:18 +0200298
Harald Weltec91085e2022-02-10 18:05:45 +0100299 Args:
300 ef : string or list of strings indicating name or path of linear fixed EF
301 """
302 r = self.select_path(ef)
303 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304
Harald Weltec91085e2022-02-10 18:05:45 +0100305 def record_count(self, ef):
306 """Determine the number of records in given file.
Harald Welteee3501f2021-04-02 13:00:18 +0200307
Harald Weltec91085e2022-02-10 18:05:45 +0100308 Args:
309 ef : string or list of strings indicating name or path of linear fixed EF
310 """
311 r = self.select_path(ef)
312 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100313
Harald Weltec91085e2022-02-10 18:05:45 +0100314 def binary_size(self, ef):
315 """Determine the size of given transparent file.
316
317 Args:
318 ef : string or list of strings indicating name or path of transparent EF
319 """
320 r = self.select_path(ef)
321 return self.__len(r)
Harald Welteee3501f2021-04-02 13:00:18 +0200322
Harald Weltec91085e2022-02-10 18:05:45 +0100323 # TS 102 221 Section 11.3.1 low-level helper
324 def _retrieve_data(self, tag: int, first: bool = True):
325 if first:
326 pdu = '80cb008001%02x' % (tag)
327 else:
328 pdu = '80cb000000'
329 return self._tp.send_apdu_checksw(pdu)
Philipp Maier32daaf52020-05-11 21:48:33 +0200330
Harald Weltec91085e2022-02-10 18:05:45 +0100331 def retrieve_data(self, ef, tag: int):
332 """Execute RETRIEVE DATA, see also TS 102 221 Section 11.3.1.
Harald Welte917d98c2021-04-21 11:51:25 +0200333
Harald Weltec91085e2022-02-10 18:05:45 +0100334 Args
335 ef : string or list of strings indicating name or path of transparent EF
336 tag : BER-TLV Tag of value to be retrieved
337 """
338 r = self.select_path(ef)
339 if len(r[-1]) == 0:
340 return (None, None)
341 total_data = ''
342 # retrieve first block
343 data, sw = self._retrieve_data(tag, first=True)
344 total_data += data
345 while sw == '62f1' or sw == '62f2':
346 data, sw = self._retrieve_data(tag, first=False)
347 total_data += data
348 return total_data, sw
Harald Welte917d98c2021-04-21 11:51:25 +0200349
Harald Weltec91085e2022-02-10 18:05:45 +0100350 # TS 102 221 Section 11.3.2 low-level helper
351 def _set_data(self, data: str, first: bool = True):
352 if first:
353 p1 = 0x80
354 else:
355 p1 = 0x00
356 if isinstance(data, bytes) or isinstance(data, bytearray):
357 data = b2h(data)
358 pdu = '80db00%02x%02x%s' % (p1, len(data)//2, data)
359 return self._tp.send_apdu_checksw(pdu)
Harald Welte917d98c2021-04-21 11:51:25 +0200360
Harald Weltec91085e2022-02-10 18:05:45 +0100361 def set_data(self, ef, tag: int, value: str, verify: bool = False, conserve: bool = False):
362 """Execute SET DATA.
Harald Welte917d98c2021-04-21 11:51:25 +0200363
Harald Weltec91085e2022-02-10 18:05:45 +0100364 Args
365 ef : string or list of strings indicating name or path of transparent EF
366 tag : BER-TLV Tag of value to be stored
367 value : BER-TLV value to be stored
368 """
369 r = self.select_path(ef)
370 if len(r[-1]) == 0:
371 return (None, None)
Harald Welte917d98c2021-04-21 11:51:25 +0200372
Harald Weltec91085e2022-02-10 18:05:45 +0100373 # in case of deleting the data, we only have 'tag' but no 'value'
374 if not value:
375 return self._set_data('%02x' % tag, first=True)
Harald Welte917d98c2021-04-21 11:51:25 +0200376
Harald Weltec91085e2022-02-10 18:05:45 +0100377 # FIXME: proper BER-TLV encode
378 tl = '%02x%s' % (tag, b2h(bertlv_encode_len(len(value)//2)))
379 tlv = tl + value
380 tlv_bin = h2b(tlv)
Harald Welte917d98c2021-04-21 11:51:25 +0200381
Harald Weltec91085e2022-02-10 18:05:45 +0100382 first = True
383 total_len = len(tlv_bin)
384 remaining = tlv_bin
385 while len(remaining) > 0:
386 fragment = remaining[:255]
387 rdata, sw = self._set_data(fragment, first=first)
388 first = False
389 remaining = remaining[255:]
390 return rdata, sw
Harald Welte917d98c2021-04-21 11:51:25 +0200391
Harald Weltec91085e2022-02-10 18:05:45 +0100392 def run_gsm(self, rand: str):
393 """Execute RUN GSM ALGORITHM.
Harald Welte917d98c2021-04-21 11:51:25 +0200394
Harald Weltec91085e2022-02-10 18:05:45 +0100395 Args:
396 rand : 16 byte random data as hex string (RAND)
397 """
398 if len(rand) != 32:
399 raise ValueError('Invalid rand')
400 self.select_path(['3f00', '7f20'])
401 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Philipp Maier712251a2021-11-04 17:09:37 +0100402
Harald Weltec91085e2022-02-10 18:05:45 +0100403 def authenticate(self, rand: str, autn: str, context='3g'):
404 """Execute AUTHENTICATE (USIM/ISIM).
Sylvain Munaut76504e02010-12-07 00:24:32 +0100405
Harald Weltec91085e2022-02-10 18:05:45 +0100406 Args:
407 rand : 16 byte random data as hex string (RAND)
408 autn : 8 byte Autentication Token (AUTN)
409 context : 16 byte random data ('3g' or 'gsm')
410 """
411 # 3GPP TS 31.102 Section 7.1.2.1
412 AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV))
413 AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV)
414 AuthResp3GSuccess = Struct(
415 Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV))
416 AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess)
417 # build parameters
418 cmd_data = {'rand': rand, 'autn': autn}
419 if context == '3g':
420 p2 = '81'
421 elif context == 'gsm':
422 p2 = '80'
423 (data, sw) = self._tp.send_apdu_constr_checksw(
424 self.cla_byte, '88', '00', p2, AuthCmd3G, cmd_data, AuthResp3G)
425 if 'auts' in data:
426 ret = {'synchronisation_failure': data}
427 else:
428 ret = {'successful_3g_authentication': data}
429 return (ret, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100430
Harald Weltec91085e2022-02-10 18:05:45 +0100431 def status(self):
432 """Execute a STATUS command as per TS 102 221 Section 11.1.2."""
433 return self._tp.send_apdu_checksw('80F20000ff')
Harald Welte15fae982021-04-10 10:22:27 +0200434
Harald Weltec91085e2022-02-10 18:05:45 +0100435 def deactivate_file(self):
436 """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14."""
437 return self._tp.send_apdu_constr_checksw(self.cla_byte, '04', '00', '00', None, None, None)
Harald Welte34b05d32021-05-25 22:03:13 +0200438
Harald Weltec91085e2022-02-10 18:05:45 +0100439 def activate_file(self, fid):
440 """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15.
Harald Weltea4631612021-04-10 18:17:55 +0200441
Harald Weltec91085e2022-02-10 18:05:45 +0100442 Args:
443 fid : file identifier as hex string
444 """
445 return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid)
Philipp Maier712251a2021-11-04 17:09:37 +0100446
Harald Weltec91085e2022-02-10 18:05:45 +0100447 def manage_channel(self, mode='open', lchan_nr=0):
448 """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17.
Harald Weltea4631612021-04-10 18:17:55 +0200449
Harald Weltec91085e2022-02-10 18:05:45 +0100450 Args:
451 mode : logical channel operation code ('open' or 'close')
452 lchan_nr : logical channel number (1-19, 0=assigned by UICC)
453 """
454 if mode == 'close':
455 p1 = 0x80
456 else:
457 p1 = 0x00
458 pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr)
459 return self._tp.send_apdu_checksw(pdu)
Philipp Maier712251a2021-11-04 17:09:37 +0100460
Harald Weltec91085e2022-02-10 18:05:45 +0100461 def reset_card(self):
462 """Physically reset the card"""
463 return self._tp.reset_card()
Harald Welte703f9332021-04-10 18:39:32 +0200464
Harald Weltec91085e2022-02-10 18:05:45 +0100465 def _chv_process_sw(self, op_name, chv_no, pin_code, sw):
466 if sw_match(sw, '63cx'):
467 raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' %
468 (op_name, chv_no, b2h(pin_code).upper(), int(sw[3])))
469 elif (sw != '9000'):
470 raise SwMatchError(sw, '9000')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100471
Harald Weltec91085e2022-02-10 18:05:45 +0100472 def verify_chv(self, chv_no: int, code: str):
473 """Verify a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100474
Harald Weltec91085e2022-02-10 18:05:45 +0100475 Args:
476 chv_no : chv number (1=CHV1, 2=CHV2, ...)
477 code : chv code as hex string
478 """
479 fc = rpad(b2h(code), 16)
480 data, sw = self._tp.send_apdu(
481 self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
482 self._chv_process_sw('verify', chv_no, code, sw)
483 return (data, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100484
Harald Weltec91085e2022-02-10 18:05:45 +0100485 def unblock_chv(self, chv_no: int, puk_code: str, pin_code: str):
486 """Unblock a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100487
Harald Weltec91085e2022-02-10 18:05:45 +0100488 Args:
489 chv_no : chv number (1=CHV1, 2=CHV2, ...)
490 puk_code : puk code as hex string
491 pin_code : new chv code as hex string
492 """
493 fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16)
494 data, sw = self._tp.send_apdu(
495 self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc)
496 self._chv_process_sw('unblock', chv_no, pin_code, sw)
497 return (data, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100498
Harald Weltec91085e2022-02-10 18:05:45 +0100499 def change_chv(self, chv_no: int, pin_code: str, new_pin_code: str):
500 """Change a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100501
Harald Weltec91085e2022-02-10 18:05:45 +0100502 Args:
503 chv_no : chv number (1=CHV1, 2=CHV2, ...)
504 pin_code : current chv code as hex string
505 new_pin_code : new chv code as hex string
506 """
507 fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16)
508 data, sw = self._tp.send_apdu(
509 self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc)
510 self._chv_process_sw('change', chv_no, pin_code, sw)
511 return (data, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100512
Harald Weltec91085e2022-02-10 18:05:45 +0100513 def disable_chv(self, chv_no: int, pin_code: str):
514 """Disable 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 pin_code : current chv code as hex string
519 new_pin_code : new chv code as hex string
520 """
521 fc = rpad(b2h(pin_code), 16)
522 data, sw = self._tp.send_apdu(
523 self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc)
524 self._chv_process_sw('disable', chv_no, pin_code, sw)
525 return (data, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100526
Harald Weltec91085e2022-02-10 18:05:45 +0100527 def enable_chv(self, chv_no: int, pin_code: str):
528 """Enable a given CHV (Card Holder Verification == PIN)
Philipp Maier46f09af2021-03-25 20:24:27 +0100529
Harald Weltec91085e2022-02-10 18:05:45 +0100530 Args:
531 chv_no : chv number (1=CHV1, 2=CHV2, ...)
532 pin_code : chv code as hex string
533 """
534 fc = rpad(b2h(pin_code), 16)
535 data, sw = self._tp.send_apdu(
536 self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc)
537 self._chv_process_sw('enable', chv_no, pin_code, sw)
538 return (data, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100539
Harald Weltec91085e2022-02-10 18:05:45 +0100540 def envelope(self, payload: str):
541 """Send one ENVELOPE command to the SIM
Harald Weltef2011662021-05-24 23:19:30 +0200542
Harald Weltec91085e2022-02-10 18:05:45 +0100543 Args:
544 payload : payload as hex string
545 """
546 return self._tp.send_apdu_checksw('80c20000%02x%s' % (len(payload)//2, payload))
Philipp Maier712251a2021-11-04 17:09:37 +0100547
Harald Weltec91085e2022-02-10 18:05:45 +0100548 def terminal_profile(self, payload: str):
549 """Send TERMINAL PROFILE to card
Harald Welte846a8982021-10-08 15:47:16 +0200550
Harald Weltec91085e2022-02-10 18:05:45 +0100551 Args:
552 payload : payload as hex string
553 """
554 data_length = len(payload) // 2
555 data, sw = self._tp.send_apdu(('80100000%02x' % data_length) + payload)
556 return (data, sw)
Philipp Maier712251a2021-11-04 17:09:37 +0100557
Harald Weltec91085e2022-02-10 18:05:45 +0100558 # ETSI TS 102 221 11.1.22
559 def suspend_uicc(self, min_len_secs: int = 60, max_len_secs: int = 43200):
560 """Send SUSPEND UICC to the card.
Harald Welteec950532021-10-20 13:09:00 +0200561
Harald Weltec91085e2022-02-10 18:05:45 +0100562 Args:
563 min_len_secs : mimumum suspend time seconds
564 max_len_secs : maximum suspend time seconds
565 """
566 def encode_duration(secs: int) -> Hexstr:
567 if secs >= 10*24*60*60:
568 return '04%02x' % (secs // (10*24*60*60))
569 elif secs >= 24*60*60:
570 return '03%02x' % (secs // (24*60*60))
571 elif secs >= 60*60:
572 return '02%02x' % (secs // (60*60))
573 elif secs >= 60:
574 return '01%02x' % (secs // 60)
575 else:
576 return '00%02x' % secs
Philipp Maier712251a2021-11-04 17:09:37 +0100577
Harald Weltec91085e2022-02-10 18:05:45 +0100578 def decode_duration(enc: Hexstr) -> int:
579 time_unit = enc[:2]
580 length = h2i(enc[2:4])
581 if time_unit == '04':
582 return length * 10*24*60*60
583 elif time_unit == '03':
584 return length * 24*60*60
585 elif time_unit == '02':
586 return length * 60*60
587 elif time_unit == '01':
588 return length * 60
589 elif time_unit == '00':
590 return length
591 else:
592 raise ValueError('Time unit must be 0x00..0x04')
593 min_dur_enc = encode_duration(min_len_secs)
594 max_dur_enc = encode_duration(max_len_secs)
595 data, sw = self._tp.send_apdu_checksw(
596 '8076000004' + min_dur_enc + max_dur_enc)
597 negotiated_duration_secs = decode_duration(data[:4])
598 resume_token = data[4:]
599 return (negotiated_duration_secs, resume_token, sw)