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
[S] Change in pysim[master]: saip: fix key usage qualifier of helper created SD keys
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43723?usp=email )
Change subject: saip: fix key usage qualifier of helper created SD keys
......................................................................
saip: fix key usage qualifier of helper created SD keys
SD_KEY_DEFS holds the GP Key Usage Qualifier as its encoded octet,
SecurityDomainKey expects the decoded FlagsEnum dict. Passing the int
encoded a 0 qualifier for every newly created key...
Change-Id: I4a94562d6052c6796929b81b1f9b9ce5b56dcd20
---
M pySim/esim/saip/personalization.py
M tests/unittests/test_esim_saip.py
2 files changed, 19 insertions(+), 1 deletion(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/23/43723/1
diff --git a/pySim/esim/saip/personalization.py b/pySim/esim/saip/personalization.py
index 6f88d52..2d6379e 100644
--- a/pySim/esim/saip/personalization.py
+++ b/pySim/esim/saip/personalization.py
@@ -749,10 +749,11 @@
key = pe.find_key(key_version_number=cls.kvn, key_id=cls.key_id)
if not key:
# Could not find matching key to patch, create a new one
+ key_usage_qualifier = KeyUsageQualifier.parse(bytes([cls.key_usage_qual]))
key = SecurityDomainKey(
key_version_number=cls.kvn,
key_id=cls.key_id,
- key_usage_qualifier=cls.key_usage_qual,
+ key_usage_qualifier=key_usage_qualifier,
key_components=set_components,
)
pe.add_key(key)
diff --git a/tests/unittests/test_esim_saip.py b/tests/unittests/test_esim_saip.py
index 75a38f4..5bac25d 100755
--- a/tests/unittests/test_esim_saip.py
+++ b/tests/unittests/test_esim_saip.py
@@ -22,6 +22,7 @@
from pySim.esim.saip import *
from pySim.esim.saip import personalization
+from pySim.global_platform import KeyUsageQualifier
from pprint import pprint as pp
@@ -105,6 +106,22 @@
print(f'{get_val2=} {set_val=}')
self.assertEqual(get_val2, ({cls.name: set_val},))
+ def test_sd_key_personalization_creates_usage_qualifier(self):
+ """helper created key qualifier must match"""
+ pes = ProfileElementSequence()
+ pes.append(ProfileElementHeader())
+ pes.append(ProfileElementSD())
+ pes.append(ProfileElementEnd())
+
+ cls = personalization.SdKeyScp02Kvn20AesEnc
+ cls('00112233445566778899aabbccddeeff').apply(pes)
+ key = pes.get_pe_for_type('securityDomain').find_key(0x20, 0x01)
+ self.assertEqual(KeyUsageQualifier.build(key.key_usage_qualifier), b'\x18')
+
+ round_trip = ProfileElementSequence.from_der(pes.to_der())
+ key = round_trip.get_pe_for_type('securityDomain').find_key(0x20, 0x01)
+ self.assertEqual(KeyUsageQualifier.build(key.key_usage_qualifier), b'\x18')
+
def test_constructor_encode(self):
"""Test that DER-encoding of PE created by "empty" constructor works without raising exception."""
for cls in [ProfileElementMF, ProfileElementPuk, ProfileElementPin, ProfileElementTelecom,
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43723?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I4a94562d6052c6796929b81b1f9b9ce5b56dcd20
Gerrit-Change-Number: 43723
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43725?usp=email )
Change subject: euicc: fix profile reset DER encoding
......................................................................
euicc: fix profile reset DER encoding
ResetOptions is an ASN.1 BIT STRING, DER encodes it with the unused
bit count first and trailing zero bits stripped, so
deleteOperationalProfiles alone is 07 80, not plain 80 produced by
FlagsEnum(Byte).
Why does this look so fancy? Well, construct has no DER BIT STRING
primitive, and the flat decoded dict ({'deleteOperationalProfiles': True, ...})
that the shell euicc_memory_reset passes has to survive, so something must
flatten the unused bit prefix.
Change-Id: I318ea7b08bad9e0b34b14929ef750151f4c5fa4e
---
M pySim/euicc.py
M tests/unittests/test_euicc.py
2 files changed, 59 insertions(+), 4 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/25/43725/1
diff --git a/pySim/euicc.py b/pySim/euicc.py
index 0a6c054..fdcb9e8 100644
--- a/pySim/euicc.py
+++ b/pySim/euicc.py
@@ -25,7 +25,8 @@
import argparse
-from construct import Array, Struct, FlagsEnum, GreedyRange
+from construct import Array, Struct, FlagsEnum, GreedyRange, Adapter, Byte, Int8ub
+from construct import Optional as COptional
from cmd2 import cmd2, CommandSet, with_default_category
from osmocom.utils import Hexstr
from osmocom.tlv import *
@@ -288,11 +289,32 @@
pass
# SGP.22 Section 5.7.19: EuiccMemoryReset
+class DerNamedBitString(Adapter):
+ """ASN.1 DER named BIT STRING over a FlagsEnum(Byte): the count of unused bits comes first,
+ trailing zero bits are stripped, all bits clear is the single octet 00."""
+ def __init__(self, flags: FlagsEnum):
+ super().__init__(Struct('unused'/Int8ub, 'value'/COptional(Byte)))
+ self.flags = flags
+
+ def _decode(self, obj, context, path):
+ if obj.value is None:
+ return self.flags.parse(b'\x00')
+ if obj.unused > 7 or obj.value & ((1 << obj.unused) - 1):
+ raise ValueError('invalid DER BIT STRING padding')
+ return self.flags.parse(bytes([obj.value]))
+
+ def _encode(self, obj, context, path):
+ value = self.flags.build(obj)[0]
+ if not value:
+ return {'unused': 0, 'value': None}
+ return {'unused': (value & -value).bit_length() - 1, 'value': value}
+
+ResetOptionsFlags = FlagsEnum(Byte, deleteOperationalProfiles=0x80, deleteFieldLoadedTestProfiles=0x40,
+ resetDefaultSmdpAddress=0x20)
class ResetOptions(BER_TLV_IE, tag=0x82):
- _construct = FlagsEnum(Byte, deleteOperationalProfiles=0x80, deleteFieldLoadedTestProfiles=0x40,
- resetDefaultSmdpAddress=0x20)
+ _construct = DerNamedBitString(ResetOptionsFlags)
class ResetResult(BER_TLV_IE, tag=0x80):
- _construct = Enum(Int8ub, ok=0, nothingToDelete=1, undefinedError=127)
+ _construct = Enum(Int8ub, ok=0, nothingToDelete=1, catBusy=5, undefinedError=127)
class EuiccMemoryResetReq(BER_TLV_IE, tag=0xbf34, nested=[ResetOptions]):
pass
class EuiccMemoryResetResp(BER_TLV_IE, tag=0xbf34, nested=[ResetResult]):
diff --git a/tests/unittests/test_euicc.py b/tests/unittests/test_euicc.py
index 29c66ea..918d888 100755
--- a/tests/unittests/test_euicc.py
+++ b/tests/unittests/test_euicc.py
@@ -27,5 +27,38 @@
self.assertEqual(compute_eid_checksum('89049032123451234512345678901299'), '89049032123451234512345678901235')
self.assertEqual(compute_eid_checksum(89049032123451234512345678901299), '89049032123451234512345678901235')
+class TestResetOptions(unittest.TestCase):
+
+ def test_der_named_bit_string_encodings(self):
+ cases = (
+ ({}, 'bf3403820100'),
+ ({'deleteOperationalProfiles': True}, 'bf340482020780'),
+ ({'deleteFieldLoadedTestProfiles': True}, 'bf340482020640'),
+ ({'resetDefaultSmdpAddress': True}, 'bf340482020520'),
+ ({'deleteOperationalProfiles': True,
+ 'deleteFieldLoadedTestProfiles': True}, 'bf3404820206c0'),
+ ({'deleteOperationalProfiles': True,
+ 'resetDefaultSmdpAddress': True}, 'bf3404820205a0'),
+ ({'deleteFieldLoadedTestProfiles': True,
+ 'resetDefaultSmdpAddress': True}, 'bf340482020560'),
+ ({'deleteOperationalProfiles': True,
+ 'deleteFieldLoadedTestProfiles': True,
+ 'resetDefaultSmdpAddress': True}, 'bf3404820205e0'),
+ )
+ for decoded, expected in cases:
+ with self.subTest(decoded=decoded):
+ encoded = EuiccMemoryResetReq(children=[ResetOptions(decoded=decoded)]).to_tlv()
+ self.assertEqual(encoded.hex(), expected)
+ parsed = EuiccMemoryResetReq()
+ parsed.from_tlv(encoded)
+ actual = parsed.children[0].decoded
+ for name in ResetOptionsFlags.flags:
+ self.assertEqual(actual[name], decoded.get(name, False))
+
+ def test_cat_busy_result(self):
+ reset = EuiccMemoryResetResp()
+ reset.from_tlv(bytes.fromhex('bf3403800105'))
+ self.assertEqual(reset.children[0].decoded, 'catBusy')
+
if __name__ == "__main__":
unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43725?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I318ea7b08bad9e0b34b14929ef750151f4c5fa4e
Gerrit-Change-Number: 43725
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43726?usp=email )
Change subject: pySim-shell: enable apdu_strict by default
......................................................................
pySim-shell: enable apdu_strict by default
I think it's time to tame the wild west of mixed tpdu/apdu commands.
Change-Id: Ic413e12e2792e8cd9d455b1b0d6791bdf757c80e
---
M pySim-shell.py
M tests/pySim-shell_test/apdu/test_apdu_legacy.script
M tests/pySim-shell_test/apdu/test_apdu_legacy_scp02.template
M tests/pySim-shell_test/apdu/test_apdu_legacy_scp03.template
4 files changed, 4 insertions(+), 8 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/26/43726/1
diff --git a/pySim-shell.py b/pySim-shell.py
index 3a0dedd..0169f38 100755
--- a/pySim-shell.py
+++ b/pySim-shell.py
@@ -102,7 +102,7 @@
self.conserve_write = True
self.json_pretty_print = True
self.apdu_trace = getattr(sl, 'apdu_tracer', None) is not None
- self.apdu_strict = False
+ self.apdu_strict = True
self.add_settable(cmd2.Settable('numeric_path', bool,
'Print File IDs instead of names',
@@ -266,13 +266,6 @@
tracked. Depending on the raw APDU sent, pySim-shell may not continue to work as expected if you e.g. select
a different file."""
- if not hasattr(self, 'apdu_strict_warning_displayed') and self.apdu_strict is False:
- self.poutput("Warning: The default for the setable parameter `apdu_strict` will be changed from")
- self.poutput(" `False` to `True` in future pySim-shell releases. In case you are using")
- self.poutput(" the `apdu` command from a script that still mixes APDUs with TPDUs, consider")
- self.poutput(" fixing or adding a `set apdu_strict false` line at the beginning.")
- self.apdu_strict_warning_displayed = True;
-
# When sending raw APDUs we access the scc object through _scc member of the card object. It should also be
# noted that the apdu command plays an exceptional role since it is the only card accessing command that
# can be executed without the presence of a runtime state (self.rs) object. However, this also means that
diff --git a/tests/pySim-shell_test/apdu/test_apdu_legacy.script b/tests/pySim-shell_test/apdu/test_apdu_legacy.script
index c3dfb1b..2359e51 100644
--- a/tests/pySim-shell_test/apdu/test_apdu_legacy.script
+++ b/tests/pySim-shell_test/apdu/test_apdu_legacy.script
@@ -1,6 +1,7 @@
set debug true
set echo true
set apdu_trace true
+set apdu_strict false
# Case #1: (open channel #1)
# No command data field, No response data field present
diff --git a/tests/pySim-shell_test/apdu/test_apdu_legacy_scp02.template b/tests/pySim-shell_test/apdu/test_apdu_legacy_scp02.template
index 51497ed..92e402b 100644
--- a/tests/pySim-shell_test/apdu/test_apdu_legacy_scp02.template
+++ b/tests/pySim-shell_test/apdu/test_apdu_legacy_scp02.template
@@ -1,6 +1,7 @@
set debug true
set echo true
set apdu_trace true
+set apdu_strict false
# Establish secure channel:
select ADF.ISD
diff --git a/tests/pySim-shell_test/apdu/test_apdu_legacy_scp03.template b/tests/pySim-shell_test/apdu/test_apdu_legacy_scp03.template
index b41620b..bdfa861 100644
--- a/tests/pySim-shell_test/apdu/test_apdu_legacy_scp03.template
+++ b/tests/pySim-shell_test/apdu/test_apdu_legacy_scp03.template
@@ -1,6 +1,7 @@
set debug true
set echo true
set apdu_trace true
+set apdu_strict false
# Establish secure channel:
select ADF.ISD-R
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43726?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ic413e12e2792e8cd9d455b1b0d6791bdf757c80e
Gerrit-Change-Number: 43726
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
[M] Change in pysim[master]: global_platform: add tracked security domain selection
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43724?usp=email )
Change subject: global_platform: add tracked security domain selection
......................................................................
global_platform: add tracked security domain selection
select_security_domain <aid> does SELECT by AID and models the result as an
ADF_SD, so the GP commands, prompt and CardKeyProvider identity work.
Plain select cannot do this: probe_file() classifies by the ISO FCP, an
application answers with a GP FCI, and whether that FCI belongs to a
Security Domain is not obvious (GPC 11.9.3.1 table 11-56 tag 73 is
optional, the sysmoEUICC1 omits it).
The CardKeyProvider identity (ICCID vs EID) used for csv
lookup of credentials is (obviously) not part of the answer at all.
This new command makes using the eUICC with MNO-SDs and SSDs easier,
because so far we only had raw apdus to select those that led to a
confused internal pysim state, i.e. install_cap after selecting like
that would try to install to the ISD-R.
Change-Id: I7c6dda0f11dc6bb175f05b3832cf49691089c297
---
M docs/put_key-tutorial.rst
M docs/shell.rst
M pySim/global_platform/__init__.py
M tests/unittests/test_globalplatform.py
4 files changed, 219 insertions(+), 12 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/24/43724/1
diff --git a/docs/put_key-tutorial.rst b/docs/put_key-tutorial.rst
index fe49729..8585167 100644
--- a/docs/put_key-tutorial.rst
+++ b/docs/put_key-tutorial.rst
@@ -44,10 +44,10 @@
`MNO-SD` is either the default AID for the Issuer Security Domain (see also GlobalPlatform, section H.1.3) or a
different value specified by the provider of the eSIM profile.
-Since the AID of the `MNO-SD` is not a fixed value, it is not known by `pySim-shell`. This means there will be no
-`ADF.ISD` file shown in the file system, but we can simply select the `ADF.ISD-R` first and then select the `MNO-SD`
-using a raw APDU. In the following example we assume that the default AID (``a000000151000000``) is used The APDU
-would look like this: ``00a4040408`` + ``a000000151000000`` + ``00``
+Since the AID of the `MNO-SD` is not a fixed value, it is not part of pySim's static card profile. Select a known
+Security Domain such as `ADF.ISD-R` first to make the GlobalPlatform commands available, then use
+``select_security_domain`` with the MNO-SD AID. Do not select it with a raw ``apdu``, that desyncs pySim's internal
+card model. In the following example we assume that the default AID (``a000000151000000``) is used.
::
@@ -61,14 +61,55 @@
"supported_version_number": "020300"
}
}
- pySIM-shell (00:MF/ADF.ISD-R)> apdu 00a4040408a00000015100000000
- SW: 9000, RESP: 6f108408a000000151000000a5049f6501ff
+ pySIM-shell (00:MF/ADF.ISD-R)> select_security_domain a000000151000000
+ CardKeyProvider identity: ICCID
+ {
+ "application_id": "a000000151000000",
+ "proprietary_data": {
+ "maximum_length_of_data_field_in_command_message": 255
+ }
+ }
-After that, the prompt will still show the `ADF.ISD-R`, but we are actually in `ADF.ISD` and the standard GlobalPlatform
-operations like `establish_scpXX`, `get_data`, and `put_key` should work. By doing this, we simply have tricked
-`pySim-shell` into making the GlobalPlatform related commands available for some other Security Domain we are not
-interested in. With the raw APDU we then have swapped out the Security Domain under the hood. The same workaround can
-be applied to any Security Domain, provided that the AID is known to the user.
+The dynamically discovered Security Domain uses the profile ICCID for CardKeyProvider lookup by default, which is
+appropriate for an MNO-SD. Use ``--key-provider-identity EID`` for an eUICC-global Security Domain instead. The command
+must be used before establishing SCP; use ``release_scp`` before switching away from a Security Domain with an active
+SCP session. If the enabled profile changes during the shell session, re-equip the card before selecting its MNO-SD;
+different profiles commonly reuse the same MNO-SD AID, while their key lookup is tied to the profile ICCID.
+
+Selecting a Supplementary Security Domain (SSD)
+------------------------------------------------
+
+``select_security_domain`` is not limited to an MNO-SD. It can also select a Supplementary Security Domain (SSD),
+provided that the SSD is in a selectable life-cycle state. An SSD frequently has no filesystem alias and need not be
+listed in ``EF.DIR``; select it using its instance AID.
+
+The SSD AID can be obtained from the profile or installation data. It can also be discovered with
+``get_status applications`` while operating through its controlling Security Domain. Look for an application registry
+entry with the ``security_domain`` privilege and a selectable life-cycle state.
+
+The following example assumes that an SSD with AID ``a000000151000042`` was created beneath the active profile's
+MNO-SD. Any SCP session with the MNO-SD must first be released. Selecting the SSD does not carry the parent's secure
+channel into the SSD: establish a new secure channel using the SSD's own keyset afterwards.
+
+::
+
+ pySIM-shell (SCP03[03]:00:MF/ADF.SD-A000000151000000)> get_status applications
+ # Locate the selectable registry entry with the security_domain privilege.
+ pySIM-shell (SCP03[03]:00:MF/ADF.SD-A000000151000000)> release_scp
+ pySIM-shell (00:MF/ADF.SD-A000000151000000)> select_security_domain a000000151000042
+ CardKeyProvider identity: ICCID
+ {
+ "application_id": "a000000151000042"
+ }
+ pySIM-shell (00:MF/ADF.SD-A000000151000042)> establish_scp03 --key-ver 1 --key-enc <SSD-ENC> --key-mac <SSD-MAC> --key-dek <SSD-DEK> --security-level 3
+
+For a newly installed SSD, ``install_for_install --privilege security_domain --make-selectable`` creates it as a
+selectable Security Domain. If SELECT-by-AID fails because the SSD is not selectable, it must first be moved to the
+appropriate life-cycle state through its controlling Security Domain. Remote administration that targets an SSD by
+AID (for example through SCP81) is a separate mechanism and does not imply that contact-interface SELECT is enabled.
+
+As with an MNO-SD, profile-scoped SSD key lookup normally uses the default ``ICCID`` identity. Use
+``--key-provider-identity EID`` only when the SSD's keys are associated with the eUICC rather than the enabled profile.
Establishing a secure channel
@@ -135,7 +176,7 @@
::
- pySIM-shell (00:MF/ADF.ISD-R)> establish_scp03 --key-enc 63af517c29ad6ac6fcadfe6ac8a3c8a041d8141c7eb845ef1cba6112a325e430 --key-mac 54b9ad6713ae922f54014ed762132e7b59bdcd2a2a6beba98fb9afe6b4df27e1 --key-dek cbb933ba2389da93c86c112739cd96389139f16c6f80f7d16bf3593e407ca893 --key-ver 48 --security-level 3
+ pySIM-shell (00:MF/ADF.SD-A000000151000000)> establish_scp03 --key-enc 63af517c29ad6ac6fcadfe6ac8a3c8a041d8141c7eb845ef1cba6112a325e430 --key-mac 54b9ad6713ae922f54014ed762132e7b59bdcd2a2a6beba98fb9afe6b4df27e1 --key-dek cbb933ba2389da93c86c112739cd96389139f16c6f80f7d16bf3593e407ca893 --key-ver 48 --security-level 3
Successfully established a SCP03[03] secure channel
diff --git a/docs/shell.rst b/docs/shell.rst
index 0dc00ba..53e55d1 100644
--- a/docs/shell.rst
+++ b/docs/shell.rst
@@ -1030,6 +1030,12 @@
pySim-shell has only the mots rudimentary support for GlobalPlatform at this point. Please use dedicated
projects like GlobalPlatformPro meanwhile.
+select_security_domain
+~~~~~~~~~~~~~~~~~~~~~~
+.. argparse::
+ :module: pySim.global_platform
+ :func: ADF_SD.AddlShellCommands.select_sd_parser
+
get_data
~~~~~~~~
.. argparse::
diff --git a/pySim/global_platform/__init__.py b/pySim/global_platform/__init__.py
index 9600c7c..854e73b 100644
--- a/pySim/global_platform/__init__.py
+++ b/pySim/global_platform/__init__.py
@@ -609,6 +609,57 @@
@with_default_category('Application-Specific Commands')
class AddlShellCommands(CommandSet):
+ select_sd_parser = argparse.ArgumentParser()
+ select_sd_parser.add_argument('aid', type=is_hexstr,
+ help='AID of the Security Domain')
+ select_sd_parser.add_argument('--key-provider-identity', choices=['ICCID', 'EID'],
+ help='CardKeyProvider identity for this Security Domain; '
+ 'default: retain it for a known SD, otherwise ICCID')
+
+ @cmd2.with_argparser(select_sd_parser)
+ def do_select_security_domain(self, opts):
+ """Select a Security Domain by AID, e.g. the MNO-SD of an eUICC profile, and
+ add it to the runtime card model so the GP commands and key lookup follow."""
+ # select() unregisters this CommandSet, self._cmd is gone afterwards
+ cmd_app = self._cmd
+ lchan = cmd_app.lchan
+ if lchan.scc.scp:
+ raise RuntimeError('Cannot select another Security Domain while an SCP session is active; '
+ 'use release_scp first')
+
+ aid = opts.aid.lower()
+ if not 10 <= len(aid) <= 32:
+ raise ValueError('A Security Domain AID must be between 5 and 16 bytes')
+ mf = cmd_app.rs.mf
+ adf = mf.applications.get(aid)
+ added = False
+ if adf is None:
+ app = CardApplicationSD(aid=aid,
+ name='ADF.SD-' + aid.upper(),
+ desc='Runtime-discovered Security Domain')
+ adf = app.adf
+ adf.scp_key_identity = opts.key_provider_identity or 'ICCID'
+ mf.add_application_df(adf)
+ added = True
+ elif not isinstance(adf, ADF_SD):
+ raise ValueError('Application %s is already known, but is not modelled as a Security Domain' % aid)
+
+ try:
+ fcp_dec = lchan.select(aid, cmd_app)
+ except Exception:
+ if added:
+ # clean up on rejected select
+ mf.applications.pop(aid, None)
+ adf.parent = None
+ raise
+
+ if not added and opts.key_provider_identity:
+ adf.scp_key_identity = opts.key_provider_identity
+ cmd_app.update_prompt()
+ cmd_app.poutput('CardKeyProvider identity: %s' %
+ (adf.scp_key_identity or 'not configured'))
+ cmd_app.poutput_json(fcp_dec)
+
get_data_parser = argparse.ArgumentParser()
get_data_parser.add_argument('data_object_name', type=str,
help='Name of the data object to be retrieved from the card')
diff --git a/tests/unittests/test_globalplatform.py b/tests/unittests/test_globalplatform.py
index d329c45..89f484f 100644
--- a/tests/unittests/test_globalplatform.py
+++ b/tests/unittests/test_globalplatform.py
@@ -31,6 +31,115 @@
KIK = h2b('102102030405060708090a0b0c0d0e0f') # DEK
ck_3des_70 = GpCardKeyset(0x20, KIC, KID, KIK)
+
+class SelectSecurityDomain_Test(unittest.TestCase):
+ class _FakeMf:
+ def __init__(self):
+ self.applications = {}
+
+ def add_application_df(self, adf):
+ if adf.aid in self.applications:
+ raise ValueError('duplicate AID')
+ self.applications[adf.aid] = adf
+ adf.parent = self
+
+ class _FakeLchan:
+ def __init__(self, mf, fail_select=False):
+ self.rs = SimpleNamespace(mf=mf)
+ self.scc = SimpleNamespace(scp=None)
+ self.fail_select = fail_select
+ self.select_calls = []
+ self.selected_file = None
+ self.selected_adf = None
+ self.selected_file_fcp = None
+
+ def select(self, aid, cmd):
+ self.select_calls.append((aid, cmd))
+ if self.fail_select:
+ raise RuntimeError('SELECT failed')
+ self.selected_file = self.rs.mf.applications[aid]
+ self.selected_adf = self.selected_file
+ self.selected_file_fcp = {'application_id': aid}
+ return self.selected_file_fcp
+
+ def _run(self, aid='a000000151000000', key_provider_identity=None,
+ mf=None, fail_select=False, scp=None, lose_selector_cmd=False):
+ mf = mf or self._FakeMf()
+ lchan = self._FakeLchan(mf, fail_select=fail_select)
+ lchan.scc.scp = scp
+ output = []
+ cmd = SimpleNamespace(
+ lchan=lchan,
+ rs=lchan.rs,
+ update_prompt=lambda: output.append(('prompt',)),
+ poutput=lambda value: output.append(('text', value)),
+ poutput_json=lambda value: output.append(('json', value)),
+ )
+ if lose_selector_cmd:
+ # make sure cmd survives unregistering
+ class Selector(ADF_SD.AddlShellCommands):
+ @property
+ def _cmd(self):
+ if lchan.selected_file is not None:
+ raise RuntimeError('CommandSet was unregistered')
+ return cmd
+ else:
+ Selector = type('Selector', (ADF_SD.AddlShellCommands,), {'_cmd': cmd})
+ selector = Selector.__new__(Selector)
+ opts = SimpleNamespace(aid=aid, key_provider_identity=key_provider_identity)
+ ADF_SD.AddlShellCommands.do_select_security_domain.__wrapped__(selector, opts)
+ return mf, lchan, output
+
+ def test_new_security_domain_is_selected_and_tracked(self):
+ mf, lchan, output = self._run()
+ adf = mf.applications['a000000151000000']
+ self.assertIsInstance(adf, ADF_SD)
+ self.assertEqual(adf.scp_key_identity, 'ICCID')
+ self.assertIs(lchan.selected_file, adf)
+ self.assertIs(lchan.selected_adf, adf)
+ self.assertEqual(output[-1], ('json', {'application_id': 'a000000151000000'}))
+
+ def test_success_survives_executing_command_set_being_unregistered(self):
+ _mf, lchan, output = self._run(lose_selector_cmd=True)
+ self.assertEqual(lchan.selected_file_fcp,
+ {'application_id': 'a000000151000000'})
+ self.assertEqual(output[-1], ('json', lchan.selected_file_fcp))
+
+ def test_explicit_key_provider_identity(self):
+ mf, _lchan, _output = self._run(key_provider_identity='EID')
+ self.assertEqual(mf.applications['a000000151000000'].scp_key_identity, 'EID')
+
+ def test_known_security_domain_retains_identity_by_default(self):
+ mf = self._FakeMf()
+ app = CardApplicationSD('a000000151000000', 'ADF.TEST-SD', 'Test SD')
+ app.adf.scp_key_identity = 'EID'
+ mf.add_application_df(app.adf)
+ self._run(mf=mf)
+ self.assertEqual(app.adf.scp_key_identity, 'EID')
+
+ def test_active_scp_is_rejected(self):
+ mf = self._FakeMf()
+ with self.assertRaisesRegex(RuntimeError, 'release_scp'):
+ self._run(mf=mf, scp=object())
+ self.assertEqual(mf.applications, {})
+
+ def test_invalid_aid_length_is_rejected(self):
+ with self.assertRaisesRegex(ValueError, 'between 5 and 16 bytes'):
+ self._run(aid='01020304')
+
+ def test_failed_select_is_not_retained(self):
+ mf = self._FakeMf()
+ with self.assertRaises(RuntimeError):
+ self._run(mf=mf, fail_select=True)
+ self.assertEqual(mf.applications, {})
+
+ def test_parser_accepts_security_domain_aid(self):
+ opts = ADF_SD.AddlShellCommands.select_sd_parser.parse_args(
+ ['a000000151000000', '--key-provider-identity', 'EID'])
+ self.assertEqual(opts.aid, 'a000000151000000')
+ self.assertEqual(opts.key_provider_identity, 'EID')
+
+
class SCP02_Auth_Test(unittest.TestCase):
host_challenge = h2b('40A62C37FA6304F8')
init_update_resp = h2b('00000000000000000000700200016B4524ABEE7CF32EA3838BC148F3')
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43724?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I7c6dda0f11dc6bb175f05b3832cf49691089c297
Gerrit-Change-Number: 43724
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
[M] Change in pysim[master]: pySim-shell: verify apdu commands in scripts and -e options up front
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43727?usp=email )
Change subject: pySim-shell: verify apdu commands in scripts and -e options up front
......................................................................
pySim-shell: verify apdu commands in scripts and -e options up front
Statically verify -e parameters and scripts so we don't end up with half
executed command chains that leave the card in a weird state due to
malformed commands. This is a structural check, and not a strict mode
linter, it will not magically fix a case 4 with missing Le that looks
like a valid case 3!
run_script, bulk_script and the @ / @@ shortcuts are followed
recursively, aliases and macros are not resolved.
Change-Id: Ida84b982d7577faa5b37f121599a59bcb2feefec
---
M pySim-shell.py
A tests/unittests/test_shell_startup_verify.py
2 files changed, 195 insertions(+), 0 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/27/43727/1
diff --git a/pySim-shell.py b/pySim-shell.py
index 0169f38..a7e22e1 100755
--- a/pySim-shell.py
+++ b/pySim-shell.py
@@ -61,6 +61,9 @@
from pySim.exceptions import *
from pySim.transport import init_reader, ApduTracer, argparse_add_reader_args, ProactiveHandler
from pySim.utils import sanitize_pin_adm, tabulate_str_list, boxed_heading_str, dec_iccid, sw_match
+from pySim.utils import parse_command_apdu
+import contextlib
+import shlex
from pySim.card_handler import CardHandler, CardHandlerAuto
from pySim.filesystem import CardMF, CardEF, CardDF, CardADF, LinFixedEF, TransparentEF, BerTlvEF
@@ -1106,6 +1109,86 @@
# TODO: implement the basics, such as SMS Sending, ...
+def verify_startup_apdus(commands: List[tuple]) -> List[str]:
+ """Statically verify the apdu commands among the given startup commands before anything
+ is executed. A structurally invalid APDU (bad hex, Lc contradicting the length of the
+ data field) raises in the transport layer whatever apdu_strict says, so with scripts or
+ stacked -e options it would abort the run midway, after the preceding commands already
+ ran against the card. run_script, bulk_script and the @ / @@ shortcuts are followed and
+ their lines verified the same way. Aliases and macros are not resolved.
+
+ Args:
+ commands : list of (location, command line) tuples
+ Returns:
+ list of human readable findings, empty when all lines pass
+ """
+ findings = []
+ visited_scripts = set()
+ run_script_parser = cmd2.Cmd._build_run_script_parser()
+
+ def split_line(line: str) -> List[str]:
+ try:
+ return shlex.split(line)
+ except ValueError:
+ return line.split()
+
+ def parse_args(loc: str, line: str, parser, args: List[str]):
+ """argparse exits on error and on --help, report both as a finding"""
+ out = StringIO()
+ try:
+ with contextlib.redirect_stderr(out), contextlib.redirect_stdout(out):
+ return parser.parse_args(args)
+ except SystemExit:
+ lines = out.getvalue().strip().splitlines()
+ findings.append('%s: "%s": %s' % (loc, line, lines[-1] if lines else 'invalid arguments'))
+ return None
+
+ def check_line(loc: str, line: str, base_dir: str):
+ tokens = split_line(line.strip())
+ if not tokens or tokens[0].startswith('#'):
+ return
+ if tokens[0].startswith('@'):
+ # cmd2 shortcuts: @ is run_script, @@ is run_script relative to the current script
+ relative = tokens[0].startswith('@@')
+ rest = tokens[0].lstrip('@')
+ tokens = ['run_script'] + ([rest] if rest else []) + tokens[1:]
+ if not relative:
+ base_dir = os.getcwd()
+ if tokens[0] == 'run_script':
+ opts = parse_args(loc, line, run_script_parser, tokens[1:])
+ if opts:
+ check_script(loc, os.path.join(base_dir, opts.script_path))
+ elif tokens[0] == 'bulk_script':
+ opts = parse_args(loc, line, PysimApp.bulk_script_parser, tokens[1:])
+ if opts:
+ check_script(loc, os.path.join(base_dir, opts.SCRIPT_PATH))
+ elif tokens[0] == 'apdu':
+ opts = parse_args(loc, line, PysimApp.apdu_cmd_parser, tokens[1:])
+ if opts is None:
+ return
+ try:
+ parse_command_apdu(h2b(opts.APDU))
+ except ValueError as e:
+ findings.append('%s: "%s": %s' % (loc, line, e))
+
+ def check_script(loc: str, path: str):
+ rpath = os.path.realpath(path)
+ if rpath in visited_scripts:
+ return
+ visited_scripts.add(rpath)
+ try:
+ with open(path, 'r') as f:
+ lines = f.readlines()
+ except OSError as e:
+ findings.append('%s: script %s not readable (%s)' % (loc, path, e.strerror))
+ return
+ for num, line in enumerate(lines, 1):
+ check_line('%s:%d' % (path, num), line.rstrip('\n'), os.path.dirname(rpath))
+
+ for loc, cmd in commands:
+ check_line(loc, cmd, os.getcwd())
+ return findings
+
option_parser = argparse.ArgumentParser(description='interactive SIM card shell',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
@@ -1147,6 +1230,19 @@
# Ensure that we are able to print formatted warnings from the beginning.
PySimLogger.setup(print, {logging.WARN: YELLOW}, opts.verbose)
+ # Refuse malformed apdu commands in startup commands and scripts before touching the card.
+ startup_commands = [('-e option %d' % (num + 1), cmd) for num, cmd in enumerate(opts.execute_command)]
+ if opts.command:
+ startup_commands.append(('command', '{} {}'.format(opts.command, ' '.join(opts.command_args))))
+ if opts.script:
+ startup_commands.append(('--script', 'run_script %s' % opts.script))
+ findings = verify_startup_apdus(startup_commands)
+ if findings:
+ for f in findings:
+ print("Error: %s" % f)
+ print("Malformed APDUs in startup commands, nothing executed.")
+ sys.exit(2)
+
# Init card key provider for automatic card key retrieval
card_key_provider_init(opts)
diff --git a/tests/unittests/test_shell_startup_verify.py b/tests/unittests/test_shell_startup_verify.py
new file mode 100644
index 0000000..18d04e5
--- /dev/null
+++ b/tests/unittests/test_shell_startup_verify.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+
+# (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 importlib.util
+import os
+import tempfile
+import unittest
+
+_shell_path = os.path.join(os.path.dirname(__file__), '..', '..', 'pySim-shell.py')
+_spec = importlib.util.spec_from_file_location('pysim_shell', _shell_path)
+pysim_shell = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(pysim_shell)
+verify = pysim_shell.verify_startup_apdus
+
+
+class VerifyStartupApdus_Test(unittest.TestCase):
+
+ def test_valid(self):
+ self.assertEqual(verify([
+ ('l1', 'apdu 00a4000400'), # case 2
+ ('l2', 'apdu 00a40004023f00'), # case 3
+ ('l3', 'apdu 00a40004023f0000'), # case 4
+ ('l4', 'apdu --expect-sw 9000 00a40004023f0000'), # options before the APDU
+ ('l5', 'select MF'), # non-apdu lines pass through
+ ('l6', '# apdu zz'), # comment
+ ('l7', ''),
+ ]), [])
+
+ def test_malformed(self):
+ findings = verify([
+ ('l1', 'apdu 00a40004022fe20000'), # Lc 2, three body bytes
+ ('l2', 'apdu 00a40004052fe2'), # Lc 5, two data bytes
+ ('l3', 'apdu 00a4zz'), # not hex, rejected by the argparser
+ ('l4', 'apdu'), # missing argument
+ ('l5', 'apdu 00a40004023f0000'), # valid, must not be dragged down by l1-l4
+ ])
+ self.assertEqual(len(findings), 4)
+ for expect_loc, finding in zip(['l1', 'l2', 'l3', 'l4'], findings):
+ self.assertTrue(finding.startswith(expect_loc + ':'))
+
+ def test_script_expansion(self):
+ with tempfile.TemporaryDirectory() as d:
+ inner = os.path.join(d, 'inner.script')
+ outer = os.path.join(d, 'outer.script')
+ with open(inner, 'w') as f:
+ f.write('apdu 00a40004052fe2\n')
+ with open(outer, 'w') as f:
+ f.write('select MF\nrun_script %s\nrun_script %s\napdu 00a4000403aabb\n' % (inner, outer))
+ findings = verify([('--script', 'run_script %s' % outer)])
+ self.assertEqual(len(findings), 2)
+ self.assertTrue(findings[0].startswith('%s:1:' % inner)) # via nested run_script
+ self.assertTrue(findings[1].startswith('%s:4:' % outer)) # self reference recursed only once
+ missing = verify([('--script', 'run_script %s' % os.path.join(d, 'nonexistent'))])
+ self.assertEqual(len(missing), 1)
+ self.assertIn('not readable', missing[0])
+
+ def test_script_command_variants(self):
+ with tempfile.TemporaryDirectory() as d:
+ bad = os.path.join(d, 'bad.script')
+ with open(bad, 'w') as f:
+ f.write('apdu 00a40004052fe2\n')
+ with open(os.path.join(d, 'outer.script'), 'w') as f:
+ f.write('@@bad.script\n@@ bad.script\n')
+ for line in ('run_script -t %s %s' % (os.path.join(d, 'transcript'), bad),
+ 'bulk_script --tries 3 %s' % bad,
+ 'bulk_script %s --halt_on_error' % bad,
+ '@%s' % bad,
+ '@ %s' % bad,
+ 'run_script %s' % os.path.join(d, 'outer.script')):
+ with self.subTest(line=line):
+ findings = verify([('l1', line)])
+ self.assertEqual(len(findings), 1)
+ self.assertTrue(findings[0].startswith('%s:1:' % bad))
+
+ def test_bad_arguments(self):
+ findings = verify([('l1', 'apdu -h'), ('l2', 'apdu --bogus 00a4000400'),
+ ('l3', 'run_script --bogus x'), ('l4', 'bulk_script')])
+ self.assertEqual([f.split(':')[0] for f in findings], ['l1', 'l2', 'l3', 'l4'])
+
+
+if __name__ == '__main__':
+ unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43727?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ida84b982d7577faa5b37f121599a59bcb2feefec
Gerrit-Change-Number: 43727
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43716?usp=email )
Change subject: bip: UDP channels for CAT_TP
......................................................................
bip: UDP channels for CAT_TP
Humble beginnings of CAT_TP support:
OPEN CHANNEL with "UDP, UICC in client mode, remote connection" gets a
datagram socket. SEND DATA without "send immediately" is buffered,
TERMINAL PROFILE byte 17 announces our new UDP client mode.
Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff
---
M pySim/bip.py
M tests/unittests/test_bip_relay.py
2 files changed, 174 insertions(+), 18 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/16/43716/1
diff --git a/pySim/bip.py b/pySim/bip.py
index 1cd3ba0..a652d1d 100644
--- a/pySim/bip.py
+++ b/pySim/bip.py
@@ -27,7 +27,9 @@
# tp = init_reader(opts, proactive_handler=handler)
+import collections
import logging
+import select
import socket
import threading
import time
@@ -74,7 +76,7 @@
# 13 (class "e" supported bearers): b2 GPRS, and b6..b8 the number of channels.
profile[12] = 0x02 | (num_channels << 5)
profile[13] = 0x40 | 0x20 # 14: b6 no display capability, b7 no keypad available
- profile[16] = 0x01 # 15: b1 TCP, UICC in client mode, remote connection
+ profile[16] = 0x01 | 0x02 # 17: b1 TCP, b2 UDP, UICC in client mode, remote connection
return bytes(profile)
@@ -205,6 +207,75 @@
self._reader.join(timeout=1.0)
self.channels.channel_delete(self.chan_nr)
+
+class ProactUdpChannel(ProactChannel):
+ """BIP channel on a connected UDP socket, for CAT_TP (TS 102 127 section 6).
+
+ TS 102 223 6.4.29/6.4.30: the Rx buffer holds one datagram SDU at a time, the next one is
+ inserted only once the card drained it, and the Tx buffer collects SEND DATA until "send
+ immediately", which emits it as one datagram."""
+ RECV_CHUNK = 65535
+
+ def __init__(self, channels: 'ProactChannels', chan_nr: int):
+ super().__init__(channels, chan_nr)
+ self.rx_dgrams = collections.deque() # datagrams waiting behind the current one
+ self.tx_buf = bytearray()
+
+ def connect(self, host: str, port: int, timeout: float = 10.0):
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ s.connect((host, port))
+ 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):
+ """One datagram per recv(). The data available event is raised for the datagram that
+ lands in an empty buffer, and again when the next queued one moves into the buffer."""
+ while not self._closing:
+ try:
+ readable, _, _ = select.select([self.sock], [], [], 0.02)
+ except (OSError, ValueError):
+ break
+ if readable:
+ try:
+ data = self.sock.recv(self.RECV_CHUNK)
+ except ConnectionRefusedError:
+ logger.warning("channel %u: ICMP port unreachable from peer", self.chan_nr)
+ continue
+ except (OSError, ValueError):
+ break
+ with self._rx_lock:
+ was_empty = len(self.rx_buf) == 0
+ if was_empty:
+ self.rx_buf.extend(data)
+ else:
+ self.rx_dgrams.append(data)
+ if was_empty and not self._closing:
+ self.channels.notify_data_available(self)
+ self._advance()
+
+ def _advance(self):
+ """Move the next datagram into the drained buffer, from the reader thread so the
+ notification never runs on the thread that is driving the card."""
+ with self._rx_lock:
+ if self.rx_buf or not self.rx_dgrams:
+ return
+ self.rx_buf.extend(self.rx_dgrams.popleft())
+ if not self._closing:
+ self.channels.notify_data_available(self)
+
+ def send(self, data: bytes, immediate: bool = True):
+ self.tx_buf.extend(data)
+ if immediate:
+ self.sock.send(bytes(self.tx_buf))
+ self.tx_buf.clear()
+
+
class ProactChannels:
"""The open BIP channels of one terminal, keyed by channel number.
@@ -222,11 +293,12 @@
self.channels = {}
self._on_data_available = on_data_available
- def channel_create(self) -> ProactChannel:
+ def channel_create(self, proto: str = 'tcp') -> ProactChannel:
"""Create a new proactive channel, allocating its integer number."""
+ cls = {'tcp': ProactChannel, 'udp': ProactUdpChannel}[proto]
for i in range(1, self.MAX_CHANNELS + 1):
if not i in self.channels:
- self.channels[i] = ProactChannel(self, i)
+ self.channels[i] = cls(self, i)
return self.channels[i]
raise ValueError('Cannot allocate another channel: All channels active')
@@ -447,7 +519,8 @@
# UICC/terminal interface transport level is Optional, TS 102 223 6.6.27.x. Absent means
# the CAT application runs its own network and transport layer, which we do not do.
- if transp_lvl_ie is None or transp_lvl_ie.decoded['protocol_type'] != 'tcp_uicc_client_remote':
+ protos = {'tcp_uicc_client_remote': 'tcp', 'udp_uicc_client_remote': 'udp'}
+ if transp_lvl_ie is None or transp_lvl_ie.decoded['protocol_type'] not in protos:
logger.warning("OpenChannel: unsupported UICC/terminal interface transport level (%s) "
"-> refusing", transp_lvl_ie.decoded if transp_lvl_ie else '(absent)')
return refuse('requested_uicc_if_transp_level_not_available')
@@ -461,9 +534,10 @@
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']
- logger.info("OpenChannel: connecting to %s:%u", ipv4_str, port_nr)
+ proto = protos[transp_lvl_ie.decoded['protocol_type']]
+ logger.info("OpenChannel: connecting to %s:%u (%s)", ipv4_str, port_nr, proto)
try:
- channel = self.channels.channel_create()
+ channel = self.channels.channel_create(proto)
except ValueError:
# TS 102 223 6.4.27.2 and 6.4.27.3: no channel left -> BIP error
logger.warning("OpenChannel: all %u channels are in use -> refusing",
@@ -568,10 +642,13 @@
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)
+ # command_qualifier bit 1 selects 'send immediately' / Tx-buffer store and forward.
+ # TCP is a stream, so just send. UDP keeps datagram boundaries, TS 102 223 6.4.30.
+ if isinstance(chan, ProactUdpChannel):
+ cd_ie = Proact._find_first_element_of_type(pcmd.children, CommandDetails)
+ chan.send(payload, immediate=bool(cd_ie.decoded['command_qualifier'] & 0x01))
+ else:
+ chan.send(payload)
# Terminal Response example: [
# {'command_details': {'command_number': 1,
# 'type_of_command': 'send_data',
diff --git a/tests/unittests/test_bip_relay.py b/tests/unittests/test_bip_relay.py
index 5f72411..6a3c568 100644
--- a/tests/unittests/test_bip_relay.py
+++ b/tests/unittests/test_bip_relay.py
@@ -71,6 +71,33 @@
pass
+class _UdpEchoServer:
+ """echoes every datagram, and records them so datagram boundaries can be asserted"""
+ def __init__(self):
+ self._srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self._srv.bind(('127.0.0.1', 0))
+ self._srv.settimeout(0.1)
+ self.port = self._srv.getsockname()[1]
+ self.datagrams = []
+ self._stop = False
+ threading.Thread(target=self._run, daemon=True).start()
+
+ def _run(self):
+ while not self._stop:
+ try:
+ data, addr = self._srv.recvfrom(65535)
+ except socket.timeout:
+ continue
+ except OSError:
+ break
+ self.datagrams.append(data)
+ self._srv.sendto(data, addr)
+
+ def close(self):
+ self._stop = True
+ self._srv.close()
+
+
def _pcmd(children_tlvs):
"""Assemble D0 proactive-command TLV from child IE bytes,
decode it like transport does after a FETCH"""
@@ -79,7 +106,7 @@
return ProactiveCommand().from_tlv(pdu)
-def _open_channel(port, ip='127.0.0.1', cmd_nr=1):
+def _open_channel(port, ip='127.0.0.1', cmd_nr=1, proto='tcp_uicc_client_remote'):
a, b, c, d = (int(x) for x in ip.split('.'))
return _pcmd([
CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'open_channel',
@@ -87,8 +114,7 @@
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(),
+ UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': port}).to_tlv(),
OtherAddress(decoded={'type_of_address': 'ipv4',
'address': bytes([a, b, c, d])}).to_tlv(),
])
@@ -105,10 +131,10 @@
] + extra_ies)
-def _send_data(payload, chan='channel_1', cmd_nr=1):
+def _send_data(payload, chan='channel_1', cmd_nr=1, immediate=True):
return _pcmd([
CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'send_data',
- 'command_qualifier': 1}).to_tlv(),
+ 'command_qualifier': 1 if immediate else 0}).to_tlv(),
DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': chan}).to_tlv(),
ChannelData(decoded=b2h(payload)).to_tlv(),
])
@@ -266,6 +292,59 @@
self.assertEqual(_first(til, ChannelDataLength).decoded, 0)
+class BipUdpRelayTest(unittest.TestCase):
+ """UDP channels keep datagram boundaries, TS 102 223 6.4.29 and 6.4.30"""
+
+ def setUp(self):
+ self.echo = _UdpEchoServer()
+ self.addCleanup(self.echo.close)
+ self.events = []
+ self.proact = Proact(data_available_sink=self.events.append)
+ self.addCleanup(lambda: [c.close() for c in list(self.proact.channels.channels.values())])
+ til = self.proact.handle_OpenChannel(_open_channel(self.echo.port, proto='udp_uicc_client_remote'))
+ b''.join(x.to_tlv() for x in til)
+ self.assertEqual(_first(til, Result).decoded['general_result'], 'performed_successfully')
+ self.assertEqual(_first(til, ChannelStatus).decoded, '8100')
+ self.chan = self.proact.channels.channels[1]
+
+ def _wait_events(self, n, timeout=2.0):
+ deadline = time.monotonic() + timeout
+ while len(self.events) < n and time.monotonic() < deadline:
+ time.sleep(0.01)
+ return len(self.events)
+
+ def test_store_and_forward_is_one_datagram(self):
+ # two buffered SEND DATA and a final "send immediately" leave as a single datagram
+ self.proact.handle_SendData(_send_data(b'one', immediate=False))
+ self.proact.handle_SendData(_send_data(b'two', immediate=False))
+ self.assertEqual(self.echo.datagrams, [])
+ self.proact.handle_SendData(_send_data(b'three'))
+ self.assertGreater(self.chan.wait_rx(2.0), 0)
+ self.assertEqual(self.echo.datagrams, [b'onetwothree'])
+
+ def test_rx_one_sdu_at_a_time(self):
+ # two datagrams from the peer: RECEIVE DATA never crosses into the second one, and
+ # the second raises its own data available event once the first is drained
+ self.proact.handle_SendData(_send_data(b'first'))
+ self.proact.handle_SendData(_send_data(b'second'))
+ time.sleep(0.2)
+ self.assertEqual(self._wait_events(1), 1)
+ self.assertEqual(self.chan.available_rx(), 5)
+ til = self.proact.handle_ReceiveData(_receive_data(100))
+ self.assertEqual(h2b(_first(til, ChannelData).decoded), b'first')
+ self.assertEqual(_first(til, ChannelDataLength).decoded, 0)
+ self.assertEqual(_first(til, Result).decoded['general_result'],
+ 'performed_with_missing_information')
+ self.assertEqual(self._wait_events(2), 2)
+ self.assertEqual(h2b(self.events[1])[-1], 6) # channel data length = len(b'second')
+ til = self.proact.handle_ReceiveData(_receive_data(3))
+ self.assertEqual(h2b(_first(til, ChannelData).decoded), b'sec')
+ self.assertEqual(_first(til, ChannelDataLength).decoded, 3)
+ til = self.proact.handle_ReceiveData(_receive_data(3))
+ self.assertEqual(h2b(_first(til, ChannelData).decoded), b'ond')
+ self.assertEqual(_first(til, ChannelDataLength).decoded, 0)
+
+
class OpenChannelRefusalTest(unittest.TestCase):
"""Refusal is a TERMINAL RESPONSE, not an exception, raising takes the whole
proactive session down and leaves the card wondering why"""
@@ -296,8 +375,8 @@
def test_transport_level(self):
cases = [[self.ADDR.to_tlv()]] # absent, 6.6.27.x Optional
- for proto in ('udp_uicc_client_remote', 'tcp_uicc_server', 'udp_uicc_client_local',
- 'tcp_uicc_client_local', 'direct_channel'): # not TCP client remote
+ for proto in ('tcp_uicc_server', 'udp_uicc_client_local', 'tcp_uicc_client_local',
+ 'direct_channel'): # not client mode remote
tl = UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': 1234})
cases.append([tl.to_tlv(), self.ADDR.to_tlv()])
for extra in cases:
@@ -375,7 +454,7 @@
self.assertEqual(self.byte(12), 0x1f) # OPEN/CLOSE CHANNEL, RECEIVE/SEND DATA, STATUS
self.assertEqual(self.byte(13) >> 5, ProactChannels.MAX_CHANNELS)
self.assertEqual(self.byte(14), 0x60) # class ND, class NK
- self.assertEqual(self.byte(17), 0x01) # TCP, UICC client mode, remote
+ self.assertEqual(self.byte(17), 0x03) # TCP + UDP, UICC client mode, remote
def test_not_announced(self):
self.assertEqual(self.byte(3) & 0x60, 0) # POLL INTERVAL, POLLING OFF
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43716?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff
Gerrit-Change-Number: 43716
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
[M] Change in pysim[master]: ota: argparse helpers for the SCP80 key set and SPI
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43720?usp=email )
Change subject: ota: argparse helpers for the SCP80 key set and SPI
......................................................................
ota: argparse helpers for the SCP80 key set and SPI
shared among scp80/cat-tp and scp81
Change-Id: I599a07f7e4e100ddce91ee7eae70bab3cf9c07c1
---
M pySim/ota.py
1 file changed, 49 insertions(+), 1 deletion(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/20/43720/1
diff --git a/pySim/ota.py b/pySim/ota.py
index 955a98d..8c7ebec 100644
--- a/pySim/ota.py
+++ b/pySim/ota.py
@@ -17,6 +17,7 @@
import zlib
import abc
+import logging
import struct
from typing import Optional, Tuple, List, Union
from construct import ConstructError, Enum, Int8ub, Int16ub, Struct, BitsInteger, BitStruct
@@ -24,9 +25,12 @@
from construct import Const, Prefixed, Select, Construct, SizeofError, stream_read, stream_write
from osmocom.construct import *
from osmocom.tlv import bertlv_encode_len, bertlv_parse_len
-from osmocom.utils import b2h
+from osmocom.utils import b2h, h2b
from pySim.sms import UserDataHeader
+from pySim.utils import is_hexstr
+
+logger = logging.getLogger(__name__)
from pySim.cat import BearerDescription, BufferSize, UiccTransportLevel, OtherAddress, ChannelData
# ETS TS 102 225 gives the general command structure and the dialects for CAT_TP, TCP/IP and HTTPS
@@ -582,6 +586,50 @@
+def argparse_add_ota_args(parser, sms: bool = False):
+ """SCP80 key set and SPI options of the OTA tools, --por-in-submit only with sms"""
+ g = parser.add_argument_group('OTA security, TS 102 225')
+ g.add_argument('--algo-crypt', choices=[c.enum_name for c in OtaAlgoCrypt.__subclasses__()],
+ default='triple_des_cbc2', help='OTA crypt algorithm')
+ g.add_argument('--algo-auth', choices=[c.enum_name for c in OtaAlgoAuth.__subclasses__()],
+ default='triple_des_cbc2', help='OTA auth algorithm')
+ g.add_argument('--kic', required=True, type=is_hexstr, help='OTA key (KIC)')
+ g.add_argument('--kic-idx', default=1, type=int, help='OTA key index (KIC)')
+ g.add_argument('--kid', required=True, type=is_hexstr, help='OTA key (KID)')
+ g.add_argument('--kid-idx', default=1, type=int, help='OTA key index (KID)')
+ g.add_argument('--cntr', default=0, type=int, help='replay protection counter')
+ g.add_argument('--tar', required=True, type=is_hexstr, help='Toolkit Application Reference')
+ g.add_argument('--cntr-req', choices=CNTR_REQ.decmapping.values(), default='no_counter',
+ help='Counter requirement')
+ g.add_argument('--no-ciphering', action='store_true', default=False, help='Disable ciphering')
+ g.add_argument('--rc-cc-ds', choices=RC_CC_DS.decmapping.values(), default='cc',
+ help='message check (rc=redundency check, cc=crypt. checksum, ds=digital signature)')
+ if sms:
+ g.add_argument('--por-in-submit', action='store_true', default=False,
+ help='require PoR to be sent via SMS-SUBMIT')
+ g.add_argument('--por-no-ciphering', action='store_true', default=False, help='Disable ciphering (PoR)')
+ g.add_argument('--por-rc-cc-ds', choices=RC_CC_DS.decmapping.values(), default='cc',
+ help='PoR check (rc=redundency check, cc=crypt. checksum, ds=digital signature)')
+ g.add_argument('--por-req', choices=POR_REQ.decmapping.values(), default='por_required',
+ help='Proof of Receipt requirements')
+
+def ota_keyset_from_args(args) -> 'OtaKeyset':
+ if args.kic_idx != args.kid_idx:
+ logger.warning('KIC index (%s) and KID index (%s) differ, the card should reject that',
+ args.kic_idx, args.kid_idx)
+ return OtaKeyset(algo_crypt=args.algo_crypt, kic_idx=args.kic_idx, kic=h2b(args.kic),
+ algo_auth=args.algo_auth, kid_idx=args.kid_idx, kid=h2b(args.kid), cntr=args.cntr)
+
+def ota_spi_from_args(args) -> dict:
+ return {'counter': args.cntr_req,
+ 'ciphering': not args.no_ciphering,
+ 'rc_cc_ds': args.rc_cc_ds,
+ 'por_in_submit': getattr(args, 'por_in_submit', False),
+ 'por_shall_be_ciphered': not args.por_no_ciphering,
+ 'por_rc_cc_ds': args.por_rc_cc_ds,
+ 'por': args.por_req}
+
+
class OtaDialectSms(OtaDialect):
"""OTA dialect for SMS based transport, as described in 3GPP TS 31.115."""
SmsResponsePacket = Struct('rpl'/Int16ub,
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43720?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I599a07f7e4e100ddce91ee7eae70bab3cf9c07c1
Gerrit-Change-Number: 43720
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
[M] Change in pysim[master]: ota: CAT_TP / TCP dialect of TS 102 225 secured packet
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43717?usp=email )
Change subject: ota: CAT_TP / TCP dialect of TS 102 225 secured packet
......................................................................
ota: CAT_TP / TCP dialect of TS 102 225 secured packet
There are 3 sections:
Section 6, CAT_TP: SCP80 secured packets as CAT_TP SDUs over BIP UDP
Section 7, TCP/IP: SCP80 secured packets, dropped raw into a TCP stream
Section 8, HTTPS = SCP81: no SCP80 packets, prev patchset
This covers 6+7 which are identical on the packet level and are basically
SCP80 OTA sms without a length limit over a different transport.
In practice I don't think anyone ever deployed scp80 over tcp...
Change-Id: I122a13000e622f7550468845e8560dec5a3c55a6
---
M pySim/ota.py
M tests/unittests/test_ota.py
2 files changed, 241 insertions(+), 1 deletion(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/17/43717/1
diff --git a/pySim/ota.py b/pySim/ota.py
index 82b1a85..69a7a33 100644
--- a/pySim/ota.py
+++ b/pySim/ota.py
@@ -23,7 +23,7 @@
from construct import Flag, Padding, Switch, this, PrefixedArray, GreedyRange
from construct import Const, Prefixed, Select, Construct, SizeofError, stream_read, stream_write
from osmocom.construct import *
-from osmocom.tlv import bertlv_encode_len
+from osmocom.tlv import bertlv_encode_len, bertlv_parse_len
from osmocom.utils import b2h
from pySim.sms import UserDataHeader
@@ -735,3 +735,141 @@
else:
dec = None
return (res, dec)
+
+
+class OtaDialectCatTp(OtaDialect):
+ """TS 102 225 section 6 (CAT_TP) and 7 (TCP/IP), which are identical on the packet level:
+ CPI '01' / RPI '02', CHI and RHI absent, CPL/CHL/RPL/RHL are BER lengths, and unlike SMS
+ the CPI+CPL+CHL (RPI+RPL+RHL) are part of the RC/CC/DS. One packet per SDU."""
+ CPI = 0x01
+ RPI = 0x02
+ IDENTIFICATION_PI = 0x03 # TS 102 225 table 6, TCP/IP only
+
+ hdr_construct = Struct('spi'/SPI, 'kic'/KIC, 'kid'/KID_CC, 'tar'/Bytes(3))
+ ResponseHead = Struct('tar'/Bytes(3), 'cntr'/Bytes(5), 'pcntr'/Int8ub,
+ 'response_status'/ResponseStatus)
+
+ @staticmethod
+ def _sig(otak: OtaKeyset, rc_cc_ds: str, data: bytes) -> bytes:
+ if rc_cc_ds == 'cc':
+ return otak.auth.sign(data)
+ if rc_cc_ds == 'rc':
+ return (zlib.crc32(data) & 0xffffffff).to_bytes(4, 'big')
+ if rc_cc_ds == 'no_rc_cc_ds':
+ return b''
+ raise ValueError("Invalid rc_cc_ds: %s" % rc_cc_ds)
+
+ @staticmethod
+ def _check_sig(otak: OtaKeyset, rc_cc_ds: str, data: bytes, sig: bytes):
+ if rc_cc_ds == 'cc':
+ otak.auth.check_sig(data, sig)
+ elif rc_cc_ds == 'rc':
+ expected = (zlib.crc32(data) & 0xffffffff).to_bytes(4, 'big')
+ if sig != expected:
+ raise OtaCheckError('Received RC (%s) != Computed RC (%s)' % (b2h(sig), b2h(expected)))
+
+ def encode_cmd(self, otak: OtaKeyset, tar: bytes, spi: dict,
+ apdu: Union[bytes, List[bytes]], remote_format: str = 'compact') -> bytes:
+ if remote_format == 'expanded':
+ apdu = encode_expanded_cmd(apdu)
+ elif remote_format != 'compact':
+ raise ValueError("Invalid remote_format: %s" % remote_format)
+ apdu = bytes(apdu)
+ len_sig = self._compute_sig_len(spi)
+ pad_cnt = 0
+ if spi['ciphering']:
+ # CNTR + PCNTR + RC/CC/DS + data are ciphered, TS 102 225 table 2 note 1
+ padding = otak.crypt._get_padding(6 + len_sig + len(apdu), otak.crypt.blocksize)
+ pad_cnt = len(padding)
+ apdu += padding
+ hdr = self.hdr_construct.build({'spi': spi, 'tar': tar,
+ 'kic': {'key': otak.kic_idx, 'algo': otak.algo_crypt},
+ 'kid': {'key': otak.kid_idx, 'algo': otak.algo_auth}})
+ cnt = otak.cntr.to_bytes(5, 'big') + bytes([pad_cnt])
+ chl = len(hdr) + len(cnt) + len_sig # SPI .. RC/CC/DS
+ cpl = len(bertlv_encode_len(chl)) + chl + len(apdu) # CHI (absent) .. end of data
+ head = bytes([self.CPI]) + bertlv_encode_len(cpl) + bertlv_encode_len(chl) + hdr
+ sig = self._sig(otak, spi['rc_cc_ds'], head + cnt + apdu)
+ body = cnt + sig + apdu
+ if spi['ciphering']:
+ body = otak.crypt.encrypt(body)
+ return head + body
+
+ def decode_cmd(self, otak: OtaKeyset, encoded: bytes) -> Tuple[bytes, dict, bytes]:
+ """Decode a command packet into (tar, spi, apdu), what the card does."""
+ if encoded[0] != self.CPI:
+ raise ValueError('Unexpected CPI 0x%02x' % encoded[0])
+ cpl, rest = bertlv_parse_len(encoded[1:])
+ if len(rest) != cpl:
+ raise ValueError('CPL %u != %u remaining octets' % (cpl, len(rest)))
+ chl, rest = bertlv_parse_len(rest)
+ hdr_len = 7
+ head = encoded[:len(encoded) - len(rest) + hdr_len]
+ hdr = self.hdr_construct.parse(rest[:hdr_len])
+ spi = hdr['spi']
+ body = rest[hdr_len:]
+ if spi['ciphering']:
+ body = otak.crypt.decrypt(body)
+ len_sig = self._compute_sig_len(spi)
+ cnt, sig, apdu = body[:6], body[6:6 + len_sig], body[6 + len_sig:]
+ if chl != hdr_len + 6 + len_sig:
+ raise ValueError('CHL %u does not match SPI' % chl)
+ self._check_sig(otak, spi['rc_cc_ds'], head + cnt + apdu, sig)
+ pad_cnt = cnt[5]
+ return hdr['tar'], spi, apdu[:len(apdu) - pad_cnt]
+
+ def encode_resp(self, otak: OtaKeyset, spi: dict, tar: bytes, response_status: str = 'por_ok',
+ data: bytes = b'', cntr: Optional[int] = None) -> bytes:
+ """Response packet as the card builds it, TS 102 225 5.2, secured per the por_* SPI bits."""
+ data = bytes(data)
+ len_sig = self._compute_sig_len({'rc_cc_ds': spi['por_rc_cc_ds']})
+ pad_cnt = 0
+ if spi['por_shall_be_ciphered']:
+ padding = otak.crypt._get_padding(7 + len_sig + len(data), otak.crypt.blocksize)
+ pad_cnt = len(padding)
+ data += padding
+ cntr = otak.cntr if cntr is None else cntr
+ hdr = self.ResponseHead.build({'tar': tar, 'cntr': cntr.to_bytes(5, 'big'),
+ 'pcntr': pad_cnt, 'response_status': response_status})
+ rhl = len(hdr) + len_sig
+ rpl = len(bertlv_encode_len(rhl)) + rhl + len(data)
+ head = bytes([self.RPI]) + bertlv_encode_len(rpl) + bertlv_encode_len(rhl)
+ sig = self._sig(otak, spi['por_rc_cc_ds'], head + hdr + data)
+ body = hdr[3:] + sig + data # CNTR onwards is ciphered
+ if spi['por_shall_be_ciphered']:
+ body = otak.crypt.encrypt(body)
+ return head + hdr[:3] + body
+
+ def decode_resp(self, otak: OtaKeyset, spi: dict, data: bytes,
+ remote_format: str = 'compact') -> (object, Optional[object]):
+ if remote_format not in ('compact', 'expanded'):
+ raise ValueError("Invalid remote_format: %s ?!" % remote_format)
+ if isinstance(data, str):
+ data = h2b(data)
+ if data[0] != self.RPI:
+ raise ValueError('Unexpected RPI 0x%02x' % data[0])
+ rpl, rest = bertlv_parse_len(data[1:])
+ if len(rest) != rpl:
+ raise ValueError('RPL %u != %u remaining octets' % (rpl, len(rest)))
+ rhl, rest = bertlv_parse_len(rest)
+ head = data[:len(data) - len(rest)]
+ tar, body = rest[:3], rest[3:]
+ if spi['por_shall_be_ciphered']:
+ body = otak.crypt.decrypt(body)
+ len_sig = rhl - 10
+ hdr = self.ResponseHead.parse(tar + body[:7])
+ sig, secured = body[7:7 + len_sig], body[7 + len_sig:]
+ if spi['por_rc_cc_ds'] == 'no_rc_cc_ds' and len_sig:
+ raise OtaCheckError('No RC/CC/DS requested, but len_sig=%u' % len_sig)
+ self._check_sig(otak, spi['por_rc_cc_ds'], head + tar + body[:7] + secured, sig)
+ if hdr['pcntr']:
+ secured = secured[:-hdr['pcntr']]
+ res = Container(rpl=rpl, rhl=rhl, tar=hdr['tar'], cntr=hdr['cntr'], pcntr=hdr['pcntr'],
+ response_status=hdr['response_status'], cc_rc=sig, secured_data=secured)
+ dec = None
+ if res.response_status == 'por_ok' and len(secured):
+ if remote_format == 'expanded':
+ dec = decode_expanded_resp(secured)
+ else:
+ dec = CompactRemoteResp.parse(secured)
+ return (res, dec)
diff --git a/tests/unittests/test_ota.py b/tests/unittests/test_ota.py
index b513355..037e7ee 100644
--- a/tests/unittests/test_ota.py
+++ b/tests/unittests/test_ota.py
@@ -589,3 +589,105 @@
if __name__ == "__main__":
unittest.main()
+
+
+######################################################################
+# CAT_TP / TCP dialect (ETSI TS 102 225 Section 6 + 7)
+######################################################################
+
+SPI_NONE_POR_NONE = {
+ 'counter': 'no_counter', 'ciphering': False, 'rc_cc_ds': 'no_rc_cc_ds',
+ 'por_in_submit': False, 'por_shall_be_ciphered': False, 'por_rc_cc_ds': 'no_rc_cc_ds',
+ 'por': 'por_required'}
+
+SPI_RC_POR_RC = dict(SPI_NONE_POR_NONE, rc_cc_ds='rc', por_rc_cc_ds='rc')
+
+
+class CatTpOtaTestCase(OtaTestCase):
+ APDU = b'\x00\xa4\x00\x04\x02\x3f\x00'
+
+ def setUp(self):
+ self.dialect = OtaDialectCatTp()
+
+ def test_cmd_plain_golden(self):
+ # CPI 01, CPL 15, CHL 0d, SPI 0001 KIc 35 KID 35 TAR, CNTR, PCNTR 00, data
+ outp = self.dialect.encode_cmd(OTA_KEYSET_SJA5_SAMPLES, self.tar, SPI_NONE_POR_NONE, self.APDU)
+ self.assertEqual(b2h(outp), '01150d00013535b000110000000000' '00' '00a40004023f00')
+ tar, spi, apdu = self.dialect.decode_cmd(OTA_KEYSET_SJA5_SAMPLES, outp)
+ self.assertEqual((tar, spi, apdu), (self.tar, SPI_NONE_POR_NONE, self.APDU))
+
+ def test_cmd_roundtrip(self):
+ for kset in (OTA_KEYSET_SJA5_SAMPLES, OTA_KEYSET_SJA5_AES128):
+ for spi in (SPI_CC_POR_CIPHERED_CC, SPI_CC_POR_UNCIPHERED_CC, SPI_RC_POR_RC):
+ for fmt in ('compact', 'expanded'):
+ with self.subTest(kset=kset.algo_crypt, spi=spi['rc_cc_ds'], fmt=fmt):
+ apdu = [self.APDU] if fmt == 'expanded' else self.APDU
+ outp = self.dialect.encode_cmd(kset, self.tar, spi, apdu, remote_format=fmt)
+ self.assertEqual(outp[0], 0x01)
+ if spi['ciphering']:
+ self.assertEqual((len(outp) - 10) % kset.crypt.blocksize, 0)
+ tar, dspi, dapdu = self.dialect.decode_cmd(kset, outp)
+ self.assertEqual(tar, self.tar)
+ self.assertEqual(dspi, spi)
+ expected = encode_expanded_cmd(apdu) if fmt == 'expanded' else self.APDU
+ self.assertEqual(dapdu, expected)
+
+ def test_cmd_tamper_detected(self):
+ outp = bytearray(self.dialect.encode_cmd(OTA_KEYSET_SJA5_SAMPLES, self.tar,
+ SPI_CC_POR_UNCIPHERED_CC, self.APDU))
+ outp[-1] ^= 0x01
+ with self.assertRaises(OtaCheckError):
+ self.dialect.decode_cmd(OTA_KEYSET_SJA5_SAMPLES, bytes(outp))
+
+ def test_cmd_long_lengths(self):
+ # CPL > 127 goes to the 81xx BER form
+ big = bytes(range(200))
+ outp = self.dialect.encode_cmd(OTA_KEYSET_SJA5_SAMPLES, self.tar, SPI_NONE_POR_NONE, big)
+ self.assertEqual(b2h(outp[:4]), '0181d60d')
+ self.assertEqual(self.dialect.decode_cmd(OTA_KEYSET_SJA5_SAMPLES, outp)[2], big)
+
+ def test_resp_plain_golden(self):
+ # RPI 02, RPL 0e, RHL 0a, TAR, CNTR, PCNTR 00, status 00, compact response 01 9000
+ resp = self.dialect.encode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_NONE_POR_NONE, self.tar,
+ data=h2b('019000'))
+ self.assertEqual(b2h(resp), '020e0ab000110000000000' '00' '00' '019000')
+ res, dec = self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_NONE_POR_NONE, resp)
+ self.assertEqual(res.response_status, 'por_ok')
+ self.assertEqual(dec.last_status_word, '9000')
+ self.assertEqual(dec.number_of_commands, 1)
+
+ def test_resp_roundtrip(self):
+ for kset in (OTA_KEYSET_SJA5_SAMPLES, OTA_KEYSET_SJA5_AES128):
+ for spi in (SPI_CC_POR_CIPHERED_CC, SPI_CC_POR_UNCIPHERED_CC,
+ SPI_CC_POR_UNCIPHERED_NOCC, SPI_RC_POR_RC):
+ with self.subTest(kset=kset.algo_crypt, por_cc=spi['por_rc_cc_ds'],
+ ciph=spi['por_shall_be_ciphered']):
+ resp = self.dialect.encode_resp(kset, spi, self.tar, data=h2b('01' '6132'))
+ res, dec = self.dialect.decode_resp(kset, spi, resp)
+ self.assertEqual(res.response_status, 'por_ok')
+ self.assertEqual(res.tar, self.tar)
+ self.assertEqual(dec.last_status_word, '6132')
+
+ def test_resp_error_status_has_no_decoded_part(self):
+ resp = self.dialect.encode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, self.tar,
+ response_status='cntr_low')
+ res, dec = self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, resp)
+ self.assertEqual(res.response_status, 'cntr_low')
+ self.assertIsNone(dec)
+
+ def test_resp_expanded(self):
+ # card answers with a TS 102 226 5.2.2 response scripting template
+ expanded = h2b('ab0780010123026132')
+ resp = self.dialect.encode_resp(OTA_KEYSET_SJA5_AES128, SPI_CC_POR_CIPHERED_CC, self.tar,
+ data=expanded)
+ res, dec = self.dialect.decode_resp(OTA_KEYSET_SJA5_AES128, SPI_CC_POR_CIPHERED_CC, resp,
+ remote_format='expanded')
+ self.assertEqual(res.response_status, 'por_ok')
+ self.assertEqual(dec.last_status_word, '6132')
+
+ def test_resp_tamper_detected(self):
+ resp = bytearray(self.dialect.encode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC,
+ self.tar, data=h2b('019000')))
+ resp[-1] ^= 0x01
+ with self.assertRaises(OtaCheckError):
+ self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, bytes(resp))
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43717?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I122a13000e622f7550468845e8560dec5a3c55a6
Gerrit-Change-Number: 43717
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
[M] Change in pysim[master]: ota: TS 102 226 PUSH command and CAT_TP trigger
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43718?usp=email )
Change subject: ota: TS 102 226 PUSH command and CAT_TP trigger
......................................................................
ota: TS 102 226 PUSH command and CAT_TP trigger
TS 102 226 section 9 PUSH covers BIP/CAT_TP/TCP/ID, we only care
about CAT_TP tho + trigger generator tool like scp81.
Change-Id: Ib3423c4fe582dbcc9434c8234709a7b845fa6bcd
---
A contrib/cattp_trigger.py
M pySim/ota.py
M tests/unittests/test_ota.py
3 files changed, 108 insertions(+), 0 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/18/43718/1
diff --git a/contrib/cattp_trigger.py b/contrib/cattp_trigger.py
new file mode 100755
index 0000000..0d7dd7c
--- /dev/null
+++ b/contrib/cattp_trigger.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+"""cattp_trigger.py -- build the PUSH APDUs that ask the card to open a CAT_TP link."""
+
+# (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/>.
+
+# TS 102 226 section 9: two PUSH C-APDUs, "request for BIP channel opening" and "request for
+# CAT_TP link establishment", printed one per line for smpp-ota-tool.py -a, compact format,
+# sent to the TAR of the application that should open the link. The card answers via the POR
+# of the SMS once the link is OPEN, the server side is contrib/cattp_admin_server.py.
+#
+# example:
+# smpp-ota-tool.py ... --tar b00010 $(cattp_trigger.py --ip 10.0.0.1 --port 6001 | sed 's/^/-a /')
+
+import argparse
+import sys
+
+from osmocom.utils import h2b
+from pySim.ota import encode_push_open_channel, encode_push_cattp_link
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--ip", required=True, help="CAT_TP server IPv4 address, OPEN CHANNEL destination")
+ ap.add_argument("--port", type=int, required=True, help="UDP port of the server, used as CAT_TP port too")
+ ap.add_argument("--buffer", type=int, default=1024, help="BIP buffer size, bounds the CAT_TP PDU size")
+ ap.add_argument("--max-sdu", type=int, help="max SDU size the card should announce (default: card decides)")
+ ap.add_argument("--identification", type=h2b, help="identification for the SYN (hex), default: ICCID")
+ ap.add_argument("--no-open", action="store_true", help="omit the BIP channel opening PUSH")
+ args = ap.parse_args()
+
+ apdus = []
+ if not args.no_open:
+ apdus.append(encode_push_open_channel(args.ip, args.port, args.buffer))
+ apdus.append(encode_push_cattp_link(args.port, args.max_sdu, args.identification))
+ for a in apdus:
+ print(a.hex())
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/pySim/ota.py b/pySim/ota.py
index 69a7a33..955a98d 100644
--- a/pySim/ota.py
+++ b/pySim/ota.py
@@ -27,6 +27,7 @@
from osmocom.utils import b2h
from pySim.sms import UserDataHeader
+from pySim.cat import BearerDescription, BufferSize, UiccTransportLevel, OtherAddress, ChannelData
# ETS TS 102 225 gives the general command structure and the dialects for CAT_TP, TCP/IP and HTTPS
# 3GPP TS 31.115 gives the dialects for SMS-PP, SMS-CB, USSD and HTTP
@@ -269,6 +270,41 @@
immediate_action_response=immediate_action_response,
script_chaining_response=script_chaining_response)
+######################################################################
+# PUSH command, ETSI TS 102 226 Section 9: asks the card to open a BIP channel and a CAT_TP
+# link (or TCP connection) so the OTA server has something to talk to.
+######################################################################
+
+# TS 102 226 table 9.1
+PushCmd = Struct('_cla'/Const(b'\x80'), '_ins'/Const(b'\xec'), '_p1'/Const(b'\x01'),
+ 'p2'/Enum(Int8ub, open_channel=1, cattp_link=2, tcp_connection=3, identification_packet=4),
+ 'data'/Prefixed(Int8ub, GreedyBytes))
+
+def encode_push(p2: str, ies: List) -> bytes:
+ """PUSH C-APDU (TS 102 226 table 9.1) with the given COMPREHENSION-TLV data objects as data field."""
+ return PushCmd.build({'p2': p2, 'data': b''.join(ie.to_tlv() for ie in ies)})
+
+def encode_push_open_channel(ip: str, port: int, buffer_size: int,
+ protocol_type: str = 'udp_uicc_client_remote') -> bytes:
+ """TS 102 226 9.2.1: OPEN CHANNEL parameters for a default bearer to ipv4 ip:port."""
+ return encode_push('open_channel', [
+ BearerDescription(decoded={'bearer_type': 'default', 'bearer_parameters': b''}),
+ BufferSize(decoded=buffer_size),
+ UiccTransportLevel(decoded={'protocol_type': protocol_type, 'port_number': port}),
+ OtherAddress(decoded={'type_of_address': 'ipv4',
+ 'address': bytes(int(x) for x in ip.split('.'))})])
+
+def encode_push_cattp_link(dest_port: int, max_sdu_size: Optional[int] = None,
+ identification: Optional[bytes] = None) -> bytes:
+ """TS 102 226 9.2.2: CAT_TP link to the server port. The card puts the identification into its
+ SYN, its ICCID if none is given. Transport protocol ignored, encoded as zero."""
+ ies = [UiccTransportLevel(decoded={'protocol_type': 0, 'port_number': dest_port})]
+ if max_sdu_size is not None:
+ ies.append(BufferSize(decoded=max_sdu_size))
+ if identification is not None:
+ ies.append(ChannelData(decoded=b2h(identification)))
+ return encode_push('cattp_link', ies)
+
RC_CC_DS = Enum(BitsInteger(2), no_rc_cc_ds=0, rc=1, cc=2, ds=3)
CNTR_REQ = Enum(BitsInteger(2), no_counter=0, counter_no_replay_or_seq=1, counter_must_be_higher=2, counter_must_be_lower=3)
POR_REQ = Enum(BitsInteger(2), no_por=0, por_required=1, por_only_when_error=2)
diff --git a/tests/unittests/test_ota.py b/tests/unittests/test_ota.py
index 037e7ee..c587acc 100644
--- a/tests/unittests/test_ota.py
+++ b/tests/unittests/test_ota.py
@@ -691,3 +691,17 @@
resp[-1] ^= 0x01
with self.assertRaises(OtaCheckError):
self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, bytes(resp))
+
+
+class PushCommandTestCase(unittest.TestCase):
+ """TS 102 226 section 9.2"""
+
+ def test_open_channel(self):
+ apdu = encode_push_open_channel('10.0.0.1', 6001, 1024)
+ # 80 EC 01 01 Lc | b5 01 03 | b9 02 0400 | bc 03 01 1771 | be 05 21 0a000001
+ self.assertEqual(b2h(apdu), '80ec010113' 'b50103' 'b9020400' 'bc03011771' 'be05210a000001')
+
+ def test_cattp_link(self):
+ self.assertEqual(b2h(encode_push_cattp_link(6001)), '80ec010205' 'bc03001771')
+ apdu = encode_push_cattp_link(6001, max_sdu_size=512, identification=h2b('0102'))
+ self.assertEqual(b2h(apdu), '80ec01020d' 'bc03001771' 'b9020200' 'b6020102')
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43718?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Ib3423c4fe582dbcc9434c8234709a7b845fa6bcd
Gerrit-Change-Number: 43718
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0
[XL] Change in pysim[master]: cattp: ETSI TS 102 127 transport for OTA over BIP UDP
by Hoernchen 23 Sep '26
by Hoernchen 23 Sep '26
23 Sep '26
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43719?usp=email )
Change subject: cattp: ETSI TS 102 127 transport for OTA over BIP UDP
......................................................................
cattp: ETSI TS 102 127 transport for OTA over BIP UDP
While this might look like "hand rolled TCP over UDP done wrong" is is
actually amazing 80s technology, based on RFC 908/1151 RDP v2.
It supports:
- three way handshake
- cumulative and extended ACKs
- retransmission with retry limit
- windows
- SEG(ments) reassembly
- NUL and RST
Has a server side the card connects to + client side for the tests, just
like scp81.
Change-Id: I6f31493c1f0fb48fb3fd5382d8af2c905d365e54
---
A pySim/cattp.py
A tests/unittests/test_cattp.py
2 files changed, 1,000 insertions(+), 0 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/19/43719/1
diff --git a/pySim/cattp.py b/pySim/cattp.py
new file mode 100644
index 0000000..ab6f346
--- /dev/null
+++ b/pySim/cattp.py
@@ -0,0 +1,605 @@
+# -*- coding: utf-8 -*-
+"""CAT_TP, the Card Application Toolkit Transport Protocol of ETSI TS 102 127"""
+
+# (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/>.
+
+# A reliable, sequenced datagram transport that a card runs over a BIP UDP channel to carry
+# TS 102 225 secured packets, one per SDU. It is the Reliable Data Protocol of RFC 908/1151
+# (handshake, sequence numbers, cumulative and extended ACKs, retransmission, per datagram
+# rather than per byte stream) plus a SEG bit to spread one SDU over several PDUs.
+# Server side, the card connects here after a TS 102 226 PUSH. The client side exists for
+# the tests.
+#
+# CatTpConnection is the protocol state machine without a socket, driven by tests or by the
+# UDP socket of CatTpServer: received PDUs go to on_pdu(), the clock to on_timer(), pop_tx()
+# returns the PDUs to send.
+
+import collections
+import logging
+import random
+import socket
+import threading
+import time
+from typing import Callable, Dict, List, Optional, Tuple
+
+from osmocom.utils import b2h
+
+logger = logging.getLogger(__name__)
+
+# TS 102 127 5.6.1 first octet: b8..b3 flags, b2..b1 version
+FLAG_SYN = 0x80
+FLAG_ACK = 0x40
+FLAG_EACK = 0x20
+FLAG_RST = 0x10
+FLAG_NUL = 0x08
+FLAG_SEG = 0x04
+VERSION = 0
+
+HDR_LEN = 18 # TS 102 127 5.6.2, without a variable header area
+
+# TS 102 127 5.10.1.4
+RST_NORMAL = 0x00
+RST_ILLEGAL_PARAMS = 0x01
+RST_TEMP_UNABLE = 0x02
+RST_PORT_NOT_AVAILABLE = 0x03
+RST_UNEXPECTED_PDU = 0x04
+RST_MAX_RETRIES = 0x05
+RST_VERSION = 0x06
+RST_REASONS = {RST_NORMAL: 'normal ending', RST_ILLEGAL_PARAMS: 'illegal parameters',
+ RST_TEMP_UNABLE: 'temporarily unable', RST_PORT_NOT_AVAILABLE: 'port not available',
+ RST_UNEXPECTED_PDU: 'unexpected PDU', RST_MAX_RETRIES: 'maximum retries exceeded',
+ RST_VERSION: 'version not supported'}
+
+
+def checksum(data: bytes) -> int:
+ """TS 102 127 5.3.2.2: the RFC 793 checksum without the pseudo header"""
+ if len(data) & 1:
+ data += b'\x00'
+ total = sum(int.from_bytes(data[i:i + 2], 'big') for i in range(0, len(data), 2))
+ while total >> 16:
+ total = (total & 0xffff) + (total >> 16)
+ return (~total) & 0xffff
+
+
+def _seq_diff(a: int, b: int) -> int:
+ """a - b modulo 2^16, < 0x8000 means a is at or after b"""
+ return (a - b) & 0xffff
+
+
+class CatTpError(Exception):
+ pass
+
+
+class Pdu:
+ """One CAT_TP PDU, TS 102 127 5.6 to 5.11"""
+ __slots__ = ('flags', 'version', 'src_port', 'dst_port', 'seq', 'ack', 'window', 'data',
+ 'eack', 'max_pdu', 'max_sdu', 'identification', 'rst_reason')
+
+ def __init__(self, flags: int, src_port: int, dst_port: int, seq: int = 0, ack: int = 0,
+ window: int = 0, data: bytes = b'', eack: Tuple[int, ...] = (),
+ max_pdu: int = 0, max_sdu: int = 0, identification: bytes = b'',
+ rst_reason: int = RST_NORMAL, version: int = VERSION):
+ self.flags = flags
+ self.version = version
+ self.src_port = src_port
+ self.dst_port = dst_port
+ self.seq = seq
+ self.ack = ack
+ self.window = window
+ self.data = bytes(data)
+ self.eack = tuple(eack)
+ self.max_pdu = max_pdu
+ self.max_sdu = max_sdu
+ self.identification = bytes(identification)
+ self.rst_reason = rst_reason
+
+ syn = property(lambda self: bool(self.flags & FLAG_SYN))
+ has_ack = property(lambda self: bool(self.flags & FLAG_ACK))
+ has_eack = property(lambda self: bool(self.flags & FLAG_EACK))
+ rst = property(lambda self: bool(self.flags & FLAG_RST))
+ nul = property(lambda self: bool(self.flags & FLAG_NUL))
+ seg = property(lambda self: bool(self.flags & FLAG_SEG))
+
+ @property
+ def needs_ack(self) -> bool:
+ """TS 102 127 5.3.2.1: SYN, NUL and data PDUs consume a sequence number and get acknowledged"""
+ return self.syn or self.nul or len(self.data) > 0
+
+ def _variable_header(self) -> bytes:
+ var = b''
+ if self.syn:
+ var += self.max_pdu.to_bytes(2, 'big') + self.max_sdu.to_bytes(2, 'big')
+ var += bytes([len(self.identification)]) + self.identification
+ elif self.has_eack:
+ var += b''.join(s.to_bytes(2, 'big') for s in self.eack)
+ if self.rst:
+ var += bytes([self.rst_reason])
+ return var
+
+ def to_bytes(self) -> bytes:
+ var = self._variable_header()
+ hdr = bytearray([self.flags | (self.version & 0x03), 0, 0, HDR_LEN + len(var)])
+ hdr += self.src_port.to_bytes(2, 'big') + self.dst_port.to_bytes(2, 'big')
+ hdr += len(self.data).to_bytes(2, 'big')
+ hdr += self.seq.to_bytes(2, 'big') + self.ack.to_bytes(2, 'big')
+ hdr += self.window.to_bytes(2, 'big') + b'\x00\x00' + var
+ csum = checksum(bytes(hdr) + self.data)
+ hdr[16:18] = csum.to_bytes(2, 'big')
+ return bytes(hdr) + self.data
+
+ @classmethod
+ def from_bytes(cls, raw: bytes) -> 'Pdu':
+ if len(raw) < HDR_LEN:
+ raise CatTpError('PDU of %u octets is shorter than the header' % len(raw))
+ hdr_len = raw[3]
+ data_len = int.from_bytes(raw[8:10], 'big')
+ if hdr_len < HDR_LEN or hdr_len + data_len != len(raw):
+ raise CatTpError('header length %u + data length %u != %u octets' %
+ (hdr_len, data_len, len(raw)))
+ if checksum(raw[:16] + b'\x00\x00' + raw[18:]) != int.from_bytes(raw[16:18], 'big'):
+ raise CatTpError('checksum mismatch')
+ pdu = cls(raw[0] & 0xfc, int.from_bytes(raw[4:6], 'big'), int.from_bytes(raw[6:8], 'big'),
+ seq=int.from_bytes(raw[10:12], 'big'), ack=int.from_bytes(raw[12:14], 'big'),
+ window=int.from_bytes(raw[14:16], 'big'), data=raw[hdr_len:],
+ version=raw[0] & 0x03)
+ var = raw[HDR_LEN:hdr_len]
+ if pdu.syn:
+ if len(var) < 5 or len(var) != 5 + var[4]:
+ raise CatTpError('malformed SYN variable header')
+ pdu.max_pdu = int.from_bytes(var[0:2], 'big')
+ pdu.max_sdu = int.from_bytes(var[2:4], 'big')
+ pdu.identification = var[5:]
+ var = b''
+ elif pdu.has_eack:
+ n = len(var) - (1 if pdu.rst else 0)
+ if n & 1:
+ raise CatTpError('malformed EACK variable header')
+ pdu.eack = tuple(int.from_bytes(var[i:i + 2], 'big') for i in range(0, n, 2))
+ var = var[n:]
+ if pdu.rst:
+ if len(var) != 1:
+ raise CatTpError('malformed RST variable header')
+ pdu.rst_reason = var[0]
+ return pdu
+
+ def __repr__(self):
+ names = [n for f, n in ((FLAG_SYN, 'SYN'), (FLAG_ACK, 'ACK'), (FLAG_EACK, 'EACK'),
+ (FLAG_RST, 'RST'), (FLAG_NUL, 'NUL'), (FLAG_SEG, 'SEG')) if self.flags & f]
+ s = '<%s %u->%u seq=%u ack=%u win=%u len=%u' % ('/'.join(names) or 'DATA', self.src_port,
+ self.dst_port, self.seq, self.ack, self.window,
+ len(self.data))
+ if self.syn:
+ s += ' max_pdu=%u max_sdu=%u id=%s' % (self.max_pdu, self.max_sdu, b2h(self.identification))
+ if self.eack:
+ s += ' eack=%s' % (self.eack,)
+ if self.rst:
+ s += ' reason=%s' % RST_REASONS.get(self.rst_reason, self.rst_reason)
+ return s + '>'
+
+
+class CatTpConnection:
+ """One connection, TS 102 127 5.3.1.4 connection record and 5.4 event processing.
+
+ Upper layer hooks:
+ - on_sdu(conn, sdu) for every reassembled SDU
+ - on_state(conn, state) on every state change, 'OPEN' is when to start sending
+ Calling send_sdu() from inside on_sdu() puts the ACK into the data PDU instead of a separate one.
+ clock is only there for tests to fake time.
+ """
+ CLOSED, LISTEN, SYN_SENT, SYN_RCVD, OPEN, CLOSE_WAIT = ('CLOSED', 'LISTEN', 'SYN-SENT',
+ 'SYN-RCVD', 'OPEN', 'CLOSE-WAIT')
+
+ def __init__(self, local_port: int, *, max_pdu: int = 1024, max_sdu: int = 65535,
+ window: int = 4, rto: float = 3.0, max_retries: int = 3, close_wait: float = 2.0,
+ on_sdu: Optional[Callable[['CatTpConnection', bytes], None]] = None,
+ on_state: Optional[Callable[['CatTpConnection', str], None]] = None,
+ clock: Callable[[], float] = time.monotonic):
+ self.clock = clock
+ self.local_port = local_port
+ self.remote_port = 0
+ self.state = self.CLOSED
+ self.rto = rto
+ self.max_retries = max_retries
+ self.close_wait = close_wait
+ self.on_sdu = on_sdu
+ self.on_state = on_state
+ self.peer_identification = b''
+ self.close_reason: Optional[int] = None
+ # sending activity, 5.3.1.4.2
+ self.snd_ini = 0
+ self.snd_nxt = 0
+ self.snd_una = 0
+ self.snd_pdu_max = 0
+ self.snd_sdu_max = 0
+ self.snd_right = 0 # last sequence number the peer window allows
+ # receiving activity, 5.3.1.4.3
+ self.rcv_ini = 0
+ self.rcv_cur = 0
+ self.rcv_out_of_seq: Dict[int, Pdu] = {}
+ self.rcv_pdu_max = max_pdu
+ self.rcv_sdu_max = max_sdu
+ self.rcv_win = window
+ self._rx_sdu = bytearray()
+ # [pdu, sent_at, retries] awaiting acknowledgement, in sequence order
+ self._rtx: List[list] = []
+ self._tx_wait: collections.deque = collections.deque() # data PDUs beyond the window
+ self._tx: List[bytes] = []
+ self._close_deadline: Optional[float] = None
+ self._ack_pending = False
+ self._data_sent = False
+
+ def __repr__(self):
+ return '<CatTpConnection %s %u<->%u snd_nxt=%u snd_una=%u rcv_cur=%u>' % (
+ self.state, self.local_port, self.remote_port, self.snd_nxt, self.snd_una, self.rcv_cur)
+
+ def listen(self):
+ """TS 102 127 5.4.1.1 passive open"""
+ self._set_state(self.LISTEN)
+
+ def connect(self, remote_port: int, identification: bytes = b''):
+ """TS 102 127 5.4.1.1 active open, what the card does after the PUSH"""
+ self.remote_port = remote_port
+ self._init_send()
+ self._queue(Pdu(FLAG_SYN, self.local_port, remote_port, seq=self.snd_ini, window=self.rcv_win,
+ max_pdu=self.rcv_pdu_max, max_sdu=self.rcv_sdu_max,
+ identification=identification))
+ self._set_state(self.SYN_SENT)
+
+ def send_sdu(self, sdu: bytes):
+ """TS 102 127 5.4.1.4: segment into data PDUs (5.2.3), send what the window allows"""
+ if self.state != self.OPEN:
+ raise CatTpError('cannot send in state %s' % self.state)
+ if len(sdu) > self.snd_sdu_max:
+ raise CatTpError('SDU of %u octets exceeds peer max SDU size %u' % (len(sdu), self.snd_sdu_max))
+ chunk = self.snd_pdu_max - HDR_LEN
+ if chunk < 1:
+ raise CatTpError('peer max PDU size %u leaves no room for data' % self.snd_pdu_max)
+ segments = [sdu[i:i + chunk] for i in range(0, len(sdu), chunk)] or [b'']
+ for i, seg in enumerate(segments):
+ flags = FLAG_ACK | (FLAG_SEG if i < len(segments) - 1 else 0)
+ self._tx_wait.append(Pdu(flags, self.local_port, self.remote_port, seq=self.snd_nxt, data=seg))
+ self.snd_nxt = (self.snd_nxt + 1) & 0xffff
+ self._flush_window()
+
+ def send_nul(self):
+ """TS 102 127 5.3.1.6 probe for a half open connection"""
+ if self.state != self.OPEN:
+ raise CatTpError('cannot send in state %s' % self.state)
+ self._tx_wait.append(Pdu(FLAG_NUL | FLAG_ACK, self.local_port, self.remote_port, seq=self.snd_nxt))
+ self.snd_nxt = (self.snd_nxt + 1) & 0xffff
+ self._flush_window()
+
+ def close(self, reason: int = RST_NORMAL):
+ """TS 102 127 5.4.1.2: RST, then CLOSE-WAIT until the timer expires"""
+ if self.state in (self.CLOSED, self.CLOSE_WAIT):
+ return
+ if self.state == self.LISTEN:
+ self._set_state(self.CLOSED)
+ return
+ flags = FLAG_RST | (FLAG_ACK if self.state in (self.OPEN, self.SYN_RCVD) else 0)
+ self._queue(Pdu(flags, self.local_port, self.remote_port, seq=self.snd_nxt, ack=self.rcv_cur,
+ window=self.rcv_win, rst_reason=reason))
+ self._enter_close_wait(reason)
+
+ def pop_tx(self) -> List[bytes]:
+ """serialised PDUs to hand to the socket, in order"""
+ out, self._tx = self._tx, []
+ return out
+
+ def on_timer(self) -> Optional[float]:
+ """TS 102 127 5.4.3: retransmit what is overdue, returns the next deadline or None"""
+ now = self.clock()
+ if self.state == self.CLOSE_WAIT:
+ if now >= self._close_deadline:
+ self._rtx.clear()
+ self._set_state(self.CLOSED)
+ return None
+ return self._close_deadline
+ for entry in self._rtx:
+ pdu, sent_at, retries = entry
+ if now - sent_at < self.rto:
+ continue
+ if retries >= self.max_retries:
+ logger.warning('%r: %r not acknowledged after %u retries', self, pdu, retries)
+ self.close(RST_MAX_RETRIES)
+ return self._close_deadline
+ logger.debug('%r: retransmit %r', self, pdu)
+ entry[1], entry[2] = now, retries + 1
+ self._emit(pdu)
+ deadlines = [sent_at + self.rto for _, sent_at, _ in self._rtx]
+ return min(deadlines) if deadlines else None
+
+ def on_pdu(self, raw: bytes):
+ """TS 102 127 5.4.2 PDU arrival"""
+ try:
+ pdu = Pdu.from_bytes(raw)
+ except CatTpError as e:
+ logger.warning('%r: discarding PDU: %s', self, e)
+ return
+ if len(raw) > self.rcv_pdu_max:
+ logger.warning('%r: discarding %u octet PDU above max PDU size', self, len(raw))
+ return
+ logger.debug('%r: rx %r', self, pdu)
+ self._ack_pending = False
+ self._data_sent = False
+ handler = {self.CLOSED: self._rx_closed, self.LISTEN: self._rx_listen,
+ self.SYN_SENT: self._rx_syn_sent, self.SYN_RCVD: self._rx_syn_rcvd,
+ self.OPEN: self._rx_open, self.CLOSE_WAIT: self._rx_close_wait}[self.state]
+ handler(pdu)
+ # the upper layer may have closed the connection from its callback, TS 102 127 5.3.1.5:
+ # nothing is sent in CLOSE-WAIT
+ if self._ack_pending and not self._data_sent and self.state == self.OPEN:
+ self._queue(self._ack_pdu())
+
+ def _rx_closed(self, pdu: Pdu):
+ # TS 102 127 5.4.2.1: tell the peer nobody is home, RST is never answered
+ if not pdu.rst:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, pdu.src_port, ack=pdu.seq,
+ rst_reason=RST_PORT_NOT_AVAILABLE))
+
+ def _rx_close_wait(self, pdu: Pdu):
+ pass # TS 102 127 5.3.1.5: discarded
+
+ def _rx_listen(self, pdu: Pdu):
+ # TS 102 127 5.4.2.3: only a SYN gets us anywhere
+ if pdu.rst:
+ return
+ if not pdu.syn or pdu.has_ack:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, pdu.src_port, ack=pdu.seq,
+ rst_reason=RST_UNEXPECTED_PDU))
+ return
+ if pdu.max_pdu < HDR_LEN + 1:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, pdu.src_port, ack=pdu.seq,
+ rst_reason=RST_ILLEGAL_PARAMS))
+ return
+ self.remote_port = pdu.src_port
+ self.rcv_ini = self.rcv_cur = pdu.seq
+ self.peer_identification = pdu.identification
+ self._init_send(pdu)
+ # TS 102 127 5.3.1.7: answer with our version, TS 102 226 9.2.2: empty identification
+ self._queue(Pdu(FLAG_SYN | FLAG_ACK, self.local_port, self.remote_port, seq=self.snd_ini,
+ ack=self.rcv_cur, window=self.rcv_win, max_pdu=self.rcv_pdu_max,
+ max_sdu=self.rcv_sdu_max))
+ self._set_state(self.SYN_RCVD)
+
+ def _rx_syn_sent(self, pdu: Pdu):
+ # TS 102 127 5.4.2.4
+ if pdu.rst:
+ self._enter_close_wait(pdu.rst_reason)
+ return
+ if not (pdu.syn and pdu.has_ack) or pdu.ack != self.snd_ini:
+ self._queue(Pdu(FLAG_RST, self.local_port, self.remote_port, seq=self.snd_nxt,
+ rst_reason=RST_UNEXPECTED_PDU))
+ self._enter_close_wait(RST_UNEXPECTED_PDU)
+ return
+ if pdu.version != VERSION:
+ self.close(RST_VERSION)
+ return
+ self.rcv_ini = self.rcv_cur = pdu.seq
+ self.peer_identification = pdu.identification
+ self.snd_pdu_max, self.snd_sdu_max = pdu.max_pdu, pdu.max_sdu
+ self._process_ack(pdu)
+ self._set_state(self.OPEN)
+ self._ack_pending = True
+
+ def _rx_syn_rcvd(self, pdu: Pdu):
+ # TS 102 127 5.4.2.5
+ if pdu.rst:
+ self._rtx.clear()
+ self._set_state(self.LISTEN)
+ return
+ if pdu.syn:
+ if pdu.seq == self.rcv_ini and not pdu.has_ack:
+ self._retransmit_syn_ack() # our SYN/ACK got lost
+ return
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, self.remote_port, ack=pdu.seq,
+ rst_reason=RST_UNEXPECTED_PDU))
+ self._enter_close_wait(RST_UNEXPECTED_PDU)
+ return
+ if not pdu.has_ack or pdu.ack != self.snd_ini:
+ return
+ self._set_state(self.OPEN)
+ self._rx_open(pdu)
+
+ def _rx_open(self, pdu: Pdu):
+ # TS 102 127 5.4.2.2, figures 25 to 28
+ if pdu.rst:
+ logger.info('%r: peer reset, %s', self, RST_REASONS.get(pdu.rst_reason, pdu.rst_reason))
+ self._enter_close_wait(pdu.rst_reason)
+ return
+ if pdu.syn:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, self.remote_port, ack=pdu.seq,
+ rst_reason=RST_UNEXPECTED_PDU))
+ self._enter_close_wait(RST_UNEXPECTED_PDU)
+ return
+ if pdu.has_ack:
+ self._process_ack(pdu)
+ if not pdu.needs_ack:
+ return
+ self._ack_pending = True
+ d = _seq_diff(pdu.seq, self.rcv_cur)
+ if d == 0 or d > self.rcv_win:
+ logger.debug('%r: seq %u outside window, duplicate ACK', self, pdu.seq)
+ return
+ if d != 1:
+ self.rcv_out_of_seq[pdu.seq] = pdu # TS 102 127 5.3.3: in the window but out of sequence
+ return
+ self._accept(pdu)
+ while ((self.rcv_cur + 1) & 0xffff) in self.rcv_out_of_seq:
+ self._accept(self.rcv_out_of_seq.pop((self.rcv_cur + 1) & 0xffff))
+
+ def _accept(self, pdu: Pdu):
+ self.rcv_cur = pdu.seq
+ if pdu.nul:
+ return
+ self._rx_sdu += pdu.data
+ if len(self._rx_sdu) > self.rcv_sdu_max:
+ logger.warning('%r: SDU exceeds %u octets', self, self.rcv_sdu_max)
+ self.close(RST_ILLEGAL_PARAMS)
+ return
+ if pdu.seg:
+ return
+ sdu, self._rx_sdu = bytes(self._rx_sdu), bytearray()
+ if self.on_sdu:
+ self.on_sdu(self, sdu)
+
+ def _set_state(self, state: str):
+ logger.info('%r: %s -> %s', self, self.state, state)
+ self.state = state
+ if self.on_state:
+ self.on_state(self, state)
+
+ def _enter_close_wait(self, reason: int):
+ self.close_reason = reason
+ self._rtx.clear()
+ self._tx_wait.clear()
+ self._close_deadline = self.clock() + self.close_wait
+ self._set_state(self.CLOSE_WAIT)
+
+ def _init_send(self, syn: Optional[Pdu] = None):
+ self.snd_ini = random.randrange(0x10000)
+ self.snd_nxt = (self.snd_ini + 1) & 0xffff
+ self.snd_una = self.snd_ini
+ self.snd_right = self.snd_ini
+ if syn is not None:
+ self.snd_pdu_max, self.snd_sdu_max = syn.max_pdu, syn.max_sdu
+
+ def _retransmit_syn_ack(self):
+ for entry in self._rtx:
+ if entry[0].syn:
+ entry[1] = self.clock()
+ self._emit(entry[0])
+
+ def _ack_pdu(self) -> Pdu:
+ """(E)ACK without data, seq is SND_NXT and is not consumed, TS 102 127 figure 45"""
+ pdu = Pdu(FLAG_ACK, self.local_port, self.remote_port, seq=self.snd_nxt)
+ if self.rcv_out_of_seq:
+ pdu.flags |= FLAG_EACK
+ pdu.eack = tuple(sorted(self.rcv_out_of_seq))
+ return pdu
+
+ def _process_ack(self, pdu: Pdu):
+ # only acknowledgements within SND_UNA-1 .. SND_NXT-1 are meaningful
+ base = (self.snd_una - 1) & 0xffff
+ if _seq_diff(pdu.ack, base) > _seq_diff((self.snd_nxt - 1) & 0xffff, base):
+ logger.debug('%r: ignoring ack %u outside %u..%u', self, pdu.ack, base, self.snd_nxt - 1)
+ return
+ acked = set(pdu.eack)
+ self._rtx = [e for e in self._rtx
+ if _seq_diff(pdu.ack, e[0].seq) >= 0x8000 and e[0].seq not in acked]
+ if _seq_diff(pdu.ack, self.snd_una) < 0x8000:
+ self.snd_una = (pdu.ack + 1) & 0xffff
+ # TS 102 127 5.3.3: the right window border never moves left
+ right = (pdu.ack + pdu.window) & 0xffff
+ if _seq_diff(right, self.snd_right) < 0x8000:
+ self.snd_right = right
+ self._flush_window()
+
+ def _flush_window(self):
+ while self._tx_wait and _seq_diff(self.snd_right, self._tx_wait[0].seq) < 0x8000:
+ pdu = self._tx_wait.popleft()
+ self._queue(pdu)
+ self._data_sent = True
+
+ def _queue(self, pdu: Pdu):
+ """TS 102 127 5.3.2.4 serialization/retransmission"""
+ if pdu.needs_ack:
+ self._rtx.append([pdu, self.clock(), 0])
+ self._emit(pdu)
+
+ def _emit(self, pdu: Pdu):
+ if pdu.has_ack and not (pdu.syn or pdu.rst):
+ pdu.ack, pdu.window = self.rcv_cur, self.rcv_win
+ logger.debug('%r: tx %r', self, pdu)
+ self._tx.append(pdu.to_bytes())
+
+
+class CatTpServer:
+ """One UDP socket, a listening CatTpConnection per peer address, single threaded.
+
+ on_sdu / on_state run on the server thread, sending from them puts the response and the
+ ACK into the same PDU."""
+ POLL = 0.05
+
+ def __init__(self, host: str, port: int, on_sdu=None, on_state=None, **conn_kwargs):
+ self.host = host
+ self.port = port
+ self.on_sdu = on_sdu
+ self.on_state = on_state
+ self.conn_kwargs = conn_kwargs
+ self.conns: Dict[tuple, CatTpConnection] = {}
+ self._sock: Optional[socket.socket] = None
+ self._stop = threading.Event()
+ self._lock = threading.RLock()
+
+ def bind(self) -> int:
+ self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self._sock.bind((self.host, self.port))
+ self._sock.settimeout(self.POLL)
+ self.port = self._sock.getsockname()[1]
+ return self.port
+
+ def serve_forever(self):
+ if self._sock is None:
+ self.bind()
+ logger.info('CAT_TP server listening on %s:%u/udp', self.host, self.port)
+ while not self._stop.is_set():
+ try:
+ raw, addr = self._sock.recvfrom(65535)
+ except socket.timeout:
+ raw, addr = None, None
+ except OSError:
+ break
+ with self._lock:
+ if raw is not None:
+ conn = self.conns.get(addr)
+ if conn is None:
+ conn = CatTpConnection(self.port, on_sdu=self.on_sdu, on_state=self.on_state,
+ **self.conn_kwargs)
+ conn.listen()
+ self.conns[addr] = conn
+ conn.on_pdu(raw)
+ self._flush(conn, addr)
+ self._tick()
+
+ def _tick(self):
+ for addr, conn in list(self.conns.items()):
+ conn.on_timer()
+ self._flush(conn, addr)
+ if conn.state == CatTpConnection.CLOSED:
+ del self.conns[addr]
+
+ def _flush(self, conn: CatTpConnection, addr):
+ for raw in conn.pop_tx():
+ try:
+ self._sock.sendto(raw, addr)
+ except OSError as e:
+ logger.warning('sendto %s failed: %s', addr, e)
+
+ def send_sdu(self, conn: CatTpConnection, sdu: bytes):
+ """thread safe entry for callers outside the server thread"""
+ with self._lock:
+ conn.send_sdu(sdu)
+ addr = next(a for a, c in self.conns.items() if c is conn)
+ self._flush(conn, addr)
+
+ def shutdown(self):
+ self._stop.set()
+ if self._sock is not None:
+ self._sock.close()
diff --git a/tests/unittests/test_cattp.py b/tests/unittests/test_cattp.py
new file mode 100644
index 0000000..5705acb
--- /dev/null
+++ b/tests/unittests/test_cattp.py
@@ -0,0 +1,395 @@
+#!/usr/bin/env python3
+
+# (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 socket
+import threading
+import time
+import unittest
+from unittest import mock
+
+from osmocom.utils import b2h, h2b
+
+from pySim.cattp import (Pdu, CatTpConnection, CatTpServer, CatTpError, checksum,
+ FLAG_SYN, FLAG_ACK, FLAG_EACK, FLAG_RST, FLAG_NUL, FLAG_SEG,
+ RST_NORMAL, RST_MAX_RETRIES, RST_VERSION, RST_UNEXPECTED_PDU)
+
+
+class PduCodecTest(unittest.TestCase):
+
+ def test_checksum_rfc1071_example(self):
+ self.assertEqual(checksum(h2b('0001f203f4f5f6f7')), 0x220d)
+
+ def test_syn_golden(self):
+ # TS 102 127 5.7: flags|ver 80, RFU, header length 17 (18 + max PDU + max SDU + id length), ports,
+ # data length 0, seq 100, ack, window, checksum, max PDU 1024, max SDU 1024, id length 0
+ pdu = Pdu(FLAG_SYN, 1024, 6001, seq=100, window=4, max_pdu=1024, max_sdu=1024)
+ raw = pdu.to_bytes()
+ self.assertEqual(b2h(raw), '80000017' '0400' '1771' '0000' '0064' '0000' '0004' '5c0f'
+ '0400' '0400' '00')
+ back = Pdu.from_bytes(raw)
+ self.assertTrue(back.syn)
+ self.assertEqual((back.src_port, back.dst_port, back.seq, back.window), (1024, 6001, 100, 4))
+ self.assertEqual((back.max_pdu, back.max_sdu, back.identification), (1024, 1024, b''))
+
+ def test_flag_bits(self):
+ # TS 102 127 figure 39: b8 SYN, b7 ACK, b6 EACK, b5 RST, b4 NUL, b3 SEG, b2..b1 version
+ self.assertEqual((FLAG_SYN, FLAG_ACK, FLAG_EACK, FLAG_RST, FLAG_NUL, FLAG_SEG),
+ (0x80, 0x40, 0x20, 0x10, 0x08, 0x04))
+ self.assertEqual(Pdu(FLAG_ACK | FLAG_SEG, 1, 2, data=b'x').to_bytes()[0], 0x44)
+ self.assertEqual(Pdu(FLAG_SYN, 1, 2, version=1).to_bytes()[0], 0x81)
+
+ def test_roundtrip_all_types(self):
+ cases = [
+ Pdu(FLAG_SYN, 5000, 6001, seq=7, window=2, max_pdu=512, max_sdu=2048,
+ identification=h2b('89490200001234567890')),
+ Pdu(FLAG_SYN | FLAG_ACK, 6001, 5000, seq=9, ack=7, window=4, max_pdu=1024, max_sdu=65535),
+ Pdu(FLAG_ACK, 6001, 5000, seq=10, ack=8, window=4),
+ Pdu(FLAG_ACK, 6001, 5000, seq=10, ack=8, window=4, data=bytes(range(200))),
+ Pdu(FLAG_ACK | FLAG_SEG, 6001, 5000, seq=10, ack=8, window=4, data=b'seg'),
+ Pdu(FLAG_ACK | FLAG_EACK, 6001, 5000, seq=10, ack=8, window=4, eack=(10, 12)),
+ Pdu(FLAG_ACK | FLAG_EACK, 6001, 5000, seq=10, ack=8, window=4, eack=(11,), data=b'd'),
+ Pdu(FLAG_RST, 6001, 5000, seq=10, rst_reason=RST_VERSION),
+ Pdu(FLAG_RST | FLAG_ACK, 6001, 5000, seq=10, ack=8, rst_reason=RST_NORMAL),
+ Pdu(FLAG_NUL | FLAG_ACK, 6001, 5000, seq=10, ack=8, window=4),
+ Pdu(FLAG_NUL | FLAG_ACK | FLAG_EACK, 6001, 5000, seq=10, ack=8, window=4, eack=(10,)),
+ ]
+ for pdu in cases:
+ with self.subTest(pdu=repr(pdu)):
+ raw = pdu.to_bytes()
+ self.assertEqual(raw[3] + len(pdu.data), len(raw)) # header length
+ back = Pdu.from_bytes(raw)
+ for f in Pdu.__slots__:
+ self.assertEqual(getattr(back, f), getattr(pdu, f), f)
+ self.assertEqual(back.to_bytes(), raw)
+
+ def test_rejects_damaged(self):
+ raw = bytearray(Pdu(FLAG_ACK, 1, 2, seq=1, data=b'abc').to_bytes())
+ raw[-1] ^= 0x01
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(bytes(raw))
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(bytes(raw[:10]))
+ raw = bytearray(Pdu(FLAG_ACK, 1, 2, seq=1, data=b'abc').to_bytes())
+ raw[9] += 1 # data length lies
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(bytes(raw))
+
+
+class _Clock:
+ def __init__(self):
+ self.t = 1000.0
+
+ def __call__(self):
+ return self.t
+
+
+class _Pair:
+ """client and server connection joined back to back, PDUs move via pump()"""
+
+ def __init__(self, test, client_kwargs=None, server_kwargs=None, isn=(100, 200)):
+ self.test = test
+ self.clock = _Clock()
+ self.log = [] # (direction, Pdu)
+ self.client_sdus = []
+ self.server_sdus = []
+ self.states = []
+ self.client = CatTpConnection(1024, clock=self.clock, on_sdu=lambda c, s: self.client_sdus.append(s),
+ on_state=lambda c, s: self.states.append(('client', s)),
+ **(client_kwargs or {}))
+ self.server = CatTpConnection(6001, clock=self.clock, on_sdu=lambda c, s: self.server_sdus.append(s),
+ on_state=lambda c, s: self.states.append(('server', s)),
+ **(server_kwargs or {}))
+ self.isn = list(isn)
+ self.drop = []
+
+ def _isn(self, *_):
+ return self.isn.pop(0)
+
+ def open(self, identification=b''):
+ with mock.patch('pySim.cattp.random.randrange', side_effect=self._isn):
+ self.server.listen()
+ self.client.connect(6001, identification)
+ self.pump()
+
+ def pump(self):
+ """move PDUs both ways until nothing is left"""
+ moved = True
+ while moved:
+ moved = False
+ for src, dst, direction in ((self.client, self.server, '>'), (self.server, self.client, '<')):
+ for raw in src.pop_tx():
+ moved = True
+ pdu = Pdu.from_bytes(raw)
+ if any(d(direction, pdu) for d in self.drop):
+ self.log.append((direction + 'x', pdu))
+ continue
+ self.log.append((direction, pdu))
+ dst.on_pdu(raw)
+
+ def trace(self):
+ return [(d, p.flags, p.seq, p.ack, len(p.data)) for d, p in self.log]
+
+ def advance(self, seconds):
+ self.clock.t += seconds
+ self.client.on_timer()
+ self.server.on_timer()
+ self.pump()
+
+
+class ConnectionTest(unittest.TestCase):
+
+ def test_handshake_annex_a1(self):
+ p = _Pair(self)
+ p.open(identification=h2b('8949'))
+ self.assertEqual(p.trace(), [
+ ('>', FLAG_SYN, 100, 0, 0), # 2. <SEQ=100><SYN>
+ ('<', FLAG_SYN | FLAG_ACK, 200, 100, 0), # 3. <SEQ=200><ACK=100><SYN,ACK>
+ ('>', FLAG_ACK, 101, 200, 0), # 4. <SEQ=101><ACK=200>
+ ])
+ self.assertEqual((p.client.state, p.server.state), ('OPEN', 'OPEN'))
+ self.assertEqual(p.server.peer_identification, h2b('8949'))
+ self.assertEqual(p.client.peer_identification, b'') # TS 102 226 9.2.2
+ self.assertEqual((p.client.snd_nxt, p.client.rcv_cur), (101, 200))
+ self.assertEqual((p.server.snd_nxt, p.server.rcv_cur), (201, 100))
+ self.assertEqual(p.server._rtx, []) # SYN/ACK acknowledged
+ # 5./6. data goes out with the next sequence number and gets an ACK without data
+ p.client.send_sdu(b'hello')
+ p.pump()
+ self.assertEqual(p.trace()[3:], [('>', FLAG_ACK, 101, 200, 5), ('<', FLAG_ACK, 201, 101, 0)])
+ self.assertEqual(p.server_sdus, [b'hello'])
+ self.assertEqual(p.client._rtx, [])
+
+ def test_request_response_piggyback(self):
+ p = _Pair(self)
+ p.open()
+ # the server answers from within on_sdu, so the ACK rides on the response data
+ p.server.on_sdu = lambda c, s: c.send_sdu(b'resp:' + s)
+ p.client.send_sdu(b'cmd')
+ p.pump()
+ self.assertEqual(p.trace()[3:], [('>', FLAG_ACK, 101, 200, 3),
+ ('<', FLAG_ACK, 201, 101, 8),
+ ('>', FLAG_ACK, 102, 201, 0)])
+ self.assertEqual(p.client_sdus, [b'resp:cmd'])
+
+ def test_lost_pdu_annex_a2(self):
+ p = _Pair(self, client_kwargs={'rto': 1.0})
+ p.open()
+ p.drop.append(lambda d, pdu: d == '>' and pdu.seq == 102 and len(pdu.data))
+ for sdu in (b'a', b'b', b'c', b'd'):
+ p.client.send_sdu(sdu)
+ p.pump()
+ del p.drop[:]
+ # 102 was lost: 101 acked, 103 and 104 acknowledged out of sequence with EACK
+ self.assertEqual([t for t in p.trace()[3:] if t[0] == '<'], [
+ ('<', FLAG_ACK, 201, 101, 0),
+ ('<', FLAG_ACK | FLAG_EACK, 201, 101, 0),
+ ('<', FLAG_ACK | FLAG_EACK, 201, 101, 0)])
+ self.assertEqual(p.log[-1][1].eack, (103, 104))
+ self.assertEqual(p.server_sdus, [b'a'])
+ self.assertEqual([e[0].seq for e in p.client._rtx], [102])
+ # retransmission timer fires, only 102 goes again and the cumulative ACK jumps to 104
+ p.advance(1.5)
+ self.assertEqual(p.trace()[-2:], [('>', FLAG_ACK, 102, 200, 1), ('<', FLAG_ACK, 201, 104, 0)])
+ self.assertEqual(p.server_sdus, [b'a', b'b', b'c', b'd'])
+ self.assertEqual(p.client._rtx, [])
+
+ def test_segmentation(self):
+ p = _Pair(self, server_kwargs={'max_pdu': 18 + 8}) # SYN is 18 + 5 already
+ p.open()
+ p.client.send_sdu(b'0123456789abcdefgh')
+ p.pump()
+ self.assertEqual([t for t in p.trace()[3:] if t[0] == '>'], [
+ ('>', FLAG_ACK | FLAG_SEG, 101, 200, 8),
+ ('>', FLAG_ACK | FLAG_SEG, 102, 200, 8),
+ ('>', FLAG_ACK, 103, 200, 2)])
+ self.assertEqual(p.server_sdus, [b'0123456789abcdefgh'])
+ with self.assertRaises(CatTpError):
+ p.client.send_sdu(bytes(65536))
+
+ def test_window_limits_outstanding_pdus(self):
+ p = _Pair(self, server_kwargs={'window': 1})
+ p.open()
+ p.drop.append(lambda d, pdu: d == '<') # server goes quiet
+ p.client.send_sdu(b'a')
+ p.client.send_sdu(b'b')
+ p.pump()
+ self.assertEqual([t for t in p.trace() if t[0] == '>' and t[4]], [('>', FLAG_ACK, 101, 200, 1)])
+ del p.drop[:]
+ p.client.send_nul() # nothing more until the window opens
+ p.advance(3.5) # 101 retransmitted, acked, then 102 flows
+ self.assertEqual(p.server_sdus, [b'a', b'b'])
+
+ def test_retransmit_gives_up_with_rst(self):
+ p = _Pair(self, server_kwargs={'rto': 1.0, 'max_retries': 2, 'close_wait': 5.0})
+ p.open()
+ p.drop.append(lambda d, pdu: d == '>') # client vanished
+ p.server.send_sdu(b'x')
+ p.pump()
+ p.advance(1.0)
+ p.advance(1.0)
+ self.assertEqual(p.server.state, 'OPEN')
+ p.advance(1.0)
+ self.assertEqual(p.server.state, 'CLOSE-WAIT')
+ self.assertEqual(p.server.close_reason, RST_MAX_RETRIES)
+ rst = p.log[-1][1]
+ self.assertTrue(rst.rst and rst.has_ack)
+ self.assertEqual(rst.rst_reason, RST_MAX_RETRIES)
+ self.assertEqual([t for t in p.trace() if t[4] == 1],
+ [('<', FLAG_ACK, 201, 100, 1)] * 3) # original + 2 retries
+ p.advance(4.0)
+ self.assertEqual(p.server.state, 'CLOSE-WAIT')
+ p.advance(1.5)
+ self.assertEqual(p.server.state, 'CLOSED')
+
+ def test_close_with_rst(self):
+ p = _Pair(self, server_kwargs={'close_wait': 1.0})
+ p.open()
+ p.client.close()
+ p.pump()
+ self.assertEqual(p.trace()[-1], ('>', FLAG_RST | FLAG_ACK, 101, 200, 0))
+ self.assertEqual((p.client.state, p.server.state), ('CLOSE-WAIT', 'CLOSE-WAIT'))
+ self.assertEqual(p.server.close_reason, RST_NORMAL)
+ with self.assertRaises(CatTpError):
+ p.server.send_sdu(b'late')
+ p.advance(1.5)
+ self.assertEqual(p.server.state, 'CLOSED')
+
+ def test_close_from_on_sdu_sends_only_the_rst(self):
+ p = _Pair(self)
+ p.open()
+ p.server.on_sdu = lambda c, s: c.close()
+ p.client.send_sdu(b'last')
+ p.pump()
+ self.assertEqual([t for t in p.trace()[3:] if t[0] == '<'],
+ [('<', FLAG_RST | FLAG_ACK, 201, 101, 0)]) # no ACK after the RST
+ self.assertEqual(p.server.state, 'CLOSE-WAIT')
+
+ def test_duplicate_data_is_acked_not_delivered(self):
+ p = _Pair(self)
+ p.open()
+ p.client.send_sdu(b'once')
+ p.pump()
+ dup = Pdu(FLAG_ACK, 1024, 6001, seq=101, ack=200, window=4, data=b'once').to_bytes()
+ p.server.on_pdu(dup)
+ self.assertEqual(len(p.server.pop_tx()), 1)
+ self.assertEqual(p.server_sdus, [b'once'])
+
+ def test_nul_keepalive(self):
+ p = _Pair(self)
+ p.open()
+ p.server.send_nul()
+ p.pump()
+ self.assertEqual(p.trace()[3:], [('<', FLAG_NUL | FLAG_ACK, 201, 100, 0),
+ ('>', FLAG_ACK, 101, 201, 0)])
+ self.assertEqual(p.server.snd_nxt, 202)
+
+ def test_syn_ack_with_other_version_is_refused(self):
+ p = _Pair(self)
+ with mock.patch('pySim.cattp.random.randrange', return_value=100):
+ p.client.connect(6001)
+ p.client.pop_tx()
+ p.client.on_pdu(Pdu(FLAG_SYN | FLAG_ACK, 6001, 1024, seq=200, ack=100, window=4, max_pdu=1024,
+ max_sdu=1024, version=1).to_bytes())
+ rst = Pdu.from_bytes(p.client.pop_tx()[0])
+ self.assertTrue(rst.rst)
+ self.assertEqual(rst.rst_reason, RST_VERSION)
+ self.assertEqual(p.client.state, 'CLOSE-WAIT')
+
+ def test_syn_in_open_is_unexpected(self):
+ p = _Pair(self)
+ p.open()
+ p.server.on_pdu(Pdu(FLAG_SYN, 1024, 6001, seq=300, max_pdu=1024, max_sdu=1024).to_bytes())
+ rst = Pdu.from_bytes(p.server.pop_tx()[0])
+ self.assertEqual((rst.rst, rst.rst_reason, rst.ack), (True, RST_UNEXPECTED_PDU, 300))
+
+ def test_lost_syn_ack_is_retransmitted(self):
+ p = _Pair(self, server_kwargs={'rto': 1.0})
+ p.drop.append(lambda d, pdu: d == '<')
+ p.open()
+ del p.drop[:]
+ self.assertEqual((p.client.state, p.server.state), ('SYN-SENT', 'SYN-RCVD'))
+ p.advance(1.0)
+ self.assertEqual((p.client.state, p.server.state), ('OPEN', 'OPEN'))
+
+
+class UdpServerTest(unittest.TestCase):
+ """CatTpServer on a real loopback socket, driven by a hand pumped client connection"""
+
+ def setUp(self):
+ self.got = []
+ self.opened = threading.Event()
+ self.server = CatTpServer('127.0.0.1', 0, on_sdu=self._on_sdu, on_state=self._on_state, rto=0.5)
+ self.server.bind()
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.addCleanup(self.server.shutdown)
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.settimeout(2.0)
+ self.sock.connect(('127.0.0.1', self.server.port))
+ self.addCleanup(self.sock.close)
+ self.client = CatTpConnection(2048)
+
+ def _on_state(self, conn, state):
+ if state == 'OPEN':
+ conn.send_sdu(b'GET STATUS') # the admin server talks first
+ self.opened.set()
+
+ def _on_sdu(self, conn, sdu):
+ self.got.append(sdu)
+ if sdu == b'bye':
+ conn.close()
+ else:
+ conn.send_sdu(b'next after ' + sdu)
+
+ def _exchange(self, deadline=3.0):
+ """push out what the client has, feed back what the socket returns"""
+ end = time.monotonic() + deadline
+ while time.monotonic() < end:
+ for raw in self.client.pop_tx():
+ self.sock.send(raw)
+ try:
+ raw = self.sock.recv(65535)
+ except socket.timeout:
+ return
+ self.client.on_pdu(raw)
+ if not self.client._tx and not self.client._rtx:
+ return
+
+ def test_session(self):
+ rx = []
+ self.client.on_sdu = lambda c, s: rx.append(s)
+ self.client.connect(self.server.port, identification=h2b('8949020000000001'))
+ self._exchange()
+ self.assertTrue(self.opened.wait(2.0))
+ self.assertEqual(self.client.state, 'OPEN')
+ self.assertEqual(rx, [b'GET STATUS'])
+ conn = next(iter(self.server.conns.values()))
+ self.assertEqual(conn.peer_identification, h2b('8949020000000001'))
+ self.client.send_sdu(b'9000')
+ self._exchange()
+ self.assertEqual(rx, [b'GET STATUS', b'next after 9000'])
+ self.client.send_sdu(b'bye')
+ self._exchange()
+ self.assertEqual(self.got, [b'9000', b'bye'])
+ self.assertEqual(self.client.state, 'CLOSE-WAIT')
+ self.assertEqual(self.client.close_reason, RST_NORMAL)
+
+
+if __name__ == "__main__":
+ unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43719?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I6f31493c1f0fb48fb3fd5382d8af2c905d365e54
Gerrit-Change-Number: 43719
Gerrit-PatchSet: 1
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
1
0