blob: 5184a77a2ba49c4bd4303723cd9fa322a54ff37b [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>
8# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
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
Philipp Maier46f09af2021-03-25 20:24:27 +010024from pySim.utils import rpad, b2h, sw_match
25from pySim.exceptions import SwMatchError
Sylvain Munaut76504e02010-12-07 00:24:32 +010026
27class SimCardCommands(object):
28 def __init__(self, transport):
Daniel Willmann677d41b2020-10-19 10:34:31 +020029 self._tp = transport
Jan Balke14b350f2015-01-26 11:15:25 +010030 self._cla_byte = "a0"
Philipp Maier41460862017-03-21 12:05:30 +010031 self.sel_ctrl = "0000"
Jan Balke14b350f2015-01-26 11:15:25 +010032
Philipp Maiercdfdd412019-12-20 13:39:24 +010033 # Extract a single FCP item from TLV
34 def __parse_fcp(self, fcp):
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020035 # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF,
36 # DF or ADF
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020037 from pytlv.TLV import TLV
Philipp Maier91f26d72019-03-20 12:12:51 +010038 tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b', '8c', '80', 'ab', 'c6', '81', '88'])
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020039
40 # pytlv is case sensitive!
41 fcp = fcp.lower()
42
43 if fcp[0:2] != '62':
44 raise ValueError('Tag of the FCP template does not match, expected 62 but got %s'%fcp[0:2])
45
46 # Unfortunately the spec is not very clear if the FCP length is
47 # coded as one or two byte vale, so we have to try it out by
48 # checking if the length of the remaining TLV string matches
49 # what we get in the length field.
50 # See also ETSI TS 102 221, chapter 11.1.1.3.0 Base coding.
51 exp_tlv_len = int(fcp[2:4], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070052 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020053 skip = 4
54 else:
55 exp_tlv_len = int(fcp[2:6], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070056 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020057 skip = 6
58
59 # Skip FCP tag and length
60 tlv = fcp[skip:]
Philipp Maiercdfdd412019-12-20 13:39:24 +010061 return tlvparser.parse(tlv)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020062
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020063 # Tell the length of a record by the card response
64 # USIMs respond with an FCP template, which is different
65 # from what SIMs responds. See also:
66 # USIM: ETSI TS 102 221, chapter 11.1.1.3 Response Data
67 # SIM: GSM 11.11, chapter 9.2.1 SELECT
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020068 def __record_len(self, r):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020069 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010070 tlv_parsed = self.__parse_fcp(r[-1])
71 file_descriptor = tlv_parsed['82']
72 # See also ETSI TS 102 221, chapter 11.1.1.4.3 File Descriptor
73 return int(file_descriptor[4:8], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020074 else:
75 return int(r[-1][28:30], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020076
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020077 # Tell the length of a binary file. See also comment
78 # above.
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020079 def __len(self, r):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020080 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010081 tlv_parsed = self.__parse_fcp(r[-1])
82 return int(tlv_parsed['80'], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020083 else:
84 return int(r[-1][4:8], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020085
Alexander Chemerisd2d660a2017-07-18 16:52:25 +030086 def get_atr(self):
87 return self._tp.get_atr()
88
Jan Balke14b350f2015-01-26 11:15:25 +010089 @property
90 def cla_byte(self):
91 return self._cla_byte
92 @cla_byte.setter
93 def cla_byte(self, value):
94 self._cla_byte = value
95
Philipp Maier41460862017-03-21 12:05:30 +010096 @property
97 def sel_ctrl(self):
98 return self._sel_ctrl
99 @sel_ctrl.setter
100 def sel_ctrl(self, value):
101 self._sel_ctrl = value
Sylvain Munaut76504e02010-12-07 00:24:32 +0100102
Harald Weltec0499c82021-01-21 16:06:50 +0100103 def try_select_path(self, dir_list):
Harald Welteca673942020-06-03 15:19:40 +0200104 rv = []
105 if type(dir_list) is not list:
106 dir_list = [dir_list]
107 for i in dir_list:
108 data, sw = self._tp.send_apdu(self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
109 rv.append((data, sw))
110 if sw != '9000':
111 return rv
112 return rv
113
Harald Weltec0499c82021-01-21 16:06:50 +0100114 def select_path(self, dir_list):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100115 rv = []
Vadim Yanitskiyedf873d2020-02-27 01:40:14 +0700116 if type(dir_list) is not list:
117 dir_list = [dir_list]
Sylvain Munaut76504e02010-12-07 00:24:32 +0100118 for i in dir_list:
Harald Welte85484a92021-01-21 16:08:56 +0100119 data, sw = self.select_file(i)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100120 rv.append(data)
121 return rv
122
Harald Welte85484a92021-01-21 16:08:56 +0100123 def select_file(self, fid):
124 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
125
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100126 def select_adf(self, aid):
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700127 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100128 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
129
Sylvain Munaut76504e02010-12-07 00:24:32 +0100130 def read_binary(self, ef, length=None, offset=0):
Harald Weltec0499c82021-01-21 16:06:50 +0100131 r = self.select_path(ef)
Max5491c482019-01-03 11:29:25 +0100132 if len(r[-1]) == 0:
133 return (None, None)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100134 if length is None:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200135 length = self.__len(r) - offset
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100136 total_data = ''
137 while offset < length:
138 chunk_len = min(255, length-offset)
139 pdu = self.cla_byte + 'b0%04x%02x' % (offset, chunk_len)
140 data,sw = self._tp.send_apdu(pdu)
141 if sw == '9000':
142 total_data += data
143 offset += chunk_len
144 else:
145 raise ValueError('Failed to read (offset %d)' % (offset))
146 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100147
Philipp Maier38c74f62021-03-17 17:19:52 +0100148 def update_binary(self, ef, data, offset=0, verify=False, conserve=False):
149 data_length = len(data) // 2
150
151 # Save write cycles by reading+comparing before write
152 if conserve:
153 data_current, sw = self.read_binary(ef, data_length, offset)
154 if data_current == data:
155 return None, sw
156
Harald Weltec0499c82021-01-21 16:06:50 +0100157 self.select_path(ef)
Philipp Maier38c74f62021-03-17 17:19:52 +0100158 pdu = self.cla_byte + 'd6%04x%02x' % (offset, data_length) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200159 res = self._tp.send_apdu_checksw(pdu)
160 if verify:
161 self.verify_binary(ef, data, offset)
162 return res
163
164 def verify_binary(self, ef, data, offset=0):
165 res = self.read_binary(ef, len(data) // 2, offset)
166 if res[0].lower() != data.lower():
167 raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100168
169 def read_record(self, ef, rec_no):
Harald Weltec0499c82021-01-21 16:06:50 +0100170 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200171 rec_length = self.__record_len(r)
Jan Balke14b350f2015-01-26 11:15:25 +0100172 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100173 return self._tp.send_apdu(pdu)
174
Philipp Maier38c74f62021-03-17 17:19:52 +0100175 def update_record(self, ef, rec_no, data, force_len=False, verify=False, conserve=False):
Harald Weltec0499c82021-01-21 16:06:50 +0100176 r = self.select_path(ef)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100177 if not force_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200178 rec_length = self.__record_len(r)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700179 if (len(data) // 2 != rec_length):
180 raise ValueError('Invalid data length (expected %d, got %d)' % (rec_length, len(data) // 2))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100181 else:
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700182 rec_length = len(data) // 2
Philipp Maier38c74f62021-03-17 17:19:52 +0100183
184 # Save write cycles by reading+comparing before write
185 if conserve:
186 data_current, sw = self.read_record(ef, rec_no)
187 data_current = data_current[0:rec_length*2]
188 if data_current == data:
189 return None, sw
190
Jan Balke14b350f2015-01-26 11:15:25 +0100191 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200192 res = self._tp.send_apdu_checksw(pdu)
193 if verify:
194 self.verify_record(ef, rec_no, data)
195 return res
196
197 def verify_record(self, ef, rec_no, data):
198 res = self.read_record(ef, rec_no)
199 if res[0].lower() != data.lower():
200 raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100201
202 def record_size(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100203 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200204 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100205
206 def record_count(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100207 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200208 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100209
Philipp Maier32daaf52020-05-11 21:48:33 +0200210 def binary_size(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100211 r = self.select_path(ef)
Philipp Maier32daaf52020-05-11 21:48:33 +0200212 return self.__len(r)
213
Sylvain Munaut76504e02010-12-07 00:24:32 +0100214 def run_gsm(self, rand):
215 if len(rand) != 32:
216 raise ValueError('Invalid rand')
Harald Weltec0499c82021-01-21 16:06:50 +0100217 self.select_path(['3f00', '7f20'])
Jan Balke14b350f2015-01-26 11:15:25 +0100218 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100219
220 def reset_card(self):
221 return self._tp.reset_card()
222
Philipp Maier46f09af2021-03-25 20:24:27 +0100223 def _chv_process_sw(self, op_name, chv_no, pin_code, sw):
224 if sw_match(sw, '63cx'):
225 raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' %
226 (op_name, chv_no, b2h(pin_code).upper(), int(sw[3])))
227 elif (sw != '9000'):
228 raise SwMatchError(sw, '9000')
229
230 def verify_chv(self, chv_no, pin_code):
231 fc = rpad(b2h(pin_code), 16)
Philipp Maiera31e9a92021-03-11 13:46:32 +0100232 data, sw = self._tp.send_apdu(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
Philipp Maier46f09af2021-03-25 20:24:27 +0100233 self._chv_process_sw('verify', chv_no, pin_code, sw)
234 return (data, sw)
235
236 def unblock_chv(self, chv_no, puk_code, pin_code):
237 fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16)
238 data, sw = self._tp.send_apdu(self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc)
239 self._chv_process_sw('unblock', chv_no, pin_code, sw)
240 return (data, sw)
241
242 def change_chv(self, chv_no, pin_code, new_pin_code):
243 fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16)
244 data, sw = self._tp.send_apdu(self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc)
245 self._chv_process_sw('change', chv_no, pin_code, sw)
246 return (data, sw)
247
248 def disable_chv(self, chv_no, pin_code):
249 fc = rpad(b2h(pin_code), 16)
250 data, sw = self._tp.send_apdu(self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc)
251 self._chv_process_sw('disable', chv_no, pin_code, sw)
252 return (data, sw)
253
254 def enable_chv(self, chv_no, pin_code):
255 fc = rpad(b2h(pin_code), 16)
256 data, sw = self._tp.send_apdu(self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc)
257 self._chv_process_sw('enable', chv_no, pin_code, sw)
258 return (data, sw)