blob: 9364b07e99598fada38ce972696a604630176a18 [file] [log] [blame]
Sylvain Munaute7c15cd2010-12-07 10:01:55 +01001# -*- coding: utf-8 -*-
2
3""" pySim: PCSC reader transport link base
4"""
5
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +02006import abc
Harald Welte28c24312021-04-11 12:19:36 +02007import argparse
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +02008from typing import Optional, Tuple
Harald Welte6e0458d2021-04-03 11:52:37 +02009
Harald Weltee79cc802021-01-21 14:10:43 +010010from pySim.exceptions import *
Harald Weltee0f9ef12021-04-10 17:22:35 +020011from pySim.construct import filter_dict
12from pySim.utils import sw_match, b2h, h2b, i2h
Harald Weltee79cc802021-01-21 14:10:43 +010013
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010014#
15# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Weltee0f9ef12021-04-10 17:22:35 +020016# Copyright (C) 2021 Harald Welte <laforge@osmocom.org>
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010017#
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 Welte7829d8a2021-04-10 11:28:53 +020032
Harald Weltec91085e2022-02-10 18:05:45 +010033class ApduTracer:
34 def trace_command(self, cmd):
35 pass
36
37 def trace_response(self, cmd, sw, resp):
38 pass
Harald Welte7829d8a2021-04-10 11:28:53 +020039
40
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +020041class LinkBase(abc.ABC):
Harald Weltec91085e2022-02-10 18:05:45 +010042 """Base class for link/transport to card."""
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010043
Harald Weltec91085e2022-02-10 18:05:45 +010044 def __init__(self, sw_interpreter=None, apdu_tracer=None):
45 self.sw_interpreter = sw_interpreter
46 self.apdu_tracer = apdu_tracer
Harald Welte4f2c5462021-04-03 11:48:22 +020047
Harald Weltec91085e2022-02-10 18:05:45 +010048 @abc.abstractmethod
49 def _send_apdu_raw(self, pdu: str) -> Tuple[str, str]:
50 """Implementation specific method for sending the PDU."""
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +020051
Harald Weltec91085e2022-02-10 18:05:45 +010052 def set_sw_interpreter(self, interp):
53 """Set an (optional) status word interpreter."""
54 self.sw_interpreter = interp
Harald Welte4f2c5462021-04-03 11:48:22 +020055
Harald Weltec91085e2022-02-10 18:05:45 +010056 @abc.abstractmethod
57 def wait_for_card(self, timeout: int = None, newcardonly: bool = False):
58 """Wait for a card and connect to it
Sylvain Munautbdca2522010-12-09 13:31:58 +010059
Harald Weltec91085e2022-02-10 18:05:45 +010060 Args:
61 timeout : Maximum wait time in seconds (None=no timeout)
62 newcardonly : Should we wait for a new card, or an already inserted one ?
63 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010064
Harald Weltec91085e2022-02-10 18:05:45 +010065 @abc.abstractmethod
66 def connect(self):
67 """Connect to a card immediately
68 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010069
Harald Weltec91085e2022-02-10 18:05:45 +010070 @abc.abstractmethod
71 def disconnect(self):
72 """Disconnect from card
73 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010074
Harald Weltec91085e2022-02-10 18:05:45 +010075 @abc.abstractmethod
76 def reset_card(self):
77 """Resets the card (power down/up)
78 """
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010079
Harald Weltec91085e2022-02-10 18:05:45 +010080 def send_apdu_raw(self, pdu: str):
81 """Sends an APDU with minimal processing
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010082
Harald Weltec91085e2022-02-10 18:05:45 +010083 Args:
84 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
85 Returns:
86 tuple(data, sw), where
87 data : string (in hex) of returned data (ex. "074F4EFFFF")
88 sw : string (in hex) of status word (ex. "9000")
89 """
90 if self.apdu_tracer:
91 self.apdu_tracer.trace_command(pdu)
92 (data, sw) = self._send_apdu_raw(pdu)
93 if self.apdu_tracer:
94 self.apdu_tracer.trace_response(pdu, sw, data)
95 return (data, sw)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010096
Harald Weltec91085e2022-02-10 18:05:45 +010097 def send_apdu(self, pdu):
98 """Sends an APDU and auto fetch response data
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010099
Harald Weltec91085e2022-02-10 18:05:45 +0100100 Args:
101 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
102 Returns:
103 tuple(data, sw), where
104 data : string (in hex) of returned data (ex. "074F4EFFFF")
105 sw : string (in hex) of status word (ex. "9000")
106 """
107 data, sw = self.send_apdu_raw(pdu)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100108
Harald Weltec91085e2022-02-10 18:05:45 +0100109 # When we have sent the first APDU, the SW may indicate that there are response bytes
110 # available. There are two SWs commonly used for this 9fxx (sim) and 61xx (usim), where
111 # xx is the number of response bytes available.
112 # See also:
113 if (sw is not None):
114 if ((sw[0:2] == '9f') or (sw[0:2] == '61')):
115 # SW1=9F: 3GPP TS 51.011 9.4.1, Responses to commands which are correctly executed
116 # SW1=61: ISO/IEC 7816-4, Table 5 — General meaning of the interindustry values of SW1-SW2
117 pdu_gr = pdu[0:2] + 'c00000' + sw[2:4]
118 data, sw = self.send_apdu_raw(pdu_gr)
119 if sw[0:2] == '6c':
120 # SW1=6C: ETSI TS 102 221 Table 7.1: Procedure byte coding
121 pdu_gr = pdu[0:8] + sw[2:4]
122 data, sw = self.send_apdu_raw(pdu_gr)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100123
Harald Weltec91085e2022-02-10 18:05:45 +0100124 return data, sw
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100125
Harald Weltec91085e2022-02-10 18:05:45 +0100126 def send_apdu_checksw(self, pdu, sw="9000"):
127 """Sends an APDU and check returned SW
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100128
Harald Weltec91085e2022-02-10 18:05:45 +0100129 Args:
130 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
131 sw : string of 4 hexadecimal characters (ex. "9000"). The user may mask out certain
132 digits using a '?' to add some ambiguity if needed.
133 Returns:
134 tuple(data, sw), where
135 data : string (in hex) of returned data (ex. "074F4EFFFF")
136 sw : string (in hex) of status word (ex. "9000")
137 """
138 rv = self.send_apdu(pdu)
Philipp Maierd4ebb6f2018-06-12 17:56:07 +0200139
Harald Weltec91085e2022-02-10 18:05:45 +0100140 if sw == '9000' and sw_match(rv[1], '91xx'):
141 # proactive sim as per TS 102 221 Setion 7.4.2
142 rv = self.send_apdu_checksw('80120000' + rv[1][2:], sw)
143 print("FETCH: %s", rv[0])
144 if not sw_match(rv[1], sw):
145 raise SwMatchError(rv[1], sw.lower(), self.sw_interpreter)
146 return rv
Harald Welte6e0458d2021-04-03 11:52:37 +0200147
Harald Weltec91085e2022-02-10 18:05:45 +0100148 def send_apdu_constr(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr):
149 """Build and sends an APDU using a 'construct' definition; parses response.
Harald Weltee0f9ef12021-04-10 17:22:35 +0200150
Harald Weltec91085e2022-02-10 18:05:45 +0100151 Args:
152 cla : string (in hex) ISO 7816 class byte
153 ins : string (in hex) ISO 7816 instruction byte
154 p1 : string (in hex) ISO 7116 Parameter 1 byte
155 p2 : string (in hex) ISO 7116 Parameter 2 byte
156 cmd_cosntr : defining how to generate binary APDU command data
157 cmd_data : command data passed to cmd_constr
158 resp_cosntr : defining how to decode binary APDU response data
159 Returns:
160 Tuple of (decoded_data, sw)
161 """
162 cmd = cmd_constr.build(cmd_data) if cmd_data else ''
163 p3 = i2h([len(cmd)])
164 pdu = ''.join([cla, ins, p1, p2, p3, b2h(cmd)])
165 (data, sw) = self.send_apdu(pdu)
166 if data:
167 # filter the resulting dict to avoid '_io' members inside
168 rsp = filter_dict(resp_constr.parse(h2b(data)))
169 else:
170 rsp = None
171 return (rsp, sw)
Harald Weltee0f9ef12021-04-10 17:22:35 +0200172
Harald Weltec91085e2022-02-10 18:05:45 +0100173 def send_apdu_constr_checksw(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr,
174 sw_exp="9000"):
175 """Build and sends an APDU using a 'construct' definition; parses response.
Harald Weltee0f9ef12021-04-10 17:22:35 +0200176
Harald Weltec91085e2022-02-10 18:05:45 +0100177 Args:
178 cla : string (in hex) ISO 7816 class byte
179 ins : string (in hex) ISO 7816 instruction byte
180 p1 : string (in hex) ISO 7116 Parameter 1 byte
181 p2 : string (in hex) ISO 7116 Parameter 2 byte
182 cmd_cosntr : defining how to generate binary APDU command data
183 cmd_data : command data passed to cmd_constr
184 resp_cosntr : defining how to decode binary APDU response data
185 exp_sw : string (in hex) of status word (ex. "9000")
186 Returns:
187 Tuple of (decoded_data, sw)
188 """
189 (rsp, sw) = self.send_apdu_constr(cla, ins,
190 p1, p2, cmd_constr, cmd_data, resp_constr)
191 if not sw_match(sw, sw_exp):
192 raise SwMatchError(sw, sw_exp.lower(), self.sw_interpreter)
193 return (rsp, sw)
194
Harald Weltee0f9ef12021-04-10 17:22:35 +0200195
Harald Welte28c24312021-04-11 12:19:36 +0200196def argparse_add_reader_args(arg_parser):
Harald Weltec91085e2022-02-10 18:05:45 +0100197 """Add all reader related arguments to the given argparse.Argumentparser instance."""
198 serial_group = arg_parser.add_argument_group('Serial Reader')
199 serial_group.add_argument('-d', '--device', metavar='DEV', default='/dev/ttyUSB0',
200 help='Serial Device for SIM access')
201 serial_group.add_argument('-b', '--baud', dest='baudrate', type=int, metavar='BAUD', default=9600,
202 help='Baud rate used for SIM access')
Harald Welte28c24312021-04-11 12:19:36 +0200203
Harald Weltec91085e2022-02-10 18:05:45 +0100204 pcsc_group = arg_parser.add_argument_group('PC/SC Reader')
205 pcsc_group.add_argument('-p', '--pcsc-device', type=int, dest='pcsc_dev', metavar='PCSC', default=None,
206 help='PC/SC reader number to use for SIM access')
Harald Welte28c24312021-04-11 12:19:36 +0200207
Harald Weltec91085e2022-02-10 18:05:45 +0100208 modem_group = arg_parser.add_argument_group('AT Command Modem Reader')
209 modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None,
210 help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)')
211 modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200,
212 help='Baud rate used for modem port')
Harald Welte28c24312021-04-11 12:19:36 +0200213
Harald Weltec91085e2022-02-10 18:05:45 +0100214 osmobb_group = arg_parser.add_argument_group('OsmocomBB Reader')
215 osmobb_group.add_argument('--osmocon', dest='osmocon_sock', metavar='PATH', default=None,
216 help='Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)')
Harald Welte28c24312021-04-11 12:19:36 +0200217
Harald Weltec91085e2022-02-10 18:05:45 +0100218 return arg_parser
219
Harald Welte28c24312021-04-11 12:19:36 +0200220
Harald Welteeb05b2f2021-04-10 11:01:56 +0200221def init_reader(opts, **kwargs) -> Optional[LinkBase]:
Harald Weltec91085e2022-02-10 18:05:45 +0100222 """
223 Init card reader driver
224 """
225 sl = None # type : :Optional[LinkBase]
226 try:
227 if opts.pcsc_dev is not None:
228 print("Using PC/SC reader interface")
229 from pySim.transport.pcsc import PcscSimLink
230 sl = PcscSimLink(opts.pcsc_dev, **kwargs)
231 elif opts.osmocon_sock is not None:
232 print("Using Calypso-based (OsmocomBB) reader interface")
233 from pySim.transport.calypso import CalypsoSimLink
234 sl = CalypsoSimLink(sock_path=opts.osmocon_sock, **kwargs)
235 elif opts.modem_dev is not None:
236 print("Using modem for Generic SIM Access (3GPP TS 27.007)")
237 from pySim.transport.modem_atcmd import ModemATCommandLink
238 sl = ModemATCommandLink(
239 device=opts.modem_dev, baudrate=opts.modem_baud, **kwargs)
240 else: # Serial reader is default
241 print("Using serial reader interface")
242 from pySim.transport.serial import SerialSimLink
243 sl = SerialSimLink(device=opts.device,
244 baudrate=opts.baudrate, **kwargs)
245 return sl
246 except Exception as e:
247 if str(e):
248 print("Card reader initialization failed with exception:\n" + str(e))
249 else:
250 print(
251 "Card reader initialization failed with an exception of type:\n" + str(type(e)))
252 return None