lists.osmocom.org
Sign In Sign Up
Manage this list Sign In Sign Up

Keyboard Shortcuts

Thread View

  • j: Next unread message
  • k: Previous unread message
  • j a: Jump to all threads
  • j l: Jump to MailingList overview

gerrit-log

Thread Start a new thread
Download
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
gerrit-log@lists.osmocom.org

September 2026

  • 1 participants
  • 1894 discussions
[M] Change in pysim[master]: cat: fix Supported Radio Access Technologies state flag
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43559?usp=email ) Change subject: cat: fix Supported Radio Access Technologies state flag ...................................................................... cat: fix Supported Radio Access Technologies state flag TS 102 223 8.105 codes each supported technology in two bytes: - the technology from 8.61 - state byte, b1 0 disabled/1 enabled - b2-b8 RFU Currently declared as FlagsEnum(Int8ub, enabled=0). kw value is used as bitmask, so currently: build {'enabled': True} -> b4 02 08 00 disabled build {'enabled': False} -> b4 02 08 00 disabled but parsed 08 00 / 08 01 / 08 ff -> all {'enabled': True} Use the bit the spec names + tests because well this is so easy that we don't need tests is apparently not the right approach here.. Change-Id: I4dd16182eb06c99265aabab5d889967b890f6bf2 --- M pySim/cat.py A tests/unittests/test_cat.py 2 files changed, 69 insertions(+), 1 deletion(-) Approvals: Jenkins Builder: Verified dexter: Looks good to me, approved diff --git a/pySim/cat.py b/pySim/cat.py index 8959004..2fda7c5 100644 --- a/pySim/cat.py +++ b/pySim/cat.py @@ -729,8 +729,12 @@ # TS 102 223 Section 8.105 class SupportedRadioAccessTechnologies(COMPR_TLV_IE, tag=0xB4): + # 2 bytes/entry: + # - technology of 8.61 + # - state byte b1 is 0 disabled/1 enabled + # - b2-b8 RFU. AccessTechTuple = Struct('technology'/AccessTechnology.SingleAccessTech, - 'state'/FlagsEnum(Int8ub, enabled=0)) + 'state'/FlagsEnum(Int8ub, enabled=1)) _construct = GreedyRange(AccessTechTuple) # TS 102 223 Section 8.107 diff --git a/tests/unittests/test_cat.py b/tests/unittests/test_cat.py new file mode 100644 index 0000000..622a105 --- /dev/null +++ b/tests/unittests/test_cat.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Tests for the CAT (Card Application Toolkit) COMPREHENSION-TLV data objects""" + +# (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/>. + +# IEs not properly coverd by test_tlvs.py + + +import unittest + +from osmocom.utils import b2h, h2b + +from pySim.cat import SupportedRadioAccessTechnologies + + +class SupportedRadioAccessTechnologies_Test(unittest.TestCase): + """TS 102 223 8.105""" + + def test_encode_technology_enabled(self): + """The flag used to have a bitmask of 0 so enabled -> 00 (that is disabled..)""" + ie = SupportedRadioAccessTechnologies( + decoded=[{'technology': 'eutran', 'state': {'enabled': True}}]) + self.assertEqual(b2h(ie.to_tlv()), 'b4020801') + + def test_encode_technology_disabled(self): + ie = SupportedRadioAccessTechnologies( + decoded=[{'technology': 'eutran', 'state': {'enabled': False}}]) + self.assertEqual(b2h(ie.to_tlv()), 'b4020800') + + def test_decode_technology(self): + """old 0 bitmask = all enabled, no way to disable""" + for encoded, enabled in [('b4020800', False), ('b4020801', True)]: + with self.subTest(encoded=encoded): + ie = SupportedRadioAccessTechnologies() + ie.from_tlv(h2b(encoded)) + self.assertEqual(ie.decoded[0]['technology'], 'eutran') + self.assertEqual(ie.decoded[0]['state']['enabled'], enabled) + + def test_decode_technology_multiple(self): + ie = SupportedRadioAccessTechnologies() + ie.from_tlv(h2b('b40408010000')) + self.assertEqual([(e['technology'], e['state']['enabled']) for e in ie.decoded], + [('eutran', True), ('gsm', False)]) + + + +if __name__ == "__main__": + unittest.main() -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43559?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I4dd16182eb06c99265aabab5d889967b890f6bf2 Gerrit-Change-Number: 43559 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[XS] Change in pysim[master]: cat: fix TS 102 223 8.61 Access technology coding
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43560?usp=email ) ( 2 is the latest approved patch-set. No files were changed between the latest approved patch-set and the submitted one. )Change subject: cat: fix TS 102 223 8.61 Access technology coding ...................................................................... cat: fix TS 102 223 8.61 Access technology coding Spelling mistakes and new values missing. Change-Id: I74f361cd5b818079636f399cb8c1b1c609b9e1f2 --- M pySim/cat.py 1 file changed, 3 insertions(+), 3 deletions(-) Approvals: dexter: Looks good to me, approved Jenkins Builder: Verified laforge: Looks good to me, but someone else must approve diff --git a/pySim/cat.py b/pySim/cat.py index 2fda7c5..991dd40 100644 --- a/pySim/cat.py +++ b/pySim/cat.py @@ -536,9 +536,9 @@ # TS 102 223 Section 8.61 class AccessTechnology(COMPR_TLV_IE, tag=0xBF): - SingleAccessTech = Enum(Int8ub, gsm=0, tia_eia_533=1, tia_eia_136_270=2, utran=3, tetra=4, - tia_eia_95_b=5, cdma1000_1x=6, cdma2000_hrpd=7, eutran=8, - ehrpd=9, nr=0x0a) + SingleAccessTech = Enum(Int8ub, gsm=0, tia_eia_553=1, tia_eia_136_270=2, utran=3, tetra=4, + tia_eia_95_b=5, cdma2000_1x=6, cdma2000_hrpd=7, eutran=8, + ehrpd=9, nr=0x0a, satellite_nr=0x0b, satellite_eutran=0x0c) _construct = GreedyRange(SingleAccessTech) # TS 102 223 Section 8.63 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43560?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I74f361cd5b818079636f399cb8c1b1c609b9e1f2 Gerrit-Change-Number: 43560 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[M] Change in pysim[master]: cat: properly decode IMEI/IMEISV IE
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43561?usp=email ) Change subject: cat: properly decode IMEI/IMEISV IE ...................................................................... cat: properly decode IMEI/IMEISV IE Currently BcdAdapter(GreedyBytes), i.e. a plain swapped nibble digit string, which is wrong, the IMEI IE is not a bcd string. See TS 124.008 10.5.1.4 figure 10.5.4 + table 10.5.4 It currently - decodes framing nibble as digit - encodes a 15 digit IMEI as 7 bytes, wrong len, dropped last digit Fix this, while at it add the 8.74 IMEISV as well + tests for the framing because the current round trip missed all of this. Change-Id: Iad7aea77513d413c338edc18ef1bcc37488ae849 --- M pySim/cat.py M tests/unittests/test_cat.py M tests/unittests/test_tlvs.py 3 files changed, 117 insertions(+), 4 deletions(-) Approvals: dexter: Looks good to me, approved Jenkins Builder: Verified diff --git a/pySim/cat.py b/pySim/cat.py index 991dd40..92b7ea3 100644 --- a/pySim/cat.py +++ b/pySim/cat.py @@ -22,7 +22,7 @@ from bidict import bidict from construct import Int8ub, Int16ub, Byte, BitsInteger from construct import Struct, Enum, BitStruct, this -from construct import Switch, GreedyRange, FlagsEnum +from construct import Switch, GreedyRange, FlagsEnum, Adapter from osmocom.tlv import TLV_IE, COMPR_TLV_IE, BER_TLV_IE, TLV_IE_Collection from osmocom.construct import PlmnAdapter, BcdAdapter, GsmStringAdapter, TonNpi, GsmString, Bytes, GreedyBytes from osmocom.utils import b2h, h2b @@ -320,9 +320,54 @@ class LocationInformation(COMPR_TLV_IE, tag=0x93): pass -# TS 102 223 Section 8.20 +class MobileIdentityAdapter(Adapter): + """TS 124.008 section 10.5.1.4 figure 10.5.4 + table 10.5.4 + + NOT a plain BCD string: + - bits 1-3 type of identity + odd/even bit 4 + - digit 1 in bits 5-8, following octets contain 2 digits, low nibble first + - if even length: high nibble of last octet 1111 + So IMEI IE of 8 bytes is 15 digits + framing nibble.""" + + # Table 10.5.4 bits 321 + TYPE_IMSI = 1 + TYPE_IMEI = 2 + TYPE_IMEISV = 3 + + def __init__(self, subcon, type_of_identity: int): + super().__init__(subcon) + self.type_of_identity = type_of_identity + + def _decode(self, obj, context, path): + data = bytes(obj) + if not data: + return '' + # TS 24.008 figure 10.5.4: octet 3 holds type of identity (b1-3), odd/even (b4) and + # digit 1 in its high nibble, the remaining digits follow BCD swapped from octet 4 + odd = bool(data[0] & 0x08) # bit 4: 1 = odd number of digits + digits = '%x' % (data[0] >> 4) # bits 5-8: digit 1 + for octet in data[1:]: + digits += '%x%x' % (octet & 0x0f, octet >> 4) + if not odd: + digits = digits[:-1] # drop the 1111 end mark + return digits + + def _encode(self, obj, context, path): + digits = str(obj) + odd = len(digits) % 2 + first = (int(digits[0], 16) << 4) | (0x08 if odd else 0x00) | self.type_of_identity + rest = digits[1:] if odd else digits[1:] + 'f' + return bytes([first]) + bytes((int(rest[i+1], 16) << 4) | int(rest[i], 16) + for i in range(0, len(rest), 2)) + +# TS 102 223 Section 8.20, len is fixed at 8: "The IMEI is coded [..] as the +# value part of the Mobile Identity IE as specified in TS 124 008", and the +# IMEI itself is the 15 digits of TS 123 003. class IMEI(COMPR_TLV_IE, tag=0x94): - _construct = BcdAdapter(GreedyBytes) + _test_de_encode = [ + ( '94081a32547698103254', '123456789012345' ), + ] + _construct = MobileIdentityAdapter(GreedyBytes, MobileIdentityAdapter.TYPE_IMEI) # TS 102 223 Section 8.21 class HelpRequest(COMPR_TLV_IE, tag=0x95): @@ -596,6 +641,14 @@ eutran_inter_rat_utran=0x08, eutran_inter_rat_nr=0x09) +# TS 102 223 Section 8.74, length is not fixed, because IMEISV is 16 digits per TS 123.003 +# -> even count needs the '1111' end mark and is 9 bytes long +class IMEISV(COMPR_TLV_IE, tag=0xE2): + _test_de_encode = [ + ( 'e2091332547698103254f6', '1234567890123456' ), + ] + _construct = MobileIdentityAdapter(GreedyBytes, MobileIdentityAdapter.TYPE_IMEISV) + # TS 102 223 Section 8.75 class NetworkSearchMode(COMPR_TLV_IE, tag=0xE5): _construct = Enum(Int8ub, manual=0, automatic=1) diff --git a/tests/unittests/test_cat.py b/tests/unittests/test_cat.py index 622a105..02cb322 100644 --- a/tests/unittests/test_cat.py +++ b/tests/unittests/test_cat.py @@ -26,7 +26,66 @@ from osmocom.utils import b2h, h2b -from pySim.cat import SupportedRadioAccessTechnologies +from pySim.cat import IMEI, IMEISV, AccessTechnology, SupportedRadioAccessTechnologies + + +class IMEI_Test(unittest.TestCase): + """TS 102 223 8.20: the IMEI IE is 8 bytes, coded as valie part of Mobile Identity IE from 124 008""" + + IMEI_15 = '123456789012345' + ENCODED = '94081a32547698103254' + + def test_encode_is_eight_bytes(self): + """15 digits in 8 byte: 16 nibbles, one is type/parity framing.""" + tlv = IMEI(decoded=self.IMEI_15).to_tlv() + self.assertEqual(b2h(tlv), self.ENCODED) + self.assertEqual(tlv[1], 0x08) # spec len 8 + self.assertEqual(len(tlv) - 2, 8) + + def test_first_octet_framing(self): + """TS 24.008 table 10.5.4""" + octet1 = IMEI(decoded=self.IMEI_15).to_tlv()[2] + self.assertEqual(octet1 & 0x07, 2) # IMEI + self.assertEqual((octet1 >> 3) & 0x01, 1) # odd + self.assertEqual(octet1 >> 4, 1) # digit 1 + + def test_decodes_to_the_raw_imei(self): + """strip framing nibble""" + ie = IMEI() + ie.from_tlv(h2b(self.ENCODED)) + self.assertEqual(ie.decoded, self.IMEI_15) + + def test_even_digit_count_uses_the_end_mark(self): + """"end marker, IMEISV case""" + ie = IMEI(decoded='1234567890123456') + tlv = ie.to_tlv() + self.assertEqual(tlv[2] >> 3 & 0x01, 0) # even + self.assertEqual(tlv[-1] >> 4, 0x0f) # end mark + back = IMEI() + back.from_tlv(tlv) + self.assertEqual(back.decoded, '1234567890123456') + + +class IMEISV_Test(unittest.TestCase): + """TS 102 223 8.74, no fixed len, end marker""" + + IMEISV_16 = '1234567890123456' + ENCODED = 'e2091332547698103254f6' + + def test_encode(self): + self.assertEqual(b2h(IMEISV(decoded=self.IMEISV_16).to_tlv()), self.ENCODED) + + def test_type_of_identity_and_end_mark(self): + value = IMEISV(decoded=self.IMEISV_16).to_tlv()[2:] + self.assertEqual(value[0] & 0x07, 3) # IMEISV + self.assertEqual((value[0] >> 3) & 0x01, 0) # even + self.assertEqual(value[-1] >> 4, 0x0f) # end mark + self.assertEqual(len(value), 9) + + def test_decode(self): + ie = IMEISV() + ie.from_tlv(h2b(self.ENCODED)) + self.assertEqual(ie.decoded, self.IMEISV_16) class SupportedRadioAccessTechnologies_Test(unittest.TestCase): diff --git a/tests/unittests/test_tlvs.py b/tests/unittests/test_tlvs.py index 7f1b72b..71eaa05 100755 --- a/tests/unittests/test_tlvs.py +++ b/tests/unittests/test_tlvs.py @@ -21,6 +21,7 @@ from osmocom.utils import b2h, h2b, all_subclasses from osmocom.tlv import * +import pySim.cat import pySim.iso7816_4 import pySim.ts_102_221 import pySim.ts_102_222 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43561?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Iad7aea77513d413c338edc18ef1bcc37488ae849 Gerrit-Change-Number: 43561 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[XS] Change in pysim[master]: osmo-smdpp: case insensitive comp of ES9+ SM-DP+ address
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43562?usp=email ) ( 2 is the latest approved patch-set. No files were changed between the latest approved patch-set and the submitted one. )Change subject: osmo-smdpp: case insensitive comp of ES9+ SM-DP+ address ...................................................................... osmo-smdpp: case insensitive comp of ES9+ SM-DP+ address Do what the comment above the line already says.. Change-Id: Ie0738e810572ea3312c885ec8aaa2da4b8b12cd7 --- M osmo-smdpp.py 1 file changed, 1 insertion(+), 1 deletion(-) Approvals: dexter: Looks good to me, approved laforge: Looks good to me, but someone else must approve Jenkins Builder: Verified diff --git a/osmo-smdpp.py b/osmo-smdpp.py index f19d3e5..024e861 100755 --- a/osmo-smdpp.py +++ b/osmo-smdpp.py @@ -525,7 +525,7 @@ """See ES9+ InitiateAuthentication SGP.22 Section 5.6.1""" # Verify that the received address matches its own SM-DP+ address, where the comparison SHALL be # case-insensitive. Otherwise, the SM-DP+ SHALL return a status code "SM-DP+ Address - Refused". - if content['smdpAddress'] != self.server_hostname: + if content['smdpAddress'].lower() != self.server_hostname.lower(): raise ApiError('8.8.1', '3.8', 'Invalid SM-DP+ Address') euiccChallenge = b64decode(content['euiccChallenge']) -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43562?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Ie0738e810572ea3312c885ec8aaa2da4b8b12cd7 Gerrit-Change-Number: 43562 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[M] Change in pysim[master]: bip: refuse OPEN CHANNEL with a TERMINAL RESPONSE
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43563?usp=email ) Change subject: bip: refuse OPEN CHANNEL with a TERMINAL RESPONSE ...................................................................... bip: refuse OPEN CHANNEL with a TERMINAL RESPONSE handle_OpenChannel() raises where TS 102 223 demands a TERMINAL RESPONSE. Raising takes the whole proactive session down with it. All four are a BIP errors and differ only in the cause byte of 8.12.11. Change-Id: If8f01e6acb9cb3f7af952a0760fc093db81be53a --- M pySim/bip.py M tests/unittests/test_bip_relay.py 2 files changed, 108 insertions(+), 11 deletions(-) Approvals: dexter: Looks good to me, approved Jenkins Builder: Verified diff --git a/pySim/bip.py b/pySim/bip.py index d4c2875..b858027 100644 --- a/pySim/bip.py +++ b/pySim/bip.py @@ -374,26 +374,53 @@ other_addr_ie = Proact._find_first_element_of_type(pcmd.children, OtherAddress) bearer_desc_ie = Proact._find_first_element_of_type(pcmd.children, BearerDescription) buffer_size_ie = Proact._find_first_element_of_type(pcmd.children, BufferSize) - if transp_lvl_ie.decoded['protocol_type'] != 'tcp_uicc_client_remote': - raise ValueError('Unsupported protocol_type') - if other_addr_ie.decoded.get('type_of_address', None) != 'ipv4': - raise ValueError('Unsupported type_of_address') + + def refuse(additional_information: str, chan_nr: int = 0): + """TERMINAL RESPONSE refusing the OPEN CHANNEL + + - always a BIP error, only the cause byte of TS 102 223 8.12.11 differs + - chan_nr 0 -> "no channel available" in the Channel status, 8.56 + - 6.8.18, 6.8.20, 6.8.21 want chan status, Bearer desc and buf size + in a successful or unsuccessful response + """ + ies = [ChannelStatus(decoded=self._channel_status(chan_nr, established=False))] + ies += [ie for ie in (bearer_desc_ie, buffer_size_ie) if ie is not None] + return self._bip_response_head(pcmd, 'bearer_independent_protocol_error', + additional_information) + ies + + # 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': + 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') + if other_addr_ie is None or other_addr_ie.decoded.get('type_of_address', None) != 'ipv4': + # No cause byte fits a wrong address family. '06' is about the transport level data + # object, and 8.12.11 leaves '14' ("IPv4 only allowed") reserved by 3GPP, so '00'. + logger.warning("OpenChannel: unsupported data destination address (%s) -> refusing", + other_addr_ie.decoded if other_addr_ie else '(absent)') + return refuse('no_specific_cause') addr_bytes = h2b(other_addr_ie.decoded['address']) if isinstance( other_addr_ie.decoded['address'], str) else other_addr_ie.decoded['address'] ipv4_str = '%u.%u.%u.%u' % (addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]) port_nr = transp_lvl_ie.decoded['port_number'] logger.info("OpenChannel: connecting to %s:%u", ipv4_str, port_nr) - channel = self.channels.channel_create() + try: + channel = self.channels.channel_create() + 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", + len(self.channels.channels)) + return refuse('no_channel_availabile') # yes, blocking connect() try: channel.connect(ipv4_str, port_nr) except OSError as e: logger.warning("OpenChannel: connect to %s:%u failed: %s", ipv4_str, port_nr, e) self.channels.channel_delete(channel.chan_nr) - return self._bip_response_head(pcmd, 'bearer_independent_protocol_error', - 'channel_closed') + [ - ChannelStatus(decoded=self._channel_status(channel.chan_nr, established=False)), - bearer_desc_ie, buffer_size_ie] + # TS 102 223 6.4.30 is the only clause naming a cause for a link that could not be + # established: BIP error, channel closed. 6.4.27.4 lists no error cases at all. + return refuse('channel_closed', channel.chan_nr) # Terminal Response example: [ # {'command_details': {'command_number': 1, diff --git a/tests/unittests/test_bip_relay.py b/tests/unittests/test_bip_relay.py index 6139d92..f5155bc 100644 --- a/tests/unittests/test_bip_relay.py +++ b/tests/unittests/test_bip_relay.py @@ -94,6 +94,17 @@ ]) +def _open_channel_raw(extra_ies, cmd_nr=1): + """OPEN CHANNEL with only the head data""" + return _pcmd([ + CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'open_channel', + 'command_qualifier': 3}).to_tlv(), + DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': 'terminal'}).to_tlv(), + BearerDescription(decoded={'bearer_type': 'default', 'bearer_parameters': b''}).to_tlv(), + BufferSize(decoded=1024).to_tlv(), + ] + extra_ies) + + def _send_data(payload, chan='channel_1', cmd_nr=1): return _pcmd([ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'send_data', @@ -255,8 +266,67 @@ self.assertEqual(_first(til, ChannelDataLength).decoded, 0) -if __name__ == "__main__": - unittest.main() +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""" + + ADDR = OtherAddress(decoded={'type_of_address': 'ipv4', 'address': bytes([127, 0, 0, 1])}) + TCP = UiccTransportLevel(decoded={'protocol_type': 'tcp_uicc_client_remote', 'port_number': 1234}) + + def setUp(self): + self.proact = Proact() + self.addCleanup(self._close_all_channels) + + def _close_all_channels(self): + for chan in list(self.proact.channels.channels.values()): + try: + chan.close() + except Exception: + pass + + def _assert_refused(self, til, additional_information, chan_nr=0): + b''.join(x.to_tlv() for x in til) # must serialise, the transport posts it + res = _first(til, Result).decoded + self.assertEqual(res['general_result'], 'bearer_independent_protocol_error') + self.assertEqual(res['additional_information'], additional_information) + self.assertEqual(_first(til, ChannelStatus).decoded, '%02x00' % chan_nr) # 8.56 + self.assertIsNotNone(_first(til, BearerDescription)) # 6.8.20 + self.assertIsNotNone(_first(til, BufferSize)) # 6.8.21 + self.assertEqual(b2h(_first(til, DeviceIdentities).to_tlv()), '82028281') # 6.8.2 + + 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 + tl = UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': 1234}) + cases.append([tl.to_tlv(), self.ADDR.to_tlv()]) + for extra in cases: + with self.subTest(extra=b2h(extra[0])): + self._assert_refused(self.proact.handle_OpenChannel(_open_channel_raw(extra)), + 'requested_uicc_if_transp_level_not_available') + + def test_destination_address(self): + v6 = OtherAddress(decoded={'type_of_address': 'ipv6', 'address': bytes(16)}) + for extra in ([self.TCP.to_tlv()], # absent + [self.TCP.to_tlv(), v6.to_tlv()]): # not IPv4 + with self.subTest(extra=len(extra)): + self._assert_refused(self.proact.handle_OpenChannel(_open_channel_raw(extra)), + 'no_specific_cause') + + def test_no_channel_left(self): + for _ in range(7): # 6.4.27.2, 6.4.27.3 + self.proact.channels.channel_create() + cmd = _open_channel_raw([self.TCP.to_tlv(), self.ADDR.to_tlv()]) + self._assert_refused(self.proact.handle_OpenChannel(cmd), 'no_channel_availabile') + + def test_connect_failure(self): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # port nothing listens on + s.bind(('127.0.0.1', 0)) + dead_port = s.getsockname()[1] + s.close() + til = self.proact.handle_OpenChannel(_open_channel(dead_port)) + self._assert_refused(til, 'channel_closed', chan_nr=1) # 6.4.30 + self.assertEqual(self.proact.channels.channels, {}) # channel given back class BipSinkTest(unittest.TestCase): -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43563?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: If8f01e6acb9cb3f7af952a0760fc093db81be53a Gerrit-Change-Number: 43563 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[M] Change in pysim[master]: bip/smpp2sim: TERMINAL PROFILE that matches what we do
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43564?usp=email ) Change subject: bip/smpp2sim: TERMINAL PROFILE that matches what we do ...................................................................... bip/smpp2sim: TERMINAL PROFILE that matches what we do pySim-smpp2sim sends "ff" * 32, that byte list tells every card the terminal has a display, a keypad, a second card slot, a radio it can query for location and NMR, five BIP bearers and six transport modes and a toaster and a dog according to TS 102 223 5.2 We only have the twelfth byte and one bit of the seventeenth and no dog. A card issues annoying weird things like PROVIDE LOCAL INFORMATION or UDP only because the profile said so, so stop pretending we know what any of that is. Annex T table T.1 lists what a Connected Entity (a CAT client that is not the modem) may announce. Announce that and the SMS-PP download and SEND SHORT MESSAGE bits the OTA path needs, only the bearer is obviously made up, it's the host TCP stack and 5.2 closest match is GPRS. We can still extend and change all of this, but for now something that works and constrains what the card asks for and is therefore actually reproducible is important. Change-Id: I91a60760fc3ad816b7385da8b26ec7330b462abd --- M pySim-smpp2sim.py M pySim/bip.py M tests/unittests/test_bip_relay.py 3 files changed, 78 insertions(+), 7 deletions(-) Approvals: Jenkins Builder: Verified dexter: Looks good to me, but someone else must approve Hoernchen: Looks good to me, approved diff --git a/pySim-smpp2sim.py b/pySim-smpp2sim.py index 95b9ccd..c1b2bb7 100755 --- a/pySim-smpp2sim.py +++ b/pySim-smpp2sim.py @@ -50,7 +50,7 @@ from pySim.sms import SMS_DELIVER, SMS_SUBMIT, AddressField -from pySim.bip import Proact +from pySim.bip import Proact, terminal_profile from pySim.transport import LinkBase, ProactiveHandler, argparse_add_reader_args, init_reader, ApduTracer from pySim.commands import SimCardCommands from pySim.cards import UiccCardBase @@ -126,8 +126,7 @@ self.scc.sel_ctrl = "0004" self.card.read_aids() self.card.select_adf_by_aid(adf='usim') - # FIXME: create a more realistic profile than ffffff - self.scc.terminal_profile('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff') + self.scc.terminal_profile(b2h(terminal_profile())) # Connect the BIP relay inbound path to the card. # relay socket receives data -> ME initiated ENVELOPE EVENT DOWNLOA # -> triggers RECEIVE DATA proactive session. diff --git a/pySim/bip.py b/pySim/bip.py index b858027..549655a 100644 --- a/pySim/bip.py +++ b/pySim/bip.py @@ -43,6 +43,35 @@ logger = logging.getLogger(__name__) + +def terminal_profile(num_channels: int = 7) -> bytes: + """TERMINAL PROFILE for what we implement, TS 102 223 5.2 and annex T. + + Annex T table T.1 lists what a Connected Entity, a CAT client that is not the modem + which is pretty much what we are, may announce, and its inverse is what only a modem may announce. + """ + if not 0 <= num_channels <= ProactChannels.MAX_CHANNELS: + raise ValueError('num_channels must be 0..%u' % ProactChannels.MAX_CHANNELS) + profile = bytearray(32) + # 1 (Download): b1 profile download, b2+b5 SMS-PP data download. Both of the latter, per the + # note in TS 31.111 5.2: "several bits may need to be set to 1 for the support of the same + # facility ... because of backward compatibility with SAT". The relay is OTA over SMS-PP. + profile[0] = 0x01 | 0x02 | 0x10 + profile[1] = 0x01 # 2 (Other): b1 command result + profile[2] = 0x80 # 3: b8 REFRESH (empty result is a valid answer, 6.4.7) + profile[3] = 0x02 # 4: b2 SEND SHORT MESSAGE (the OTA response path) + profile[4] = 0x01 # 5: b1 SET UP EVENT LIST + profile[5] = 0x04 | 0x08 # 6: b3 Event Data available, b4 Event Channel status + # 12 (class "e"): b1..b5 OPEN CHANNEL, CLOSE CHANNEL, RECEIVE DATA, SEND DATA, GET CHANNEL + # STATUS. + profile[11] = 0x1f + # 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 + return bytes(profile) + + class ProactChannel: """One BIP channel, TS 102 223 class "e", backed by a blocking TCP socket. @@ -178,13 +207,18 @@ thread when data arrives in an empty Rx buffer. Proact turns it into an ENVELOPE EVENT DOWNLOAD (data available). """ + + # TS 102 223 8.56 channel identifier in 3 bits as "1 to 7", 0 == no channel available + # TERMINAL PROFILE has to agree with byte 13 , "number of channels supported by terminal" + MAX_CHANNELS = 7 + def __init__(self, on_data_available=None): self.channels = {} self._on_data_available = on_data_available def channel_create(self) -> ProactChannel: """Create a new proactive channel, allocating its integer number.""" - for i in range(1, 8): + for i in range(1, self.MAX_CHANNELS + 1): if not i in self.channels: self.channels[i] = ProactChannel(self, i) return self.channels[i] @@ -223,8 +257,8 @@ """Answer anything this handler has no specific handler for. A card coming up will usually issue PROVIDE LOCAL INFORMATION, - POLL INTERVAL or TIMER MANAGEMENT before it gets anywhere near a BIP channel - because we claim to support every feature flag there is. + POLL INTERVAL or TIMER MANAGEMENT before it gets anywhere near a BIP channel, + whatever the TERMINAL PROFILE announces. Note that this is not the spec-correct answer. TS 102 223 6.8.7 says a successful TERMINAL RESPONSE to PROVIDE LOCAL INFORMATION "shall" carry the diff --git a/tests/unittests/test_bip_relay.py b/tests/unittests/test_bip_relay.py index f5155bc..46281bd 100644 --- a/tests/unittests/test_bip_relay.py +++ b/tests/unittests/test_bip_relay.py @@ -30,7 +30,7 @@ OtherAddress, ChannelData, ChannelDataLength, ChannelStatus, Result) -from pySim.bip import Proact +from pySim.bip import Proact, ProactChannels, terminal_profile class _EchoServer: @@ -329,6 +329,44 @@ self.assertEqual(self.proact.channels.channels, {}) # channel given back +class TerminalProfileTest(unittest.TestCase): + """TS 102 223 5.2, one bit per CAT facility""" + + def setUp(self): + self.profile = terminal_profile() + + def byte(self, n): + return self.profile[n - 1] # 1-based, as 5.2 numbers them + + def test_announced(self): + self.assertEqual(len(self.profile), 32) + self.assertEqual(self.byte(1), 0x13) # profile download, SMS-PP download b2+b5 + self.assertEqual(self.byte(4), 0x02) # SEND SHORT MESSAGE + self.assertEqual(self.byte(5) & 0x01, 0x01) # SET UP EVENT LIST + self.assertEqual(self.byte(6), 0x0c) # events: data available, channel status + 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 + + def test_not_announced(self): + self.assertEqual(self.byte(3) & 0x60, 0) # POLL INTERVAL, POLLING OFF + self.assertEqual(self.byte(4) & 0xc0, 0) # PROVIDE LOCAL INFORMATION, NMR + self.assertEqual(self.byte(12) & 0xe0, 0) # SERVICE SEARCH/INFORMATION, DECLARE SERVICE + self.assertEqual(self.byte(14) & 0x1f, 0) # no characters down the display + for n in (7, 9, 10, 11, 15, 16, 18): # class "a", class "d", display, ESN/IMEISV + self.assertEqual(self.byte(n), 0) + + def test_channel_count(self): + self.assertEqual(terminal_profile(3)[12] >> 5, 3) + with self.assertRaises(ValueError): # 8.56: 1 to 7 + terminal_profile(8) + + +if __name__ == "__main__": + unittest.main() + + class BipSinkTest(unittest.TestCase): """Both sinks are optional, a driver with no SMS path at all must not crash and burn with a card that sends one, and one that has one must get the PDU.""" -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43564?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I91a60760fc3ad816b7385da8b26ec7330b462abd Gerrit-Change-Number: 43564 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[M] Change in pysim[master]: ota: indefinite length en/decoding support
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43546?usp=email ) Change subject: ota: indefinite length en/decoding support ...................................................................... ota: indefinite length en/decoding support Adds TS 102 226 tables 5.2a/5.10a indefinite length coding, recommended by TS 102 226 5.2.1 for RAM/RFM over HTTPS. Noteworthy notable things to note: - encode_expanded_cmd() indefinite version -> inner C-APDU TLVs are still definite - decode_expanded_resp()s returned container does not care, but Indef has no 'number of executed commands' TLV -> number_of_commands is the R-APDU count. Tests are being fed with some known-good values from my sja5 sessions. Change-Id: I4e023112e98729489ed443eec3ed5ab45c773b17 --- M pySim/ota.py M tests/unittests/test_ota.py 2 files changed, 140 insertions(+), 17 deletions(-) Approvals: dexter: Looks good to me, approved Jenkins Builder: Verified diff --git a/pySim/ota.py b/pySim/ota.py index adbf56b..82b1a85 100644 --- a/pySim/ota.py +++ b/pySim/ota.py @@ -19,7 +19,7 @@ import abc import struct from typing import Optional, Tuple, List, Union -from construct import Enum, Int8ub, Int16ub, Struct, BitsInteger, BitStruct +from construct import ConstructError, Enum, Int8ub, Int16ub, Struct, BitsInteger, BitStruct 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 * @@ -67,6 +67,8 @@ # 5.2.1.4 Script Chaining TLV # 5.2.2 Expanded Remote response structure (tables 5.10 .. 5.16) # +# definite length coding and indefinite length coding are supported. +# # BER-TLV tag values from ETSI TS 101 220 V19.0.0 tables 7.18, 7.19, 7.20 # C-APDU / R-APDU ETSI TS 102 223 Section 8.35 + 8.36 # inside these the CR flag of the tag is 0 (TS 101 220 tables 7.19/7.20), @@ -112,16 +114,31 @@ def _encode(self, obj, context, path): return h2b(obj['response_data']) + h2b(obj['status_word']) -#### Command Scripting template TS 102 226 table 5.2, TS 101 220 tables 7.18/7.19 +#### Command Scripting template TS 102 226 tables 5.2 / 5.2a, TS 101 220 tables 7.18/7.19 +# +# The two TS 101 220 table 7.18 length codings use different template tags: +# - definite tag AA +# - indefinite AE +# In both codings the inner Command TLVs use definite length coding, only the +# surrounding template differs. # TS 102 223 8.35 ExpandedC_APDU = Struct('_tag'/Const(b'\x22'), 'c_apdu'/Prefixed(BerTlvLen, HexAdapter(GreedyBytes))) -ExpandedCmd = Struct('_tag'/Const(b'\xaa'), - 'commands'/Prefixed(BerTlvLen, GreedyRange(ExpandedC_APDU))) +# shared by both length codings. +ExpandedCmdItems = GreedyRange(ExpandedC_APDU) -#### Response Scripting template TS 102 226 tables 5.10-5.16, TS 101 220 table 7.20 +# TS 102 226 table 5.2: Command Scripting template, definite length coding only +ExpandedCmd = Struct('_tag'/Const(b'\xaa'), + 'commands'/Prefixed(BerTlvLen, ExpandedCmdItems)) + +# TS 102 226 table 5.2a: indefinite length coding, 'AE 80 <C-APDU TLVs> 00 00'. GreedyRange +# stops at the first octet that is not a C-APDU tag, which is the end-of-contents marker. +ExpandedCmdIndef = Struct('_tag'/Const(b'\xae'), '_indef'/Const(b'\x80'), + 'commands'/ExpandedCmdItems, '_eoc'/Const(b'\x00\x00')) + +#### Response Scripting template TS 102 226 5.2.2, tables 5.10-5.16, TS 101 220 table 7.20 # TS 102 223 8.36 ExpandedR_APDU = Struct('_tag'/Const(b'\x23'), @@ -148,39 +165,57 @@ Enum(Int8ub, no_previous_script=1, not_supported=2, unable_to_process=3))) +# response TLVs shared by the def and indef Response Scripting templates +ExpandedRespItems = GreedyRange(Select(ExpandedR_APDU, + ExpandedBadFormat, + ExpandedImmediateActionResp, + ExpandedScriptChainingResp)) + # - starts with the "Number of executed command TLV objects" (table 5.10/5.13/5.15) # - followed by a sequence of R-APDU TLVs # - and/or one of the error # response TLVs ExpandedRemoteResp = Struct('_tag'/Const(b'\xab'), 'body'/Prefixed(BerTlvLen, Struct( 'num_executed'/ExpandedNumExecuted, - 'responses'/GreedyRange(Select(ExpandedR_APDU, - ExpandedBadFormat, - ExpandedImmediateActionResp, - ExpandedScriptChainingResp))))) + 'responses'/ExpandedRespItems))) + +# TS 102 226 table 5.10a: indefinite length coding, no "number of executed" TLV +ExpandedRemoteRespIndef = Struct('_tag'/Const(b'\xaf'), '_indef'/Const(b'\x80'), + 'responses'/ExpandedRespItems, '_eoc'/Const(b'\x00\x00')) -def encode_expanded_cmd(apdus: Union[bytes, List[bytes]]) -> bytes: - """builds the Command Scripting template, TS 102 226 5.2.1, definite length coding +def encode_expanded_cmd(apdus: Union[bytes, List[bytes]], + length_coding: str = 'definite') -> bytes: + """builds the Command Scripting template, TS 102 226 5.2.1 Args: apdus: single C-APDU bytes or list of C-APDUs bytes. Each C-APDU is wrapped into a C-APDU TLV- This function does not add or modify Le. + length_coding: 'definite' (the default, tag 'AA', table 5.2) or + 'indefinite' (tag 'AE', table 5.2a: 'AE 80 <cmd TLVs> 00 00'). + Inner C-APDU TLVs use definite length coding in both cases. Returns: - encoded Command Scripting template (AA...) as bytes + encoded Command Scripting template as bytes """ if isinstance(apdus, (bytes, bytearray)): apdus = [apdus] - return ExpandedCmd.build({'commands': [{'c_apdu': b2h(a)} for a in apdus]}) + commands = [{'c_apdu': b2h(a)} for a in apdus] + if length_coding == 'definite': + return ExpandedCmd.build({'commands': commands}) + if length_coding == 'indefinite': + return ExpandedCmdIndef.build({'commands': commands}) + raise ValueError("Invalid length_coding: %r" % length_coding) def decode_expanded_resp(data: bytes) -> Container: - """Decode a Response Scripting template, TS 102 226 5.2.2 definite length + """Decode a Response Scripting template, TS 102 226 5.2.2 def and indef length coding returned Container has: number_of_commands -- "number of executed command TLV objects" table 5.11 + for definite coding. indefinite coding does not have + this TLV, so report the number of returned R-APDUs instead. commands -- list of Containers, one per R-APDU TLV, each with 'response_data' and 'status_word' hexstr last_response_data -- response_data of the last R-APDU or '' @@ -198,12 +233,22 @@ CompactRemoteResp so existing callers keep working.""" if isinstance(data, str): data = h2b(data) - parsed = ExpandedRemoteResp.parse(data) + try: + if data[:1] == b'\xaf': + responses = ExpandedRemoteRespIndef.parse(data)['responses'] + num_executed = None + else: + parsed = ExpandedRemoteResp.parse(data) + responses = parsed['body']['responses'] + num_executed = parsed['body']['num_executed']['number_of_commands'] + except ConstructError as e: + raise ValueError('malformed Response Scripting template: %s' % e) from e + commands = [] bad_format = None immediate_action_response = None script_chaining_response = None - for item in parsed['body']['responses']: + for item in responses: if 'r_apdu' in item: commands.append(Container(response_data=item['r_apdu']['response_data'], status_word=item['r_apdu']['status_word'])) @@ -215,7 +260,7 @@ script_chaining_response = item['script_chaining_response'] # TS 102 226 5.2.1.1: 62F1 means response of a C-APDU was truncated, processing terminated truncated = any(c['status_word'].lower() == '62f1' for c in commands) - return Container(number_of_commands=parsed['body']['num_executed']['number_of_commands'], + return Container(number_of_commands=num_executed if num_executed is not None else len(commands), commands=commands, last_response_data=commands[-1]['response_data'] if commands else '', last_status_word=commands[-1]['status_word'] if commands else None, diff --git a/tests/unittests/test_ota.py b/tests/unittests/test_ota.py index e7c7230..b513355 100644 --- a/tests/unittests/test_ota.py +++ b/tests/unittests/test_ota.py @@ -451,6 +451,84 @@ self.assertFalse(decode_expanded_resp(data).truncated) +class ExpandedIndefiniteTestCase(unittest.TestCase): + """Indef len coding of expanded format TS 102 226 tables + 5.2a/5.10a; cmd tag AE, resp tag AF. + Golden vectors captured from live eUICC over SCP81/HTTPS.""" + + def test_cmd_single_golden(self): + # RAM GET DATA 80CA00E000 -> AE 80 | 22 05 80ca00e000 | 00 00 + out = encode_expanded_cmd(h2b('80ca00e000'), length_coding='indefinite') + self.assertEqual(b2h(out), 'ae80220580ca00e0000000') + + def test_cmd_multi_golden(self): + # RFM: SELECT MF / SELECT EF.ICCID / READ BINARY, each in one C-APDU + # TLV, wrapped in indef Command Scripting template + out = encode_expanded_cmd([h2b('00a4000c023f00'), h2b('00a4000c022fe2'), + h2b('00b000000a')], length_coding='indefinite') + self.assertEqual(b2h(out), + 'ae80220700a4000c023f00220700a4000c022fe2220500b000000a0000') + + def test_cmd_definite_is_default(self): + # The default/explicit definite keeps the tag AA + self.assertEqual(encode_expanded_cmd(h2b('80ca00e000')), + encode_expanded_cmd(h2b('80ca00e000'), length_coding='definite')) + self.assertEqual(b2h(encode_expanded_cmd(h2b('80ca00e000'))), 'aa07220580ca00e000') + + def test_cmd_invalid_length_coding(self): + with self.assertRaises(ValueError): + encode_expanded_cmd(h2b('80ca00e000'), length_coding='bogus') + + def test_resp_rfm_golden(self): + # AF 80 | 23 02 9000 | 23 02 9000 | 23 0c <ICCID> 9000 | 00 00 + # indef res has no "number of executed" TLV. + dec = decode_expanded_resp(h2b( + 'af80' '23029000' '23029000' '230c988812010000408608149000' '0000')) + self.assertEqual(len(dec.commands), 3) + self.assertEqual([(c.status_word, c.response_data) for c in dec.commands], + [('9000', ''), ('9000', ''), ('9000', '98881201000040860814')]) + self.assertEqual(dec.last_status_word, '9000') + self.assertEqual(dec.last_response_data, '98881201000040860814') + # report the R-APDU count instead + self.assertEqual(dec.number_of_commands, 3) + + def test_resp_ram_golden(self): + # RAM GET DATA: R-APDU carrying the SD key info TLV + SW. + resp = ('af80' '2334e030c00403308810c00402308810c00401308810c00402408810' + 'c00401408510c00403018810c00402018810c004010188109000' '0000') + dec = decode_expanded_resp(h2b(resp)) + self.assertEqual(len(dec.commands), 1) + self.assertEqual(dec.last_status_word, '9000') + self.assertEqual(dec.last_response_data, + 'e030c00403308810c00402308810c00401308810c00402408810' + 'c00401408510c00403018810c00402018810c00401018810') + + def test_resp_truncated_is_rejected(self): + # last byte chopped off: the end-of-contents marker is incomplete + good = h2b('af80' '23029000' '230c988812010000408608149000' '0000') + for cut in (1, 2, 3): + with self.subTest(cut=cut): + with self.assertRaises(ValueError): + decode_expanded_resp(good[:-cut]) + + def test_resp_definite_still_parses(self): + # same decoder still handles the definite AB template. + dec = decode_expanded_resp(h2b('ab0780010123029000')) + self.assertEqual(dec.number_of_commands, 1) + self.assertEqual(dec.last_status_word, '9000') + + def test_resp_indefinite_bad_format(self): + # AF 80 | 90 01 01 | 00 00 unknown_tag no R-APDU + dec = decode_expanded_resp(h2b('af8090010100 00'.replace(' ', ''))) + self.assertEqual(str(dec.bad_format), 'unknown_tag') + self.assertIsNone(dec.last_status_word) + + def test_resp_missing_eoc_raises(self): + # AF 80 | 23 02 9000 without end-of-contents. + with self.assertRaises(ValueError): + decode_expanded_resp(h2b('af8023029000')) + + class ExpandedSmsPipelineTestCase(unittest.TestCase): """expanded format + TS 102 225 SMS security witj 3DES keyset, to ensure remote_format does not affect the compact path""" -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43546?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I4e023112e98729489ed443eec3ed5ab45c773b17 Gerrit-Change-Number: 43546 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[S] Change in pysim[master]: osmo-smdpp: fix Twisted ALPN issues with pyOpenSSL
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43548?usp=email ) ( 2 is the latest approved patch-set. No files were changed between the latest approved patch-set and the submitted one. )Change subject: osmo-smdpp: fix Twisted ALPN issues with pyOpenSSL ...................................................................... osmo-smdpp: fix Twisted ALPN issues with pyOpenSSL pyOpenSSL >= 25.0.0 makes a Context immutable once it has been used and raises. Downgrading pyOpenSSL is not a fix either: < 25 does not import against recent cryptography. This server only speaks HTTP/1.1 anway so ALPN negotiation is unused and this can be hotpatched for affected versions. Change-Id: I5d53216f24a20625d12f0757015c19fe341303b9 --- M osmo-smdpp.py 1 file changed, 46 insertions(+), 0 deletions(-) Approvals: Jenkins Builder: Verified laforge: Looks good to me, but someone else must approve dexter: Looks good to me, approved diff --git a/osmo-smdpp.py b/osmo-smdpp.py index 2a8e478..8120b0f 100755 --- a/osmo-smdpp.py +++ b/osmo-smdpp.py @@ -136,6 +136,52 @@ import logging # noqa: E402 logger = logging.getLogger(__name__) + +def _disable_twisted_alpn_if_incompatible(): + """Twisted <-> pyOpenSSL TLS compatibility guard applied at import. + + Twisted TLSMemoryBIOFactory applies ALPN by setting the 'select' callback + on the SSL Context after it has already created a Connection from that + Context (_createConnection -> _applyProtocolNegotiation). + pyOpenSSL >= 25.0.0 makes a Context immutable once it has been used and + raises, which aborts every inbound TLS handshake, client sees unexpected-EOF + / decode_error that looks like a cert/cipher problem but is not. + pyOpenSSL < 25 does not import against recent cryptography, so downgrading + it is not a fix. + + This server only speaks HTTP/1.1 anyway, so ALPN negotiation is not + needed. + """ + def _major(v): + import re + m = re.match(r'\d+', (v or '').strip()) + return int(m.group()) if m else 0 + + try: + import OpenSSL + except Exception: + return # no pyOpenSSL ??? + pyossl_ver = getattr(OpenSSL, '__version__', '0') + if _major(pyossl_ver) < 25: + return # pre-25 pyOpenSSL allows mutating a used Context + + try: + import twisted + from twisted.protocols import tls + except Exception: + return + factory = getattr(tls, 'TLSMemoryBIOFactory', None) + if factory is None or not hasattr(factory, '_applyProtocolNegotiation'): + return # Twisted already fixed + + factory._applyProtocolNegotiation = lambda self, connection: None + logger.warning("Disabled Twisted ALPN negotiation: Twisted %s + " + "pyOpenSSL %s are incompatible for it", + getattr(twisted, '__version__', '?'), pyossl_ver) + + +_disable_twisted_alpn_if_incompatible() + # HACK: make this configurable DATA_DIR = './smdpp-data' HOSTNAME = 'testsmdpplus1.example.com' # must match certificates! -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43548?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I5d53216f24a20625d12f0757015c19fe341303b9 Gerrit-Change-Number: 43548 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: lynxis lazus <lynxis(a)fe80.eu>
1 0
0 0
[L] Change in pysim[master]: contrib: SCP81 TLS-PSK RAS for RAM/RFM over HTTPS
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43547?usp=email ) Change subject: contrib: SCP81 TLS-PSK RAS for RAM/RFM over HTTPS ...................................................................... contrib: SCP81 TLS-PSK RAS for RAM/RFM over HTTPS GP Amendment B "Remote Application Management over HTTP" v1.2 and ETSI TS 102 226 RFM/RAM server. APDU command/response bodies use the Expanded Remote Application data format. --mode {ram,rfm} selects what we want to do, make sure to target the right thing in the right mode, SD for RAM, AID for RFM. This is hand-rolled on purpose: Klein/Twisted do not help us here, have annoying headers and settings, and don't work well at all if you want to import the file for tests and so on. I have wasted quite some time trying to make this prettier by re-using existing http handler parts because I thought well we import all kinds of packages already it can't be that hard, unfortunately it is. Change-Id: I4f243aeca65d0f33ff34e6932e3f4e156446af8b --- A contrib/scp81_admin_server.py 1 file changed, 524 insertions(+), 0 deletions(-) Approvals: Jenkins Builder: Verified dexter: Looks good to me, approved diff --git a/contrib/scp81_admin_server.py b/contrib/scp81_admin_server.py new file mode 100755 index 0000000..9b243aa --- /dev/null +++ b/contrib/scp81_admin_server.py @@ -0,0 +1,524 @@ +#!/usr/bin/env python3 +"""TLS-PSK HTTP Remote Administration Server for SCP81 / RAM over HTTP""" + +# (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/>. + +# The card (specifically a SD supporting SCP81) is the TLS client: +# - it opens a TCP connection to this server, +# - performs a TLS handshake authenticated with a PSK, +# - and then drives the HTTP admin loop of to fetch remote APDU command strings +# - and posts back their responses. +# This program is the server side of that exchange, it: +# - accepts the PSK-TLS connection, +# - hands the card a queue of commands +# - and logs the decoded responses. +# +# The two TS 102 226 annex B figure B.1 administration modes are supported over the +# same session, selected with --mode: +# ram GP Amendment B RAM: +# command is handled by (--targeted-application) a SD +# rfm ETSI TS 102 226 RFM/RAM: +# command is routed to the Receiving/RFM Application specified by +# --targeted-application, for example UICC-filesystem/USIM-ADF RFM app. +# +# Remote APDU command/response bodies use the Expanded Remote Application +# data format. +# + +import ssl +import socket +import logging +import argparse +import threading +from pathlib import Path +from typing import List, Optional, Callable, Dict, Tuple + +from osmocom.utils import h2b, b2h + +from pySim.ota import encode_expanded_cmd, decode_expanded_resp + +logger = logging.getLogger(Path(__file__).stem) + +# Amendment B section 3.4 +ADMIN_PROTOCOL = 'globalplatform-remote-admin/1.0' +CT_COMMAND = 'application/vnd.globalplatform.card-content-mgt;version=1.0' +CT_RESPONSE = 'application/vnd.globalplatform.card-content-mgt-response;version=1.0' + +# TS 102 226 annex B, figure B.1 RFM/RAM over HTTPS content types +CT_RFM_COMMAND = 'application/vnd.etsi.scp.command-data;version=1.0' +CT_RFM_RESPONSE = 'application/vnd.etsi.scp.response-data;version=1.0' + +MODE_CONTENT_TYPE = { + 'ram': CT_COMMAND, # GP Amendment B RAM: target = a Security Domain + 'rfm': CT_RFM_COMMAND, # ETSI TS 102 226 RFM/RAM: target = an application +} + +# Amendment B Table 3-2. The 3DES and NULL suites are left out and can be enabled with +# --ciphers / --seclevel. +DEFAULT_CIPHERS = ':'.join([ + 'PSK-AES128-CBC-SHA256', # TLS_PSK_WITH_AES_128_CBC_SHA256, TLS 1.2 + 'PSK-AES128-CBC-SHA', # TLS_PSK_WITH_AES_128_CBC_SHA, TLS 1.0/1.1 +]) + +TLS_VERSION_MAP = { + '1.0': ssl.TLSVersion.TLSv1, + '1.1': ssl.TLSVersion.TLSv1_1, + '1.2': ssl.TLSVersion.TLSv1_2, + '1.3': ssl.TLSVersion.TLSv1_3, +} + + +def format_aid(aid: str) -> str: + """AID -> //aid/<RID>/<PIX> for X-Admin-Targeted-Application from Amendment B section 3.4.2 + First 5 bytes RID, the PIX the remainder, string in //aid/ notation is passed through.""" + if aid.startswith('//aid/'): + return aid + aid = aid.replace(' ', '').lower() + if len(aid) < 10: + raise ValueError('AID %r is shorter than the 5 byte RID' % aid) + rid, pix = aid[:10], aid[10:] + return '//aid/%s/%s' % (rid, pix) + + +def make_ssl_context(psk: bytes, identity: str, *, + ciphers: str = DEFAULT_CIPHERS, + min_tls: str = '1.2', max_tls: str = '1.3', + seclevel: Optional[int] = None, + identity_hint: Optional[str] = None, + allow_any_identity: bool = False, + extra_psks: Optional[Dict[str, bytes]] = None) -> ssl.SSLContext: + """PSK SSLContext, resolvesg the key from the client psk_identity + + extra_psks can carry additional identity->key mappings. + allow_any_identity can be used for debugging + """ + # the PSK callback must return immutable bytes, h2b() gives a bytearray + psk = bytes(psk) + keymap: Dict[str, bytes] = {identity: psk} + if extra_psks: + keymap.update({k: bytes(v) for k, v in extra_psks.items()}) + + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.minimum_version = TLS_VERSION_MAP[min_tls] + ctx.maximum_version = TLS_VERSION_MAP[max_tls] + cipher_str = ciphers + if seclevel is not None: + # @SECLEVEL=0 is to enable NULL/3DES/legacy PSK suites + cipher_str = '%s:@SECLEVEL=%d' % (ciphers, seclevel) + if cipher_str: + ctx.set_ciphers(cipher_str) + + def psk_server_callback(client_identity: Optional[str]) -> bytes: + if allow_any_identity: + logger.info('PSK handshake: identity=%r (ACEPTING ANY!)', client_identity) + return psk + key = keymap.get(client_identity) + if key is None: + logger.warning('PSK handshake: unknown identity %r (known: %r) -> rejecting', + client_identity, list(keymap.keys())) + return b'' # empty PSK aborts handshake + logger.info('PSK handshake: identity=%r resolved', client_identity) + return key + + ctx.set_psk_server_callback(psk_server_callback, identity_hint=identity_hint) + return ctx + + +class HttpRequest: + """A parsed HTTP request (request line + headers + body).""" + __slots__ = ('method', 'uri', 'version', 'headers', 'body') + + def __init__(self, method: str, uri: str, version: str, + headers: Dict[str, str], body: bytes): + self.method = method + self.uri = uri + self.version = version + self.headers = headers # lower cased field names + self.body = body + + def get(self, name: str, default=None) -> Optional[str]: + return self.headers.get(name.lower(), default) + + +# http.client bound on a single HTTP line. +MAX_LINE = 65536 + + +def _read_line(rfile) -> bytes: + """readline() with a bound. reaching the bound without a + terminator means the card is out of sync somehow, not that the line is long.""" + line = rfile.readline(MAX_LINE) + if line and not line.endswith(b'\n'): + raise ValueError('HTTP line longer than %u bytes' % MAX_LINE) + return line + + +def _read_chunked_body(rfile) -> bytes: + """Read a Transfer-Encoding: chunked body. Amendment B section 3.4.1 lets + the card send its response string with either a Content-Length or chunked""" + out = bytearray() + while True: + size_line = _read_line(rfile) + if not size_line: + break + size = int(size_line.split(b';', 1)[0].strip() or b'0', 16) + if size == 0: + # consume trailer headers up to the terminating blank line + while _read_line(rfile) not in (b'\r\n', b'\n', b''): + pass + break + chunk = rfile.read(size) + if len(chunk) != size: + raise ValueError('chunked body ended after %u of %u bytes' % (len(chunk), size)) + out += chunk + _read_line(rfile) # trailing CRLF after the chunk data + return bytes(out) + + +def read_http_request(rfile, send: Optional[Callable[[bytes], None]] = None) -> Optional[HttpRequest]: + """Read one HTTP request from a buffered binary reader or None when closed""" + request_line = _read_line(rfile) + if not request_line: + return None + parts = request_line.rstrip(b'\r\n').decode('iso-8859-1').split(' ') + if len(parts) < 3: + raise ValueError('Malformed HTTP request line: %r' % request_line) + method, uri, version = parts[0], parts[1], parts[2] + + headers: Dict[str, str] = {} + while True: + line = _read_line(rfile) + if line in (b'\r\n', b'\n', b''): + break + name, _, value = line.rstrip(b'\r\n').decode('iso-8859-1').partition(':') + headers[name.strip().lower()] = value.strip() + + # Expect: 100-continue waits for the response before it sends the body, + # and RFC 2616 8.2.3 (Amendment B references RFC 2616 as [HTTP]) + # requires the server to send it. Amendment B 3.4.1 does not mention this + # header, tho, might be useless. + if send and '100-continue' in headers.get('expect', '').lower(): + logger.info('-> 100 Continue ') + send(b'HTTP/1.1 100 Continue\r\n\r\n') + + body = b'' + te = headers.get('transfer-encoding', '').lower() + if 'chunked' in te: + body = _read_chunked_body(rfile) + elif 'content-length' in headers: + n = int(headers['content-length']) + if n: + body = rfile.read(n) + return HttpRequest(method, uri, version, headers, body) + + +def build_http_response(status_line: str, headers: List[Tuple[str, str]], + body: bytes = b'') -> bytes: + """Serialise HTTP response. status_line 'HTTP/1.1 200 OK'.""" + lines = [status_line] + lines += ['%s: %s' % (name, value) for name, value in headers] + head = ('\r\n'.join(lines) + '\r\n\r\n').encode('iso-8859-1') + return head + body + + +def format_decoded_response(dec) -> str: + """hand over the data""" + bits = ['%u command(s) executed' % dec.number_of_commands] + for i, c in enumerate(dec.commands): + data = c.response_data or '-' + bits.append(' R-APDU[%u]: SW=%s data=%s' % (i, c.status_word, data)) + if dec.get('truncated'): + bits.append(' TRUNCATED: an R-APDU returned SW 62F1, so the card cut the response data ' + 'short and stopped executing the rest of the script ') # TS 102 226 5.2.1.1 + if dec.bad_format is not None: + bits.append(' bad-format: %s' % dec.bad_format) + if dec.immediate_action_response is not None: + bits.append(' immediate-action-response: %s' % dec.immediate_action_response) + if dec.script_chaining_response is not None: + bits.append(' script-chaining-response: %s' % dec.script_chaining_response) + return '\n'.join(bits) + + +class AdminSession: + + def __init__(self, command_bodies: List[bytes], + next_uri: Optional[str] = None, + targeted_application: Optional[str] = None, + on_response: Optional[Callable[[object], None]] = None, + content_type: str = CT_COMMAND): + self.pending: List[bytes] = list(command_bodies) + self.next_uri = next_uri # None -> echo the request URI + self.targeted_application = targeted_application + self.on_response = on_response + self.content_type = content_type # Content-Type for the command body + self.responses: List[object] = [] # decoded Containers, in order + + def record_response(self, dec) -> None: + self.responses.append(dec) + if self.on_response: + self.on_response(dec) + + +def run_admin_loop(rfile, send: Callable[[bytes], None], session: AdminSession) -> AdminSession: + """Drive the admin loop for one connection. + Just keep answering the card POST requests with the next queued command + (200 OK + Expanded command body) until the queue is empty, end session with 204 No Content.""" + while True: + req = read_http_request(rfile, send) + if req is None: + logger.info('connection closed by card') + return session + + if req.method != 'POST': + logger.warning('unexpected method %s %s -> 405', req.method, req.uri) + send(build_http_response('HTTP/1.1 405 Method Not Allowed', + [('X-Admin-Protocol', ADMIN_PROTOCOL), + ('Connection', 'close')])) + return session + + proto = req.get('x-admin-protocol') + if proto and proto != ADMIN_PROTOCOL: + logger.warning('card X-Admin-Protocol=%r (expected %r)', proto, ADMIN_PROTOCOL) + status = req.get('x-admin-script-status') + resume = req.get('x-admin-resume') + logger.info('POST %s from=%r status=%r resume=%r body=%uB', + req.uri, req.get('x-admin-from'), status, resume, len(req.body)) + + # section 3.4.1: + # - body with "X-Admin-Script-Status: ok" carries the previous command + # response string (Expanded Remote response format); + # - other status values carry no body (). + if req.body: + # Expanded Remote response: + # - GP Amd B 'card-content-mgt-response' + # - ETSI 'scp.response-data' + logger.debug(' response Content-Type=%r raw body (%uB): %s', + req.get('content-type'), len(req.body), b2h(req.body)) + if status in (None, 'ok'): + try: + dec = decode_expanded_resp(req.body) + session.record_response(dec) + logger.info('card response:\n%s', format_decoded_response(dec)) + except Exception as e: + logger.error('failed to decode response body %s: %s', b2h(req.body), e) + else: + logger.warning('body present with status=%r; ignoring', status) # section 3.4.1 + elif status and status != 'ok': + logger.info('card reported script-status=%r (no response body)', status) + + if session.pending: + body = session.pending.pop(0) + next_uri = session.next_uri or req.uri + headers = [('X-Admin-Protocol', ADMIN_PROTOCOL), + ('X-Admin-Next-URI', next_uri), + ('Content-Type', session.content_type)] + if session.targeted_application: + headers.append(('X-Admin-Targeted-Application', session.targeted_application)) + headers.append(('Content-Length', str(len(body)))) + logger.info('-> 200 OK, next command (%uB): %s', len(body), b2h(body)) + send(build_http_response('HTTP/1.1 200 OK', headers, body)) + else: + # section 3.4.2: No more commands, end session + # No Content-Type or body for 204 + logger.info('-> 204 No Content, ending administration session') + send(build_http_response('HTTP/1.1 204 No Content', + [('X-Admin-Protocol', ADMIN_PROTOCOL), + ('Connection', 'close')])) + return session + + +class Scp81AdminServer: + """Threaded TLS-PSK server that runs the Amendment B admin loop against each + connecting card.""" + + def __init__(self, host: str, port: int, ssl_ctx: ssl.SSLContext, + command_bodies: List[bytes], + next_uri: Optional[str] = None, + targeted_application: Optional[str] = None, + on_response: Optional[Callable[[object], None]] = None, + on_session_end: Optional[Callable[[AdminSession], None]] = None, + content_type: str = CT_COMMAND): + self.host = host + self.port = port + self.ssl_ctx = ssl_ctx + self.command_bodies = command_bodies + self.next_uri = next_uri + self.targeted_application = targeted_application + self.content_type = content_type + self.on_response = on_response + self.on_session_end = on_session_end + self._sock: Optional[socket.socket] = None + self._stop = threading.Event() + + def bind(self) -> int: + self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._sock.bind((self.host, self.port)) + self._sock.listen(5) + self._sock.settimeout(0.5) + self.port = self._sock.getsockname()[1] + return self.port + + def serve_forever(self) -> None: + if self._sock is None: + self.bind() + logger.info('SCP81 admin server listening on %s:%u (%u command(s) queued)', + self.host, self.port, len(self.command_bodies)) + while not self._stop.is_set(): + try: + conn, addr = self._sock.accept() + except socket.timeout: + continue + except OSError: + break + threading.Thread(target=self._handle, args=(conn, addr), daemon=True).start() + + def shutdown(self) -> None: + self._stop.set() + if self._sock is not None: + self._sock.close() + + def _handle(self, conn: socket.socket, addr) -> None: + try: + tls = self.ssl_ctx.wrap_socket(conn, server_side=True) + except (ssl.SSLError, OSError) as e: + logger.warning('TLS-PSK handshake with %s failed: %s', addr, e) + try: + conn.close() + except OSError: + pass + return + logger.info('TLS-PSK established with %s: %s / %s', addr, tls.version(), tls.cipher()) + session = AdminSession(self.command_bodies, next_uri=self.next_uri, + targeted_application=self.targeted_application, + on_response=self.on_response, + content_type=self.content_type) + try: + rfile = tls.makefile('rb') + run_admin_loop(rfile, tls.sendall, session) + except (ssl.SSLError, OSError, ValueError) as e: + logger.warning('session with %s aborted: %s', addr, e) + finally: + try: + tls.close() + except OSError: + pass + logger.info('session with %s ended: %u response(s) collected', addr, len(session.responses)) + if self.on_session_end: + self.on_session_end(session) + + +def build_command_bodies(apdus: List[bytes], batch: bool = False, + length_coding: str = 'definite') -> List[bytes]: + """wrpa apdus + each C-APDU -> one cmd message + one HTTP response per APDU + batch=True -> all C-APDUs in one Command Scripting template. + length_coding selects the definite or indefinite Command Scripting template.""" + if not apdus: + return [] + if batch: + return [encode_expanded_cmd(apdus, length_coding=length_coding)] + return [encode_expanded_cmd(a, length_coding=length_coding) for a in apdus] + + +def main(): + parser = argparse.ArgumentParser( + description='TLS-PSK HTTP Remote Administration Server for SCP81 / RAM over HTTP') + parser.add_argument('--host', default='0.0.0.0', help='Host/IP to bind to (default: 0.0.0.0)') + parser.add_argument('--port', type=int, default=8443, help='TCP port to bind to (default: 8443)') + parser.add_argument('--psk', required=True, + help='PSK TLS key, Amendment B key type 85 as hex') + parser.add_argument('--psk-identity', required=True, + help='Expected PSK identity string presented by the card') + parser.add_argument('--psk-identity-hint', default=None, + help='Optional PSK identity hint to send to the card (default: none)') + parser.add_argument('--allow-any-identity', action='store_true', + help='DEBUG: Accept any psk_identity') + parser.add_argument('--ciphers', default=DEFAULT_CIPHERS, + help='OpenSSL cipher string for TLS<=1.2') + parser.add_argument('--min-tls', default='1.2', choices=sorted(TLS_VERSION_MAP), + help='Minimum TLS version (default: 1.2)') + parser.add_argument('--max-tls', default='1.3', choices=sorted(TLS_VERSION_MAP), + help='Maximum TLS version (default: 1.3)') + parser.add_argument('--seclevel', type=int, default=None, + help='OpenSSL @SECLEVEL to force (0 to enable NULL/3DES/legacy PSK)') + parser.add_argument('--uri', default=None, + help='X-Admin-Next-URI to hand the card (default: request URI)') + parser.add_argument('--mode', choices=sorted(MODE_CONTENT_TYPE), default='ram', + help='"ram" = GP Amendment B RAM to a SD (default), ' + '"rfm" = TS 102 226 RFM/RAM to the --targeted-application.') + parser.add_argument('--targeted-application', default=None, + help='X-Admin-Targeted-Application AID (hex). ' + 'Required by --mode rfm, optional for --mode ram') + parser.add_argument('--length-coding', choices=('definite', 'indefinite'), default='definite', + help='Expanded format length coding "definite" "indefinite"') + parser.add_argument('--apdu', action='append', default=[], metavar='HEX', + help='one of many C-APDU (hex) to send, executed in order') + parser.add_argument('--apdu-file', default=None, + help='File with one C-APDU (hex) per line to push (# comments allowed)') + parser.add_argument('--batch', action='store_true', + help='All C-APDUs in one large command message') + parser.add_argument('--raw-cmd', action='append', default=[], metavar='HEX', + help='Debug, raw command') + parser.add_argument('-v', '--verbose', action='store_true', help='enable debug output') + args = parser.parse_args() + + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, + format='%(asctime)s %(levelname)s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + + if args.mode == 'rfm' and not args.targeted_application: + parser.error('--mode rfm requires --targeted-application <RFM Application AID>') + content_type = MODE_CONTENT_TYPE[args.mode] + + apdus: List[bytes] = [h2b(a) for a in args.apdu] + if args.apdu_file: + for line in Path(args.apdu_file).read_text().splitlines(): + line = line.split('#', 1)[0].strip() + if line: + apdus.append(h2b(line)) + command_bodies = build_command_bodies(apdus, batch=args.batch, + length_coding=args.length_coding) + command_bodies += [h2b(r) for r in args.raw_cmd] + if not command_bodies: + logger.warning('no C-APDUs: the server will answer the first POST with 204...') + + targeted = format_aid(args.targeted_application) if args.targeted_application else None + logger.info('mode=%s content-type=%s length-coding=%s targeted-application=%s', + args.mode, content_type, args.length_coding, targeted or '(none)') + + ssl_ctx = make_ssl_context(h2b(args.psk), args.psk_identity, + ciphers=args.ciphers, + min_tls=args.min_tls, max_tls=args.max_tls, + seclevel=args.seclevel, + identity_hint=args.psk_identity_hint, + allow_any_identity=args.allow_any_identity) + + server = Scp81AdminServer(args.host, args.port, ssl_ctx, command_bodies, + next_uri=args.uri, targeted_application=targeted, + content_type=content_type) + try: + server.serve_forever() + except KeyboardInterrupt: + logger.info('shutting down') + server.shutdown() + + +if __name__ == '__main__': + main() -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43547?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I4f243aeca65d0f33ff34e6932e3f4e156446af8b Gerrit-Change-Number: 43547 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: daniel <dwillmann(a)sysmocom.de> Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: lynxis lazus <lynxis(a)fe80.eu>
1 0
0 0
[XS] Change in pysim[master]: osmo-smdpp: add --smdp-address to set ES9+ SM-DP+ address
by Hoernchen 25 Sep '26

25 Sep '26
Hoernchen has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43549?usp=email ) Change subject: osmo-smdpp: add --smdp-address to set ES9+ SM-DP+ address ...................................................................... osmo-smdpp: add --smdp-address to set ES9+ SM-DP+ address The ES9+ SM-DP+ address is used for the smdpAddress check and for serverSigned1.serverAddress, both default to HOSTNAME. Add --smdp-address (default: HOSTNAME) so the advertised address can carry a port and still match what the LPA connects to when the TLS endpoint is bound to other ports than 443. TLS certificate identity is unaffected, this is only the ES9+ address. SGP.22 defines both smdpAddress and serverSigned1.serverAddress as an FQDN. Taken strictly that leaves no way to run an SM-DP+ on a port other than 443, so an address with a port is arguably outside the spec but needed for testing. Change-Id: I2fa822c7d5e0d5b68a6704a1779f9923505f9008 --- M osmo-smdpp.py 1 file changed, 6 insertions(+), 1 deletion(-) Approvals: Jenkins Builder: Verified dexter: Looks good to me, but someone else must approve Hoernchen: Looks good to me, approved diff --git a/osmo-smdpp.py b/osmo-smdpp.py index 8120b0f..2add23f 100755 --- a/osmo-smdpp.py +++ b/osmo-smdpp.py @@ -916,12 +916,17 @@ action='store_true', default=False) parser.add_argument("-m", "--in-memory", help="Use ephermal in-memory session storage (for concurrent runs)", action='store_true', default=False) + parser.add_argument("--smdp-address", default=HOSTNAME, + help="ES9+ SM-DP+ address advertised, defaults to \"%(default)s\". " + "Include the TLS port (e.g. %(default)s:8443) when binding a port other " + "than 443, so it matches the address the LPA connects to. " + "The TLS certificate identity is unaffected.") args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING) common_cert_path = os.path.join(DATA_DIR, args.certdir) - hs = SmDppHttpServer(server_hostname=HOSTNAME, ci_certs_path=os.path.join(common_cert_path, 'CertificateIssuer'), common_cert_path=common_cert_path, use_brainpool=args.brainpool) + hs = SmDppHttpServer(server_hostname=args.smdp_address, ci_certs_path=os.path.join(common_cert_path, 'CertificateIssuer'), common_cert_path=common_cert_path, use_brainpool=args.brainpool) if(args.nossl): hs.app.run(args.host, args.port) else: -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43549?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I2fa822c7d5e0d5b68a6704a1779f9923505f9008 Gerrit-Change-Number: 43549 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
  • ← Newer
  • 1
  • ...
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • ...
  • 190
  • Older →

HyperKitty Powered by HyperKitty version 1.3.12.