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""" |
Harald Welte | baec4e9 | 2023-11-03 11:49:54 +0100 | [diff] [blame] | 32 | name = 'Serial' |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 33 | |
Harald Welte | 0f177c1 | 2023-12-17 12:38:29 +0100 | [diff] [blame] | 34 | def __init__(self, opts = argparse.Namespace(device='/dev/ttyUSB0', baudrate=9600), rst: str = '-rts', |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 35 | debug: bool = False, **kwargs): |
| 36 | super().__init__(**kwargs) |
Harald Welte | 0f177c1 | 2023-12-17 12:38:29 +0100 | [diff] [blame] | 37 | if not os.path.exists(opts.device): |
| 38 | raise ValueError("device file %s does not exist -- abort" % opts.device) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 39 | self._sl = serial.Serial( |
Harald Welte | 0f177c1 | 2023-12-17 12:38:29 +0100 | [diff] [blame] | 40 | port=opts.device, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 41 | parity=serial.PARITY_EVEN, |
| 42 | bytesize=serial.EIGHTBITS, |
| 43 | stopbits=serial.STOPBITS_TWO, |
| 44 | timeout=1, |
| 45 | xonxoff=0, |
| 46 | rtscts=0, |
Harald Welte | 0f177c1 | 2023-12-17 12:38:29 +0100 | [diff] [blame] | 47 | baudrate=opts.baudrate, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 48 | ) |
| 49 | self._rst_pin = rst |
| 50 | self._debug = debug |
| 51 | self._atr = None |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 52 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 53 | def __del__(self): |
| 54 | if (hasattr(self, "_sl")): |
| 55 | self._sl.close() |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 56 | |
Harald Welte | ab6897c | 2023-07-09 16:21:23 +0200 | [diff] [blame] | 57 | def wait_for_card(self, timeout: Optional[int] = None, newcardonly: bool = False): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 58 | # Direct try |
| 59 | existing = False |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 60 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 61 | try: |
| 62 | self.reset_card() |
| 63 | if not newcardonly: |
| 64 | return |
| 65 | else: |
| 66 | existing = True |
| 67 | except NoCardError: |
| 68 | pass |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 69 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 70 | # Poll ... |
| 71 | mt = time.time() + timeout if timeout is not None else None |
| 72 | pe = 0 |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 73 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 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 |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 91 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 92 | # Timed out ... |
| 93 | raise NoCardError() |
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 | def connect(self): |
| 96 | self.reset_card() |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 97 | |
Harald Welte | ab6897c | 2023-07-09 16:21:23 +0200 | [diff] [blame] | 98 | def get_atr(self) -> Hexstr: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 99 | return self._atr |
Alexander Chemeris | d2d660a | 2017-07-18 16:52:25 +0300 | [diff] [blame] | 100 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 101 | def disconnect(self): |
| 102 | pass # Nothing to do really ... |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 103 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 104 | def reset_card(self): |
| 105 | rv = self._reset_card() |
| 106 | if rv == 0: |
| 107 | raise NoCardError() |
| 108 | elif rv < 0: |
| 109 | raise ProtocolError() |
Philipp Maier | 621f78c | 2023-06-01 18:00:54 +0200 | [diff] [blame] | 110 | return rv |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 111 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 112 | def _reset_card(self): |
| 113 | self._atr = None |
| 114 | rst_meth_map = { |
| 115 | 'rts': self._sl.setRTS, |
| 116 | 'dtr': self._sl.setDTR, |
| 117 | } |
| 118 | rst_val_map = {'+': 0, '-': 1} |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 119 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 120 | try: |
| 121 | rst_meth = rst_meth_map[self._rst_pin[1:]] |
| 122 | rst_val = rst_val_map[self._rst_pin[0]] |
| 123 | except: |
| 124 | raise ValueError('Invalid reset pin %s' % self._rst_pin) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 125 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 126 | rst_meth(rst_val) |
| 127 | time.sleep(0.1) # 100 ms |
| 128 | self._sl.flushInput() |
| 129 | rst_meth(rst_val ^ 1) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 130 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 131 | b = self._rx_byte() |
| 132 | if not b: |
| 133 | return 0 |
| 134 | if ord(b) != 0x3b: |
| 135 | return -1 |
| 136 | self._dbg_print("TS: 0x%x Direct convention" % ord(b)) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 137 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 138 | while ord(b) == 0x3b: |
| 139 | b = self._rx_byte() |
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 | if not b: |
| 142 | return -1 |
| 143 | t0 = ord(b) |
| 144 | self._dbg_print("T0: 0x%x" % t0) |
| 145 | self._atr = [0x3b, ord(b)] |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 146 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 147 | for i in range(4): |
| 148 | if t0 & (0x10 << i): |
| 149 | b = self._rx_byte() |
| 150 | self._atr.append(ord(b)) |
| 151 | self._dbg_print("T%si = %x" % (chr(ord('A')+i), ord(b))) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 152 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 153 | for i in range(0, t0 & 0xf): |
| 154 | b = self._rx_byte() |
| 155 | self._atr.append(ord(b)) |
| 156 | self._dbg_print("Historical = %x" % ord(b)) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 157 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 158 | while True: |
| 159 | x = self._rx_byte() |
| 160 | if not x: |
| 161 | break |
| 162 | self._atr.append(ord(x)) |
| 163 | self._dbg_print("Extra: %x" % ord(x)) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 164 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 165 | return 1 |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 166 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 167 | def _dbg_print(self, s): |
| 168 | if self._debug: |
| 169 | print(s) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 170 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 171 | def _tx_byte(self, b): |
| 172 | self._sl.write(b) |
| 173 | r = self._sl.read() |
| 174 | if r != b: # TX and RX are tied, so we must clear the echo |
| 175 | raise ProtocolError("Bad echo value. Expected %02x, got %s)" % ( |
| 176 | ord(b), '%02x' % ord(r) if r else '(nil)')) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 177 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 178 | def _tx_string(self, s): |
| 179 | """This is only safe if it's guaranteed the card won't send any data |
| 180 | during the time of tx of the string !!!""" |
| 181 | self._sl.write(s) |
| 182 | r = self._sl.read(len(s)) |
| 183 | if r != s: # TX and RX are tied, so we must clear the echo |
| 184 | raise ProtocolError( |
| 185 | "Bad echo value (Expected: %s, got %s)" % (b2h(s), b2h(r))) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 186 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 187 | def _rx_byte(self): |
| 188 | return self._sl.read() |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 189 | |
Harald Welte | f9f8d7a | 2023-07-09 17:06:16 +0200 | [diff] [blame] | 190 | def _send_apdu_raw(self, pdu: Hexstr) -> ResTuple: |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 191 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 192 | pdu = h2b(pdu) |
| 193 | data_len = pdu[4] # P3 |
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 | # Send first CLASS,INS,P1,P2,P3 |
| 196 | self._tx_string(pdu[0:5]) |
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 | # Wait ack which can be |
| 199 | # - INS: Command acked -> go ahead |
| 200 | # - 0x60: NULL, just wait some more |
| 201 | # - SW1: The card can apparently proceed ... |
| 202 | while True: |
| 203 | b = self._rx_byte() |
| 204 | if ord(b) == pdu[1]: |
| 205 | break |
| 206 | elif b != '\x60': |
| 207 | # Ok, it 'could' be SW1 |
| 208 | sw1 = b |
| 209 | sw2 = self._rx_byte() |
| 210 | nil = self._rx_byte() |
| 211 | if (sw2 and not nil): |
| 212 | return '', b2h(sw1+sw2) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 213 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 214 | raise ProtocolError() |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 215 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 216 | # Send data (if any) |
| 217 | if len(pdu) > 5: |
| 218 | self._tx_string(pdu[5:]) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 219 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 220 | # Receive data (including SW !) |
| 221 | # length = [P3 - tx_data (=len(pdu)-len(hdr)) + 2 (SW1//2) ] |
| 222 | to_recv = data_len - len(pdu) + 5 + 2 |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 223 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 224 | data = bytes(0) |
| 225 | while (len(data) < to_recv): |
| 226 | b = self._rx_byte() |
| 227 | if (to_recv == 2) and (b == '\x60'): # Ignore NIL if we have no RX data (hack ?) |
| 228 | continue |
| 229 | if not b: |
| 230 | break |
| 231 | data += b |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 232 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 233 | # Split datafield from SW |
| 234 | if len(data) < 2: |
| 235 | return None, None |
| 236 | sw = data[-2:] |
| 237 | data = data[0:-2] |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 238 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 239 | # Return value |
| 240 | return b2h(data), b2h(sw) |
Philipp Maier | 6bfa8a8 | 2023-10-09 13:32:49 +0200 | [diff] [blame] | 241 | |
Philipp Maier | 58e89eb | 2023-10-10 11:59:03 +0200 | [diff] [blame] | 242 | def __str__(self) -> str: |
Philipp Maier | 6bfa8a8 | 2023-10-09 13:32:49 +0200 | [diff] [blame] | 243 | return "serial:%s" % (self._sl.name) |
Philipp Maier | 8c82378 | 2023-10-23 10:44:44 +0200 | [diff] [blame] | 244 | |
| 245 | @staticmethod |
| 246 | def argparse_add_reader_args(arg_parser: argparse.ArgumentParser): |
Harald Welte | 0ecbf63 | 2023-11-03 12:38:42 +0100 | [diff] [blame] | 247 | serial_group = arg_parser.add_argument_group('Serial Reader', """Use a simple/ultra-low-cost serial reader |
| 248 | attached to a (physical or USB/virtual) RS232 port. This doesn't work with all RS232-attached smart card |
| 249 | readers, only with the very primitive readers following the ancient `Phoenix` or `Smart Mouse` design.""") |
Philipp Maier | 8c82378 | 2023-10-23 10:44:44 +0200 | [diff] [blame] | 250 | serial_group.add_argument('-d', '--device', metavar='DEV', default='/dev/ttyUSB0', |
| 251 | help='Serial Device for SIM access') |
| 252 | serial_group.add_argument('-b', '--baud', dest='baudrate', type=int, metavar='BAUD', default=9600, |
| 253 | help='Baud rate used for SIM access') |