blob: d6159ea6a7b48f6af3d2fe4dfdbbaf887aef3064 [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:
Philipp Maier41460862017-03-21 12:05:30 +0100118 data, sw = self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100119 rv.append(data)
120 return rv
121
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100122 def select_adf(self, aid):
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700123 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100124 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
125
Sylvain Munaut76504e02010-12-07 00:24:32 +0100126 def read_binary(self, ef, length=None, offset=0):
Harald Weltec0499c82021-01-21 16:06:50 +0100127 r = self.select_path(ef)
Max5491c482019-01-03 11:29:25 +0100128 if len(r[-1]) == 0:
129 return (None, None)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100130 if length is None:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200131 length = self.__len(r) - offset
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100132 total_data = ''
133 while offset < length:
134 chunk_len = min(255, length-offset)
135 pdu = self.cla_byte + 'b0%04x%02x' % (offset, chunk_len)
136 data,sw = self._tp.send_apdu(pdu)
137 if sw == '9000':
138 total_data += data
139 offset += chunk_len
140 else:
141 raise ValueError('Failed to read (offset %d)' % (offset))
142 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100143
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200144 def update_binary(self, ef, data, offset=0, verify=False):
Harald Weltec0499c82021-01-21 16:06:50 +0100145 self.select_path(ef)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700146 pdu = self.cla_byte + 'd6%04x%02x' % (offset, len(data) // 2) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200147 res = self._tp.send_apdu_checksw(pdu)
148 if verify:
149 self.verify_binary(ef, data, offset)
150 return res
151
152 def verify_binary(self, ef, data, offset=0):
153 res = self.read_binary(ef, len(data) // 2, offset)
154 if res[0].lower() != data.lower():
155 raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100156
157 def read_record(self, ef, rec_no):
Harald Weltec0499c82021-01-21 16:06:50 +0100158 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200159 rec_length = self.__record_len(r)
Jan Balke14b350f2015-01-26 11:15:25 +0100160 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100161 return self._tp.send_apdu(pdu)
162
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200163 def update_record(self, ef, rec_no, data, force_len=False, verify=False):
Harald Weltec0499c82021-01-21 16:06:50 +0100164 r = self.select_path(ef)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100165 if not force_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200166 rec_length = self.__record_len(r)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700167 if (len(data) // 2 != rec_length):
168 raise ValueError('Invalid data length (expected %d, got %d)' % (rec_length, len(data) // 2))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100169 else:
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700170 rec_length = len(data) // 2
Jan Balke14b350f2015-01-26 11:15:25 +0100171 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200172 res = self._tp.send_apdu_checksw(pdu)
173 if verify:
174 self.verify_record(ef, rec_no, data)
175 return res
176
177 def verify_record(self, ef, rec_no, data):
178 res = self.read_record(ef, rec_no)
179 if res[0].lower() != data.lower():
180 raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100181
182 def record_size(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100183 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200184 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100185
186 def record_count(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100187 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200188 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100189
Philipp Maier32daaf52020-05-11 21:48:33 +0200190 def binary_size(self, ef):
Harald Weltec0499c82021-01-21 16:06:50 +0100191 r = self.select_path(ef)
Philipp Maier32daaf52020-05-11 21:48:33 +0200192 return self.__len(r)
193
Sylvain Munaut76504e02010-12-07 00:24:32 +0100194 def run_gsm(self, rand):
195 if len(rand) != 32:
196 raise ValueError('Invalid rand')
Harald Weltec0499c82021-01-21 16:06:50 +0100197 self.select_path(['3f00', '7f20'])
Jan Balke14b350f2015-01-26 11:15:25 +0100198 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100199
200 def reset_card(self):
201 return self._tp.reset_card()
202
203 def verify_chv(self, chv_no, code):
204 fc = rpad(b2h(code), 16)
Neels Hofmeyr3ce84d92017-03-21 13:07:46 +0100205 return self._tp.send_apdu_checksw(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)