blob: 9aed5882abdf3662ed577093e6a0d06e3da4f16f [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
Sylvain Munaut530076e2010-12-23 20:28:58 +010024from pySim.utils import rpad, b2h
Sylvain Munaut76504e02010-12-07 00:24:32 +010025
26class SimCardCommands(object):
27 def __init__(self, transport):
Daniel Willmann677d41b2020-10-19 10:34:31 +020028 self._tp = transport
Jan Balke14b350f2015-01-26 11:15:25 +010029 self._cla_byte = "a0"
Philipp Maier41460862017-03-21 12:05:30 +010030 self.sel_ctrl = "0000"
Jan Balke14b350f2015-01-26 11:15:25 +010031
Philipp Maiercdfdd412019-12-20 13:39:24 +010032 # Extract a single FCP item from TLV
33 def __parse_fcp(self, fcp):
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020034 # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF,
35 # DF or ADF
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020036 from pytlv.TLV import TLV
Philipp Maier91f26d72019-03-20 12:12:51 +010037 tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b', '8c', '80', 'ab', 'c6', '81', '88'])
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020038
39 # pytlv is case sensitive!
40 fcp = fcp.lower()
41
42 if fcp[0:2] != '62':
43 raise ValueError('Tag of the FCP template does not match, expected 62 but got %s'%fcp[0:2])
44
45 # Unfortunately the spec is not very clear if the FCP length is
46 # coded as one or two byte vale, so we have to try it out by
47 # checking if the length of the remaining TLV string matches
48 # what we get in the length field.
49 # See also ETSI TS 102 221, chapter 11.1.1.3.0 Base coding.
50 exp_tlv_len = int(fcp[2:4], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070051 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020052 skip = 4
53 else:
54 exp_tlv_len = int(fcp[2:6], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070055 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020056 skip = 6
57
58 # Skip FCP tag and length
59 tlv = fcp[skip:]
Philipp Maiercdfdd412019-12-20 13:39:24 +010060 return tlvparser.parse(tlv)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020061
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020062 # Tell the length of a record by the card response
63 # USIMs respond with an FCP template, which is different
64 # from what SIMs responds. See also:
65 # USIM: ETSI TS 102 221, chapter 11.1.1.3 Response Data
66 # SIM: GSM 11.11, chapter 9.2.1 SELECT
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020067 def __record_len(self, r):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020068 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010069 tlv_parsed = self.__parse_fcp(r[-1])
70 file_descriptor = tlv_parsed['82']
71 # See also ETSI TS 102 221, chapter 11.1.1.4.3 File Descriptor
72 return int(file_descriptor[4:8], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020073 else:
74 return int(r[-1][28:30], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020075
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020076 # Tell the length of a binary file. See also comment
77 # above.
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020078 def __len(self, r):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020079 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010080 tlv_parsed = self.__parse_fcp(r[-1])
81 return int(tlv_parsed['80'], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020082 else:
83 return int(r[-1][4:8], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020084
Alexander Chemerisd2d660a2017-07-18 16:52:25 +030085 def get_atr(self):
86 return self._tp.get_atr()
87
Jan Balke14b350f2015-01-26 11:15:25 +010088 @property
89 def cla_byte(self):
90 return self._cla_byte
91 @cla_byte.setter
92 def cla_byte(self, value):
93 self._cla_byte = value
94
Philipp Maier41460862017-03-21 12:05:30 +010095 @property
96 def sel_ctrl(self):
97 return self._sel_ctrl
98 @sel_ctrl.setter
99 def sel_ctrl(self, value):
100 self._sel_ctrl = value
Sylvain Munaut76504e02010-12-07 00:24:32 +0100101
Harald Weltec0499c82021-01-21 16:06:50 +0100102 def try_select_path(self, dir_list):
Harald Welteca673942020-06-03 15:19:40 +0200103 rv = []
104 if type(dir_list) is not list:
105 dir_list = [dir_list]
106 for i in dir_list:
107 data, sw = self._tp.send_apdu(self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
108 rv.append((data, sw))
109 if sw != '9000':
110 return rv
111 return rv
112
Harald Weltec0499c82021-01-21 16:06:50 +0100113 def select_path(self, dir_list):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100114 rv = []
Vadim Yanitskiyedf873d2020-02-27 01:40:14 +0700115 if type(dir_list) is not list:
116 dir_list = [dir_list]
Sylvain Munaut76504e02010-12-07 00:24:32 +0100117 for i in dir_list:
Harald Welte85484a92021-01-21 16:08:56 +0100118 data, sw = self.select_file(i)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100119 rv.append(data)
120 return rv
121
Harald Welte85484a92021-01-21 16:08:56 +0100122 def select_file(self, fid):
123 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
124
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100125 def select_adf(self, aid):
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700126 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100127 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
128
Sylvain Munaut76504e02010-12-07 00:24:32 +0100129 def read_binary(self, ef, length=None, offset=0):
Harald Weltec0499c82021-01-21 16:06:50 +0100130 r = self.select_path(ef)
Max5491c482019-01-03 11:29:25 +0100131 if len(r[-1]) == 0:
132 return (None, None)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100133 if length is None:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200134 length = self.__len(r) - offset
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100135 total_data = ''
136 while offset < length:
137 chunk_len = min(255, length-offset)
138 pdu = self.cla_byte + 'b0%04x%02x' % (offset, chunk_len)
139 data,sw = self._tp.send_apdu(pdu)
140 if sw == '9000':
141 total_data += data
142 offset += chunk_len
143 else:
144 raise ValueError('Failed to read (offset %d)' % (offset))
145 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100146
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200147 def update_binary(self, ef, data, offset=0, verify=False):
Harald Weltec0499c82021-01-21 16:06:50 +0100148 self.select_path(ef)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700149 pdu = self.cla_byte + 'd6%04x%02x' % (offset, len(data) // 2) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200150 res = self._tp.send_apdu_checksw(pdu)
151 if verify:
152 self.verify_binary(ef, data, offset)
153 return res
154
155 def verify_binary(self, ef, data, offset=0):
156 res = self.read_binary(ef, len(data) // 2, offset)
157 if res[0].lower() != data.lower():
158 raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100159
160 def read_record(self, ef, rec_no):
Harald Weltec0499c82021-01-21 16:06:50 +0100161 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200162 rec_length = self.__record_len(r)
Jan Balke14b350f2015-01-26 11:15:25 +0100163 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100164 return self._tp.send_apdu(pdu)
165
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200166 def update_record(self, ef, rec_no, data, force_len=False, verify=False):
Harald Weltec0499c82021-01-21 16:06:50 +0100167 r = self.select_path(ef)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100168 if not force_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200169 rec_length = self.__record_len(r)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700170 if (len(data) // 2 != rec_length):
171 raise ValueError('Invalid data length (expected %d, got %d)' % (rec_length, len(data) // 2))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100172 else:
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700173 rec_length = len(data) // 2
Jan Balke14b350f2015-01-26 11:15:25 +0100174 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200175 res = self._tp.send_apdu_checksw(pdu)
176 if verify:
177 self.verify_record(ef, rec_no, data)
178 return res
179
180 def verify_record(self, ef, rec_no, data):
181 res = self.read_record(ef, rec_no)
182 if res[0].lower() != data.lower():
183 raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100184
185 def record_size(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100186 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200187 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100188
189 def record_count(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100190 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200191 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100192
Philipp Maier32daaf52020-05-11 21:48:33 +0200193 def binary_size(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100194 r = self.select_path(ef)
Philipp Maier32daaf52020-05-11 21:48:33 +0200195 return self.__len(r)
196
Sylvain Munaut76504e02010-12-07 00:24:32 +0100197 def run_gsm(self, rand):
198 if len(rand) != 32:
199 raise ValueError('Invalid rand')
Harald Weltec0499c82021-01-21 16:06:50 +0100200 self.select_path(['3f00', '7f20'])
Jan Balke14b350f2015-01-26 11:15:25 +0100201 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100202
203 def reset_card(self):
204 return self._tp.reset_card()
205
206 def verify_chv(self, chv_no, code):
207 fc = rpad(b2h(code), 16)
Philipp Maiera31e9a92021-03-11 13:46:32 +0100208 data, sw = self._tp.send_apdu(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
209 if (sw != '9000'):
210 raise RuntimeError('Failed to authenticate with ADM key %s, %i tries left.' % (code, int(sw[3])))
211 return (data,sw)