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