Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| 3 | """ pySim: Transport Link for serial (RS232) based readers included with simcard |
| 4 | """ |
| 5 | |
| 6 | # |
| 7 | # Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com> |
| 8 | # |
| 9 | # This program is free software: you can redistribute it and/or modify |
| 10 | # it under the terms of the GNU General Public License as published by |
| 11 | # the Free Software Foundation, either version 2 of the License, or |
| 12 | # (at your option) any later version. |
| 13 | # |
| 14 | # This program is distributed in the hope that it will be useful, |
| 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | # GNU General Public License for more details. |
| 18 | # |
| 19 | # You should have received a copy of the GNU General Public License |
| 20 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 21 | # |
| 22 | |
| 23 | from __future__ import absolute_import |
| 24 | |
| 25 | import serial |
| 26 | import time |
Philipp Maier | 92bdd5e | 2021-02-22 16:14:47 +0100 | [diff] [blame] | 27 | import os.path |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 28 | |
| 29 | from pySim.exceptions import NoCardError, ProtocolError |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 30 | from pySim.transport import LinkBase |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 31 | from pySim.utils import h2b, b2h |
| 32 | |
| 33 | |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 34 | class SerialSimLink(LinkBase): |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 35 | |
| 36 | def __init__(self, device='/dev/ttyUSB0', baudrate=9600, rst='-rts', debug=False): |
Philipp Maier | 92bdd5e | 2021-02-22 16:14:47 +0100 | [diff] [blame] | 37 | if not os.path.exists(device): |
| 38 | raise ValueError("device file %s does not exist -- abort" % device) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 39 | self._sl = serial.Serial( |
| 40 | port = device, |
| 41 | parity = serial.PARITY_EVEN, |
| 42 | bytesize = serial.EIGHTBITS, |
| 43 | stopbits = serial.STOPBITS_TWO, |
| 44 | timeout = 1, |
| 45 | xonxoff = 0, |
| 46 | rtscts = 0, |
| 47 | baudrate = baudrate, |
| 48 | ) |
| 49 | self._rst_pin = rst |
| 50 | self._debug = debug |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 51 | self._atr = None |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 52 | |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 53 | def __del__(self): |
Philipp Maier | 289fd28 | 2021-02-22 16:20:43 +0100 | [diff] [blame] | 54 | if (hasattr(self, "_sl")): |
| 55 | self._sl.close() |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 56 | |
| 57 | def wait_for_card(self, timeout=None, newcardonly=False): |
| 58 | # Direct try |
| 59 | existing = False |
| 60 | |
| 61 | try: |
| 62 | self.reset_card() |
| 63 | if not newcardonly: |
| 64 | return |
| 65 | else: |
| 66 | existing = True |
| 67 | except NoCardError: |
| 68 | pass |
| 69 | |
| 70 | # Poll ... |
| 71 | mt = time.time() + timeout if timeout is not None else None |
| 72 | pe = 0 |
| 73 | |
| 74 | while (mt is None) or (time.time() < mt): |
| 75 | try: |
| 76 | time.sleep(0.5) |
| 77 | self.reset_card() |
| 78 | if not existing: |
| 79 | return |
| 80 | except NoCardError: |
| 81 | existing = False |
| 82 | except ProtocolError: |
| 83 | if existing: |
| 84 | existing = False |
| 85 | else: |
| 86 | # Tolerate a couple of protocol error ... can happen if |
| 87 | # we try when the card is 'half' inserted |
| 88 | pe += 1 |
| 89 | if (pe > 2): |
| 90 | raise |
| 91 | |
| 92 | # Timed out ... |
| 93 | raise NoCardError() |
| 94 | |
| 95 | def connect(self): |
| 96 | self.reset_card() |
| 97 | |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 98 | def get_atr(self): |
| 99 | return self._atr |
| 100 | |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 101 | def disconnect(self): |
| 102 | pass # Nothing to do really ... |
| 103 | |
| 104 | def reset_card(self): |
| 105 | rv = self._reset_card() |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 106 | if rv == 0: |
| 107 | raise NoCardError() |
| 108 | elif rv < 0: |
| 109 | raise ProtocolError() |
| 110 | |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 111 | def _reset_card(self): |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 112 | self._atr = None |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 113 | rst_meth_map = { |
| 114 | 'rts': self._sl.setRTS, |
| 115 | 'dtr': self._sl.setDTR, |
| 116 | } |
| 117 | rst_val_map = { '+':0, '-':1 } |
| 118 | |
| 119 | try: |
| 120 | rst_meth = rst_meth_map[self._rst_pin[1:]] |
| 121 | rst_val = rst_val_map[self._rst_pin[0]] |
| 122 | except: |
Daniel Willmann | 677d41b | 2020-10-19 10:34:31 +0200 | [diff] [blame] | 123 | raise ValueError('Invalid reset pin %s' % self._rst_pin) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 124 | |
| 125 | rst_meth(rst_val) |
| 126 | time.sleep(0.1) # 100 ms |
| 127 | self._sl.flushInput() |
| 128 | rst_meth(rst_val ^ 1) |
| 129 | |
| 130 | b = self._rx_byte() |
| 131 | if not b: |
| 132 | return 0 |
| 133 | if ord(b) != 0x3b: |
Daniel Willmann | 677d41b | 2020-10-19 10:34:31 +0200 | [diff] [blame] | 134 | return -1 |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 135 | self._dbg_print("TS: 0x%x Direct convention" % ord(b)) |
| 136 | |
| 137 | while ord(b) == 0x3b: |
| 138 | b = self._rx_byte() |
| 139 | |
| 140 | if not b: |
| 141 | return -1 |
| 142 | t0 = ord(b) |
| 143 | self._dbg_print("T0: 0x%x" % t0) |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 144 | self._atr = [0x3b, ord(b)] |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 145 | |
| 146 | for i in range(4): |
| 147 | if t0 & (0x10 << i): |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 148 | b = self._rx_byte() |
Martin Hauke | 6cbecaa | 2018-02-18 17:04:50 +0100 | [diff] [blame] | 149 | self._atr.append(ord(b)) |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 150 | self._dbg_print("T%si = %x" % (chr(ord('A')+i), ord(b))) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 151 | |
| 152 | for i in range(0, t0 & 0xf): |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 153 | b = self._rx_byte() |
Martin Hauke | 6cbecaa | 2018-02-18 17:04:50 +0100 | [diff] [blame] | 154 | self._atr.append(ord(b)) |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 155 | self._dbg_print("Historical = %x" % ord(b)) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 156 | |
| 157 | while True: |
| 158 | x = self._rx_byte() |
| 159 | if not x: |
| 160 | break |
Martin Hauke | 6cbecaa | 2018-02-18 17:04:50 +0100 | [diff] [blame] | 161 | self._atr.append(ord(x)) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 162 | self._dbg_print("Extra: %x" % ord(x)) |
| 163 | |
| 164 | return 1 |
| 165 | |
| 166 | def _dbg_print(self, s): |
| 167 | if self._debug: |
Vadim Yanitskiy | 6727f0c | 2020-01-22 23:38:24 +0700 | [diff] [blame] | 168 | print(s) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 169 | |
| 170 | def _tx_byte(self, b): |
| 171 | self._sl.write(b) |
| 172 | r = self._sl.read() |
| 173 | if r != b: # TX and RX are tied, so we must clear the echo |
| 174 | raise ProtocolError("Bad echo value. Expected %02x, got %s)" % (ord(b), '%02x'%ord(r) if r else '(nil)')) |
| 175 | |
| 176 | def _tx_string(self, s): |
| 177 | """This is only safe if it's guaranteed the card won't send any data |
| 178 | during the time of tx of the string !!!""" |
| 179 | self._sl.write(s) |
| 180 | r = self._sl.read(len(s)) |
| 181 | if r != s: # TX and RX are tied, so we must clear the echo |
| 182 | raise ProtocolError("Bad echo value (Expected: %s, got %s)" % (b2h(s), b2h(r))) |
| 183 | |
| 184 | def _rx_byte(self): |
| 185 | return self._sl.read() |
| 186 | |
| 187 | def send_apdu_raw(self, pdu): |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 188 | """see LinkBase.send_apdu_raw""" |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 189 | |
| 190 | pdu = h2b(pdu) |
| 191 | data_len = ord(pdu[4]) # P3 |
| 192 | |
| 193 | # Send first CLASS,INS,P1,P2,P3 |
| 194 | self._tx_string(pdu[0:5]) |
| 195 | |
| 196 | # Wait ack which can be |
| 197 | # - INS: Command acked -> go ahead |
| 198 | # - 0x60: NULL, just wait some more |
| 199 | # - SW1: The card can apparently proceed ... |
| 200 | while True: |
| 201 | b = self._rx_byte() |
| 202 | if b == pdu[1]: |
| 203 | break |
| 204 | elif b != '\x60': |
| 205 | # Ok, it 'could' be SW1 |
| 206 | sw1 = b |
| 207 | sw2 = self._rx_byte() |
| 208 | nil = self._rx_byte() |
| 209 | if (sw2 and not nil): |
| 210 | return '', b2h(sw1+sw2) |
| 211 | |
| 212 | raise ProtocolError() |
| 213 | |
| 214 | # Send data (if any) |
| 215 | if len(pdu) > 5: |
| 216 | self._tx_string(pdu[5:]) |
| 217 | |
| 218 | # Receive data (including SW !) |
Vadim Yanitskiy | 99affe1 | 2020-02-15 05:03:09 +0700 | [diff] [blame] | 219 | # length = [P3 - tx_data (=len(pdu)-len(hdr)) + 2 (SW1//2) ] |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 220 | to_recv = data_len - len(pdu) + 5 + 2 |
| 221 | |
| 222 | data = '' |
| 223 | while (len(data) < to_recv): |
| 224 | b = self._rx_byte() |
| 225 | if (to_recv == 2) and (b == '\x60'): # Ignore NIL if we have no RX data (hack ?) |
| 226 | continue |
| 227 | if not b: |
Daniel Willmann | 677d41b | 2020-10-19 10:34:31 +0200 | [diff] [blame] | 228 | break |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 229 | data += b |
| 230 | |
| 231 | # Split datafield from SW |
| 232 | if len(data) < 2: |
| 233 | return None, None |
| 234 | sw = data[-2:] |
| 235 | data = data[0:-2] |
| 236 | |
| 237 | # Return value |
| 238 | return b2h(data), b2h(sw) |