gerrit-log
Threads by month
- ----- 2026 -----
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
September 2026
- 1 participants
- 1894 discussions
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43550?usp=email )
(
2 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: osmo-smdpp: bind TLS endpoint to -H interface
......................................................................
osmo-smdpp: bind TLS endpoint to -H interface
klein ignores host/port when endpoint_description is set, so -H has
no effect on the TLS listener, it binds every interface.
Append interface= to the string so -H means the same thing with and
without TLS.
Change-Id: I737c2e7cfa1ca7b825bd36a4a489760918031b8b
---
M osmo-smdpp.py
1 file changed, 1 insertion(+), 1 deletion(-)
Approvals:
laforge: Looks good to me, but someone else must approve
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/osmo-smdpp.py b/osmo-smdpp.py
index 2add23f..f19d3e5 100755
--- a/osmo-smdpp.py
+++ b/osmo-smdpp.py
@@ -955,7 +955,7 @@
with open(cert_pempath, 'wb') as pem_file:
pem_file.write(pem_cert)
- SERVER_STRING = f'ssl:{args.port}:privateKey={cert_skpath}:certKey={cert_pempath}:dhParameters={dhparam_path}'
+ SERVER_STRING = f'ssl:{args.port}:privateKey={cert_skpath}:certKey={cert_pempath}:dhParameters={dhparam_path}:interface={args.host}'
print(SERVER_STRING)
hs.app.run(host=HOSTNAME, port=args.port, endpoint_description=SERVER_STRING)
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43550?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I737c2e7cfa1ca7b825bd36a4a489760918031b8b
Gerrit-Change-Number: 43550
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[L] Change in pysim[master]: transport: stop the T=0 layer from breaking GP 6310
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43551?usp=email )
Change subject: transport: stop the T=0 layer from breaking GP 6310
......................................................................
transport: stop the T=0 layer from breaking GP 6310
TS 102 221 section 7.3.1.1.4 clause 4b lets the card answer a case #4
command TPDU with a 62xx/63xx warning, upon which the terminal sends a
dummy GET RESPONSE to obtain the 61xx that announces the response length.
__send_apdu_T0() applies that unconditionally, to the status word that
terminates a GET RESPONSE...
That is not "redundant", as per GPC v2.3.1 section 11.4.3.2 table 11-38
GP GET STATUS (80 F2) answers 6310 "more data available", meaning reissue
the command as get next occurrence(s) with P2 bit 1 set (11.4.2.2 table
11-34), so for example a paginated registry
listing exchange looks like this:
84f22000024f00 => 61e4 first match, e4 bytes waiting
84c00000e4 => <page 1> 6310 more matches pending
84c0000000 => 6982 <- unsolicited, card rejects it
The card rejects the unsolicited GET RESPONSE with 6982, our SCP02
session breaks, and the next command fail with 6985. The 6310 never
reaches ADF_SD.get_status() either, so the pagination loop exits after
page 1 and prints a sliently truncated listing. Observed with a SJA5.
Fix by turning clause 4b würgaround into what it should be: a one shot
reaction to the SW returned for the command TPDU.
While at it, stop ADF_SD.get_status() from silently returning a truncated
registry: it treated every status word other than 6310 as
"nothing more to report". 6A88 is now the explicit empty result and anything
else raises, so a partial listing can no longer silently pass.
Adds unit tests for all of that so we dont break basic T0 things.
Change-Id: I10f8afa8dd5623a49a6a0e7132607b3a1fad2d8c
---
M pySim/exceptions.py
M pySim/global_platform/__init__.py
M pySim/transport/__init__.py
M tests/unittests/test_globalplatform.py
M tests/unittests/test_transport.py
5 files changed, 286 insertions(+), 10 deletions(-)
Approvals:
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/pySim/exceptions.py b/pySim/exceptions.py
index 1c9e3b8..d8e4964 100644
--- a/pySim/exceptions.py
+++ b/pySim/exceptions.py
@@ -38,15 +38,16 @@
"""Raised when an operation specifies an expected SW but the actual SW from
the card doesn't match."""
- def __init__(self, sw_actual: str, sw_expected: str, rs=None):
+ def __init__(self, sw_actual: str, sw_expected, rs=None):
"""
Args:
sw_actual : the SW we actually received from the card (4 hex digits)
- sw_expected : the SW we expected to receive from the card (4 hex digits)
+ sw_expected : the SW we expected to receive from the card (4 hex digits),
+ or a list of acceptable ones
rs : interpreter class to convert SW to string
"""
self.sw_actual = sw_actual
- self.sw_expected = sw_expected
+ self.sw_expected = '/'.join(sw_expected) if isinstance(sw_expected, (list, tuple)) else sw_expected
self.rs = rs
@property
diff --git a/pySim/global_platform/__init__.py b/pySim/global_platform/__init__.py
index a450561..ed35810 100644
--- a/pySim/global_platform/__init__.py
+++ b/pySim/global_platform/__init__.py
@@ -737,22 +737,29 @@
subset_hex = b2h(build_construct(StatusSubset, subset))
aid = ApplicationAID(decoded=aid_search_qualifier)
cmd_data = aid.to_tlv() + h2b('5c054f9f70c5cc')
- p2 = 0x02 # TLV format according to Table 11-36
+ p2 = 0x02 # GPC v2.3.1 11.4.2.2 table 11-34, b2: response data structure per table 11-36
grd_list = []
while True:
hdr = "80F2%s%02x%02x" % (subset_hex, p2, len(cmd_data))
data, sw = self._cmd.lchan.scc.send_apdu(hdr + b2h(cmd_data) + "00")
+ if sw == '6a88':
+ # "Referenced data not found": nothing (more) matches the requested subset and AID
+ # search qualifier. That is empty, not error?
+ return grd_list
+ if sw not in ['9000', '6310']:
+ # Never return a silently truncated registry
+ raise SwMatchError(sw, ['9000', '6310'])
remainder = h2b(data)
while len(remainder):
# tlv sequence, each element is one GpRegistryRelatedData()
grd = GpRegistryRelatedData()
_dec, remainder = grd.from_tlv(remainder)
grd_list.append(grd)
- if sw != '6310':
+ if sw == '9000':
return grd_list
- else:
- p2 |= 0x01
- return grd_list
+ # 6310 = more data available, table 11-38: reissue as get next occurrence(s), b1 of
+ # table 11-34. Keeps b2 unchanged.
+ p2 |= 0x01
set_status_parser = argparse.ArgumentParser()
set_status_parser.add_argument('scope', choices=list(SetStatusScope.ksymapping.values()),
diff --git a/pySim/transport/__init__.py b/pySim/transport/__init__.py
index 268eec6..5a630c8 100644
--- a/pySim/transport/__init__.py
+++ b/pySim/transport/__init__.py
@@ -333,6 +333,18 @@
# correctly the Le byte (usually 0x00) must be present, is often forgotten. To avoid problems with
# legacy scripts that use raw APDU strings, we will still loosely apply GET RESPONSE based on what
# the status word indicates. Unless the user explicitly enables the strict mode (set apdu_strict true)
+ #
+ # The dummy GET RESPONSE of clause 4b (see below) is one shot: it turns a warning SW into the 61xx
+ # that announces the response length. It is only ever a valid reaction to the SW returned for the
+ # _command_ TPDU. Once a response has been fetched there is nothing left to announce, so a warning
+ # SW is the final result of the command and has to be passed on to the caller unmodified.
+ #
+ # This matters because the 62xx/63xx range is not exclusive to ETSI TS 102 221.
+ # GPC v2.3.1 section 11.4.3.2 table 11-38 GP GET STATUS (80 F2) answers
+ # 6310 "more data available", meaning "reissue with P2 bit 1 set" as per section 11.4.2.2 table 11-34
+ # rather than "response data is waiting". Trying a random GET RESPONSE at that point
+ # makes the card answer 6982 and tears down the whole SCP session and following commands fail with 6985.
+ dummy_gr_allowed = not data
while True:
if sw in ['9000', '9100']:
# A status word of 9000 (or 9100 in case there is pending data from a proactive SIM command)
@@ -345,7 +357,7 @@
# word. (see also ETSI TS 102 221, section 7.3.1.1.4, clause 4a and 3GPP TS 51.011 9.4.1 and
# ISO/IEC 7816-4, Table 5)
le_gr = sw[2:4]
- elif sw[0:2] in ['62', '63']:
+ elif sw[0:2] in ['62', '63'] and dummy_gr_allowed:
# There are corner cases (status word is 62xx or 63xx) where the UICC/eUICC/SIM asks us
# to send a dummy GET RESPONSE command. We send a GET RESPONSE command with a length of 0.
# (see also ETSI TS 102 221, section 7.3.1.1.4, clause 4b and ETSI TS 151 011, section 9.4.1)
@@ -360,6 +372,7 @@
data_gr, sw = self.send_tpdu(tpdu_gr)
log.debug("T0: GET RESPONSE TPDU: %s => %s %s", tpdu_gr, data_gr or "(no data)", sw or "(no status word)")
data += data_gr
+ dummy_gr_allowed = False
if sw[0:2] == '6c':
# SW1=6C: ETSI TS 102 221 Table 7.1: Procedure byte coding
tpdu_gr = prev_tpdu[0:8] + sw[2:4]
diff --git a/tests/unittests/test_globalplatform.py b/tests/unittests/test_globalplatform.py
index 78a195e..c48f260 100644
--- a/tests/unittests/test_globalplatform.py
+++ b/tests/unittests/test_globalplatform.py
@@ -713,5 +713,73 @@
self.assertLessEqual(wrapped[4], 255)
+class _FakeScc:
+ """mock lchan.scc: replays scripted (data, sw) pairs + records the APDUs sent."""
+
+ def __init__(self, responses):
+ self._responses = list(responses)
+ self.sent = []
+
+ def send_apdu(self, apdu):
+ self.sent.append(apdu.lower())
+ if not self._responses:
+ raise AssertionError('get_status sent unexpected APDU: %s' % apdu)
+ return self._responses.pop(0)
+
+
+class GetStatus_Pagination_Test(unittest.TestCase):
+ """GPC v2.3.1 section 11.4.3.2 table 11-38 GET STATUS pagination test
+
+ Card answers 6310 when further matches are pending; command reissued with
+ P2 bit 1 "next occurrence" set. Tied to T=0 handling pySim/transport, which
+ used to swallow that 6310 and replied with GET RESPONSE, so page 2 was never fetched."""
+
+ ENTRY_1 = 'e3074f05a000000151'
+ ENTRY_2 = 'e3074f05a000000152'
+
+ def _sd(self, responses):
+ scc = _FakeScc(responses)
+ cmd = type('_Cmd', (), {'lchan': type('_Lchan', (), {'scc': scc})()})()
+ # cmd2 strikes again, CommandSet exposes _cmd as a read only property, needs shadowing
+ _SD = type('_SD', (ADF_SD.AddlShellCommands,), {'_cmd': cmd})
+ return _SD.__new__(_SD), scc
+
+ def _aids(self, grd_list):
+ return [b2h(grd.to_dict()['gp_registry_related_data'][0]['application_aid']) for grd in grd_list]
+
+ def test_single_page(self):
+ sd, scc = self._sd([(self.ENTRY_1, '9000')])
+ grd_list = sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f24002094f005c054f9f70c5cc00'])
+ self.assertEqual(self._aids(grd_list), ['a000000151'])
+
+ def test_two_pages(self):
+ """6310 -> reissue with P2 bit 1 set -> 9000, both pages in result"""
+ sd, scc = self._sd([(self.ENTRY_1, '6310'), (self.ENTRY_2, '9000')])
+ grd_list = sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f24002094f005c054f9f70c5cc00',
+ '80f24003094f005c054f9f70c5cc00'])
+ self.assertEqual(self._aids(grd_list), ['a000000151', 'a000000152'])
+
+ def test_three_pages_keep_p2_next_occurrence(self):
+ sd, scc = self._sd([(self.ENTRY_1, '6310'), (self.ENTRY_2, '6310'), (self.ENTRY_1, '9000')])
+ grd_list = sd.get_status('applications')
+ self.assertEqual([a[6:8] for a in scc.sent], ['02', '03', '03'])
+ self.assertEqual(len(grd_list), 3)
+
+ def test_no_match_returns_empty(self):
+ """6A88 "referenced data not found" is empty result not failure."""
+ sd, _scc = self._sd([('', '6a88')])
+ self.assertEqual(sd.get_status('applications'), [])
+
+ def test_unexpected_sw_is_not_silently_truncated(self):
+ """partial is not complete result"""
+ sd, _scc = self._sd([(self.ENTRY_1, '6310'), ('', '6982')])
+ with self.assertRaises(SwMatchError) as ctx:
+ sd.get_status('applications')
+ self.assertEqual(ctx.exception.sw_actual, '6982')
+
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/unittests/test_transport.py b/tests/unittests/test_transport.py
index 7a9c69c..f7e71d9 100644
--- a/tests/unittests/test_transport.py
+++ b/tests/unittests/test_transport.py
@@ -23,7 +23,7 @@
import unittest
from osmocom.utils import h2b, b2h
from pySim.cat import ProactiveCommand, CommandDetails, DeviceIdentities, Result
-from pySim.transport import ProactiveHandler
+from pySim.transport import ProactiveHandler, LinkBaseTpdu
def _send_short_message_pcmd():
@@ -73,5 +73,192 @@
self.assertIn('CommandDetails', str(ctx.exception))
+class FakeTpduLink(LinkBaseTpdu):
+ """mock LinkBaseTpdu that replays a list of (data, sw) responses + records every TPDU that
+ the T=0 state machine sends. Secretly sending more TPDUs than intended is the error,
+ designed to test "unsolicited GET RESPONSE" mishaps"""
+
+ def __init__(self, responses):
+ super().__init__()
+ self._responses = list(responses)
+ self.sent = []
+
+ def send_tpdu(self, tpdu):
+ self.sent.append(tpdu.lower())
+ if not self._responses:
+ raise AssertionError('T=0 layer sent an unpexpected TPDU: %s (total so far: %s)'
+ % (tpdu, self.sent))
+ return self._responses.pop(0)
+
+ def __str__(self):
+ return 'FakeTpduLink'
+
+ def wait_for_card(self, timeout=None, newcardonly=False):
+ pass
+
+ def connect(self):
+ pass
+
+ def get_atr(self):
+ return '3b00'
+
+ def disconnect(self):
+ pass
+
+ def _reset_card(self):
+ pass
+
+
+# GP GET STATUS, wrapped in SCP02 CLA 84, Case #4.
+GET_STATUS = '84f22002094f005c054f9f70c5cc' + '00'
+GET_STATUS_TPDU = '84f22002094f005c054f9f70c5cc'
+
+# generic #4 SELECT by DF name command
+CASE4 = '00a4040c07a0000000871002' + '00'
+CASE4_TPDU = '00a4040c07a0000000871002'
+
+
+class Test_send_apdu_T0(unittest.TestCase):
+ """regression tests for the T=0 state machine in LinkBaseTpdu.__send_apdu_T0()"""
+
+ def _exchange(self, apdu, responses, strict=True, protocol=0):
+ link = FakeTpduLink(responses)
+ link.apdu_strict = strict
+ link.set_tpdu_format(protocol)
+ data, sw = link._send_apdu(apdu)
+ return link, data, sw
+
+ #### TS 102 221 section 7.3.1.1 TPDU construction
+
+ def test_case1_gets_le_appended(self):
+ link, data, sw = self._exchange('00200001', [('', '9000')])
+ self.assertEqual(link.sent, ['0020000100'])
+ self.assertEqual((data, sw), ('', '9000'))
+
+ def test_case3_passed_through_unmodified(self):
+ apdu = '00200001081122334455667788'
+ link, _data, sw = self._exchange(apdu, [('', '9000')])
+ self.assertEqual(link.sent, [apdu])
+ self.assertEqual(sw, '9000')
+
+ def test_case4_le_stripped(self):
+ link, data, sw = self._exchange(CASE4, [('', '9000')])
+ self.assertEqual(link.sent, [CASE4_TPDU])
+ self.assertEqual((data, sw), ('', '9000'))
+
+ #### TS 102 221 7.3.1.1.4 4a GP GET RESPONSE for 61xx / 9fxx
+
+ def test_61xx_fetches_response(self):
+ link, data, sw = self._exchange(CASE4, [('', '6103'), ('a1b2c3', '9000')])
+ self.assertEqual(link.sent, [CASE4_TPDU, '00c0000003'])
+ self.assertEqual((data, sw), ('a1b2c3', '9000'))
+
+ def test_61xx_chained(self):
+ link, data, sw = self._exchange(CASE4,
+ [('', '6102'), ('aabb', '6102'), ('ccdd', '9000')])
+ self.assertEqual(link.sent, [CASE4_TPDU, '00c0000002', '00c0000002'])
+ self.assertEqual((data, sw), ('aabbccdd', '9000'))
+
+ def test_9fxx_fetches_response(self):
+ link, data, sw = self._exchange(CASE4, [('', '9f04'), ('deadbeef', '9000')])
+ self.assertEqual(link.sent, [CASE4_TPDU, '00c0000004'])
+ self.assertEqual((data, sw), ('deadbeef', '9000'))
+
+ def test_get_response_inherits_cla(self):
+ """GET RESPONSE must reuse CLA of command"""
+ link, _data, _sw = self._exchange(GET_STATUS, [('', '6102'), ('aabb', '9000')])
+ self.assertEqual(link.sent, [GET_STATUS_TPDU, '84c0000002'])
+
+ def test_9100_terminates(self):
+ """9100 is final status word, not fetch trigger"""
+ link, data, sw = self._exchange(CASE4, [('', '9100')])
+ self.assertEqual(link.sent, [CASE4_TPDU])
+ self.assertEqual((data, sw), ('', '9100'))
+
+ def test_error_sw_terminates(self):
+ link, data, sw = self._exchange(CASE4, [('', '6982')])
+ self.assertEqual(link.sent, [CASE4_TPDU])
+ self.assertEqual((data, sw), ('', '6982'))
+
+ def test_no_status_word_raises(self):
+ with self.assertRaises(ValueError):
+ self._exchange(CASE4, [('', None)])
+
+ #### TS 102 221 7.3.1.1.4 4b dummy GET RESPONSE
+
+ def test_clause_4b_warning_before_data_bootstraps(self):
+ """warning SW returned for the _command_ TPDU triggers dummy GET RESPONSE (Le=00)"""
+ for warn in ('6200', '6281', '62f1', '6300', '63f1'):
+ with self.subTest(sw=warn):
+ link, data, sw = self._exchange(CASE4,
+ [('', warn), ('', '6103'), ('a1b2c3', '9000')])
+ self.assertEqual(link.sent, [CASE4_TPDU, '00c0000000', '00c0000003'])
+ self.assertEqual((data, sw), ('a1b2c3', '9000'))
+
+ def test_warning_after_data_terminates(self):
+ """Once the response has been fetched a warning status word is the final result of the command"""
+ for warn in ('6281', '6283', '63c2', '6300', '62f1', '63f1', '6310'):
+ with self.subTest(sw=warn):
+ link, data, sw = self._exchange(CASE4, [('', '6102'), ('aabb', warn)])
+ self.assertEqual(link.sent, [CASE4_TPDU, '00c0000002'])
+ self.assertEqual((data, sw), ('aabb', warn))
+
+ def test_no_dummy_get_response_when_command_already_returned_data(self):
+ """warning that arrives together with response data (for example 6282 on a case #2 read) is final, too"""
+ link, data, sw = self._exchange('00b0000004', [('01020304', '6282')], strict=False)
+ self.assertEqual(link.sent, ['00b0000004'])
+ self.assertEqual((data, sw), ('01020304', '6282'))
+
+ def test_repeated_warning_does_not_loop(self):
+ """warning -> dummy GET RESPONSE -> warning again must terminate"""
+ link, data, sw = self._exchange(CASE4, [('', '6281'), ('', '6281')])
+ self.assertEqual(link.sent, [CASE4_TPDU, '00c0000000'])
+ self.assertEqual((data, sw), ('', '6281'))
+
+ #### fixed GlobalPlatform GET STATUS pagination
+
+ def test_gp_6310_reaches_the_caller(self):
+ """GET STATUS answers 6310"""
+ link, data, sw = self._exchange(GET_STATUS, [('', '6104'), ('e3024f00', '6310')])
+ self.assertEqual(link.sent, [GET_STATUS_TPDU, '84c0000004'])
+ self.assertEqual((data, sw), ('e3024f00', '6310'))
+
+ def test_gp_get_status_two_pages(self):
+ """Both GET STATUS pages, page 1 6310, reissued with P2 bit 1 set, page 2 9000."""
+ page1 = self._exchange(GET_STATUS, [('', '6104'), ('e3024f00', '6310')])
+ self.assertEqual(page1[1:], ('e3024f00', '6310'))
+ page2 = self._exchange('84f22003094f005c054f9f70c5cc00',
+ [('', '6104'), ('e3024f01', '9000')])
+ self.assertEqual(page2[0].sent, ['84f22003094f005c054f9f70c5cc', '84c0000004'])
+ self.assertEqual(page2[1:], ('e3024f01', '9000'))
+
+ #### 6cxx and apdu_strict
+
+ def test_6cxx_reissues_command_with_correct_length(self):
+ link, data, sw = self._exchange('00b0000000', [('', '6c04'), ('01020304', '9000')])
+ self.assertEqual(link.sent, ['00b0000000', '00b0000004'])
+ self.assertEqual((data, sw), ('01020304', '9000'))
+
+ def test_strict_mode_does_not_auto_fetch_for_case3(self):
+ apdu = '00200001081122334455667788'
+ link, data, sw = self._exchange(apdu, [('', '6104')], strict=True)
+ self.assertEqual(link.sent, [apdu])
+ self.assertEqual((data, sw), ('', '6104'))
+
+ def test_non_strict_mode_auto_fetches_for_case3(self):
+ apdu = '00200001081122334455667788'
+ link, data, sw = self._exchange(apdu, [('', '6104'), ('aabbccdd', '9000')], strict=False)
+ self.assertEqual(link.sent, [apdu, '00c0000004'])
+ self.assertEqual((data, sw), ('aabbccdd', '9000'))
+
+ #### T=1 briefly
+
+ def test_t1_is_passed_through(self):
+ """T=1 has no GET RESPONSE"""
+ link, data, sw = self._exchange(GET_STATUS, [('e3024f00', '6310')], protocol=1)
+ self.assertEqual(link.sent, [GET_STATUS.lower()])
+ self.assertEqual((data, sw), ('e3024f00', '6310'))
+
+
if __name__ == "__main__":
unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43551?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I10f8afa8dd5623a49a6a0e7132607b3a1fad2d8c
Gerrit-Change-Number: 43551
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[XS] Change in pysim[master]: pySim-shell: let --apdu-trace cover the session
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43553?usp=email )
(
2 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: pySim-shell: let --apdu-trace cover the session
......................................................................
pySim-shell: let --apdu-trace cover the session
pySim has two APDU tracers: the StdoutApduTracer that --apdu-trace
installs in the transport for every program using pySim.transport, and
pySim-shell Cmd2ApduTracer for "set apdu_trace true", which prints with
cmd2. The command line option exists because the setting
applies too late to see the pySim startup APDUs.
The guard in init_reader() exists but is useless:
if opts.apdu_trace and not 'apdu_tracer' in kwargs:
no caller supplies a tracer that way, every tool calls init_reader()
without one?.
The current help string does not say "trace or maybe not lol" so set
the setting from the transport rather than hardcoding False, so the
option implies "set apdu_trace true", and it finally works as advertised.
Change-Id: I83469e15f4cdd67418cd11df3869f2536105dbc8
---
M pySim-shell.py
1 file changed, 1 insertion(+), 1 deletion(-)
Approvals:
laforge: Looks good to me, but someone else must approve
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/pySim-shell.py b/pySim-shell.py
index 4f84514..be1d783 100755
--- a/pySim-shell.py
+++ b/pySim-shell.py
@@ -101,7 +101,7 @@
self.numeric_path = False
self.conserve_write = True
self.json_pretty_print = True
- self.apdu_trace = False
+ self.apdu_trace = getattr(sl, 'apdu_tracer', None) is not None
self.apdu_strict = False
self.add_settable(cmd2.Settable('numeric_path', bool,
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43553?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I83469e15f4cdd67418cd11df3869f2536105dbc8
Gerrit-Change-Number: 43553
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[M] Change in pysim[master]: GP: only send a GET STATUS tag list to cards that support it
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43552?usp=email )
Change subject: GP: only send a GET STATUS tag list to cards that support it
......................................................................
GP: only send a GET STATUS tag list to cards that support it
get_status() has appended a hardcoded '5c054f9f70c5cc' to the command data
field. Of the data objects in GP CS v2.3.1 Table 11-35 only the AID
search tag 4F is mandatory, the tag list is optional and not supported
in v2.1.1, where Section 9.4.2.3 defines the data field as the search
qualifier. Cards implementing that revision can reject anything else
with 6A80 as per v2.1.1 Table 9-26.
A sysmocom SJA5 does that. Its data field must be one 4F
TLV, the value is free, but nothing may precede or follow it.
So every subset returned nothing at all...
There is no need to guess: v2.1.1/v2.3.1 Section 7.4.1.3 Card Recognition
Data is "shall be present" and contains the GP version on selected SD.
Query it once, and send the tag list to cards that announce v2.2 or later.
SJA5 reports 2.1.1, sysmoEUICC reports 2.2.
Two more problems with the old list:
- A tag list is an inclusion list, old list omits tag 84, so it
suppressed the Executable Module AIDs
- It asks for tag C5 for Executable Load Files, which "may" be answered
with an error status.
Fix this by constricting or omitting the tag list depending on reported
GP version.
Change-Id: I74cd2bd47617d616bede6453397f544cde5abcb7
---
M pySim/global_platform/__init__.py
M tests/unittests/test_globalplatform.py
2 files changed, 207 insertions(+), 11 deletions(-)
Approvals:
Jenkins Builder: Verified
dexter: Looks good to me, approved
diff --git a/pySim/global_platform/__init__.py b/pySim/global_platform/__init__.py
index ed35810..9600c7c 100644
--- a/pySim/global_platform/__init__.py
+++ b/pySim/global_platform/__init__.py
@@ -37,6 +37,9 @@
from pySim.profile import CardProfile
from pySim.ota import SimFileAccessAndToolkitAppSpecParams
from pySim.javacard import CapFile
+from pySim.log import PySimLogger
+
+log = PySimLogger.get(__name__)
# GPCS Table 11-48 Load Parameter Tags
class NonVolatileCodeMinMemoryReq(BER_TLV_IE, tag=0xC6):
@@ -532,6 +535,63 @@
ExecutableModuleAID, AssociatedSecurityDomainAID]):
pass
+# GP CS v2.3.1 Table 11-36/11-37 possible data objects requested/returned from GET STATUS for each registry entry.
+# Applications and Executable Load Files have _different_ sets, so a tag list requesting them has
+# to match the subset because 11.4.2.3 warns that asking for a data object an entry does not have
+# "may" be answered with an error status.
+GetStatusTagListIEs = {
+ # Table 11-36 GP Application Data
+ 'isd': [ApplicationAID, LifeCycleState, Privileges, ImplicitSelectionParameter,
+ ExecutableLoadFileAID, AssociatedSecurityDomainAID],
+ 'applications': [ApplicationAID, LifeCycleState, Privileges, ImplicitSelectionParameter,
+ ExecutableLoadFileAID, AssociatedSecurityDomainAID],
+ # Table 11-37 GP Executable Load File Data. 84 only for the subset that asks for the modules (Note 2)!
+ 'files': [ApplicationAID, LifeCycleState, ExecutableLoadFileVersionNumber,
+ AssociatedSecurityDomainAID],
+ 'files_and_modules': [ApplicationAID, LifeCycleState, ExecutableLoadFileVersionNumber,
+ ExecutableModuleAID, AssociatedSecurityDomainAID],
+}
+
+def get_status_tag_list(subset: str) -> bytes:
+ """Encode the GET STATUS tag list for the given status subset"""
+ tags = b''.join([bertlv_encode_tag(ie.tag) for ie in GetStatusTagListIEs[subset]])
+ return b'\x5c' + bertlv_encode_len(len(tags)) + tags
+
+# GP CS v2.3.1 Appendix H.2 / Table H-1
+# oid prefix {iso(1) member-body(2) country-USA(840) globalPlatform(114283)} + card management type 2
+# afterwards GP version.
+OID_GP_CARD_MGMT_TYPE = h2b('2a864886fc6b02')
+
+def _find_tlv_value(decoded, key: str):
+ """depth first search for the nested decoded TLV_IE dict/list"""
+ if isinstance(decoded, dict):
+ for k, v in decoded.items():
+ if k == key:
+ return v
+ found = _find_tlv_value(v, key)
+ if found is not None:
+ return found
+ elif isinstance(decoded, list):
+ for item in decoded:
+ found = _find_tlv_value(item, key)
+ if found is not None:
+ return found
+ return None
+
+def decode_gp_version(card_data: bytes) -> Optional[Tuple[int, ...]]:
+ """GP version from Card Data returned by GET DATA, like (2, 1, 1) or (2, 2).
+ None if cm type OID is absent/unknown"""
+ cd = CardData()
+ cd.from_tlv(card_data)
+ ctv = _find_tlv_value(cd.to_dict(), 'card_management_type_and_version')
+ oid = _find_tlv_value(ctv, 'object_identifier') if ctv is not None else None
+ if oid is None:
+ return None
+ oid = h2b(oid) if isinstance(oid, str) else bytes(oid)
+ if not oid.startswith(OID_GP_CARD_MGMT_TYPE):
+ return None
+ return tuple(oid[len(OID_GP_CARD_MGMT_TYPE):])
+
# Application Dedicated File of a Security Domain
class ADF_SD(CardADF):
StoreData = BitStruct('last_block'/Flag,
@@ -733,19 +793,64 @@
for grd in grd_list:
self._cmd.poutput_json(grd.to_dict())
+ def gp_version(self) -> Optional[Tuple[int, ...]]:
+ """GP version the selected SD reports in its Card Recognition
+ Data, e.g. (2, 1, 1). Card Recognition Data "shall be present" v2.1.1/v2.3.1 section 7.4.1.3,
+ so this must succeed no matter the GP version. None if card did not answer GET DATA / OID unknown.
+ Cached, it cannot change during a session."""
+ if not hasattr(self, '_gp_version'):
+ self._gp_version = None
+ try:
+ data, _sw = self._cmd.lchan.scc.get_data(cla=0x80, tag=CardData.tag)
+ self._gp_version = decode_gp_version(h2b(data))
+ except (SwMatchError, ValueError) as e:
+ log.warning("Could not determine GlobalPlatform version: %s", e)
+ return self._gp_version
+
def get_status(self, subset:str, aid_search_qualifier:Hexstr = '') -> List[GpRegistryRelatedData]:
- subset_hex = b2h(build_construct(StatusSubset, subset))
aid = ApplicationAID(decoded=aid_search_qualifier)
- cmd_data = aid.to_tlv() + h2b('5c054f9f70c5cc')
+ # GPC CardSpec v2.3.1 Table 11-35 says only the AID search tag is mandatory, tag list is
+ # Optional and not present in the older v2.1.1, where section 9.4.2.3 defines the data
+ # field as the search qualifier.
+ # Cards like the sja5 implementing that old GP version reject anything else with 6A80
+ # from v2.1.1 Table 9-26 so only send a tag list to a card that announces v2.2 or later.
+ #
+ # Not sending one is not a problem on older cards, the tag list only gives us data beyond
+ # what 11.4.3.1 gives us anyway, for example the associated SD AID which matters on an eUICC
+ # where entries belong to different SD.
+ version = self.gp_version()
+ log.debug("Card Recognition Data reports GlobalPlatform %s",
+ '.'.join(str(v) for v in version) if version else 'unknown')
+ if version is not None and version >= (2, 2):
+ try:
+ return self._get_status(subset, aid.to_tlv() + get_status_tag_list(subset))
+ except SwMatchError as e:
+ # Retry if v2.2 or later but rejected the tag list anyway.
+ # 6A80 and 6A88 are the error conditions GET STATUS defines in table 11-39.
+ # Retrying beats not ending up with a list again...
+ if e.sw_actual not in ('6a80', '6a88'):
+ raise
+ log.warning("Card reports GlobalPlatform %s but answered %s to the GET STATUS tag list; "
+ "retrying with the default search",
+ '.'.join(str(v) for v in version), e.sw_actual)
+ return self._get_status(subset, aid.to_tlv(), empty_on_6a88=True)
+
+ def _get_status(self, subset:str, cmd_data:bytes,
+ empty_on_6a88: bool = False) -> List[GpRegistryRelatedData]:
+ subset_hex = b2h(build_construct(StatusSubset, subset))
p2 = 0x02 # GPC v2.3.1 11.4.2.2 table 11-34, b2: response data structure per table 11-36
grd_list = []
while True:
hdr = "80F2%s%02x%02x" % (subset_hex, p2, len(cmd_data))
data, sw = self._cmd.lchan.scc.send_apdu(hdr + b2h(cmd_data) + "00")
if sw == '6a88':
- # "Referenced data not found": nothing (more) matches the requested subset and AID
- # search qualifier. That is empty, not error?
- return grd_list
+ # Table 11-39 "Referenced data not found". After collecting all pages this can
+ # only mean "nothing more matches" -> listing is complete. On the first page
+ # it is ambiguous, empty result or bad command data field, so leave that to get_status()
+ # which knows if a tag list was sent.
+ if grd_list or empty_on_6a88:
+ return grd_list
+ raise SwMatchError(sw, ['9000', '6310'])
if sw not in ['9000', '6310']:
# Never return a silently truncated registry
raise SwMatchError(sw, ['9000', '6310'])
diff --git a/tests/unittests/test_globalplatform.py b/tests/unittests/test_globalplatform.py
index c48f260..d329c45 100644
--- a/tests/unittests/test_globalplatform.py
+++ b/tests/unittests/test_globalplatform.py
@@ -712,14 +712,26 @@
for wrapped in scc.wrapped:
self.assertLessEqual(wrapped[4], 255)
+# Real Card Data (GET DATA '66'), as returned by sja5 + euicc
+CARD_DATA_V211 = ('6631732f06072a864886fc6b01600c060a2a864886fc6b0202010163090607'
+ '2a864886fc6b03640b06092a864886fc6b040215')
+CARD_DATA_V22 = ('663b733906072a864886fc6b01600b06092a864886fc6b020202630906072a86'
+ '4886fc6b03640b06092a864886fc6b040370640b06092a864886fc6b04810400')
+
class _FakeScc:
"""mock lchan.scc: replays scripted (data, sw) pairs + records the APDUs sent."""
- def __init__(self, responses):
+ def __init__(self, responses, card_data=CARD_DATA_V211):
self._responses = list(responses)
+ self._card_data = card_data
self.sent = []
+ def get_data(self, cla, tag):
+ if self._card_data is None:
+ raise SwMatchError('6a88', '9000')
+ return self._card_data, '9000'
+
def send_apdu(self, apdu):
self.sent.append(apdu.lower())
if not self._responses:
@@ -727,6 +739,28 @@
return self._responses.pop(0)
+class GpVersion_Test(unittest.TestCase):
+ """GP version from Card Recognition Data, which v2.1.1/v2.3.1 section 7.4.1.3
+ require to be present. The OID under tag 60 is {globalPlatform 2 v...}."""
+
+ def test_decode_real_cards(self):
+ self.assertEqual(decode_gp_version(h2b(CARD_DATA_V211)), (2, 1, 1))
+ self.assertEqual(decode_gp_version(h2b(CARD_DATA_V22)), (2, 2))
+
+ def test_unknown_oid_is_none(self):
+ self.assertIsNone(decode_gp_version(h2b('66097307060512345678')))
+
+ def test_tag_lists_follow_the_spec_tables(self):
+ """table 11-36 applications, table 11-37 for load files"""
+ self.assertEqual(b2h(get_status_tag_list('isd')), '5c074f9f70c5cfc4cc')
+ self.assertEqual(b2h(get_status_tag_list('applications')), '5c074f9f70c5cfc4cc')
+ self.assertEqual(b2h(get_status_tag_list('files')), '5c054f9f70cecc')
+ self.assertEqual(b2h(get_status_tag_list('files_and_modules')), '5c064f9f70ce84cc')
+ # C5 never load files, 84 never applications
+ self.assertNotIn('c5', b2h(get_status_tag_list('files')))
+ self.assertNotIn('84', b2h(get_status_tag_list('applications'))[4:])
+
+
class GetStatus_Pagination_Test(unittest.TestCase):
"""GPC v2.3.1 section 11.4.3.2 table 11-38 GET STATUS pagination test
@@ -737,8 +771,8 @@
ENTRY_1 = 'e3074f05a000000151'
ENTRY_2 = 'e3074f05a000000152'
- def _sd(self, responses):
- scc = _FakeScc(responses)
+ def _sd(self, responses, card_data=CARD_DATA_V211):
+ scc = _FakeScc(responses, card_data)
cmd = type('_Cmd', (), {'lchan': type('_Lchan', (), {'scc': scc})()})()
# cmd2 strikes again, CommandSet exposes _cmd as a read only property, needs shadowing
_SD = type('_SD', (ADF_SD.AddlShellCommands,), {'_cmd': cmd})
@@ -750,15 +784,15 @@
def test_single_page(self):
sd, scc = self._sd([(self.ENTRY_1, '9000')])
grd_list = sd.get_status('applications')
- self.assertEqual(scc.sent, ['80f24002094f005c054f9f70c5cc00'])
+ self.assertEqual(scc.sent, ['80f24002024f0000'])
self.assertEqual(self._aids(grd_list), ['a000000151'])
def test_two_pages(self):
"""6310 -> reissue with P2 bit 1 set -> 9000, both pages in result"""
sd, scc = self._sd([(self.ENTRY_1, '6310'), (self.ENTRY_2, '9000')])
grd_list = sd.get_status('applications')
- self.assertEqual(scc.sent, ['80f24002094f005c054f9f70c5cc00',
- '80f24003094f005c054f9f70c5cc00'])
+ self.assertEqual(scc.sent, ['80f24002024f0000',
+ '80f24003024f0000'])
self.assertEqual(self._aids(grd_list), ['a000000151', 'a000000152'])
def test_three_pages_keep_p2_next_occurrence(self):
@@ -772,6 +806,44 @@
sd, _scc = self._sd([('', '6a88')])
self.assertEqual(sd.get_status('applications'), [])
+ def test_v211_card_gets_no_tag_list(self):
+ """v2.1.1 section 9.4.2.3 has no tag list,not send a tag list"""
+ sd, scc = self._sd([(self.ENTRY_1, '9000')], card_data=CARD_DATA_V211)
+ sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f24002024f0000'])
+ self.assertNotIn('5c', scc.sent[0][8:])
+
+ def test_v22_card_gets_a_tag_list(self):
+ sd, scc = self._sd([(self.ENTRY_1, '9000')], card_data=CARD_DATA_V22)
+ sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f240020b4f005c074f9f70c5cfc4cc00'])
+
+ def test_unknown_version_gets_no_tag_list(self):
+ """If the card will not say, assume the conservative form that works everywhere."""
+ sd, scc = self._sd([(self.ENTRY_1, '9000')], card_data=None)
+ sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f24002024f0000'])
+
+ def test_v22_card_rejecting_tag_list_falls_back(self):
+ """card announcing v2.2+ that still answers 6A80 to the tag list."""
+ sd, scc = self._sd([('', '6a80'), (self.ENTRY_1, '9000')], card_data=CARD_DATA_V22)
+ grd_list = sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f240020b4f005c074f9f70c5cfc4cc00',
+ '80f24002024f0000'])
+ self.assertEqual(self._aids(grd_list), ['a000000151'])
+
+ def test_aid_search_qualifier(self):
+ sd, scc = self._sd([(self.ENTRY_1, '9000')])
+ sd.get_status('applications', 'a000000087')
+ self.assertEqual(scc.sent, ['80f24002074f05a00000008700'])
+
+ def test_6a80_is_reported_on_a_v211_card(self):
+ """no tag list -> 6A80 is error"""
+ sd, _scc = self._sd([('', '6a80')], card_data=CARD_DATA_V211)
+ with self.assertRaises(SwMatchError) as ctx:
+ sd.get_status('applications')
+ self.assertEqual(ctx.exception.sw_actual, '6a80')
+
def test_unexpected_sw_is_not_silently_truncated(self):
"""partial is not complete result"""
sd, _scc = self._sd([(self.ENTRY_1, '6310'), ('', '6982')])
@@ -779,7 +851,26 @@
sd.get_status('applications')
self.assertEqual(ctx.exception.sw_actual, '6982')
+ def test_v22_card_answering_6a88_to_the_tag_list_falls_back(self):
+ """6A88 is the other GET STATUS error condition of table 11-39, section 11.4.2.3
+ says we may get get an error status. 6A88 to the tag-list attempt should be retried
+ without it or we get nothing"""
+ sd, scc = self._sd([('', '6a88'), (self.ENTRY_1, '9000')], card_data=CARD_DATA_V22)
+ grd_list = sd.get_status('applications')
+ self.assertEqual(scc.sent, ['80f240020b4f005c074f9f70c5cfc4cc00',
+ '80f24002024f0000'])
+ self.assertEqual(self._aids(grd_list), ['a000000151'])
+ def test_v22_card_with_a_genuinely_empty_subset(self):
+ """...and when the retry answers 6A88, the list really is empty."""
+ sd, scc = self._sd([('', '6a88'), ('', '6a88')], card_data=CARD_DATA_V22)
+ self.assertEqual(sd.get_status('applications'), [])
+ self.assertEqual(len(scc.sent), 2)
+
+ def test_6a88_after_a_page_keeps_that_page(self):
+ """6A88 is "no more matches" after we have data, we're done"""
+ sd, _scc = self._sd([(self.ENTRY_1, '6310'), ('', '6a88')], card_data=CARD_DATA_V22)
+ self.assertEqual(self._aids(sd.get_status('applications')), ['a000000151'])
if __name__ == "__main__":
unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43552?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I74cd2bd47617d616bede6453397f544cde5abcb7
Gerrit-Change-Number: 43552
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43554?usp=email )
(
2 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: transport: trace APDUs when they are sent
......................................................................
transport: trace APDUs when they are sent
Right now APDUs that never return/fail are omitted from the trace output.
Move the print, so it actually tells me what failed..
Change-Id: I828ea36b06da36b6bb0aa073d235d4f49cbb3161
---
M pySim-shell.py
M pySim/transport/__init__.py
2 files changed, 6 insertions(+), 2 deletions(-)
Approvals:
Jenkins Builder: Verified
laforge: Looks good to me, but someone else must approve
dexter: Looks good to me, approved
diff --git a/pySim-shell.py b/pySim-shell.py
index be1d783..2d9d356 100755
--- a/pySim-shell.py
+++ b/pySim-shell.py
@@ -210,8 +210,10 @@
def __init__(self, cmd2_app):
self.cmd2 = cmd2_app
- def trace_response(self, cmd, sw, resp):
+ def trace_command(self, cmd):
self.cmd2.poutput("-> %s %s" % (cmd[:10], cmd[10:]))
+
+ def trace_response(self, cmd, sw, resp):
self.cmd2.poutput("<- %s: %s" % (sw, resp))
def update_prompt(self):
diff --git a/pySim/transport/__init__.py b/pySim/transport/__init__.py
index 5a630c8..f99fd89 100644
--- a/pySim/transport/__init__.py
+++ b/pySim/transport/__init__.py
@@ -45,8 +45,10 @@
class StdoutApduTracer(ApduTracer):
"""Minimalistic APDU tracer, printing commands to stdout."""
- def trace_response(self, cmd, sw, resp):
+ def trace_command(self, cmd):
log.info("-> %s %s", cmd[:10], cmd[10:])
+
+ def trace_response(self, cmd, sw, resp):
log.info("<- %s: %s", sw, resp)
def trace_reset(self):
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43554?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I828ea36b06da36b6bb0aa073d235d4f49cbb3161
Gerrit-Change-Number: 43554
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[XS] Change in pysim[master]: tools: print tracebacks to the same stream as delimiters
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43555?usp=email )
(
2 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: tools: print tracebacks to the same stream as delimiters
......................................................................
tools: print tracebacks to the same stream as delimiters
Error output is currently a garbled mess, delimiters are printed with
poutput() or print(), traceback with traceback.print_exc() which goes
to stderr.
Reading stdout alone omits the report but not -->8-- lines.
Reading both streams makes the traceback appear where the two buffers
just happen to interleave, stderr is usually unbuffered but stdout is
not, so I get the error trace, APDU trace, then empty -->8-- lines.
Fix this by aligning the printing funcs.
Change-Id: I2ed37dfe241d014e4a26894cddbc9b21be1fd0c2
---
M pySim-prog.py
M pySim-shell.py
2 files changed, 4 insertions(+), 4 deletions(-)
Approvals:
dexter: Looks good to me, approved
laforge: Looks good to me, but someone else must approve
Jenkins Builder: Verified
diff --git a/pySim-prog.py b/pySim-prog.py
index 6111fc1..0a3e888 100755
--- a/pySim-prog.py
+++ b/pySim-prog.py
@@ -816,7 +816,7 @@
print("")
print("Card programming failed with an exception:")
print("---------------------8<---------------------")
- traceback.print_exc()
+ print(traceback.format_exc().rstrip())
print("---------------------8<---------------------")
print("")
rc = -1
diff --git a/pySim-shell.py b/pySim-shell.py
index 2d9d356..3a0dedd 100755
--- a/pySim-shell.py
+++ b/pySim-shell.py
@@ -351,7 +351,7 @@
self.poutput("")
self.poutput("Card initialization (%s) failed with an exception:" % str(self.sl))
self.poutput("---------------------8<---------------------")
- traceback.print_exc()
+ self.poutput(traceback.format_exc().rstrip())
self.poutput("---------------------8<---------------------")
self.poutput("")
return -1
@@ -465,7 +465,7 @@
self.poutput("")
self.poutput("Card handling (%s) failed with an exception:" % str(self.sl))
self.poutput("---------------------8<---------------------")
- traceback.print_exc()
+ self.poutput(traceback.format_exc().rstrip())
self.poutput("---------------------8<---------------------")
self.poutput("")
fail_count = fail_count + 1
@@ -1176,7 +1176,7 @@
startup_errors = True
print("Card initialization (%s) failed with an exception:" % str(sl))
print("---------------------8<---------------------")
- traceback.print_exc()
+ print(traceback.format_exc().rstrip())
print("---------------------8<---------------------")
if not opts.noprompt:
print("(you may still try to recover from this manually by using the 'equip' command.)")
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43555?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I2ed37dfe241d014e4a26894cddbc9b21be1fd0c2
Gerrit-Change-Number: 43555
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[M] Change in pysim[master]: transport/smpp2sim: TERMINAL RESPONSE for proactive SEND SHORT MESSAGE
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43543?usp=email )
Change subject: transport/smpp2sim: TERMINAL RESPONSE for proactive SEND SHORT MESSAGE
......................................................................
transport/smpp2sim: TERMINAL RESPONSE for proactive SEND SHORT MESSAGE
A multi part OTA response (full GP GET STATUS registry or some other fat
response that exceeds one SMS) is delivered as several SMS via proactive
SEND SHORT MESSAGE. The card only gives us another part if it receives a
TERMINAL RESPONSE for the previous one.
Currently smpp2sim Proact.handle_SendShortMessage relays the SMS but
returns None, so the transport falls back to prepare_response(pcmd) with
the ProactiveCommand collection (empty .children) and crashes with
'not enough values to unpack (expected 1, got 0)', dropps the SMPP link,
and never fetches the remaining parts.
Fix: make handle_SendShortMessage return a successful TERMINAL RESPONSE
built from the decoded command so the handshake proceeds.
prepare_response() is extended to handle collection via .decoded
and raises a useful error.
The send_apdu_checksw general_result='FIXME' path is now avoided for
SendShortMessage but remains a problem for other handlers that return
None.
Change-Id: Ib96ce81c4ff093b8a6fc715f79617e95a2dd8433
---
M pySim/bip.py
M pySim/transport/__init__.py
A tests/unittests/test_transport.py
3 files changed, 103 insertions(+), 2 deletions(-)
Approvals:
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/pySim/bip.py b/pySim/bip.py
index ececf6d..6c7de57 100644
--- a/pySim/bip.py
+++ b/pySim/bip.py
@@ -116,6 +116,14 @@
addr_ie.decoded['ton_npi']['numbering_plan_id'])
logger.info(submit)
self.send_sms_via_smpp(submit)
+ # Return a successful TERMINAL RESPONSE.
+ # This is important:
+ # - without it the transport cannot complete the proactive command
+ # - for a multi part OTA response, the card would never be asked to give us
+ # the remaining SMS chunks.
+ # 'pcmd' is a decoded SendShortMessage IE, which contains CommandDetails and
+ # DeviceIdentities that prepare_response() echoes/inverts.
+ return self.prepare_response(pcmd)
def handle_OpenChannel(self, pcmd: ProactiveCommand):
"""Card requests opening a new channel via a UDP/TCP socket."""
diff --git a/pySim/transport/__init__.py b/pySim/transport/__init__.py
index d689a0a..268eec6 100644
--- a/pySim/transport/__init__.py
+++ b/pySim/transport/__init__.py
@@ -70,10 +70,26 @@
raise NotImplementedError('No handler method for %s' % pcmd.decoded)
def prepare_response(self, pcmd: ProactiveCommand, general_result: str = 'performed_successfully'):
+ # TERMINAL RESPONSE per ETSI TS 102 223 section 6.8: Command details (6.8.1) echoed from the
+ # command, Device identities (6.8.2) with source and destination swapped, Result (6.8.3).
+ # pcmd can be
+ # - decoded proactive command IE (.children contains CommandDetails/DeviceIdentities)
+ # - ProactiveCommand collection wrapper (empty .children).
+ # Normalise to the children obj, so both work:
+ # - handler that passes its decoded command
+ # - fallback path that passes collection
+ children = list(getattr(pcmd, 'children', None) or [])
+ if not any(isinstance(c, CommandDetails) for c in children):
+ decoded = getattr(pcmd, 'decoded', None)
+ if decoded is not None and decoded is not pcmd:
+ children = list(getattr(decoded, 'children', None) or [])
# The Command Details are echoed from the command that has been processed.
- (command_details,) = [c for c in pcmd.children if isinstance(c, CommandDetails)]
+ command_details = next((c for c in children if isinstance(c, CommandDetails)), None)
# invert the device identities
- (command_dev_ids,) = [c for c in pcmd.children if isinstance(c, DeviceIdentities)]
+ command_dev_ids = next((c for c in children if isinstance(c, DeviceIdentities)), None)
+ if command_details is None or command_dev_ids is None:
+ raise ValueError('failed to prepare TERMINAL RESPONSE: proactive command has no '
+ 'CommandDetails/DeviceIdentities (%r)' % (pcmd,))
rsp_dev_ids = DeviceIdentities()
rsp_dev_ids.from_dict({'device_identities': {
'dest_dev_id': command_dev_ids.decoded['source_dev_id'],
diff --git a/tests/unittests/test_transport.py b/tests/unittests/test_transport.py
new file mode 100644
index 0000000..7a9c69c
--- /dev/null
+++ b/tests/unittests/test_transport.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+
+"""Transport (as in t0/t1) tests"""
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild(a)sysmocom.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import unittest
+from osmocom.utils import h2b, b2h
+from pySim.cat import ProactiveCommand, CommandDetails, DeviceIdentities, Result
+from pySim.transport import ProactiveHandler
+
+
+def _send_short_message_pcmd():
+ """proactive SEND SHORT MESSAGE:
+ D0 | CommandDetails(cmd 1, t 0x13, q 0) | DeviceIdentities(uicc->network)
+ | dummy SMS_TPDU"""
+ body = h2b('8103011300' + '82028183' + '8B04DEADBEEF')
+ pdu = h2b('D0') + bytes([len(body)]) + body
+ pcmd = ProactiveCommand()
+ decoded = pcmd.from_tlv(pdu)
+ return pcmd, decoded
+
+
+class Test_prepare_response(unittest.TestCase):
+ """TERMINAL RESPONSE.
+ multi-part OTA response crash regression test."""
+
+ def setUp(self):
+ self.h = ProactiveHandler.__new__(ProactiveHandler)
+
+ def test_on_decoded_command(self):
+ _pcmd, decoded = _send_short_message_pcmd()
+ til = self.h.prepare_response(decoded)
+ self.assertEqual([type(c).__name__ for c in til],
+ ['CommandDetails', 'DeviceIdentities', 'Result'])
+ # command details echoed, device id inverted, result OK
+ self.assertEqual(b2h(til[0].to_tlv()), '8103011300')
+ self.assertEqual(b2h(til[1].to_tlv()), '82028381')
+ self.assertEqual(b2h(til[2].to_tlv()), '830100')
+
+ def test_on_collection_resolves_via_decoded(self):
+ # Check that ProactiveCommand collection (empty .children) still works
+ pcmd, _decoded = _send_short_message_pcmd()
+ self.assertEqual(list(getattr(pcmd, 'children', []) or []), [])
+ til = self.h.prepare_response(pcmd)
+ self.assertEqual([type(c).__name__ for c in til],
+ ['CommandDetails', 'DeviceIdentities', 'Result'])
+ self.assertEqual(b2h(til[0].to_tlv()), '8103011300')
+ self.assertEqual(b2h(til[1].to_tlv()), '82028381')
+ self.assertEqual(b2h(til[2].to_tlv()), '830100')
+
+ def test_missing_command_details_raises_clear_error(self):
+ class _NoChildren:
+ children = []
+ with self.assertRaises(ValueError) as ctx:
+ self.h.prepare_response(_NoChildren())
+ self.assertIn('CommandDetails', str(ctx.exception))
+
+
+if __name__ == "__main__":
+ unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43543?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ib96ce81c4ff093b8a6fc715f79617e95a2dd8433
Gerrit-Change-Number: 43543
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: daniel <dwillmann(a)sysmocom.de>
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[L] Change in pysim[master]: sms/smpp-ota-tool: reassemble multi part response SMS
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43544?usp=email )
Change subject: sms/smpp-ota-tool: reassemble multi part response SMS
......................................................................
sms/smpp-ota-tool: reassemble multi part response SMS
A large OTA response (for example GP GET STATUS app registry) is split by the card
into multiple SMS, each carries a TS 23.040 9.2.3.24 'concatenated short messages'
IE in its UDH. Nothing recombines them, so smpp-ota-tool currently only sees the
first incomplete part.
Add ConcatenatedSmsReassembler that accepts TP-User-Data, buffers parts
by reference number, and returns the reassembled TP-User-Data in the canonical
single-part form. Non-concatenated SMS pass through unchanged.
Both the 8-bit+16-bit references are supported.
A reserved value in the concatenation IE is not an error, these messages
are handed back as is rather than rejected, so the caller can deal with that.
Reassembly leads to a result that looks like a fat single part message the
card could have produced given infinite sms sizes, so the existing decode_resp
path is unaffected.
Feeding those parts to the ota tool needs two more fixes because the card returns
the application response as several SMS via proactive SEND SHORT MESSAGE while
the ENVELOPE SMS-PP DOWNLOAD itself contains the POR without a app R-APDU.
smpplib poll() drains everything, so message_received_handler runs on each:
- a later status-only response must not overwrite an application response
already captured, or transceive_apdu finds no last_response_data and raises
- a response that cannot be decoded is be logged and skipped rather raised
out of client.poll() which kills the tool.
Plus tests from a sja5 session.
Incomplete sets are capped (oldest evicted) so they cannot pile up.
Change-Id: I8c81097e607e0d055c4f031bbcc8a74d5c24a0e7
---
M contrib/smpp-ota-tool.py
M pySim/sms.py
A tests/unittests/test_smpp_ota_tool.py
M tests/unittests/test_sms.py
4 files changed, 455 insertions(+), 16 deletions(-)
Approvals:
Jenkins Builder: Verified
dexter: Looks good to me, approved
diff --git a/contrib/smpp-ota-tool.py b/contrib/smpp-ota-tool.py
index 3698001..885cf94 100755
--- a/contrib/smpp-ota-tool.py
+++ b/contrib/smpp-ota-tool.py
@@ -24,7 +24,8 @@
import smpplib.client
import smpplib.consts
import time
-from pySim.ota import OtaKeyset, OtaDialectSms, OtaAlgoCrypt, OtaAlgoAuth, CNTR_REQ, RC_CC_DS, POR_REQ
+from pySim.ota import OtaKeyset, OtaDialectSms, OtaAlgoCrypt, OtaAlgoAuth, OtaCheckError, CNTR_REQ, RC_CC_DS, POR_REQ
+from pySim.sms import ConcatenatedSmsReassembler
from pySim.utils import b2h, h2b, is_hexstr
from pathlib import Path
@@ -108,28 +109,57 @@
self.tar = tar
self.spi = spi
self.remote_format = remote_format
+ self.reassembler = ConcatenatedSmsReassembler()
def __del__(self):
if self.client:
self.client.unbind()
self.client.disconnect()
+ def _decode_resp(self, tpud: bytes) -> tuple:
+ """Decode a response SMS-TPDU into (response_packet, decoded).
+
+ Retry to decoding with ciphering disabled (in case the card has problems to decode the SMS-TDPU
+ we have sent, the response will contain an unencrypted error message)
+ """
+ try:
+ return self.ota_dialect.decode_resp(self.ota_keyset, self.spi, tpud,
+ remote_format=self.remote_format)
+ except (ValueError, OtaCheckError):
+ spi = self.spi.copy()
+ spi['por_shall_be_ciphered'] = False
+ spi['por_rc_cc_ds'] = 'no_rc_cc_ds'
+ return self.ota_dialect.decode_resp(self.ota_keyset, spi, tpud,
+ remote_format=self.remote_format)
+
def message_received_handler(self, pdu):
- if pdu.short_message:
- logger.info("SMS-TPDU received: %s", b2h(pdu.short_message))
- try:
- dec = self.ota_dialect.decode_resp(self.ota_keyset, self.spi, pdu.short_message,
- remote_format=self.remote_format)
- except ValueError:
- # Retry to decoding with ciphering disabled (in case the card has problems to decode the SMS-TDPU
- # we have sent, the response will contain an unencrypted error message)
- spi = self.spi.copy()
- spi['por_shall_be_ciphered'] = False
- spi['por_rc_cc_ds'] = 'no_rc_cc_ds'
- dec = self.ota_dialect.decode_resp(self.ota_keyset, spi, pdu.short_message,
- remote_format=self.remote_format)
- logger.info("SMS-TPDU decoded: %s", dec)
- self.response = dec
+ if not pdu.short_message:
+ return None
+ logger.info("SMS-TPDU received: %s", b2h(pdu.short_message))
+ tpud = self.reassembler.add(pdu.short_message)
+ if tpud is None:
+ logger.info("SMS-TPDU is part of concat message, waiting for more parts...")
+ return None
+ if tpud != pdu.short_message:
+ logger.info("SMS-TPDU reassembled: %s", b2h(tpud))
+ try:
+ res, decoded = self._decode_resp(tpud)
+ except Exception as e:
+ # for example ENVELOPE POR
+ logger.warning("Ignoring undecodable resp SMS-TPDU (%s: %s)", type(e).__name__, e)
+ return None
+ logger.info("SMS-TPDU decoded: %s", (res, decoded))
+ # large app response as reassembled SEND SHORT MESSAGE, but
+ # the ENVELOPE itself returns a POR without R-APDU.
+ # smpplib poll() drains all pending SMS in one call, so that PoR is processed
+ # right after the real response and would overwrite it,
+ # which leaves transceive_apdu with no last_response_data to return.
+ # Only allow a response that has no application data (decoded == None)
+ # if we do not already have a real one.
+ if decoded is None and self.response is not None and self.response[1] is not None:
+ logger.info("ignoring status response to keep earlier app response")
+ return None
+ self.response = (res, decoded)
return None
def message_sent_handler(self, pdu):
diff --git a/pySim/sms.py b/pySim/sms.py
index 62601b0..75a9bde 100644
--- a/pySim/sms.py
+++ b/pySim/sms.py
@@ -19,6 +19,7 @@
import typing
import abc
+import logging
from bidict import bidict
from construct import Int8ub, Byte, Bit, Flag, BitsInteger
from construct import Struct, Enum, Tell, BitStruct, this, Padding
@@ -28,6 +29,8 @@
from smpp.pdu import pdu_types, operations
+logger = logging.getLogger(__name__)
+
BytesOrHex = typing.Union[Hexstr, bytes]
class UserDataHeader:
@@ -60,6 +63,109 @@
return self._construct.build({'ies':self.ies, 'data':b''})
+class ConcatenatedSmsReassembler:
+ """3GPP TS 23.040 section 9.2.3.24 concat multi part reassembly
+
+ A large user-data payload (e.g. a big OTA response packet) is split by the
+ sending entity into several SMS,
+ each carries a
+ - "concat short messages" IE in its UDH that identifies the set (ref num),
+ - total number of parts
+ - this parts seqno.
+ supports both:
+ IEI 0x00, section 9.2.3.24.1 8-bit ref form
+ IEI 0x08, section 9.2.3.24.8 the 16-bit ref form
+
+ Feed each received TP-User-Data (UDH + payload) to add() which
+ returns the reassembled TP-User-Data once all parts of the set have arrived,
+ or None as long as parts are still missing.
+
+ A non-concatenated SMS is returned unchanged,
+ just like one where the concat IE holds a reserved value:
+ TS 23.040 9.2.3.24.1 says
+ - both a total of zero
+ - a sequence number that is zero or greater than the total
+ that "the receiving entity shall ignore the whole IE",
+ we treat the message as a single, non-concatenated one and warn, not
+ as an error, so the caller does not die.
+
+ The reassembled TP-User-Data is built with a UDH that contains
+ the non-concat IEs seen in the parts, for example the the OTA "response packet"
+ indicator IE 0x71, followed by the concatenated payloads in sequence order,
+ so exactly the single-SMS form the sender would have produced for a payload that fits
+ into one SMS.
+ This allows convenient decoding by the normal single part path."""
+
+ # IEI: Concatenated short messages, 8-bit reference number
+ # (see 3GPP TS 23.040 section 9.2.3.24 and section 9.2.3.24.1)
+ CONCAT_8BIT = 0x00
+ # IEI: Concatenated short message, 16-bit reference number
+ # (see 3GPP TS 23.040 section 9.2.3.24 and section 9.2.3.24.8)
+ CONCAT_16BIT = 0x08
+
+ def __init__(self, max_sets: int = 8):
+ # keyed by (iei, ref, total): {'parts': {seq: payload}, 'header_ies'}, insertion ordered
+ self.sets = {}
+ self.max_sets = max_sets # incomplete sets kept, oldest is dropped beyond that
+
+ @classmethod
+ def _parse_concat_ie(cls, ies) -> typing.Optional[typing.Tuple[int, int, int, int]]:
+ """Return (iei, ref, total, seq) of the concat IE, or None"""
+ for ie in ies:
+ if ie['iei'] == cls.CONCAT_8BIT and ie['length'] == 3:
+ v = ie['value']
+ return cls.CONCAT_8BIT, v[0], v[1], v[2]
+ if ie['iei'] == cls.CONCAT_16BIT and ie['length'] == 4:
+ v = ie['value']
+ return cls.CONCAT_16BIT, int.from_bytes(v[0:2], 'big'), v[2], v[3]
+ return None
+
+ def add(self, tpud: BytesOrHex) -> typing.Optional[bytes]:
+ """Add one TP-User-Data.
+ Returns
+ - the reassembled TP-User-Data if set is complete or sms not multipart,
+ - else None"""
+ if isinstance(tpud, str):
+ tpud = h2b(tpud)
+ udh, payload = UserDataHeader.from_bytes(tpud)
+ concat = self._parse_concat_ie(udh.ies)
+ if concat is None:
+ return tpud
+ iei, ref, total, seq = concat
+ if total < 1 or seq < 1 or seq > total:
+ # TS 23.040 9.2.3.24.1 / 9.2.3.24.8, total zero or seqno zero / > total:
+ # Ignoring the IE means the message has no valid concat IE, which is a single part message.
+ # Better warn and hand it back rather than raise, so we don't kill the callers receive loop/session
+ logger.warning('Ignoring reserved concat IE (ref=%u total=%u seq=%u), treating the '
+ 'message as non-concat', ref, total, seq)
+ return tpud
+ # TS 23.040 9.2.3.24.1 Total is constant in a set, refno only unique per IE form -> both set identity
+ # - full count = seqno 1..total is present
+ # - part disagreeing on the total ends up as set that cannot complete like set with missing parts
+ key = (iei, ref, total)
+ if key not in self.sets and len(self.sets) >= self.max_sets:
+ del self.sets[next(iter(self.sets))]
+ s = self.sets.setdefault(key, {'parts': {}, 'header_ies': []})
+ s['parts'][seq] = payload
+ # - remember the non concat IEs (OTA 0x71 indicator for example)
+ # - keep first seen occurrence of each IEI,
+ # so app IE present only in the first segment is preserved independent of arrival order
+ seen = {ie['iei'] for ie in s['header_ies']}
+ for ie in udh.ies:
+ if ie['iei'] in (self.CONCAT_8BIT, self.CONCAT_16BIT):
+ continue
+ if ie['iei'] not in seen:
+ s['header_ies'].append(ie)
+ seen.add(ie['iei'])
+ if len(s['parts']) < total:
+ return None
+ # all parts present -> reassemble in seq order
+ del self.sets[(iei, ref, total)]
+ body = b''.join(s['parts'][i] for i in range(1, total + 1))
+ header = UserDataHeader(s['header_ies']).to_bytes()
+ return header + body
+
+
def smpp_dcs_is_8bit(dcs: pdu_types.DataCoding) -> bool:
"""Determine if the given SMPP data coding scheme is 8-bit or not."""
if dcs == pdu_types.DataCoding(pdu_types.DataCodingScheme.DEFAULT,
diff --git a/tests/unittests/test_smpp_ota_tool.py b/tests/unittests/test_smpp_ota_tool.py
new file mode 100644
index 0000000..ec60c85
--- /dev/null
+++ b/tests/unittests/test_smpp_ota_tool.py
@@ -0,0 +1,180 @@
+#!/usr/bin/env python3
+""" test for smpp-ota-tool SMS handling, specifically the multi part sms OTA response"""
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild(a)sysmocom.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import os.path
+import importlib.util
+import unittest
+
+from osmocom.utils import h2b, b2h
+
+from pySim.ota import OtaKeyset, OtaDialectSms, ExpandedRemoteResp
+from pySim.sms import ConcatenatedSmsReassembler, UserDataHeader
+
+# import the hyphenated contrib script as a module to get at SmppHandler
+# why do people name python files like that? why does everything have to be so hard?
+_TOOL_PATH = os.path.join(os.path.dirname(__file__), '..', '..', 'contrib', 'smpp-ota-tool.py')
+_spec = importlib.util.spec_from_file_location('smpp_ota_tool', _TOOL_PATH)
+smpp_ota_tool = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(smpp_ota_tool)
+SmppHandler = smpp_ota_tool.SmppHandler
+
+
+class _FakePdu:
+ """Minimal mock for smpplib deliver_sm pdu."""
+ def __init__(self, short_message):
+ self.short_message = short_message
+
+
+class MultipartRelayTestCase(unittest.TestCase):
+ """message_received_handler must return the reassembled application
+ response and survive POR messages."""
+
+ # 3DES test keyset from tests/unittests/test_ota.py) used to make the
+ # handler happy. responses are plaintext, tests do not depend on keys.
+ def _handler(self, remote_format='expanded'):
+ h = object.__new__(SmppHandler)
+ h.client = None
+ h.ota_dialect = OtaDialectSms()
+ h.ota_keyset = OtaKeyset(algo_crypt='triple_des_cbc2', kic_idx=3,
+ kic=h2b('C21DD66ACAC13CB3BC8B331B24AFB57B'),
+ algo_auth='triple_des_cbc2', kid_idx=3,
+ kid=h2b('12110C78E678C25408233076AA033615'))
+ h.tar = h2b('000000')
+ # unciphered, no CC, PoR required
+ h.spi = {'counter': 'no_counter', 'ciphering': False, 'rc_cc_ds': 'no_rc_cc_ds',
+ 'por_in_submit': False, 'por': 'por_required',
+ 'por_shall_be_ciphered': False, 'por_rc_cc_ds': 'no_rc_cc_ds'}
+ h.remote_format = remote_format
+ h.reassembler = ConcatenatedSmsReassembler()
+ h.response = None
+ return h
+
+ @staticmethod
+ def _plaintext_resp_sms(secured: bytes, sts: int = 0x00) -> bytes:
+ """Build a plaintext (unciphered, no-CC) OTA SMS response packet in the
+ canonical single-part form (UDH 02 71 00 + response packet)."""
+ rpl = 1 + 3 + 5 + 1 + 1 + len(secured) # RHL-STS + secured data
+ body = (rpl.to_bytes(2, 'big') + b'\x0a' + h2b('000000') + b'\x00' * 5
+ + b'\x00' + bytes([sts]) + secured)
+ return b'\x02\x71\x00' + body
+
+ @staticmethod
+ def _expanded_secured(response_data_hex: str, sw: str = '9000') -> bytes:
+ return ExpandedRemoteResp.build(dict(body=dict(
+ num_executed=dict(number_of_commands=1),
+ responses=[dict(r_apdu=dict(response_data=response_data_hex, status_word=sw))])))
+
+ @staticmethod
+ def _fragment_2(tpud: bytes, ref: int, first_len: int):
+ """Split 02 71 00 + body TP-UD into two SMS parts:
+ - part1 carries the OTA (0x71) IE
+ - part2 only concatenat IE
+ matches sja5 interaction"""
+ assert tpud[:3] == b'\x02\x71\x00'
+ body = tpud[3:]
+ ota_ie = {'iei': 0x71, 'length': 0, 'value': b''}
+
+ def concat(seq):
+ return {'iei': 0x00, 'length': 3, 'value': bytes([ref, 2, seq])}
+ p1 = UserDataHeader([concat(1), ota_ie]).to_bytes() + body[:first_len]
+ p2 = UserDataHeader([concat(2)]).to_bytes() + body[first_len:]
+ return p1, p2
+
+ # ground truth: TP-User-Data captured from a sja5
+ REAL_PART1 = h2b('070003010201710000e412000000df63afe4b06db21e2113be1be09e9b66f1c113ae841cca2d030064ec16b5b80ee5ce824604a4568109d25a82fb74a325df6f911bd0a4f858ece2c770039002c480269fc65953f5fd93ebbe528d97838bac4389a7303db2b073a37a9a1a51890457f41b49fc7905ce337e83449b65560501b8b845fe63339d557a928f2643')
+ REAL_PART2 = h2b('050003010202fd9c4e50ec40fb4427af518e9c08697405d91fbb6e9fa0b0935f48a560e15f2f3f27a2e44ef3a47280acce77f030fb70eb3df863c159177e2c0e3e53052fc7bb7ed171a491ded3ab7921861176a04305bc09fcf526c07bf6bb48a19e67cf18be5bc1')
+ REAL_REASSEMBLED = '02710000e412000000df63afe4b06db21e2113be1be09e9b66f1c113ae841cca2d030064ec16b5b80ee5ce824604a4568109d25a82fb74a325df6f911bd0a4f858ece2c770039002c480269fc65953f5fd93ebbe528d97838bac4389a7303db2b073a37a9a1a51890457f41b49fc7905ce337e83449b65560501b8b845fe63339d557a928f2643fd9c4e50ec40fb4427af518e9c08697405d91fbb6e9fa0b0935f48a560e15f2f3f27a2e44ef3a47280acce77f030fb70eb3df863c159177e2c0e3e53052fc7bb7ed171a491ded3ab7921861176a04305bc09fcf526c07bf6bb48a19e67cf18be5bc1'
+
+ def test_real_card_parts_reassemble(self):
+ """two real card TP-UDs recombine into 233-byte single part packet:
+ UDH 02 71 00 + response packet"""
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self.REAL_PART1))
+ out = r.add(self.REAL_PART2)
+ self.assertEqual(len(out), 233)
+ self.assertEqual(b2h(out), self.REAL_REASSEMBLED)
+
+ def test_multipart_response_not_overwritten_by_por(self):
+ """reassembled application response must survive the ENVELOPE
+ trailing POR which contains no R-APDU"""
+ registry = bytes(range(198))
+ app = self._plaintext_resp_sms(self._expanded_secured(b2h(registry)))
+ part1, part2 = self._fragment_2(app, ref=0x42, first_len=132)
+ # single part form must be too fat -> both parts must be concatenated
+ self.assertGreater(len(app), 140)
+ # ENVELOPE PoR: por_ok, but no app R-APDU
+ inline_por = self._plaintext_resp_sms(b'', sts=0x00)
+
+ h = self._handler()
+ # arrival order
+ self.assertIsNone(h.message_received_handler(_FakePdu(part1)))
+ h.message_received_handler(_FakePdu(part2))
+ h.message_received_handler(_FakePdu(inline_por))
+
+ # self.response must be app response, not the PoR!
+ self.assertIsNotNone(h.response)
+ res, decoded = h.response
+ self.assertEqual(res.response_status, 'por_ok')
+ self.assertIsNotNone(decoded)
+ self.assertEqual(decoded.last_response_data, b2h(registry))
+ self.assertEqual(decoded.last_status_word, '9000')
+
+ def test_undecodable_response_does_not_crash(self):
+ """response the handler can't decode must not escape out of the poll()
+ loop which would kill the tool, it must be ignored"""
+ # por_ok with a not expanded 'secured data' -> expanded parse raises
+ bad = self._plaintext_resp_sms(h2b('01612f'), sts=0x00)
+ h = self._handler(remote_format='expanded')
+ # must NOT raise
+ self.assertIsNone(h.message_received_handler(_FakePdu(bad)))
+ self.assertIsNone(h.response)
+
+ def test_undecodable_por_after_good_response(self):
+ """real app response followed by undecodable PoR:
+ - good response is saved
+ - tool does not crash."""
+ registry = bytes(range(120))
+ app = self._plaintext_resp_sms(self._expanded_secured(b2h(registry)))
+ part1, part2 = self._fragment_2(app, ref=0x07, first_len=110)
+ bad_por = self._plaintext_resp_sms(h2b('deadbeef'), sts=0x00)
+
+ h = self._handler()
+ h.message_received_handler(_FakePdu(part1))
+ h.message_received_handler(_FakePdu(part2))
+ self.assertIsNone(h.message_received_handler(_FakePdu(bad_por))) # no crash
+ res, decoded = h.response
+ self.assertIsNotNone(decoded)
+ self.assertEqual(decoded.last_response_data, b2h(registry))
+
+ def test_single_part_response_still_works(self):
+ """small response that fits one SMS turns into self.response, handled as before"""
+ h = self._handler()
+ sms = self._plaintext_resp_sms(self._expanded_secured('abcd', sw='9000'))
+ self.assertLessEqual(len(sms), 140)
+ h.message_received_handler(_FakePdu(sms))
+ res, decoded = h.response
+ self.assertIsNotNone(decoded)
+ self.assertEqual(decoded.last_response_data, 'abcd')
+ self.assertEqual(decoded.last_status_word, '9000')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/unittests/test_sms.py b/tests/unittests/test_sms.py
index d190528..e82377a 100644
--- a/tests/unittests/test_sms.py
+++ b/tests/unittests/test_sms.py
@@ -103,3 +103,126 @@
self.assertEqual(d.tp_pid, 0x7f)
self.assertEqual(d.tp_dcs, 0xf6)
self.assertEqual(d.tp_udl, 8)
+
+
+class Test_ConcatenatedSmsReassembler(unittest.TestCase):
+ """3GPP TS 23.040 9.2.3.24 reassembly of multi-part SMS.
+
+ An OTA response that exceeds a single SHORT MESSAGE is delivered in several parts using
+ the SEND SHORT MESSAGE proactive command. The receiver must recombine the individual
+ parts into a single part before decoding."""
+
+ OTA_IE = {'iei': 0x71, 'length': 0, 'value': b''}
+
+ @staticmethod
+ def _concat8(ref, tot, seq):
+ return {'iei': 0x00, 'length': 3, 'value': bytes([ref, tot, seq])}
+
+ @staticmethod
+ def _concat16(ref, tot, seq):
+ return {'iei': 0x08, 'length': 4, 'value': ref.to_bytes(2, 'big') + bytes([tot, seq])}
+
+ @staticmethod
+ def _part(ies, frag):
+ return UserDataHeader(ies).to_bytes() + frag
+
+ def test_ground_truth_udh(self):
+ # part 1 UDH observed from sja5: 07 00 03 01 02 01 71 00
+ built = self._part([self._concat8(1, 2, 1), self.OTA_IE], b'')
+ self.assertEqual(b2h(built), '0700030102017100')
+
+ def test_ground_truth_udh_16bit(self):
+ # 9.2.3.24.8: 08 | 08 04 <ref16> <total> <seq> | 71 00
+ built = self._part([self._concat16(0x1234, 2, 1), self.OTA_IE], b'')
+ self.assertEqual(b2h(built), '080804123402017100')
+
+ def test_single_part_passthrough(self):
+ r = ConcatenatedSmsReassembler()
+ single = h2b('027100') + bytes(range(20))
+ self.assertEqual(r.add(single), single)
+
+ def test_two_part(self):
+ # second segment contains only the concat IE, no OTA IE
+ pkt = bytes(range(60))
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat8(1, 2, 1), self.OTA_IE], pkt[:35])))
+ out = r.add(self._part([self._concat8(1, 2, 2)], pkt[35:]))
+ self.assertEqual(out, h2b('027100') + pkt)
+
+ def test_out_of_order(self):
+ pkt = bytes(range(60))
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat8(5, 2, 2), self.OTA_IE], pkt[35:])))
+ out = r.add(self._part([self._concat8(5, 2, 1), self.OTA_IE], pkt[:35]))
+ self.assertEqual(out, h2b('027100') + pkt)
+
+ def test_three_part_out_of_order(self):
+ pkt = bytes(range(90))
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat8(7, 3, 3)], pkt[60:])))
+ self.assertIsNone(r.add(self._part([self._concat8(7, 3, 1), self.OTA_IE], pkt[:30])))
+ out = r.add(self._part([self._concat8(7, 3, 2)], pkt[30:60]))
+ self.assertEqual(out, h2b('027100') + pkt)
+
+ def test_16bit_reference(self):
+ pkt = bytes(range(40))
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat16(0x1234, 2, 1), self.OTA_IE], pkt[:20])))
+ out = r.add(self._part([self._concat16(0x1234, 2, 2)], pkt[20:]))
+ self.assertEqual(out, h2b('027100') + pkt)
+
+ def test_interleaved_references(self):
+ # two concurrent concatenation sets at the same time
+ pkt = bytes(range(60))
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat8(1, 2, 1), self.OTA_IE], pkt[:35])))
+ self.assertIsNone(r.add(self._part([self._concat8(9, 2, 1), self.OTA_IE], b'\xaa')))
+ self.assertEqual(r.add(self._part([self._concat8(1, 2, 2)], pkt[35:])), h2b('027100') + pkt)
+ self.assertEqual(r.add(self._part([self._concat8(9, 2, 2)], b'\xbb')), h2b('027100') + b'\xaa\xbb')
+
+ def test_reserved_concat_ie_is_ignored(self):
+ # TS 23.040 9.2.3.24.1:
+ # - a total of 0
+ # - or a sequence number that is 0 or > total
+ # means "the receiving entity shall ignore the whole Information Element"
+ # the message is handed back unchanged as a single part msg and not rejected
+ # so the caller can handle the problem
+ r = ConcatenatedSmsReassembler()
+ for tot, seq in [(2, 3), # seq > total
+ (2, 0), # seq == 0
+ (0, 1)]: # total == 0
+ with self.subTest(total=tot, seq=seq):
+ part = self._part([self._concat8(1, tot, seq)], b'\x00')
+ self.assertEqual(r.add(part), part)
+ # nothing buffered so later valid set still reassembles properly
+ self.assertEqual(r.sets, {})
+ pkt = bytes(range(40))
+ self.assertIsNone(r.add(self._part([self._concat8(1, 2, 1), self.OTA_IE], pkt[:20])))
+ self.assertEqual(r.add(self._part([self._concat8(1, 2, 2)], pkt[20:])), h2b('027100') + pkt)
+
+ def test_inconsistent_totals_do_not_crash(self):
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat8(1, 3, 3)], b'\x33')))
+ self.assertIsNone(r.add(self._part([self._concat8(1, 2, 1)], b'\x11')))
+ self.assertEqual(r.add(self._part([self._concat8(1, 2, 2)], b'\x22')),
+ h2b('00') + b'\x11\x22') # complete total=2 set
+ self.assertIn((0x00, 1, 3), r.sets) # total=3 set still waits
+
+ def test_incomplete_sets_are_capped(self):
+ r = ConcatenatedSmsReassembler(max_sets=2)
+ for ref in (1, 2, 3):
+ self.assertIsNone(r.add(self._part([self._concat8(ref, 2, 1)], bytes([ref]))))
+ self.assertEqual(sorted(k[1] for k in r.sets), [2, 3]) # oldest evicted
+ self.assertIsNone(r.add(self._part([self._concat8(1, 2, 2)], b'\x11')))
+ self.assertEqual(sorted(k[1] for k in r.sets), [1, 3])
+ self.assertEqual(r.add(self._part([self._concat8(3, 2, 2)], b'\x33')), h2b('00') + b'\x03\x33')
+
+ def test_same_reference_in_both_ie_forms(self):
+ # the refno only unique per IE form (9.2.3.24.1 vs .8) -> two sets
+ r = ConcatenatedSmsReassembler()
+ self.assertIsNone(r.add(self._part([self._concat8(1, 2, 1)], b'\x0a')))
+ self.assertIsNone(r.add(self._part([self._concat16(1, 2, 2)], b'\x1b')))
+ self.assertEqual(r.add(self._part([self._concat16(1, 2, 1)], b'\x0b')),
+ h2b('00') + b'\x0b\x1b')
+ self.assertEqual(r.add(self._part([self._concat8(1, 2, 2)], b'\x1a')),
+ h2b('00') + b'\x0a\x1a')
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43544?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I8c81097e607e0d055c4f031bbcc8a74d5c24a0e7
Gerrit-Change-Number: 43544
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43545?usp=email )
Change subject: smpp2sim: make the SCP81 BIP relay work
......................................................................
smpp2sim: make the SCP81 BIP relay work
The BIP relay ( the "handset" side for SCP81) never worked: the
connect callback in handle_OpenChannel was "never called" as the fixme
says, everything else was missing.
Fixme cause: card APDU I/O is driven synchronously, proactive command loop
lives in a blocking while loop (pySim.transport.LinkBase.send_apdu_checksw)
that runs on the Twisted reactor thread. A Twisted TCP4ClientEndpoint +
connectProtocol only completes when the reactor does reactor things,
but the reactor thread is stuck in that loop for the whole proactive
session...
Fixme fix: don't fight the reactor, just drive the relay channel with a plain
old blocking socket, which fits the synchronous execution model.
Channel numbers now come from the command Device identities (channel_N ->
low nibble) instead of the hard coded chan_nr == 1.
Additionally fix two bugs found on the path to scp81 glory:
- TERMINAL RESPONSE device identities are forced to terminal->UICC per
TS 102 223 6.8.2 (prepare_response() inverts the command identities,
which for a channel-addressed BIP command yields channel_N->UICC).
- Error responses now build a valid AddlInfoBip cause, prepare_response()
hard coded empty "additional information" cannot be encoded for a
BIP error.
And some tests based on real card interactions.
Change-Id: If96c768f2e35c20ea3753e601059410121517b60
---
M pySim-smpp2sim.py
M pySim/bip.py
M tests/unittests/test_bip_relay.py
3 files changed, 569 insertions(+), 54 deletions(-)
Approvals:
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/pySim-smpp2sim.py b/pySim-smpp2sim.py
index 9420130..f7a45f5 100755
--- a/pySim-smpp2sim.py
+++ b/pySim-smpp2sim.py
@@ -30,6 +30,9 @@
import argparse
import logging
+import socket
+import threading
+import time
import colorlog
from twisted.protocols import basic
@@ -55,6 +58,7 @@
from pySim.cat import ProactiveCommand, SendShortMessage, SMS_TPDU, SMSPPDownload, BearerDescription
from pySim.cat import DeviceIdentities, Address, OtherAddress, UiccTransportLevel, BufferSize
from pySim.cat import ChannelStatus, ChannelData, ChannelDataLength
+from pySim.cat import EventList, EventDownload, Result
from pySim.utils import b2h, h2b
logger = logging.getLogger(__name__)
@@ -106,6 +110,11 @@
smppEndpoint = endpoints.TCP6ServerEndpoint(reactor, tcp_port, interface=bind_ip)
smppEndpoint.listen(self.factory)
self.tp = self.scc = self.card = None
+ # Serialise card/APDU access.
+ # - SMPP handler drives the card from reactor thread
+ # - BIP relay data-available path drives it from socket reader thread.
+ # The transport is not re-entrant, both must take this lock.
+ self._card_lock = threading.Lock()
def connect_to_card(self, tp: LinkBase):
self.tp = tp
@@ -118,6 +127,21 @@
self.card.select_adf_by_aid(adf='usim')
# FIXME: create a more realistic profile than ffffff
self.scc.terminal_profile('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
+ # Connect the BIP relay inbound path to the card.
+ # relay socket receives data -> ME initiated ENVELOPE EVENT DOWNLOA
+ # -> triggers RECEIVE DATA proactive session.
+ # FIXME this cross-thread push to the card is exercised only with real hardware
+ # the card free tests cover socket relay + envelope construction, not delivery.
+ handler = getattr(tp, 'proactive_handler', None)
+ if isinstance(handler, Proact):
+ handler.data_available_sink = self._deliver_data_available
+
+ def _deliver_data_available(self, envelope_hex: str):
+ """push ME initiated ENVELOPE EVENT DOWNLOAD to the card"""
+ with self._card_lock:
+ logger.info("ENVELOPE(Data available): %s" % envelope_hex)
+ (data, sw) = self.scc.envelope(envelope_hex)
+ logger.info("SW %s: %s" % (sw, data))
def _msgHandler(self, system_id, smpp, pdu):
"""Handler for incoming messages received via SMPP from ESME."""
@@ -152,7 +176,8 @@
# 3) send to the card
envelope_hex = b2h(sms_dl.to_tlv())
logger.info("ENVELOPE: %s" % envelope_hex)
- (data, sw) = self.scc.envelope(envelope_hex)
+ with self._card_lock:
+ (data, sw) = self.scc.envelope(envelope_hex)
logger.info("SW %s: %s" % (sw, data))
if sw in ['9200', '9300']:
# TODO send back RP-ERROR message with TP-FCS == 'SIM Application Toolkit Busy'
diff --git a/pySim/bip.py b/pySim/bip.py
index 6c7de57..a23741e 100644
--- a/pySim/bip.py
+++ b/pySim/bip.py
@@ -17,13 +17,21 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+# A ProactiveHandler with TCP sockets that backs the BIP channels,
+# so a card can run its own IP session (SCP81/HTTPS, CAT_TP, ...)
+#
+# Currently used by pySim-smpp2sim.py which connects the SMS path to its SMPP server.
+# Other drivers can pass their own sinks:
+#
+# handler = Proact(data_available_sink=..., sms_sink=...)
+# tp = init_reader(opts, proactive_handler=handler)
+
+
import logging
import socket
import threading
import time
-from twisted.internet import endpoints, protocol, reactor
-
from osmocom.utils import b2h, h2b
from pySim.transport import ProactiveHandler
@@ -35,56 +43,181 @@
logger = logging.getLogger(__name__)
-class TcpProtocol(protocol.Protocol):
- def dataReceived(self, data):
- pass
-
- def connectionLost(self, reason):
- pass
-
-
-def tcp_connected_callback(p: protocol.Protocol):
- """called by twisted TCP client."""
- logger.error("%s: connected!" % p)
-
class ProactChannel:
- """Representation of a single protective channel."""
+ """One BIP channel, TS 102 223 class "e", backed by a blocking TCP socket.
+
+ Created by ProactChannels.channel_create(). A reader thread fills the Rx buffer from the
+ socket, the Proact handlers drain it (RECEIVE DATA) and write to it (SEND DATA). Payload
+ is opaque, TLS or CAT_TP run on the card.
+
+ Args:
+ channels: the owning ProactChannels, notified of data arrival and of close()
+ chan_nr: channel number 1..7 as used in the Device identities
+ """
+ # Why blocking sockets and not Twisted endpoints, considering we have twisted?
+ # The proactive-command loop lives in a blocking while-loop,
+ # "pySim.transport.LinkBase.send_apdu_checksw" that runs on the Twisted reactor thread.
+ # A Twisted async TCP client only makes any progress when the reactor uhh... reacts, but
+ # the reactor is stuck in that loop for the whole proactive session -> the
+ # connectProtocol() Deferred never fires while we are handling OPEN/SEND/RECEIVE CHANNEL.
+ # Plain blocking sockets just work: connect() in handle_OpenChannel, send() in
+ # handle_SendData, recv() feeding a buffer for handle_ReceiveData. No need to make it
+ # harder than it has to be to handle the "massive" T0 bandwidth..
+ # how much we try to read off the socket per recv()
+ RECV_CHUNK = 4096
+
def __init__(self, channels: 'ProactChannels', chan_nr: int):
self.channels = channels
self.chan_nr = chan_nr
- self.ep = None
+ self.sock = None
+ # TS 102 223 says the terminal keeps an Rx buffer per channel; RECEIVE
+ # DATA drains it, and it is filled asynchronously as the peer sends.
+ self.rx_buf = bytearray()
+ self._rx_lock = threading.Lock()
+ self._reader = None
+ self._closing = False
+ self.peer_closed = False
+
+ def connect(self, host: str, port: int, timeout: float = 10.0):
+ """Open the blocking TCP socket and start the background Rx reader."""
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ s.settimeout(timeout)
+ s.connect((host, port))
+ # Back to blocking mode for the reader thread.
+ # CLOSE CHANNEL unblocks the pending recv() via shutdown().
+ s.settimeout(None)
+ except OSError:
+ s.close()
+ raise
+ self.sock = s
+ self._reader = threading.Thread(target=self._rx_loop,
+ name='bip-rx-%d' % self.chan_nr, daemon=True)
+ self._reader.start()
+
+ def _rx_loop(self):
+ """Continuously read from the socket into rx_buf, like a real ME.
+
+ TS 102 223 7.5.10.1 says the event is raised 'only if the targeted channel buffer is
+ empty when new data arrives in it', so the data available hook fires on the
+ empty->non-empty transition only. That is enough: every RECEIVE DATA response tells
+ the card how many bytes remain, so it keeps fetching until the buffer is empty, and
+ the next event restarts it when more data arrives."""
+ while not self._closing:
+ try:
+ data = self.sock.recv(self.RECV_CHUNK)
+ except (OSError, ValueError):
+ break
+ if not data:
+ self.peer_closed = True
+ break
+ with self._rx_lock:
+ was_empty = len(self.rx_buf) == 0
+ self.rx_buf.extend(data)
+ if was_empty and not self._closing:
+ self.channels.notify_data_available(self)
+
+ def send(self, data: bytes):
+ """Tx, write bytes to the socket == SEND DATA"""
+ self.sock.sendall(data)
+
+ def available_rx(self) -> int:
+ """Number of bytes waiting in the Rx buffer, what RECEIVE DATA can return right now."""
+ with self._rx_lock:
+ return len(self.rx_buf)
+
+ def take_rx(self, n: int):
+ """Take up to n bytes out of the Rx buffer. Returns (bytes, bytes still remaining)."""
+ with self._rx_lock:
+ chunk = bytes(self.rx_buf[:n])
+ del self.rx_buf[:n]
+ remaining = len(self.rx_buf)
+ return chunk, remaining
+
+ def wait_rx(self, timeout: float) -> int:
+ """wait up to timeout seconds until the rxbuf has data
+ returns the number of bytes available
+ Cards have a "data available" event, card free callers use
+ this to wait for the echoed bytes."""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ avail = self.available_rx()
+ if avail or self.peer_closed:
+ return avail
+ time.sleep(0.005)
+ return self.available_rx()
def close(self):
- """Close the channel."""
- if self.ep:
- self.ep.disconnect()
+ """Close channel: stop reader, close socket, drop bookkeeping."""
+ self._closing = True
+ if self.sock is not None:
+ try:
+ self.sock.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ try:
+ self.sock.close()
+ except OSError:
+ pass
+ # CLOSE CHANNEL synchronously handled inside the rx reader thread
+ # (data-available -> ENVELOPE -> FETCH -> handle_CloseChannel -> close),
+ # so close() can be called on the reader thread.
+ # Joining self raises "cannot join current thread" so better skip i..
+ # setting _closing + shutting down the socket already makes _rx_loop
+ # return on the next iteration anyway.
+ if self._reader is not None and self._reader is not threading.current_thread():
+ self._reader.join(timeout=1.0)
self.channels.channel_delete(self.chan_nr)
class ProactChannels:
- """Wrapper class for maintaining state of proactive channels."""
- def __init__(self):
+ """The open BIP channels of one terminal, keyed by channel number.
+
+ Args:
+ on_data_available: callback(chan: ProactChannel), invoked from the channel's reader
+ thread when data arrives in an empty Rx buffer. Proact turns it into an
+ ENVELOPE EVENT DOWNLOAD (data available).
+ """
+ def __init__(self, on_data_available=None):
self.channels = {}
+ self._on_data_available = on_data_available
def channel_create(self) -> ProactChannel:
"""Create a new proactive channel, allocating its integer number."""
- for i in range(1, 9):
+ for i in range(1, 8):
if not i in self.channels:
self.channels[i] = ProactChannel(self, i)
return self.channels[i]
raise ValueError('Cannot allocate another channel: All channels active')
def channel_delete(self, chan_nr: int):
- del self.channels[chan_nr]
+ """Forget a channel, called by ProactChannel.close()."""
+ self.channels.pop(chan_nr, None)
+
+ def notify_data_available(self, chan: ProactChannel):
+ """Run the on_data_available callback for chan, if one was given."""
+ if self._on_data_available:
+ self._on_data_available(chan)
class Proact(ProactiveHandler):
- #def __init__(self, smpp_factory):
- # self.smpp_factory = smpp_factory
- def __init__(self, sms_sink=None):
- # sms_sink(pdu) delivers an MO-SMS the card sent (SEND SHORT MESSAGE)
- # onwards; pySim-smpp2sim.py hands it to its SMPP server. None -> log
- # and drop.
+ """ProactiveHandler that answers the BIP proactive commands with TCP sockets.
+
+ The transport calls the handle_* methods with the decoded proactive command and posts
+ the returned IE list as TERMINAL RESPONSE.
+
+ Args:
+ data_available_sink: callback(envelope_hex: str), called from a channel reader thread
+ with an encoded ENVELOPE EVENT DOWNLOAD (data available). The caller forwards it
+ to the card with the ENVELOPE command, the card then FETCHes RECEIVE DATA.
+ None: the event is only logged (card free / test mode).
+ sms_sink: callback(pdu), called with the SMPP deliver_sm of a SEND SHORT MESSAGE
+ the card issued; pySim-smpp2sim.py hands it to its SMPP server.
+ None: the SMS is logged and dropped.
+ """
+ def __init__(self, data_available_sink=None, sms_sink=None):
+ self.data_available_sink = data_available_sink
self.sms_sink = sms_sink
- self.channels = ProactChannels()
+ self.channels = ProactChannels(on_data_available=self._on_channel_data_available)
@staticmethod
def _find_first_element_of_type(instlist, cls):
@@ -93,8 +226,82 @@
return i
return None
- """Call-back which the pySim transport core calls whenever it receives a
- proactive command from the SIM."""
+ @staticmethod
+ def _channel_nr_from_dev_ids(dev_id_ie: DeviceIdentities) -> int:
+ """Maps id like channel_1 -> channel number.
+ TS 102 223 Section 8.7 says low nibble is channel number,
+ channel-N = 0x21..0x27"""
+ dest = dev_id_ie.decoded['dest_dev_id']
+ return DeviceIdentities.DEV_IDS.inverse[dest] & 0x0f
+
+ def _channel_for(self, dev_id_ie: DeviceIdentities):
+ """Resolve the ProactChannel addressed by a command dev id, or None"""
+ return self.channels.channels.get(self._channel_nr_from_dev_ids(dev_id_ie), None)
+
+ @staticmethod
+ def _channel_status(chan_nr: int, established: bool = True) -> str:
+ """TS 102 223 Section 8.56 channel status value for the
+ default/network bearer:
+ - byte 3 low 3 bits = channel id
+ - bit 8 = link established
+ - byte 4 = 00 no further info"""
+ b3 = (0x80 if established else 0x00) | (chan_nr & 0x07)
+ return '%02x00' % b3
+
+ def _bip_response_head(self, pcmd: ProactiveCommand,
+ general_result: str = 'performed_successfully',
+ additional_information: str = ''):
+ """CommandDetails / DeviceIdentities / Result head part of a BIP TERMINAL
+ RESPONSE. Built on prepare_response() but with two changes:
+
+ - Device identities forced source=terminal, dest=UICC.
+ TS 102 223 6.8.2 mandates for every TERMINAL RESPONSE
+ prepare_response() inverts the commands device id, which is
+ right for a uicc->terminal command but would yield a wrong
+ channel_N->UICC for the channel addressed BIP commands.
+
+ - Result is recreated for non success cases. prepare_response()
+ hard codes empty "additional information", but for enum results
+ like BIP error -> AddlInfoBip the empty value cannot be encoded at
+ all, so we always ask prepare_response() for a success Result
+ and swap for a properly encoded one here."""
+ head = self.prepare_response(pcmd, 'performed_successfully')
+ for i, ie in enumerate(head):
+ if isinstance(ie, DeviceIdentities):
+ head[i] = DeviceIdentities(decoded={'source_dev_id': 'terminal',
+ 'dest_dev_id': 'uicc'})
+ elif isinstance(ie, Result) and general_result != 'performed_successfully':
+ res = Result()
+ res.from_dict({'result': {'general_result': general_result,
+ 'additional_information': additional_information}})
+ head[i] = res
+ return head
+
+ def _build_data_available_envelope(self, chan: ProactChannel) -> bytes:
+ """TS 102 223 7.5.10.2 ENVELOPE EVENT DOWNLOAD
+ Event list, Device id terminal->UICC, Channel status,
+ Channel data length (bytes available or FF for > 255)."""
+ avail = min(chan.available_rx(), 0xff)
+ ed = EventDownload(children=[
+ EventList(decoded=['data_available']),
+ DeviceIdentities(decoded={'source_dev_id': 'terminal', 'dest_dev_id': 'uicc'}),
+ ChannelStatus(decoded=self._channel_status(chan.chan_nr)),
+ ChannelDataLength(decoded=avail),
+ ])
+ return ed.to_tlv()
+
+ def _on_channel_data_available(self, chan: ProactChannel):
+ """rx reader thread hook: socket data arrived while the channel buffer
+ was empty. card uses ENVELOPE EVENT DOWNLOAD + responds by FETCHing RECEIVE DATA
+ proactive command. Card free only builds and logs"""
+ envelope_hex = b2h(self._build_data_available_envelope(chan))
+ logger.info("channel %u: %u byte(s) available -> ENVELOPE(Data available) %s",
+ chan.chan_nr, chan.available_rx(), envelope_hex)
+ if self.data_available_sink:
+ self.data_available_sink(envelope_hex)
+
+ # handle_*: called by the transport with the decoded proactive command, the returned IE
+ # list becomes the TERMINAL RESPONSE.
def handle_SendShortMessage(self, pcmd: ProactiveCommand):
# {'smspp_download': [{'device_identities': {'source_dev_id': 'network',
# 'dest_dev_id': 'uicc'}},
@@ -104,7 +311,8 @@
# 'call_number': '79'}},
# {'sms_tpdu': {'tpdu': '40048111227ff6407070611535004d02700000481516011212000001fe4c0943aea42e45021c078ae06c66afc09303608874b72f58bacadb0dcf665c29349c799fbb522e61709c9baf1890015e8e8e196e36153106c8b92f95153774'}}
# ]}
- """Card requests sending a SMS. We need to pass it on to the ESME via SMPP."""
+ """SEND SHORT MESSAGE: hand the MO-SMS to sms_sink, answer with success so the card
+ continues with the next part of a multi part response."""
logger.info("SendShortMessage")
logger.info(pcmd)
# Relevant parts in pcmd: Address, SMS_TPDU
@@ -126,7 +334,8 @@
return self.prepare_response(pcmd)
def handle_OpenChannel(self, pcmd: ProactiveCommand):
- """Card requests opening a new channel via a UDP/TCP socket."""
+ """OPEN CHANNEL: connect a TCP socket to the given address and port, allocate a
+ channel number and report it in the Channel status of the response."""
# {'open_channel': [{'command_details': {'command_number': 1,
# 'type_of_command': 'open_channel',
# 'command_qualifier': 3}},
@@ -150,16 +359,22 @@
raise ValueError('Unsupported protocol_type')
if other_addr_ie.decoded.get('type_of_address', None) != 'ipv4':
raise ValueError('Unsupported type_of_address')
- ipv4_bytes = h2b(other_addr_ie.decoded['address'])
- ipv4_str = '%u.%u.%u.%u' % (ipv4_bytes[0], ipv4_bytes[1], ipv4_bytes[2], ipv4_bytes[3])
+ addr_bytes = h2b(other_addr_ie.decoded['address']) if isinstance(
+ other_addr_ie.decoded['address'], str) else other_addr_ie.decoded['address']
+ ipv4_str = '%u.%u.%u.%u' % (addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3])
port_nr = transp_lvl_ie.decoded['port_number']
- print("%s:%u" % (ipv4_str, port_nr))
+ logger.info("OpenChannel: connecting to %s:%u", ipv4_str, port_nr)
channel = self.channels.channel_create()
- channel.ep = endpoints.TCP4ClientEndpoint(reactor, ipv4_str, port_nr)
- channel.prot = TcpProtocol()
- d = endpoints.connectProtocol(channel.ep, channel.prot)
- # FIXME: why is this never called despite the client showing the inbound connection?
- d.addCallback(tcp_connected_callback)
+ # yes, blocking connect()
+ try:
+ channel.connect(ipv4_str, port_nr)
+ except OSError as e:
+ logger.warning("OpenChannel: connect to %s:%u failed: %s", ipv4_str, port_nr, e)
+ self.channels.channel_delete(channel.chan_nr)
+ return self._bip_response_head(pcmd, 'bearer_independent_protocol_error',
+ 'channel_closed') + [
+ ChannelStatus(decoded=self._channel_status(channel.chan_nr, established=False)),
+ bearer_desc_ie, buffer_size_ie]
# Terminal Response example: [
# {'command_details': {'command_number': 1,
@@ -171,15 +386,26 @@
# {'bearer_description': {'bearer_type': 'default', 'bearer_parameters': ''}},
# {'buffer_size': 1024}
# ]
- return self.prepare_response(pcmd) + [ChannelStatus(decoded='8100'), bearer_desc_ie, buffer_size_ie]
+ return self._bip_response_head(pcmd) + [
+ ChannelStatus(decoded=self._channel_status(channel.chan_nr)),
+ bearer_desc_ie, buffer_size_ie]
def handle_CloseChannel(self, pcmd: ProactiveCommand):
- """Close a channel."""
+ """CLOSE CHANNEL: close the socket of the addressed channel and free its number."""
logger.info("CloseChannel")
logger.info(pcmd)
+ dev_id_ie = Proact._find_first_element_of_type(pcmd.children, DeviceIdentities)
+ chan = self._channel_for(dev_id_ie)
+ if chan is None:
+ # channel closed / invalid
+ return self._bip_response_head(pcmd, 'bearer_independent_protocol_error',
+ 'channel_id_not_valid')
+ chan.close()
+ return self._bip_response_head(pcmd)
def handle_ReceiveData(self, pcmd: ProactiveCommand):
- """Receive/read data from the socket."""
+ """RECEIVE DATA: the card fetches up to Channel data length bytes from the Rx buffer
+ of the addressed channel, the response also carries how many bytes remain."""
# {'receive_data': [{'command_details': {'command_number': 1,
# 'type_of_command': 'receive_data',
# 'command_qualifier': 0}},
@@ -189,6 +415,21 @@
# ]}
logger.info("ReceiveData")
logger.info(pcmd)
+ dev_id_ie = Proact._find_first_element_of_type(pcmd.children, DeviceIdentities)
+ req_len_ie = Proact._find_first_element_of_type(pcmd.children, ChannelDataLength)
+ chan = self._channel_for(dev_id_ie)
+ if chan is None:
+ return self._bip_response_head(pcmd, 'bearer_independent_protocol_error',
+ 'channel_id_not_valid')
+ # TS 102 223 8.54: RECEIVE DATA contains the requested count the card wants
+ requested = req_len_ie.decoded if req_len_ie is not None else chan.available_rx()
+ data, remaining = chan.take_rx(requested)
+ # TS 102 223 6.4.29:
+ # - return data available in the Rx buffer + num bytes still remaining (FF if > 255)
+ # - if fewer than requested available terminal must NOT wait, report and returns what we have
+ general_result = 'performed_successfully'
+ if len(data) < requested:
+ general_result = 'performed_with_missing_information'
# Terminal Response example: [
# {'command_details': {'command_number': 1,
# 'type_of_command': 'receive_data',
@@ -198,10 +439,13 @@
# {'channel_data': '16030100040e000000'},
# {'channel_data_length': 0}
# ]
- return self.prepare_response(pcmd) + []
+ return self._bip_response_head(pcmd, general_result) + [
+ ChannelData(decoded=b2h(data)),
+ ChannelDataLength(decoded=min(remaining, 0xff))]
def handle_SendData(self, pcmd: ProactiveCommand):
- """Send/write data received from the SIM to the socket."""
+ """SEND DATA: write the Channel data of the command to the socket of the addressed
+ channel."""
# {'send_data': [{'command_details': {'command_number': 1,
# 'type_of_command': 'send_data',
# 'command_qualifier': 1}},
@@ -213,10 +457,18 @@
logger.info(pcmd)
dev_id_ie = Proact._find_first_element_of_type(pcmd.children, DeviceIdentities)
chan_data_ie = Proact._find_first_element_of_type(pcmd.children, ChannelData)
- chan_str = dev_id_ie.decoded['dest_dev_id']
- chan_nr = 1 # FIXME
- chan = self.channels.channels.get(chan_nr, None)
- # FIXME chan.prot.transport.write(h2b(chan_data_ie.decoded))
+ chan = self._channel_for(dev_id_ie)
+ if chan is None:
+ return self._bip_response_head(pcmd, 'bearer_independent_protocol_error',
+ 'channel_id_not_valid')
+ # lets accept hexstrings as well
+ payload = chan_data_ie.decoded
+ if isinstance(payload, str):
+ payload = h2b(payload)
+ # command_qualifier bit 1 selects 'send immediately' / Tx-buffer store and forward
+ # For TCP stream all we have is a socket and TCP takes care of segmentation,
+ # so just send.
+ chan.send(payload)
# Terminal Response example: [
# {'command_details': {'command_number': 1,
# 'type_of_command': 'send_data',
@@ -225,9 +477,11 @@
# {'result': {'general_result': 'performed_successfully', 'additional_information': ''}},
# {'channel_data_length': 255}
# ]
- return self.prepare_response(pcmd) + [ChannelDataLength(decoded=255)]
+ # TS 102 223 6.4.30 / 8.54 Channel data length = free space tx buf; FF == > 255 available
+ return self._bip_response_head(pcmd) + [ChannelDataLength(decoded=255)]
def handle_SetUpEventList(self, pcmd: ProactiveCommand):
+ """SET UP EVENT LIST: acknowledged, data available and channel status are always on."""
# {'set_up_event_list': [{'command_details': {'command_number': 1,
# 'type_of_command': 'set_up_event_list',
# 'command_qualifier': 0}},
diff --git a/tests/unittests/test_bip_relay.py b/tests/unittests/test_bip_relay.py
index e2e7ff8..6139d92 100644
--- a/tests/unittests/test_bip_relay.py
+++ b/tests/unittests/test_bip_relay.py
@@ -17,10 +17,246 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+import socket
+import threading
+import time
import unittest
-from pySim.bip import Proact
+from osmocom.utils import b2h, h2b
+
from pySim.sms import SMS_SUBMIT, AddressField
+from pySim.cat import (ProactiveCommand, CommandDetails, DeviceIdentities,
+ BearerDescription, BufferSize, UiccTransportLevel,
+ OtherAddress, ChannelData, ChannelDataLength, ChannelStatus,
+ Result)
+
+from pySim.bip import Proact
+
+
+class _EchoServer:
+ """behold, my tiny threaded TCP echo server listening on 127.0.0.1:<port>"""
+ def __init__(self):
+ self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self._srv.bind(('127.0.0.1', 0))
+ self._srv.listen(1)
+ self.port = self._srv.getsockname()[1]
+ self.accepted = threading.Event()
+ self._conns = []
+ self._stop = False
+ threading.Thread(target=self._run, daemon=True).start()
+
+ def _run(self):
+ try:
+ conn, _ = self._srv.accept()
+ except OSError:
+ return
+ self._conns.append(conn)
+ self.accepted.set()
+ while not self._stop:
+ try:
+ data = conn.recv(4096)
+ except OSError:
+ break
+ if not data:
+ break
+ conn.sendall(data)
+
+ def close(self):
+ self._stop = True
+ for s in [self._srv] + self._conns:
+ try:
+ s.close()
+ except OSError:
+ pass
+
+
+def _pcmd(children_tlvs):
+ """Assemble D0 proactive-command TLV from child IE bytes,
+ decode it like transport does after a FETCH"""
+ body = b''.join(children_tlvs)
+ pdu = h2b('D0') + bytes([len(body)]) + body
+ return ProactiveCommand().from_tlv(pdu)
+
+
+def _open_channel(port, ip='127.0.0.1', cmd_nr=1):
+ a, b, c, d = (int(x) for x in ip.split('.'))
+ return _pcmd([
+ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'open_channel',
+ 'command_qualifier': 3}).to_tlv(),
+ DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': 'terminal'}).to_tlv(),
+ BearerDescription(decoded={'bearer_type': 'default', 'bearer_parameters': b''}).to_tlv(),
+ BufferSize(decoded=1024).to_tlv(),
+ UiccTransportLevel(decoded={'protocol_type': 'tcp_uicc_client_remote',
+ 'port_number': port}).to_tlv(),
+ OtherAddress(decoded={'type_of_address': 'ipv4',
+ 'address': bytes([a, b, c, d])}).to_tlv(),
+ ])
+
+
+def _send_data(payload, chan='channel_1', cmd_nr=1):
+ return _pcmd([
+ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'send_data',
+ 'command_qualifier': 1}).to_tlv(),
+ DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': chan}).to_tlv(),
+ ChannelData(decoded=b2h(payload)).to_tlv(),
+ ])
+
+
+def _receive_data(length, chan='channel_1', cmd_nr=1):
+ return _pcmd([
+ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'receive_data',
+ 'command_qualifier': 0}).to_tlv(),
+ DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': chan}).to_tlv(),
+ ChannelDataLength(decoded=length).to_tlv(),
+ ])
+
+
+def _close_channel(chan='channel_1', cmd_nr=1):
+ return _pcmd([
+ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'close_channel',
+ 'command_qualifier': 0}).to_tlv(),
+ DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': chan}).to_tlv(),
+ ])
+
+
+def _first(til, cls):
+ return next((x for x in til if isinstance(x, cls)), None)
+
+
+class BipRelayRoundTripTest(unittest.TestCase):
+ """Drive the fixed Proact handlers (blocking sockets) with synthetic
+ proactive commands against a local echo server and assert a byte round-trip
+ plus the channel bookkeeping / error handling."""
+
+ def setUp(self):
+ self.echo = _EchoServer()
+ self.addCleanup(self.echo.close)
+ self.events = []
+ self.proact = Proact(data_available_sink=self.events.append)
+ self.addCleanup(self._close_all_channels)
+
+ def _close_all_channels(self):
+ for chan in list(self.proact.channels.channels.values()):
+ try:
+ chan.close()
+ except Exception:
+ pass
+
+ def _open(self, cmd_nr=1):
+ til = self.proact.handle_OpenChannel(_open_channel(self.echo.port, cmd_nr=cmd_nr))
+ # every TLV in the response must serialise (the transport does exactly
+ # this to post the TERMINAL RESPONSE)
+ b''.join(x.to_tlv() for x in til)
+ return til
+
+ def test_open_send_receive_roundtrip(self):
+ # OPEN CHANNEL -> socket connected, channel 1 opened, link established
+ til = self._open()
+ self.assertTrue(self.echo.accepted.wait(timeout=2.0))
+ self.assertIn(1, self.proact.channels.channels)
+ cd = _first(til, CommandDetails)
+ self.assertEqual(cd.decoded['type_of_command'], 'open_channel')
+ # TS 102 223 6.8.2 TERMINAL RESPONSE device id: terminal -> UICC
+ self.assertEqual(b2h(_first(til, DeviceIdentities).to_tlv()), '82028281')
+ # channel status: channel 1, link established
+ self.assertEqual(_first(til, ChannelStatus).decoded, '8100')
+ self.assertEqual(_first(til, Result).decoded['general_result'], 'performed_successfully')
+
+ # SEND DATA -> bytes written to the socket, echo server sends them back
+ payload = b'Hello SCP81 relay - opaque TLS record bytes'
+ til = self.proact.handle_SendData(_send_data(payload))
+ b''.join(x.to_tlv() for x in til)
+ # channel data length in the response = free Tx space, FF = ">255"
+ self.assertEqual(_first(til, ChannelDataLength).decoded, 255)
+ self.assertEqual(_first(til, Result).decoded['general_result'], 'performed_successfully')
+
+ # RECEIVE DATA -> drain the bytes back to the "card". real card
+ # uses data-available event, we poll the buffer
+ # and may need several RECEIVE DATA commands, as the spec allows.
+ got = bytearray()
+ deadline = time.monotonic() + 3.0
+ while len(got) < len(payload) and time.monotonic() < deadline:
+ chan = self.proact.channels.channels[1]
+ chan.wait_rx(1.0)
+ til = self.proact.handle_ReceiveData(_receive_data(len(payload) - len(got)))
+ b''.join(x.to_tlv() for x in til)
+ self.assertEqual(b2h(_first(til, DeviceIdentities).to_tlv()), '82028281')
+ got += h2b(_first(til, ChannelData).decoded)
+ self.assertEqual(bytes(got), payload, "byte round-trip through the BIP relay")
+
+ # CLOSE CHANNEL -> socket closed, bookkeeping cleared
+ til = self.proact.handle_CloseChannel(_close_channel())
+ b''.join(x.to_tlv() for x in til)
+ self.assertEqual(_first(til, Result).decoded['general_result'], 'performed_successfully')
+ self.assertNotIn(1, self.proact.channels.channels)
+
+ def test_data_available_event_envelope(self):
+ # The empty->non-empty Rx transition raises ENVELOPE EVENT DOWNLOAD
+ self._open()
+ self.assertTrue(self.echo.accepted.wait(timeout=2.0))
+ payload = b'PONG'
+ self.proact.handle_SendData(_send_data(payload))
+ chan = self.proact.channels.channels[1]
+ self.assertGreater(chan.wait_rx(2.0), 0)
+ # give the reader thread a beat to invoke the sink
+ deadline = time.monotonic() + 2.0
+ while not self.events and time.monotonic() < deadline:
+ time.sleep(0.01)
+ self.assertEqual(len(self.events), 1, "one data-available event on the empty->non-empty edge")
+ env = h2b(self.events[0])
+ # d6 0e | 99 01 09 (event: data available) | 82 02 82 81 terminal->UICC
+ # | b8 02 81 00 (channel 1 established) | b7 01 XX bytes available
+ self.assertEqual(b2h(env[:15]), 'd60e99010982028281b8028100b701')
+ self.assertGreaterEqual(env[15], 1)
+ self.assertLessEqual(env[15], len(payload))
+
+ def test_channel_number_from_device_identities(self):
+ # Two channels, not the old hardcoded 1
+ e2 = _EchoServer()
+ self.addCleanup(e2.close)
+ self.proact.handle_OpenChannel(_open_channel(self.echo.port))
+ # open a second channel with a second echo server
+ til2 = self.proact.handle_OpenChannel(_open_channel(e2.port))
+ self.assertEqual(sorted(self.proact.channels.channels), [1, 2])
+ self.assertEqual(_first(til2, ChannelStatus).decoded, '8200') # channel 2, established
+
+ # SEND DATA addressed to channel_2 must reach the second socket
+ self.assertTrue(e2.accepted.wait(timeout=2.0))
+ self.proact.handle_SendData(_send_data(b'two', chan='channel_2'))
+ chan2 = self.proact.channels.channels[2]
+ self.assertGreater(chan2.wait_rx(2.0), 0)
+ til = self.proact.handle_ReceiveData(_receive_data(3, chan='channel_2'))
+ self.assertEqual(h2b(_first(til, ChannelData).decoded), b'two')
+ # ..and nothing on chan 1
+ self.assertEqual(self.proact.channels.channels[1].available_rx(), 0)
+
+ def test_commands_on_closed_channel_report_bip_error(self):
+ # SEND/RECEIVE/CLOSE on a channel that was never opened must be rejected
+ # with a BIP error
+ for til in (self.proact.handle_SendData(_send_data(b'x', chan='channel_4')),
+ self.proact.handle_ReceiveData(_receive_data(1, chan='channel_4')),
+ self.proact.handle_CloseChannel(_close_channel(chan='channel_4'))):
+ b''.join(x.to_tlv() for x in til)
+ res = _first(til, Result).decoded
+ self.assertEqual(res['general_result'], 'bearer_independent_protocol_error')
+ self.assertEqual(res['additional_information'], 'channel_id_not_valid')
+
+ def test_receive_more_than_available_is_missing_info(self):
+ # terminal must NOT wait if fewer than the requested bytes are buffered,
+ # eturns what it has with "performed with missing information".
+ self._open()
+ self.assertTrue(self.echo.accepted.wait(timeout=2.0))
+ til = self.proact.handle_ReceiveData(_receive_data(10))
+ b''.join(x.to_tlv() for x in til)
+ self.assertEqual(_first(til, Result).decoded['general_result'],
+ 'performed_with_missing_information')
+ self.assertEqual(h2b(_first(til, ChannelData).decoded), b'')
+ self.assertEqual(_first(til, ChannelDataLength).decoded, 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
class BipSinkTest(unittest.TestCase):
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43545?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: If96c768f2e35c20ea3753e601059410121517b60
Gerrit-Change-Number: 43545
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: daniel <dwillmann(a)sysmocom.de>
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[M] Change in pysim[master]: bip/smpp2sim: TERMINAL PROFILE that matches what we do
by Hoernchen 25 Sep '26
by Hoernchen 25 Sep '26
25 Sep '26
Attention is currently required from: dexter, laforge.
Hoernchen has posted comments on this change by Hoernchen. ( https://gerrit.osmocom.org/c/pysim/+/43564?usp=email )
Change subject: bip/smpp2sim: TERMINAL PROFILE that matches what we do
......................................................................
Patch Set 3: Code-Review+2
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43564?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: comment
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I91a60760fc3ad816b7385da8b26ec7330b462abd
Gerrit-Change-Number: 43564
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Attention: laforge <laforge(a)osmocom.org>
Gerrit-Attention: dexter <pmaier(a)sysmocom.de>
Gerrit-Comment-Date: Fri, 25 Sep 2026 12:55:32 +0000
Gerrit-HasComments: No
Gerrit-Has-Labels: Yes
1
0