blob: 72a80a968d03d526dbcf05b9752536c0c42e397a [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 +020032class ApduTracer:
33 def trace_command(self, cmd):
34 pass
35
36 def trace_response(self, cmd, sw, resp):
37 pass
38
39
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +020040class LinkBase(abc.ABC):
Harald Welteee3501f2021-04-02 13:00:18 +020041 """Base class for link/transport to card."""
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010042
Harald Welte7829d8a2021-04-10 11:28:53 +020043 def __init__(self, sw_interpreter=None, apdu_tracer=None):
Harald Welteeb05b2f2021-04-10 11:01:56 +020044 self.sw_interpreter = sw_interpreter
Harald Welte7829d8a2021-04-10 11:28:53 +020045 self.apdu_tracer = apdu_tracer
Harald Welte4f2c5462021-04-03 11:48:22 +020046
Vadim Yanitskiye8c34ca2021-05-02 02:29:52 +020047 @abc.abstractmethod
48 def _send_apdu_raw(self, pdu:str) -> Tuple[str, str]:
49 """Implementation specific method for sending the PDU."""
50
Harald Welte4f2c5462021-04-03 11:48:22 +020051 def set_sw_interpreter(self, interp):
52 """Set an (optional) status word interpreter."""
53 self.sw_interpreter = interp
54
Harald Welte903bdaa2021-05-03 22:58:53 +020055 @abc.abstractmethod
Harald Welteee3501f2021-04-02 13:00:18 +020056 def wait_for_card(self, timeout:int=None, newcardonly:bool=False):
57 """Wait for a card and connect to it
Sylvain Munautbdca2522010-12-09 13:31:58 +010058
Harald Welteee3501f2021-04-02 13:00:18 +020059 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 Munautbdca2522010-12-09 13:31:58 +010062 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010063
Harald Welte903bdaa2021-05-03 22:58:53 +020064 @abc.abstractmethod
Sylvain Munautbdca2522010-12-09 13:31:58 +010065 def connect(self):
Harald Welteee3501f2021-04-02 13:00:18 +020066 """Connect to a card immediately
Sylvain Munautbdca2522010-12-09 13:31:58 +010067 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010068
Harald Welte903bdaa2021-05-03 22:58:53 +020069 @abc.abstractmethod
Sylvain Munautbdca2522010-12-09 13:31:58 +010070 def disconnect(self):
Harald Welteee3501f2021-04-02 13:00:18 +020071 """Disconnect from card
Sylvain Munautbdca2522010-12-09 13:31:58 +010072 """
Sylvain Munautbdca2522010-12-09 13:31:58 +010073
Harald Welte903bdaa2021-05-03 22:58:53 +020074 @abc.abstractmethod
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010075 def reset_card(self):
Harald Welteee3501f2021-04-02 13:00:18 +020076 """Resets the card (power down/up)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010077 """
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010078
Harald Welteee3501f2021-04-02 13:00:18 +020079 def send_apdu_raw(self, pdu:str):
80 """Sends an APDU with minimal processing
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010081
Harald Welteee3501f2021-04-02 13:00:18 +020082 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 Munaute7c15cd2010-12-07 10:01:55 +010088 """
Harald Welte7829d8a2021-04-10 11:28:53 +020089 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 Munaute7c15cd2010-12-07 10:01:55 +010095
96 def send_apdu(self, pdu):
Harald Welteee3501f2021-04-02 13:00:18 +020097 """Sends an APDU and auto fetch response data
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010098
Harald Welteee3501f2021-04-02 13:00:18 +020099 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 Munaute7c15cd2010-12-07 10:01:55 +0100105 """
106 data, sw = self.send_apdu_raw(pdu)
107
Philipp Maier859e0fd2018-06-12 18:40:24 +0200108 # 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 Welte8dfd6d02021-05-25 21:54:45 +0200112 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 Munaute7c15cd2010-12-07 10:01:55 +0100122
123 return data, sw
124
125 def send_apdu_checksw(self, pdu, sw="9000"):
Harald Welteee3501f2021-04-02 13:00:18 +0200126 """Sends an APDU and check returned SW
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100127
Harald Welteee3501f2021-04-02 13:00:18 +0200128 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 Munaute7c15cd2010-12-07 10:01:55 +0100136 """
137 rv = self.send_apdu(pdu)
Philipp Maierd4ebb6f2018-06-12 17:56:07 +0200138
Harald Welte67d551a2021-01-21 14:50:01 +0100139 if not sw_match(rv[1], sw):
Harald Welte4f2c5462021-04-03 11:48:22 +0200140 raise SwMatchError(rv[1], sw.lower(), self.sw_interpreter)
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100141 return rv
Harald Welte6e0458d2021-04-03 11:52:37 +0200142
Harald Weltee0f9ef12021-04-10 17:22:35 +0200143 def send_apdu_constr(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr):
144 """Build and sends an APDU using a 'construct' definition; parses response.
145
146 Args:
147 cla : string (in hex) ISO 7816 class byte
148 ins : string (in hex) ISO 7816 instruction byte
149 p1 : string (in hex) ISO 7116 Parameter 1 byte
150 p2 : string (in hex) ISO 7116 Parameter 2 byte
151 cmd_cosntr : defining how to generate binary APDU command data
152 cmd_data : command data passed to cmd_constr
153 resp_cosntr : defining how to decode binary APDU response data
154 Returns:
155 Tuple of (decoded_data, sw)
156 """
157 cmd = cmd_constr.build(cmd_data) if cmd_data else ''
158 p3 = i2h([len(cmd)])
159 pdu = ''.join([cla, ins, p1, p2, p3, b2h(cmd)])
160 (data, sw) = self.send_apdu(pdu)
161 if data:
162 # filter the resulting dict to avoid '_io' members inside
163 rsp = filter_dict(resp_constr.parse(h2b(data)))
164 else:
165 rsp = None
166 return (rsp, sw)
167
168 def send_apdu_constr_checksw(self, cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr,
169 sw_exp="9000"):
170 """Build and sends an APDU using a 'construct' definition; parses response.
171
172 Args:
173 cla : string (in hex) ISO 7816 class byte
174 ins : string (in hex) ISO 7816 instruction byte
175 p1 : string (in hex) ISO 7116 Parameter 1 byte
176 p2 : string (in hex) ISO 7116 Parameter 2 byte
177 cmd_cosntr : defining how to generate binary APDU command data
178 cmd_data : command data passed to cmd_constr
179 resp_cosntr : defining how to decode binary APDU response data
180 exp_sw : string (in hex) of status word (ex. "9000")
181 Returns:
182 Tuple of (decoded_data, sw)
183 """
184 (rsp, sw) = self.send_apdu_constr(cla, ins, p1, p2, cmd_constr, cmd_data, resp_constr)
185 if not sw_match(sw, sw_exp):
186 raise SwMatchError(sw, sw_exp.lower(), self.sw_interpreter)
187 return (rsp, sw)
188
Harald Welte28c24312021-04-11 12:19:36 +0200189def argparse_add_reader_args(arg_parser):
190 """Add all reader related arguments to the given argparse.Argumentparser instance."""
191 serial_group = arg_parser.add_argument_group('Serial Reader')
192 serial_group.add_argument('-d', '--device', metavar='DEV', default='/dev/ttyUSB0',
193 help='Serial Device for SIM access')
194 serial_group.add_argument('-b', '--baud', dest='baudrate', type=int, metavar='BAUD', default=9600,
195 help='Baud rate used for SIM access')
196
197 pcsc_group = arg_parser.add_argument_group('PC/SC Reader')
198 pcsc_group.add_argument('-p', '--pcsc-device', type=int, dest='pcsc_dev', metavar='PCSC', default=None,
199 help='PC/SC reader number to use for SIM access')
200
201 modem_group = arg_parser.add_argument_group('AT Command Modem Reader')
202 modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None,
203 help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)')
204 modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200,
205 help='Baud rate used for modem port')
206
207 osmobb_group = arg_parser.add_argument_group('OsmocomBB Reader')
208 osmobb_group.add_argument('--osmocon', dest='osmocon_sock', metavar='PATH', default=None,
209 help='Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)')
210
211 return arg_parser
212
Harald Welteeb05b2f2021-04-10 11:01:56 +0200213def init_reader(opts, **kwargs) -> Optional[LinkBase]:
Harald Welte6e0458d2021-04-03 11:52:37 +0200214 """
215 Init card reader driver
216 """
217 sl = None # type : :Optional[LinkBase]
218 try:
219 if opts.pcsc_dev is not None:
220 print("Using PC/SC reader interface")
221 from pySim.transport.pcsc import PcscSimLink
Harald Welteeb05b2f2021-04-10 11:01:56 +0200222 sl = PcscSimLink(opts.pcsc_dev, **kwargs)
Harald Welte6e0458d2021-04-03 11:52:37 +0200223 elif opts.osmocon_sock is not None:
224 print("Using Calypso-based (OsmocomBB) reader interface")
225 from pySim.transport.calypso import CalypsoSimLink
Harald Welteeb05b2f2021-04-10 11:01:56 +0200226 sl = CalypsoSimLink(sock_path=opts.osmocon_sock, **kwargs)
Harald Welte6e0458d2021-04-03 11:52:37 +0200227 elif opts.modem_dev is not None:
228 print("Using modem for Generic SIM Access (3GPP TS 27.007)")
229 from pySim.transport.modem_atcmd import ModemATCommandLink
Harald Welteeb05b2f2021-04-10 11:01:56 +0200230 sl = ModemATCommandLink(device=opts.modem_dev, baudrate=opts.modem_baud, **kwargs)
Harald Welte6e0458d2021-04-03 11:52:37 +0200231 else: # Serial reader is default
232 print("Using serial reader interface")
233 from pySim.transport.serial import SerialSimLink
Harald Welteeb05b2f2021-04-10 11:01:56 +0200234 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate, **kwargs)
Harald Welte6e0458d2021-04-03 11:52:37 +0200235 return sl
236 except Exception as e:
Philipp Maier7328f102021-09-21 10:12:48 +0200237 if str(e):
238 print("Card reader initialization failed with exception:\n" + str(e))
239 else:
240 print("Card reader initialization failed with an exception of type:\n" + str(type(e)))
Harald Welte6e0458d2021-04-03 11:52:37 +0200241 return None