blob: 09752ac65be06368ec8c2a2d69b8b0cb958d91a7 [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
Harald Weltefd476b42022-08-06 14:01:26 +020012from pySim.utils import sw_match, b2h, h2b, i2h, Hexstr
Christian Amsüss59f3b112022-08-12 15:46:52 +020013from pySim.cat import ProactiveCommand, CommandDetails, DeviceIdentities, Result
Harald Weltee79cc802021-01-21 14:10:43 +010014
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010015#
16# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Weltefd476b42022-08-06 14:01:26 +020017# Copyright (C) 2021-2022 Harald Welte <laforge@osmocom.org>
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010018#
19# This program is free software: you can redistribute it and/or modify
20# it under the terms of the GNU General Public License as published by
21# the Free Software Foundation, either version 2 of the License, or
22# (at your option) any later version.
23#
24# This program is distributed in the hope that it will be useful,
25# but WITHOUT ANY WARRANTY; without even the implied warranty of
26# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27# GNU General Public License for more details.
28#
29# You should have received a copy of the GNU General Public License
30# along with this program. If not, see <http://www.gnu.org/licenses/>.
31#
32
Harald Welte7829d8a2021-04-10 11:28:53 +020033
Harald Weltec91085e2022-02-10 18:05:45 +010034class ApduTracer:
35 def trace_command(self, cmd):
36 pass
37
38 def trace_response(self, cmd, sw, resp):
39 pass
Harald Welte7829d8a2021-04-10 11:28:53 +020040
Harald Weltefd476b42022-08-06 14:01:26 +020041class ProactiveHandler(abc.ABC):
42 """Abstract base class representing the interface of some code that handles
43 the proactive commands, as returned by the card in responses to the FETCH
44 command."""
Christian Amsüss59f3b112022-08-12 15:46:52 +020045 def receive_fetch_raw(self, pcmd: ProactiveCommand, parsed: Hexstr):
Harald Weltefd476b42022-08-06 14:01:26 +020046 # try to find a generic handler like handle_SendShortMessage
47 handle_name = 'handle_%s' % type(parsed).__name__
48 if hasattr(self, handle_name):
49 handler = getattr(self, handle_name)
50 return handler(pcmd.decoded)
51 # fall back to common handler
52 return self.receive_fetch(pcmd)
53
54 def receive_fetch(self, pcmd: ProactiveCommand):
55 """Default handler for not otherwise handled proactive commands."""
56 raise NotImplementedError('No handler method for %s' % pcmd.decoded)
57
58
Harald Welte7829d8a2021-04-10 11:28:53 +020059
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +020060class LinkBase(abc.ABC):
Harald Weltec91085e2022-02-10 18:05:45 +010061 """Base class for link/transport to card."""
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010062
Harald Weltefd476b42022-08-06 14:01:26 +020063 def __init__(self, sw_interpreter=None, apdu_tracer=None,
64 proactive_handler: Optional[ProactiveHandler]=None):
Harald Weltec91085e2022-02-10 18:05:45 +010065 self.sw_interpreter = sw_interpreter
66 self.apdu_tracer = apdu_tracer
Harald Weltefd476b42022-08-06 14:01:26 +020067 self.proactive_handler = proactive_handler
Harald Welte4f2c5462021-04-03 11:48:22 +020068
Harald Weltec91085e2022-02-10 18:05:45 +010069 @abc.abstractmethod
70 def _send_apdu_raw(self, pdu: str) -> Tuple[str, str]:
71 """Implementation specific method for sending the PDU."""
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +020072
Harald Weltec91085e2022-02-10 18:05:45 +010073 def set_sw_interpreter(self, interp):
74 """Set an (optional) status word interpreter."""
75 self.sw_interpreter = interp
Harald Welte4f2c5462021-04-03 11:48:22 +020076
Harald Weltec91085e2022-02-10 18:05:45 +010077 @abc.abstractmethod
78 def wait_for_card(self, timeout: int = None, newcardonly: bool = False):
79 """Wait for a card and connect to it
Sylvain Munautbdca2522010-12-09 13:31:58 +010080
Harald Weltec91085e2022-02-10 18:05:45 +010081 Args:
82 timeout : Maximum wait time in seconds (None=no timeout)
83 newcardonly : Should we wait for a new card, or an already inserted one ?
84 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010085
Harald Weltec91085e2022-02-10 18:05:45 +010086 @abc.abstractmethod
87 def connect(self):
88 """Connect to a card immediately
89 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010090
Harald Weltec91085e2022-02-10 18:05:45 +010091 @abc.abstractmethod
92 def disconnect(self):
93 """Disconnect from card
94 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010095
Harald Weltec91085e2022-02-10 18:05:45 +010096 @abc.abstractmethod
97 def reset_card(self):
98 """Resets the card (power down/up)
99 """
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100100
Harald Weltec91085e2022-02-10 18:05:45 +0100101 def send_apdu_raw(self, pdu: str):
102 """Sends an APDU with minimal processing
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100103
Harald Weltec91085e2022-02-10 18:05:45 +0100104 Args:
105 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
106 Returns:
107 tuple(data, sw), where
108 data : string (in hex) of returned data (ex. "074F4EFFFF")
109 sw : string (in hex) of status word (ex. "9000")
110 """
111 if self.apdu_tracer:
112 self.apdu_tracer.trace_command(pdu)
113 (data, sw) = self._send_apdu_raw(pdu)
114 if self.apdu_tracer:
115 self.apdu_tracer.trace_response(pdu, sw, data)
116 return (data, sw)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100117
Harald Weltec91085e2022-02-10 18:05:45 +0100118 def send_apdu(self, pdu):
119 """Sends an APDU and auto fetch response data
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100120
Harald Weltec91085e2022-02-10 18:05:45 +0100121 Args:
122 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
123 Returns:
124 tuple(data, sw), where
125 data : string (in hex) of returned data (ex. "074F4EFFFF")
126 sw : string (in hex) of status word (ex. "9000")
127 """
128 data, sw = self.send_apdu_raw(pdu)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100129
Harald Weltec91085e2022-02-10 18:05:45 +0100130 # When we have sent the first APDU, the SW may indicate that there are response bytes
131 # available. There are two SWs commonly used for this 9fxx (sim) and 61xx (usim), where
132 # xx is the number of response bytes available.
133 # See also:
134 if (sw is not None):
135 if ((sw[0:2] == '9f') or (sw[0:2] == '61')):
136 # SW1=9F: 3GPP TS 51.011 9.4.1, Responses to commands which are correctly executed
137 # SW1=61: ISO/IEC 7816-4, Table 5 — General meaning of the interindustry values of SW1-SW2
138 pdu_gr = pdu[0:2] + 'c00000' + sw[2:4]
139 data, sw = self.send_apdu_raw(pdu_gr)
140 if sw[0:2] == '6c':
141 # SW1=6C: ETSI TS 102 221 Table 7.1: Procedure byte coding
142 pdu_gr = pdu[0:8] + sw[2:4]
143 data, sw = self.send_apdu_raw(pdu_gr)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100144
Harald Weltec91085e2022-02-10 18:05:45 +0100145 return data, sw
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100146
Harald Weltec91085e2022-02-10 18:05:45 +0100147 def send_apdu_checksw(self, pdu, sw="9000"):
148 """Sends an APDU and check returned SW
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100149
Harald Weltec91085e2022-02-10 18:05:45 +0100150 Args:
151 pdu : string of hexadecimal characters (ex. "A0A40000023F00")
152 sw : string of 4 hexadecimal characters (ex. "9000"). The user may mask out certain
153 digits using a '?' to add some ambiguity if needed.
154 Returns:
155 tuple(data, sw), where
156 data : string (in hex) of returned data (ex. "074F4EFFFF")
157 sw : string (in hex) of status word (ex. "9000")
158 """
159 rv = self.send_apdu(pdu)
Christian Amsüss98552ef2022-08-11 19:29:37 +0200160 last_sw = rv[1]
Philipp Maierd4ebb6f2018-06-12 17:56:07 +0200161
Christian Amsüss98552ef2022-08-11 19:29:37 +0200162 while sw == '9000' and sw_match(last_sw, '91xx'):
163 # It *was* successful after all -- the extra pieces FETCH handled
164 # need not concern the caller.
165 rv = (rv[0], '9000')
Harald Weltec91085e2022-02-10 18:05:45 +0100166 # proactive sim as per TS 102 221 Setion 7.4.2
Christian Amsüss59f3b112022-08-12 15:46:52 +0200167 # TODO: Check SW manually to avoid recursing on the stack (provided this piece of code stays in this place)
Christian Amsüss98552ef2022-08-11 19:29:37 +0200168 fetch_rv = self.send_apdu_checksw('80120000' + last_sw[2:], sw)
Christian Amsüss59f3b112022-08-12 15:46:52 +0200169 # Setting this in case we later decide not to send a terminal
170 # response immediately unconditionally -- the card may still have
171 # something pending even though the last command was not processed
172 # yet.
Christian Amsüss98552ef2022-08-11 19:29:37 +0200173 last_sw = fetch_rv[1]
Christian Amsüss59f3b112022-08-12 15:46:52 +0200174 # parse the proactive command
175 pcmd = ProactiveCommand()
176 parsed = pcmd.from_tlv(h2b(fetch_rv[0]))
177 print("FETCH: %s (%s)" % (fetch_rv[0], type(parsed).__name__))
178 result = Result()
Harald Weltefd476b42022-08-06 14:01:26 +0200179 if self.proactive_handler:
Christian Amsüss59f3b112022-08-12 15:46:52 +0200180 # Extension point: If this does return a list of TLV objects,
181 # they could be appended after the Result; if the first is a
182 # Result, that cuold replace the one built here.
183 self.proactive_handler.receive_fetch_raw(pcmd, parsed)
184 result.from_dict({'general_result': 'performed_successfully', 'additional_information': ''})
185 else:
186 result.from_dict({'general_result': 'command_beyond_terminal_capability', 'additional_information': ''})
187
188 # Send response immediately, thus also flushing out any further
189 # proactive commands that the card already wants to send
190 #
191 # Structure as per TS 102 223 V4.4.0 Section 6.8
192
193 # The Command Details are echoed from the command that has been processed.
194 (command_details,) = [c for c in pcmd.decoded.children if isinstance(c, CommandDetails)]
195 # The Device Identities are fixed. (TS 102 223 V4.0.0 Section 6.8.2)
196 device_identities = DeviceIdentities()
197 device_identities.from_dict({'source_dev_id': 'terminal', 'dest_dev_id': 'uicc'})
198
199 # Testing hint: The value of tail does not influence the behavior
200 # of an SJA2 that sent ans SMS, so this is implemented only
201 # following TS 102 223, and not fully tested.
202 tail = command_details.to_tlv() + device_identities.to_tlv() + result.to_tlv()
203 # Testing hint: In contrast to the above, this part is positively
204 # essential to get the SJA2 to provide the later parts of a
205 # multipart SMS in response to an OTA RFM command.
206 terminal_response = '80140000' + b2h(len(tail).to_bytes(1, 'big') + tail)
207
208 terminal_response_rv = self.send_apdu(terminal_response)
209 last_sw = terminal_response_rv[1]
210
Harald Weltec91085e2022-02-10 18:05:45 +0100211 if not sw_match(rv[1], sw):
212 raise SwMatchError(rv[1], sw.lower(), self.sw_interpreter)
213 return rv
Harald Welte6e0458d2021-04-03 11:52:37 +0200214
Harald Weltec91085e2022-02-10 18:05:45 +0100215 def send_apdu_constr(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr):
216 """Build and sends an APDU using a 'construct' definition; parses response.
Harald Weltee0f9ef12021-04-10 17:22:35 +0200217
Harald Weltec91085e2022-02-10 18:05:45 +0100218 Args:
219 cla : string (in hex) ISO 7816 class byte
220 ins : string (in hex) ISO 7816 instruction byte
221 p1 : string (in hex) ISO 7116 Parameter 1 byte
222 p2 : string (in hex) ISO 7116 Parameter 2 byte
223 cmd_cosntr : defining how to generate binary APDU command data
224 cmd_data : command data passed to cmd_constr
225 resp_cosntr : defining how to decode binary APDU response data
226 Returns:
227 Tuple of (decoded_data, sw)
228 """
229 cmd = cmd_constr.build(cmd_data) if cmd_data else ''
230 p3 = i2h([len(cmd)])
231 pdu = ''.join([cla, ins, p1, p2, p3, b2h(cmd)])
232 (data, sw) = self.send_apdu(pdu)
233 if data:
234 # filter the resulting dict to avoid '_io' members inside
235 rsp = filter_dict(resp_constr.parse(h2b(data)))
236 else:
237 rsp = None
238 return (rsp, sw)
Harald Weltee0f9ef12021-04-10 17:22:35 +0200239
Harald Weltec91085e2022-02-10 18:05:45 +0100240 def send_apdu_constr_checksw(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr,
241 sw_exp="9000"):
242 """Build and sends an APDU using a 'construct' definition; parses response.
Harald Weltee0f9ef12021-04-10 17:22:35 +0200243
Harald Weltec91085e2022-02-10 18:05:45 +0100244 Args:
245 cla : string (in hex) ISO 7816 class byte
246 ins : string (in hex) ISO 7816 instruction byte
247 p1 : string (in hex) ISO 7116 Parameter 1 byte
248 p2 : string (in hex) ISO 7116 Parameter 2 byte
249 cmd_cosntr : defining how to generate binary APDU command data
250 cmd_data : command data passed to cmd_constr
251 resp_cosntr : defining how to decode binary APDU response data
252 exp_sw : string (in hex) of status word (ex. "9000")
253 Returns:
254 Tuple of (decoded_data, sw)
255 """
256 (rsp, sw) = self.send_apdu_constr(cla, ins,
257 p1, p2, cmd_constr, cmd_data, resp_constr)
258 if not sw_match(sw, sw_exp):
259 raise SwMatchError(sw, sw_exp.lower(), self.sw_interpreter)
260 return (rsp, sw)
261
Harald Weltee0f9ef12021-04-10 17:22:35 +0200262
Harald Welte28c24312021-04-11 12:19:36 +0200263def argparse_add_reader_args(arg_parser):
Harald Weltec91085e2022-02-10 18:05:45 +0100264 """Add all reader related arguments to the given argparse.Argumentparser instance."""
265 serial_group = arg_parser.add_argument_group('Serial Reader')
266 serial_group.add_argument('-d', '--device', metavar='DEV', default='/dev/ttyUSB0',
267 help='Serial Device for SIM access')
268 serial_group.add_argument('-b', '--baud', dest='baudrate', type=int, metavar='BAUD', default=9600,
269 help='Baud rate used for SIM access')
Harald Welte28c24312021-04-11 12:19:36 +0200270
Harald Weltec91085e2022-02-10 18:05:45 +0100271 pcsc_group = arg_parser.add_argument_group('PC/SC Reader')
272 pcsc_group.add_argument('-p', '--pcsc-device', type=int, dest='pcsc_dev', metavar='PCSC', default=None,
273 help='PC/SC reader number to use for SIM access')
Harald Welte28c24312021-04-11 12:19:36 +0200274
Harald Weltec91085e2022-02-10 18:05:45 +0100275 modem_group = arg_parser.add_argument_group('AT Command Modem Reader')
276 modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None,
277 help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)')
278 modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200,
279 help='Baud rate used for modem port')
Harald Welte28c24312021-04-11 12:19:36 +0200280
Harald Weltec91085e2022-02-10 18:05:45 +0100281 osmobb_group = arg_parser.add_argument_group('OsmocomBB Reader')
282 osmobb_group.add_argument('--osmocon', dest='osmocon_sock', metavar='PATH', default=None,
283 help='Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)')
Harald Welte28c24312021-04-11 12:19:36 +0200284
Harald Weltec91085e2022-02-10 18:05:45 +0100285 return arg_parser
286
Harald Welte28c24312021-04-11 12:19:36 +0200287
Harald Welteeb05b2f2021-04-10 11:01:56 +0200288def init_reader(opts, **kwargs) -> Optional[LinkBase]:
Harald Weltec91085e2022-02-10 18:05:45 +0100289 """
290 Init card reader driver
291 """
292 sl = None # type : :Optional[LinkBase]
293 try:
294 if opts.pcsc_dev is not None:
295 print("Using PC/SC reader interface")
296 from pySim.transport.pcsc import PcscSimLink
297 sl = PcscSimLink(opts.pcsc_dev, **kwargs)
298 elif opts.osmocon_sock is not None:
299 print("Using Calypso-based (OsmocomBB) reader interface")
300 from pySim.transport.calypso import CalypsoSimLink
301 sl = CalypsoSimLink(sock_path=opts.osmocon_sock, **kwargs)
302 elif opts.modem_dev is not None:
303 print("Using modem for Generic SIM Access (3GPP TS 27.007)")
304 from pySim.transport.modem_atcmd import ModemATCommandLink
305 sl = ModemATCommandLink(
306 device=opts.modem_dev, baudrate=opts.modem_baud, **kwargs)
307 else: # Serial reader is default
308 print("Using serial reader interface")
309 from pySim.transport.serial import SerialSimLink
310 sl = SerialSimLink(device=opts.device,
311 baudrate=opts.baudrate, **kwargs)
312 return sl
313 except Exception as e:
314 if str(e):
315 print("Card reader initialization failed with exception:\n" + str(e))
316 else:
317 print(
318 "Card reader initialization failed with an exception of type:\n" + str(type(e)))
319 return None