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 <[email protected]>
+#
+# 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 <[email protected]>

Reply via email to