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