Commit Graph

76 Commits

Author SHA1 Message Date
Harald Welte 24a7f168bd pcsc: open reader/card in EXCLUSIVE mode by default
There was a support request hinting that other applications
concurrently accessed the SIM and were messing up the card state while
pySim-shell was running.

Let's avoid such situations by opening the card/reader in EXCLUSIVE mode
by default.  If somebody really has a special use case, they can now add
the --pcsc-shared flag to restore the legacy behavior (SHARED mode).

Change-Id: I90d887714b559a4604708d3c6dd23b5e05f40576
2024-03-15 20:33:09 +00:00
Harald Welte 49d69335b2 pylint: transport/__init__.py
pySim/transport/__init__.py:139:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)

Change-Id: Ibeeb7d6fde40bb37774bbd09ad185203ac7bcb48
2024-02-05 09:52:46 +01:00
Harald Welte fdaefd9a8a pylint: transport/serial.py
pySim/transport/serial.py:54:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)
pySim/transport/serial.py:89:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)
pySim/transport/serial.py:225:0: C0325: Unnecessary parens after 'while' keyword (superfluous-parens)
pySim/transport/serial.py:63:12: R1705: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it (no-else-return)
pySim/transport/serial.py:106:8: R1720: Unnecessary "elif" after "raise", remove the leading "el" from "elif" (no-else-raise)
pySim/transport/serial.py:124:12: W0707: Consider explicitly re-raising using 'except Exception as exc' and 'raise ValueError('Invalid reset pin %s' % self._rst_pin) from exc' (raise-missing-from)
pySim/transport/serial.py:204:12: R1723: Unnecessary "elif" after "break", remove the leading "el" from "elif" (no-else-break)
pySim/transport/serial.py:20:0: C0411: standard import "import time" should be placed before "import serial" (wrong-import-order)
pySim/transport/serial.py:21:0: C0411: standard import "import os" should be placed before "import serial" (wrong-import-order)
pySim/transport/serial.py:22:0: C0411: standard import "import argparse" should be placed before "import serial" (wrong-import-order)
pySim/transport/serial.py:23:0: C0411: standard import "from typing import Optional" should be placed before "import serial" (wrong-import-order)

Change-Id: I82ef12492615a18a13cbdecf0371b3a5d02bbd5c
2024-02-05 09:52:40 +01:00
Harald Welte 7781c70c09 pylint: transport/pcsc.py
pySim/transport/pcsc.py:26:0: W0404: Reimport 'CardConnectionException' (imported line 26) (reimported)
pySim/transport/pcsc.py:60:4: R1711: Useless return at end of function or method (useless-return)
pySim/transport/pcsc.py:74:12: W0707: Consider explicitly re-raising using 'except CardRequestTimeoutException as exc' and 'raise NoCardError() from exc' (raise-missing-from)
pySim/transport/pcsc.py:86:12: W0707: Consider explicitly re-raising using 'except CardConnectionException as exc' and 'raise ProtocolError() from exc' (raise-missing-from)
pySim/transport/pcsc.py:88:12: W0707: Consider explicitly re-raising using 'except NoCardException as exc' and 'raise NoCardError() from exc' (raise-missing-from)
pySim/transport/pcsc.py:22:0: W0611: Unused Union imported from typing (unused-import)

Change-Id: I0ef440d8825300d6efb8959a67da095ab5623f9c
2024-02-05 09:52:29 +01:00
Harald Welte 181becb676 pylint: transport/modem_atcmd.py
pySim/transport/modem_atcmd.py:70:0: C0325: Unnecessary parens after 'assert' keyword (superfluous-parens)
pySim/transport/modem_atcmd.py:28:0: W0401: Wildcard import pySim.exceptions (wildcard-import)
pySim/transport/modem_atcmd.py:60:22: C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck)
pySim/transport/modem_atcmd.py:72:12: W0707: Consider explicitly re-raising using 'except Exception as exc' and 'raise ReaderError('Failed to send AT command: %s' % cmd) from exc' (raise-missing-from)
pySim/transport/modem_atcmd.py:120:12: R1705: Unnecessary "elif" after "return", remove the leading "el" from "elif" (no-else-return)
pySim/transport/modem_atcmd.py:138:8: W1201: Use lazy % formatting in logging functions (logging-not-lazy)
pySim/transport/modem_atcmd.py:170:12: W0707: Consider explicitly re-raising using 'except Exception as exc' and 'raise ReaderError('Failed to parse response from modem: %s' % rsp) from exc' (raise-missing-from)
pySim/transport/modem_atcmd.py:168:13: W0612: Unused variable 'rsp_pdu_len' (unused-variable)
pySim/transport/modem_atcmd.py:21:0: C0411: standard import "import time" should be placed before "import serial" (wrong-import-order)
pySim/transport/modem_atcmd.py:22:0: C0411: standard import "import re" should be placed before "import serial" (wrong-import-order)
pySim/transport/modem_atcmd.py:23:0: C0411: standard import "import argparse" should be placed before "import serial" (wrong-import-order)
pySim/transport/modem_atcmd.py:24:0: C0411: standard import "from typing import Optional" should be placed before "import serial" (wrong-import-order)
pySim/transport/modem_atcmd.py:28:0: W0614: Unused import(s) NoCardError and SwMatchError from wildcard import of pySim.exceptions (unused-wildcard-import)

Change-Id: I2c8994eabd973b65132af1030429b1021d0c20df
2024-02-05 09:52:24 +01:00
Harald Welte c4d80870e8 pylint: transport/calypso.py
pySim/transport/calypso.py:27:0: W0401: Wildcard import pySim.exceptions (wildcard-import)
pySim/transport/calypso.py:61:23: W0622: Redefining built-in 'type' (redefined-builtin)
pySim/transport/calypso.py:62:8: R1725: Consider using Python 3 style super() without arguments (super-with-arguments)
pySim/transport/calypso.py:73:8: R1725: Consider using Python 3 style super() without arguments (super-with-arguments)
pySim/transport/calypso.py:27:0: W0614: Unused import(s) NoCardError and SwMatchError from wildcard import of pySim.exceptions (unused-wildcard-import)

Change-Id: I6b10d5f3370c00b07288300b537c6f0e17c84a87
2024-02-05 09:52:17 +01:00
Harald Welte eecef54eee commands.py: Wrap the transport send_apdu* methods
Let's not have higher level code directly call the transports send_apdu*
methods.  We do this as a precursor to introducing secure channel
support, where the secure channel driver would add MAC and/or encrypt
APDUs before they are sent to the transport.

Change-Id: I1b870140959aa8241cda2246e74576390123cb2d
2024-02-01 12:06:07 +01:00
Harald Welte 0ecbf63a02 transport: Extend the documentation for each transport driver
This driver description we add to the code is automatically added to the
respective user manual sections.

Change-Id: I8807bfb11f43b167f1321d556e09ec5234fff629
2023-12-21 12:33:12 +01:00
Harald Welte baec4e9c81 transport: Move printing of reader number/name to generic code
Let's avoid copy+pasting print statements everywhere.  The instances
do already have a __str__ method for the purpose of printing their name in a
generic way.

Change-Id: I663a9ea69bf7e7aaa6502896b6a71ef692f8d844
2023-12-21 12:33:12 +01:00
Harald Welte ad002797e2 transport/pcsc: Allow opening PC/SC readers by a regex of their name
Opening PC/SC readers by index/number is very error-prone as the order
is never deterministic in any system with multiple (hot-plugged, USB)
readers.  Instead, let's offer the alternative of specifying a regular
expression to match the reader name (similar to remsim-bankd).

Change-Id: I983f19c6741904c1adf27749c9801b44a03a5d78
2023-12-21 12:33:12 +01:00
Harald Welte 0f177c1d29 transport: Pass argparse.Namespace directly into transport classes
It's odd that the individual transport driver specifies their argparse
options but then the core transport part evaluates them individually.
This means we cannot add new options within a transport.

Let's pass the Namespace instance into the constructor of the
specific transport to improve this.

Change-Id: Ib977007dd605ec9a9c09a3d143d2c2308991a12c
2023-12-21 11:31:57 +00:00
Harald Welte 4e02436dba perform multiple GET RESPONSE cycles if more data is available
So far we implemented only one round of "Send the APDU, get SW=61xx,
call GET RESPONSE".  This permitted us to receive only data up to 256
bytes.

Let's extend that to doing multiple rounds, concatenating the result.
This allows us to obtain arbitrary-length data from the card.

See Annex C.1 of ETSI TS 102 221 for examples showing multiple 61xx
iterations.

Change-Id: Ib17da655aa0b0eb203c29dc92690c81bd1300778
Closes: OS#6287
2023-12-04 21:38:50 +01:00
Harald Welte 2d44f03af2 transport: Log it explicitly if user doesn't specify a reader
Change-Id: I37e9d62fabf237ece7e49d8f2253c606999d3d02
2023-11-04 15:48:55 +00:00
Philipp Maier 4af63dc760 transport: print reader device/number on init
When we initialize the reader, we currently tell only which type of
interface we are using, but we do not print the reader number or the
device path.

Let's extend the messages so that the path is printed. To prevent
problems with integration-tests, let's also add an environment variable
that we can use to detect when pySim runs inside a integration-test.

Related: OS#6210
Change-Id: Ibe296d51885b1ef5f9c9ecaf1d28da52014dcc4b
2023-10-26 15:17:07 +00:00
Philipp Maier 8c82378bfd transport: move argument parser setup into concrete classes
The argument parser is set up globally for all LinkBase objects in
__init__.py. Since we tend to have only platform independed code in
__init__.py, we should move the argument parser setup into the
specific LinkBase classes.

Related: OS#6210
Change-Id: I22c32aa81ca0588e3314c3ff4546f6e5092c11df
2023-10-24 19:28:34 +00:00
Philipp Maier 3077343739 transport: move init message into concrete classes
In in the module __init__.py we print an init message (which type of
LinkBase class is providing the SimLink). However in __init__.py we tend
to have only platform independed code but the message string can already
be categorized as platform depened. Let's put the init message into the
constructor of the concrete classes of LinkBase.

Related: OS#6210
Change-Id: I0a6dd7deb79a5f3e42b29094a1cf2535075fa430
2023-10-24 19:28:34 +00:00
Philipp Maier af4e5bb18c transport: do not catch exceptions in init_reader
We currently catch any exceptions that may occur when the card reader is
initialized. Then we print the exception string or the exception type
when no string is available. However, a failure during the reader
initialization is usually a severe problem, so a traceback would provde
a lot of helpful information to debug the issue. So lets not catch any
exceptions at this level so that we get the full backtrace.

Related: OS#6210
Change-Id: I4c4807576fe63cf71a7d33b243a3f8fea0b7ff23
2023-10-16 14:36:02 +02:00
Philipp Maier 58e89eb15a transport: add return type annotation to method __str__
The abstract class LinkBase has no return type annotation on its
__str__ method.

Related: OS#6210
Change-Id: I26d3d2714708dbe957704b60d17ba2afa325b2c4
2023-10-10 12:06:57 +02:00
Philipp Maier 6bfa8a8533 pySim-shell: print device info in case an exception occurs
When an exception occurs while initializing or handling the card we
print a traceback, but we do not print any info that allows us to
identify the device that was involved when the exception occurred. Let's
include the device path or number in the error message before we print
the traceback.

In order to make it easier to print the device information, let's add a
__str__() method to all of our devices. This method shall return the
device number or path.

Related: OS#6210
Change-Id: I200463e692245da40ea6d5b609bfc0ca02d15bdb
2023-10-10 11:51:08 +02:00
Harald Welte f9f8d7a294 pySim/transport: Use newly-defined ResTuple type
Let's use the newly-added ResTuple type annotation rather than
open-coding it everywhere.

Change-Id: I122589e8aec4bf66dc2e86d7602ebecb771dcb93
2023-07-11 08:42:12 +02:00
Harald Welte ab6897c4cd pySim/transport: More type annotations
Change-Id: I62e081271e3a579851a588a4ed7282017e56f852
2023-07-11 08:42:12 +02:00
Philipp Maier 621f78c943 serial: return a return code in reset_card()
The method reset_card does not return a return code, while the
coresponding pcsc implementation does return 1 on success.

Change-Id: I658dd6857580652696b4a77e7d6cfe5778f09eff
2023-06-07 10:00:52 +00:00
Tobias Engel d70ac22618 modem_atcmd: raise ProtocolError instead of ReaderError on CME ERROR
Also accept ProtocolError in addition to SwMatchError in filesystem.py
when probing for applications

Change-Id: I82b50408328f8eaaee5c9e311c4620d20f930642
2023-06-02 15:35:43 +00:00
Christian Amsüss 59f3b1154f proactive: Send a Terminal Response automatically after a Fetch
Change-Id: I43bc994e7517b5907fb40a98d84797c54056c47d
2022-08-21 11:54:33 +00:00
Christian Amsüss 98552ef1bd proactive: Avoid clobbering the output of the command that triggered the FETCH
Change-Id: I2b794a5c5bc808b9703b4bc679c119341a0ed41c
2022-08-21 11:54:00 +00:00
Harald Welte fd476b4d62 pySim.transport: Add mechanism for handling for CAT/USAT proactive cmds
This introduces an optional argument to the LinkBase class constructor,
where the application can pass an instance of a ProactiveHandler derived
class in order to handle the proactive commands that the LinkBase is
automatically fetching whenever the card indicates so.

Change-Id: I844504e2fc1b27ce4fc7ede20b2307e698baa0f6
2022-08-06 18:56:42 +02:00
Vadim Yanitskiy 04b5d9d7ab Py2 -> Py3: do not inherit classes from object
https://stackoverflow.com/questions/4015417/why-do-python-classes-inherit-object/45062077

Change-Id: I15003ba591510d68f3235f71526ad5d8a456088e
2022-07-07 03:05:30 +07:00
Vadim Yanitskiy e6b86872ce transport/pcsc: throw ReaderError with a message
Before this patch:

  $ ./pySim-shell.py -p 0
  Card reader initialization failed with an exception of type:
  <class 'pySim.exceptions.ReaderError'>

after:

  $ ./pySim-shell.py -p 0
  Card reader initialization failed with exception:
  No reader found for number 0

Change-Id: Id08c4990857f7083a8d1cefc90ff85fc20ab6fef
2022-04-25 18:24:41 +03:00
Harald Welte c91085e744 cosmetic: Switch to consistent four-spaces indent; run autopep8
We had a mixture of tab and 4space based indenting, which is a bad
idea.  4space is the standard in python, so convert all our code to
that.  The result unfortuantely still shoed even more inconsistencies,
so I've decided to run autopep8 on the entire code base.

Change-Id: I4a4b1b444a2f43fab05fc5d2c8a7dd6ddecb5f07
2022-02-11 13:32:58 +01:00
Steve Markgraf 9c93cec32a transport/serial: fix for Python 3
Change-Id: I21e5a7ad4f623ed30681dce1ff819679b8714c5b
2022-01-25 01:14:44 +01:00
Harald Welte 846a898ee0 Add API + shell command for sending TERMINAL PROFILE to card
This allows a very first start to play with PROACTIVE SIM

Change-Id: Id8f23f7cebe0f9efce2c0ce4229509f35cd93d6a
2021-10-14 16:41:57 +02:00
Philipp Maier 8bf2125a19 transport/pcsc: make sure reader is disconnected
Make sure that a reader is disconnected before connecting it. This will
efectively prevent resource leakage in the lower PCSC layers when the
reader is connected multiple times during bulk provisioning

Change-Id: I266e56f2330da25c680a76f4c0ca630a38e1f61b
2021-09-22 16:21:16 +02:00
Philipp Maier 7328f10165 transport/init: print exception type if the execption has no string
There may be corner cases where an execption contains no error message.
In this case it might still be helpful to display the type of the
exeption calss to get at least an idea of what kind of error we are
dealing with.

Change-Id: I6e6b3acd17e40934050b9b088960a2f851120b26
2021-09-22 16:11:33 +02:00
Harald Welte 8dfd6d070f transport: Add support for SW 6Cxx
According to ETSI TS 102 221 Section 7.2.2.3.1 Table 7.1 the UICC
may respond with SW 6Cxx to tell us to re-issue the command with
a modified P3/Le.

Change-Id: Ia7e6202bbd0f61034a985ecf76d0542d959922ce
2021-05-25 22:23:00 +02:00
Harald Welte 2db843e7b5 transport/pcsc: Raise exception if reader number is out of range
Change-Id: I0acd6900feabb1cfa03b84f24903c6b746a6bdea
2021-05-22 09:32:39 +02:00
Robert Falkenberg dddcc60f2d ModemATCommandLink: improve response time for "+CME ERROR"
Change-Id: I41af33c1898f5ed3d1c5238e45f956c6ceab2826
2021-05-06 20:36:55 +02:00
Robert Falkenberg 7cb7c78ca8 ModemATCommandLink: add/adjust some logging
Change-Id: I303506a751b4a34d83c18bc097e0cfb0517ee82c
2021-05-06 20:23:00 +02:00
Robert Falkenberg e5a5ffb44f ModemATCommandLink: return lower case hexstring
Change-Id: Id56e92962c1d75b832b42516099f97aac5a9d1d3
2021-05-06 09:51:29 +02:00
Harald Welte 903bdaaca8 transport: Mark more methods as abstractmethod
Change-Id: Ied3dbd07fdd0d3fa9bbe2dd7dd674700cf13bf63
2021-05-04 13:24:07 +02:00
Vadim Yanitskiy 52efc0372c ModemATCommandLink: fix AttributeError exception in __del__()
self._sl will not be assigned if serial.Serial() fails.

Change-Id: I179a7efd92eaa3469a17b6ef252b3949c44ea6ea
2021-05-03 14:13:14 +00:00
Robert Falkenberg 18fb82bd38 Speed up AT command interface (~130 times faster)
Previous implementation waits 300ms for response after
each command issued. But many commands finish earlier.

This patch improves the command execution time by frequently
checking for the response to complete (i.e. ends with
OK or ERROR), or the occurence of a timeout (default 200ms).

Timeout can be adapted per command to support long response
times of certain commands like AT+COPS=? (network search)

Execution time benchmark (20 AT commands/responses):
Previous: 6.010s (100.0%)
New code: 0.045s (  0.7%)

Change-Id: I69b1cbc0a20d54791e5800bf27ebafc2c8606d93
2021-05-03 10:06:10 +02:00
Vadim Yanitskiy e8c34ca3e2 [pylint] Declare abstract LinkBase._send_apdu_raw() method as such
pySim/transport/__init__.py:86:15: E1101:
	Instance of 'LinkBase' has no '_send_apdu_raw' member;
	maybe 'send_apdu_raw'? (no-member)

Change-Id: I14fcdceca5d1e35491b6ad98f96b4276b69b2fc1
2021-05-02 20:22:15 +00:00
Robert Falkenberg 8e15c18498 transport/AT: Make sure PDU has upper case hex digits
Some modems may reject AT+CSIM if PDU contains lower
case hex digits [a-f]. Modem response is "ERROR"
without any error code.

This patch converts each PDU to upper case.

Tested with Sierra Wireless EM7565.
Example:
AT+CSIM=14,"00a40004023F00"
ERROR
AT+CSIM=14,"00A40004023F00"
+CSIM: 4,"612F"

OK


Change-Id: I318e36abc7ae975c62d32b7fe0ec949bf5997d13
2021-05-02 20:11:32 +00:00
Harald Welte 28c2431f9c Move reader related argument parser to transport module
Ideally that shared definition would be used by all programs,
rather than copy+pasting it.  Unfortunately pySim-{read,prog}
are still using optparse and first need to be converted to
argparse.

Change-Id: If77f53850e1ca65f42cf1dca3e0f460dac1b0d1a
2021-04-22 09:11:23 +02:00
Harald Welte e0f9ef1606 integrate 'construct' python library
'construct' is a declarative symmetric encoder/decoder for user
specified binary formats.  It should come in extremely handy in
tools like pySim.

We start the integration by adding transport methods for transceiving
APDUs with built-in encoding of the command data and decoding of the
response data.

Change-Id: Ibf457aa8b9480a8db5979defcfafd67674303f6c
2021-04-11 12:20:29 +02:00
Harald Welte 7829d8a357 shell: Add 'apdu_trace' settable parameter for hex-dumping APDUs
Change-Id: I0c957c0b86473413f31e4bd8bc4e633fc1470222
2021-04-10 18:41:15 +02:00
Harald Welte eb05b2f60e transport: Pass arbitrary kwargs to base-class constructor
Change-Id: I3cd5ba87cf53409ea97196d5789ed28eef072c68
2021-04-10 18:41:15 +02:00
Harald Welte c34f9405f1 transport: Make all calls go through base class send_apdu_raw()
This allows us to add APDU tracing at one central location in the code

Change-Id: Id0593a2e6d846cc3151443f1022ae7ee030e6673
2021-04-10 18:41:15 +02:00
Harald Welte 4f2c546613 transport: Pass status word interpreter to exception handler
Prior to this patch, any SwMatchError raised within the 'transport'
would not be interpreted.

EXCEPTION of type 'SwMatchError' occurred with message: 'SW match failed! Expected 9000 and got 6982.'

vs (now)

EXCEPTION of type 'SwMatchError' occurred with message: 'SW match failed! Expected 9000 and got 6982: Command not allowed - Security status not satisfied'

Change-Id: I08b7f2b6bd422f7f2f36094bc8a29b187ff882a6
2021-04-04 10:54:46 +02:00
Harald Welte 6e0458dda6 Move init_reader() from utils.py to transport/__init__.py
This avoids a circular dependency when introducing type annotations.

Change-Id: I168597ac14497fb188a15cb632f32452128bc1c6
2021-04-04 10:53:36 +02:00