Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| 3 | """ pySim: PCSC reader transport link base |
| 4 | """ |
| 5 | |
Vadim Yanitskiy | e8c34ca | 2021-05-02 02:29:52 +0200 | [diff] [blame] | 6 | import abc |
Harald Welte | 28c2431 | 2021-04-11 12:19:36 +0200 | [diff] [blame] | 7 | import argparse |
Vadim Yanitskiy | e8c34ca | 2021-05-02 02:29:52 +0200 | [diff] [blame] | 8 | from typing import Optional, Tuple |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 9 | |
Harald Welte | e79cc80 | 2021-01-21 14:10:43 +0100 | [diff] [blame] | 10 | from pySim.exceptions import * |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 11 | from pySim.construct import filter_dict |
| 12 | from pySim.utils import sw_match, b2h, h2b, i2h |
Harald Welte | e79cc80 | 2021-01-21 14:10:43 +0100 | [diff] [blame] | 13 | |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 14 | # |
| 15 | # Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com> |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 16 | # Copyright (C) 2021 Harald Welte <laforge@osmocom.org> |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 17 | # |
| 18 | # This program is free software: you can redistribute it and/or modify |
| 19 | # it under the terms of the GNU General Public License as published by |
| 20 | # the Free Software Foundation, either version 2 of the License, or |
| 21 | # (at your option) any later version. |
| 22 | # |
| 23 | # This program is distributed in the hope that it will be useful, |
| 24 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 25 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 26 | # GNU General Public License for more details. |
| 27 | # |
| 28 | # You should have received a copy of the GNU General Public License |
| 29 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 30 | # |
| 31 | |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 32 | class ApduTracer: |
| 33 | def trace_command(self, cmd): |
| 34 | pass |
| 35 | |
| 36 | def trace_response(self, cmd, sw, resp): |
| 37 | pass |
| 38 | |
| 39 | |
Vadim Yanitskiy | e8c34ca | 2021-05-02 02:29:52 +0200 | [diff] [blame] | 40 | class LinkBase(abc.ABC): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 41 | """Base class for link/transport to card.""" |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 42 | |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 43 | def __init__(self, sw_interpreter=None, apdu_tracer=None): |
Harald Welte | eb05b2f | 2021-04-10 11:01:56 +0200 | [diff] [blame] | 44 | self.sw_interpreter = sw_interpreter |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 45 | self.apdu_tracer = apdu_tracer |
Harald Welte | 4f2c546 | 2021-04-03 11:48:22 +0200 | [diff] [blame] | 46 | |
Vadim Yanitskiy | e8c34ca | 2021-05-02 02:29:52 +0200 | [diff] [blame] | 47 | @abc.abstractmethod |
| 48 | def _send_apdu_raw(self, pdu:str) -> Tuple[str, str]: |
| 49 | """Implementation specific method for sending the PDU.""" |
| 50 | |
Harald Welte | 4f2c546 | 2021-04-03 11:48:22 +0200 | [diff] [blame] | 51 | def set_sw_interpreter(self, interp): |
| 52 | """Set an (optional) status word interpreter.""" |
| 53 | self.sw_interpreter = interp |
| 54 | |
Harald Welte | 903bdaa | 2021-05-03 22:58:53 +0200 | [diff] [blame] | 55 | @abc.abstractmethod |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 56 | def wait_for_card(self, timeout:int=None, newcardonly:bool=False): |
| 57 | """Wait for a card and connect to it |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 58 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 59 | Args: |
| 60 | timeout : Maximum wait time in seconds (None=no timeout) |
| 61 | newcardonly : Should we wait for a new card, or an already inserted one ? |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 62 | """ |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 63 | |
Harald Welte | 903bdaa | 2021-05-03 22:58:53 +0200 | [diff] [blame] | 64 | @abc.abstractmethod |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 65 | def connect(self): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 66 | """Connect to a card immediately |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 67 | """ |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 68 | |
Harald Welte | 903bdaa | 2021-05-03 22:58:53 +0200 | [diff] [blame] | 69 | @abc.abstractmethod |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 70 | def disconnect(self): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 71 | """Disconnect from card |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 72 | """ |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 73 | |
Harald Welte | 903bdaa | 2021-05-03 22:58:53 +0200 | [diff] [blame] | 74 | @abc.abstractmethod |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 75 | def reset_card(self): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 76 | """Resets the card (power down/up) |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 77 | """ |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 78 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 79 | def send_apdu_raw(self, pdu:str): |
| 80 | """Sends an APDU with minimal processing |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 81 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 82 | Args: |
| 83 | pdu : string of hexadecimal characters (ex. "A0A40000023F00") |
| 84 | Returns: |
| 85 | tuple(data, sw), where |
| 86 | data : string (in hex) of returned data (ex. "074F4EFFFF") |
| 87 | sw : string (in hex) of status word (ex. "9000") |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 88 | """ |
Harald Welte | 7829d8a | 2021-04-10 11:28:53 +0200 | [diff] [blame] | 89 | if self.apdu_tracer: |
| 90 | self.apdu_tracer.trace_command(pdu) |
| 91 | (data, sw) = self._send_apdu_raw(pdu) |
| 92 | if self.apdu_tracer: |
| 93 | self.apdu_tracer.trace_response(pdu, sw, data) |
| 94 | return (data, sw) |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 95 | |
| 96 | def send_apdu(self, pdu): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 97 | """Sends an APDU and auto fetch response data |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 98 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 99 | Args: |
| 100 | pdu : string of hexadecimal characters (ex. "A0A40000023F00") |
| 101 | Returns: |
| 102 | tuple(data, sw), where |
| 103 | data : string (in hex) of returned data (ex. "074F4EFFFF") |
| 104 | sw : string (in hex) of status word (ex. "9000") |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 105 | """ |
| 106 | data, sw = self.send_apdu_raw(pdu) |
| 107 | |
Philipp Maier | 859e0fd | 2018-06-12 18:40:24 +0200 | [diff] [blame] | 108 | # When whe have sent the first APDU, the SW may indicate that there are response bytes |
| 109 | # available. There are two SWs commonly used for this 9fxx (sim) and 61xx (usim), where |
| 110 | # xx is the number of response bytes available. |
| 111 | # See also: |
Harald Welte | 8dfd6d0 | 2021-05-25 21:54:45 +0200 | [diff] [blame] | 112 | if (sw is not None): |
| 113 | if ((sw[0:2] == '9f') or (sw[0:2] == '61')): |
| 114 | # SW1=9F: 3GPP TS 51.011 9.4.1, Responses to commands which are correctly executed |
| 115 | # SW1=61: ISO/IEC 7816-4, Table 5 — General meaning of the interindustry values of SW1-SW2 |
| 116 | pdu_gr = pdu[0:2] + 'c00000' + sw[2:4] |
| 117 | data, sw = self.send_apdu_raw(pdu_gr) |
| 118 | if sw[0:2] == '6c': |
| 119 | # SW1=6C: ETSI TS 102 221 Table 7.1: Procedure byte coding |
| 120 | pdu_gr = pdu[0:8] + sw[2:4] |
| 121 | data,sw = self.send_apdu_raw(pdu_gr) |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 122 | |
| 123 | return data, sw |
| 124 | |
| 125 | def send_apdu_checksw(self, pdu, sw="9000"): |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 126 | """Sends an APDU and check returned SW |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 127 | |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 128 | Args: |
| 129 | pdu : string of hexadecimal characters (ex. "A0A40000023F00") |
| 130 | sw : string of 4 hexadecimal characters (ex. "9000"). The user may mask out certain |
| 131 | digits using a '?' to add some ambiguity if needed. |
| 132 | Returns: |
| 133 | tuple(data, sw), where |
| 134 | data : string (in hex) of returned data (ex. "074F4EFFFF") |
| 135 | sw : string (in hex) of status word (ex. "9000") |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 136 | """ |
| 137 | rv = self.send_apdu(pdu) |
Philipp Maier | d4ebb6f | 2018-06-12 17:56:07 +0200 | [diff] [blame] | 138 | |
Harald Welte | 846a898 | 2021-10-08 15:47:16 +0200 | [diff] [blame^] | 139 | if sw == '9000' and sw_match(rv[1], '91xx'): |
| 140 | # proactive sim as per TS 102 221 Setion 7.4.2 |
| 141 | rv = self.send_apdu_checksw('80120000' + rv[1][2:], sw) |
| 142 | print("FETCH: %s", rv[0]) |
Harald Welte | 67d551a | 2021-01-21 14:50:01 +0100 | [diff] [blame] | 143 | if not sw_match(rv[1], sw): |
Harald Welte | 4f2c546 | 2021-04-03 11:48:22 +0200 | [diff] [blame] | 144 | raise SwMatchError(rv[1], sw.lower(), self.sw_interpreter) |
Sylvain Munaut | e7c15cd | 2010-12-07 10:01:55 +0100 | [diff] [blame] | 145 | return rv |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 146 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 147 | def send_apdu_constr(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr): |
| 148 | """Build and sends an APDU using a 'construct' definition; parses response. |
| 149 | |
| 150 | Args: |
| 151 | cla : string (in hex) ISO 7816 class byte |
| 152 | ins : string (in hex) ISO 7816 instruction byte |
| 153 | p1 : string (in hex) ISO 7116 Parameter 1 byte |
| 154 | p2 : string (in hex) ISO 7116 Parameter 2 byte |
| 155 | cmd_cosntr : defining how to generate binary APDU command data |
| 156 | cmd_data : command data passed to cmd_constr |
| 157 | resp_cosntr : defining how to decode binary APDU response data |
| 158 | Returns: |
| 159 | Tuple of (decoded_data, sw) |
| 160 | """ |
| 161 | cmd = cmd_constr.build(cmd_data) if cmd_data else '' |
| 162 | p3 = i2h([len(cmd)]) |
| 163 | pdu = ''.join([cla, ins, p1, p2, p3, b2h(cmd)]) |
| 164 | (data, sw) = self.send_apdu(pdu) |
| 165 | if data: |
| 166 | # filter the resulting dict to avoid '_io' members inside |
| 167 | rsp = filter_dict(resp_constr.parse(h2b(data))) |
| 168 | else: |
| 169 | rsp = None |
| 170 | return (rsp, sw) |
| 171 | |
| 172 | def send_apdu_constr_checksw(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr, |
| 173 | sw_exp="9000"): |
| 174 | """Build and sends an APDU using a 'construct' definition; parses response. |
| 175 | |
| 176 | Args: |
| 177 | cla : string (in hex) ISO 7816 class byte |
| 178 | ins : string (in hex) ISO 7816 instruction byte |
| 179 | p1 : string (in hex) ISO 7116 Parameter 1 byte |
| 180 | p2 : string (in hex) ISO 7116 Parameter 2 byte |
| 181 | cmd_cosntr : defining how to generate binary APDU command data |
| 182 | cmd_data : command data passed to cmd_constr |
| 183 | resp_cosntr : defining how to decode binary APDU response data |
| 184 | exp_sw : string (in hex) of status word (ex. "9000") |
| 185 | Returns: |
| 186 | Tuple of (decoded_data, sw) |
| 187 | """ |
| 188 | (rsp, sw) = self.send_apdu_constr(cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr) |
| 189 | if not sw_match(sw, sw_exp): |
| 190 | raise SwMatchError(sw, sw_exp.lower(), self.sw_interpreter) |
| 191 | return (rsp, sw) |
| 192 | |
Harald Welte | 28c2431 | 2021-04-11 12:19:36 +0200 | [diff] [blame] | 193 | def argparse_add_reader_args(arg_parser): |
| 194 | """Add all reader related arguments to the given argparse.Argumentparser instance.""" |
| 195 | serial_group = arg_parser.add_argument_group('Serial Reader') |
| 196 | serial_group.add_argument('-d', '--device', metavar='DEV', default='/dev/ttyUSB0', |
| 197 | help='Serial Device for SIM access') |
| 198 | serial_group.add_argument('-b', '--baud', dest='baudrate', type=int, metavar='BAUD', default=9600, |
| 199 | help='Baud rate used for SIM access') |
| 200 | |
| 201 | pcsc_group = arg_parser.add_argument_group('PC/SC Reader') |
| 202 | pcsc_group.add_argument('-p', '--pcsc-device', type=int, dest='pcsc_dev', metavar='PCSC', default=None, |
| 203 | help='PC/SC reader number to use for SIM access') |
| 204 | |
| 205 | modem_group = arg_parser.add_argument_group('AT Command Modem Reader') |
| 206 | modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None, |
| 207 | help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)') |
| 208 | modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200, |
| 209 | help='Baud rate used for modem port') |
| 210 | |
| 211 | osmobb_group = arg_parser.add_argument_group('OsmocomBB Reader') |
| 212 | osmobb_group.add_argument('--osmocon', dest='osmocon_sock', metavar='PATH', default=None, |
| 213 | help='Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)') |
| 214 | |
| 215 | return arg_parser |
| 216 | |
Harald Welte | eb05b2f | 2021-04-10 11:01:56 +0200 | [diff] [blame] | 217 | def init_reader(opts, **kwargs) -> Optional[LinkBase]: |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 218 | """ |
| 219 | Init card reader driver |
| 220 | """ |
| 221 | sl = None # type : :Optional[LinkBase] |
| 222 | try: |
| 223 | if opts.pcsc_dev is not None: |
| 224 | print("Using PC/SC reader interface") |
| 225 | from pySim.transport.pcsc import PcscSimLink |
Harald Welte | eb05b2f | 2021-04-10 11:01:56 +0200 | [diff] [blame] | 226 | sl = PcscSimLink(opts.pcsc_dev, **kwargs) |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 227 | elif opts.osmocon_sock is not None: |
| 228 | print("Using Calypso-based (OsmocomBB) reader interface") |
| 229 | from pySim.transport.calypso import CalypsoSimLink |
Harald Welte | eb05b2f | 2021-04-10 11:01:56 +0200 | [diff] [blame] | 230 | sl = CalypsoSimLink(sock_path=opts.osmocon_sock, **kwargs) |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 231 | elif opts.modem_dev is not None: |
| 232 | print("Using modem for Generic SIM Access (3GPP TS 27.007)") |
| 233 | from pySim.transport.modem_atcmd import ModemATCommandLink |
Harald Welte | eb05b2f | 2021-04-10 11:01:56 +0200 | [diff] [blame] | 234 | sl = ModemATCommandLink(device=opts.modem_dev, baudrate=opts.modem_baud, **kwargs) |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 235 | else: # Serial reader is default |
| 236 | print("Using serial reader interface") |
| 237 | from pySim.transport.serial import SerialSimLink |
Harald Welte | eb05b2f | 2021-04-10 11:01:56 +0200 | [diff] [blame] | 238 | sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate, **kwargs) |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 239 | return sl |
| 240 | except Exception as e: |
Philipp Maier | 7328f10 | 2021-09-21 10:12:48 +0200 | [diff] [blame] | 241 | if str(e): |
| 242 | print("Card reader initialization failed with exception:\n" + str(e)) |
| 243 | else: |
| 244 | print("Card reader initialization failed with an exception of type:\n" + str(type(e))) |
Harald Welte | 6e0458d | 2021-04-03 11:52:37 +0200 | [diff] [blame] | 245 | return None |