fix: emit wire-shaped TPDUs in the GSMTAP stream (v3.1.1)
The GSMTAP stream sent logical APDUs, so a receiver (SIMtrace Analyser,
Wireshark) flagged almost every packet: case-4 commands carried their Le
byte ('length_mismatch: excessive') and responses were headerless packets
decoded as bogus commands ('truncated'). The ATR also arrived in the
middle of the stream.
- gsmtap.py: the tracer now emits wire-shaped TPDUs, matching a hardware
sniffer capture: case 4 -> the command without Le plus the 61XX 'bytes
available' SW (derived from the real response length), then the data as
a GET RESPONSE TPDU (00C00000<len> + data + SW, chunked at 255); case
1/2/3 -> one packet cmd + data + SW; unparseable APDUs fall back to raw
command/response packets.
- No ATR/VCC/RST/PPS events at all (no line-level access over PC/SC);
the ATR sending helper and the server-side plumbing were removed.
- Verified by replaying the bad capture's exchanges through the new
tracer: 116 packets, zero decoder warnings (previously nearly all).
- tests: the per-case wire forms, chunking, fallbacks; README/AGENTS
document the wire shape and its limits; version 3.1.1, sw simple-v236.
This commit is contained in:
@@ -14,7 +14,7 @@ from pySim.cards import UiccCardBase
|
||||
from .shell import load_pysim_app
|
||||
from . import fastinit
|
||||
from . import gsmtap
|
||||
from .server import PysimHandler, StderrApduTracer, _LoggingApduTracer, VERSION, _send_terminal_profile, _DefaultProactiveHandler, _handle_proactive_chain, _send_status, _init_proactive_session, _timing_on, _tlog, _set_menu_timeout, start_card_monitor, set_auto_equip, _read_iccid, _netstate_read, _netstate_install, _send_gsmtap_atr, _LineFilter
|
||||
from .server import PysimHandler, StderrApduTracer, _LoggingApduTracer, VERSION, _send_terminal_profile, _DefaultProactiveHandler, _handle_proactive_chain, _send_status, _init_proactive_session, _timing_on, _tlog, _set_menu_timeout, start_card_monitor, set_auto_equip, _read_iccid, _netstate_read, _netstate_install, _LineFilter
|
||||
|
||||
|
||||
_server_start = 0
|
||||
@@ -267,10 +267,6 @@ def main():
|
||||
server.card_present = card is not None
|
||||
server.card_session = 1 if card is not None else 0
|
||||
server.iccid = iccid
|
||||
server.gsmtap = gsmtap_sender
|
||||
# Stream the ATR so a GSMTAP receiver (SIMtrace Analyser, Wireshark) has
|
||||
# the session context before the first APDU of this session.
|
||||
_send_gsmtap_atr(server)
|
||||
# Network state monitor: install the state read during the startup init
|
||||
# (right after the ICCID, before the TERMINAL PROFILE). No readable
|
||||
# ICCID means the card is considered unusable - give up.
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
# coding=utf-8
|
||||
"""GSMTAP-SIM UDP sender for live APDU capture.
|
||||
|
||||
Streams every APDU the server sends/receives as GSMTAP-SIM packets, so a
|
||||
Streams the card APDUs the server sends/receives as GSMTAP-SIM packets, so a
|
||||
GSMTAP receiver (SIMtrace Analyser ``--capture gsmtap``, Wireshark, or
|
||||
simtrace2-sniff) can follow the card dialogue live. Enabled with
|
||||
``--gsmtap [HOST[:PORT]]`` only (default ``127.0.0.1:4729``) - there is no
|
||||
UI or API for it.
|
||||
``--gsmtap [HOST[:PORT]]`` only (default ``127.0.0.1:4729``) - there is no UI
|
||||
or API for it.
|
||||
|
||||
The packet format is the one shared by libosmocore's ``gsmtap.h``,
|
||||
simtrace2-sniff, sigrok-iso7816-stream and the SIMtrace Analyser: a 16-byte
|
||||
big-endian header (version 2, ``hdr_len`` 4, type 0x04 = SIM, sub_type,
|
||||
``res`` flags) followed by the raw APDU/TPDU bytes. A response is sent as
|
||||
``data + SW1SW2`` (the wire form); the receiver infers the direction from
|
||||
the ISO 7816 case, exactly like a sniffer capture.
|
||||
big-endian header (version 2, ``hdr_len`` 4, type 0x04 = SIM, sub_type 0x00 =
|
||||
APDU, ``res`` flags) followed by the raw TPDU bytes.
|
||||
|
||||
The tracer emits **wire-shaped TPDUs**, not logical APDUs, because that is
|
||||
what a receiver pairs and decodes:
|
||||
|
||||
* case 4 (command with data + Le): the command without its Le byte plus the
|
||||
"61XX bytes available" status word, then the response data as a GET
|
||||
RESPONSE TPDU (``00C00000<len> + data + SW``);
|
||||
* case 2 / 1 / 3: one packet with the command, the response data and the SW;
|
||||
* unparseable APDUs fall back to a raw command packet and a raw response one.
|
||||
|
||||
The APDU data is always the real one - only the T=0 framing (which the PC/SC
|
||||
reader hides) is reconstructed, so the ``61XX`` length is the final response
|
||||
length and internal retries are not visible. No ATR/VCC/RST/PPS events are
|
||||
sent (the server has no line-level access).
|
||||
|
||||
Sending is fire-and-forget on a non-blocking socket: a missing listener must
|
||||
never affect card I/O.
|
||||
@@ -22,13 +34,14 @@ import socket
|
||||
import struct
|
||||
|
||||
from pySim.transport import ApduTracer
|
||||
from pySim.utils import h2b, parse_command_apdu
|
||||
|
||||
GSMTAP_VERSION = 0x02
|
||||
GSMTAP_HDR_LEN = 4 # in 32-bit words (16 bytes)
|
||||
GSMTAP_TYPE_SIM = 0x04
|
||||
|
||||
GSMTAP_SIM_APDU = 0x00
|
||||
GSMTAP_SIM_ATR = 0x01
|
||||
GSMTAP_SIM_ATR = 0x01 # not sent; kept for reference
|
||||
|
||||
GSMTAP_UDP_PORT = 4729
|
||||
DEFAULT_TARGET = '127.0.0.1:%d' % GSMTAP_UDP_PORT
|
||||
@@ -36,6 +49,8 @@ DEFAULT_TARGET = '127.0.0.1:%d' % GSMTAP_UDP_PORT
|
||||
_HDR_FMT = '!BBBBHBBIBBBB' # 16 bytes, big-endian
|
||||
_HDR_SIZE = struct.calcsize(_HDR_FMT)
|
||||
|
||||
_GET_RESPONSE_CHUNK = 255 # max GET RESPONSE payload per TPDU
|
||||
|
||||
|
||||
def build_packet(sub_type, data, flags=0, slot_nr=0):
|
||||
"""Build a complete GSMTAP-SIM packet (header + payload) as bytes."""
|
||||
@@ -91,9 +106,6 @@ class GsmtapSender:
|
||||
def send_apdu(self, data, slot_nr=0):
|
||||
self.send(GSMTAP_SIM_APDU, data, slot_nr=slot_nr)
|
||||
|
||||
def send_atr(self, data, slot_nr=0):
|
||||
self.send(GSMTAP_SIM_ATR, data, slot_nr=slot_nr)
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self._sock.close()
|
||||
@@ -101,12 +113,20 @@ class GsmtapSender:
|
||||
pass
|
||||
|
||||
|
||||
class GsmtapApduTracer(ApduTracer):
|
||||
"""pySim APDU tracer that streams every APDU as a GSMTAP-SIM packet.
|
||||
def _apdu_case(cmd):
|
||||
"""ISO 7816-3 case of a command APDU, or None when unparseable."""
|
||||
try:
|
||||
case, _lc, _le, _data = parse_command_apdu(h2b(cmd))
|
||||
return case
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
Commands are sent as-is; a response is sent as ``data + SW1SW2`` so the
|
||||
receiver sees the same wire TPDU a hardware sniffer would capture.
|
||||
Malformed hex never raises into pySim's transport.
|
||||
|
||||
class GsmtapApduTracer(ApduTracer):
|
||||
"""pySim APDU tracer streaming wire-shaped TPDUs as GSMTAP-SIM packets.
|
||||
|
||||
See the module docstring for the emitted forms. Malformed hex never
|
||||
raises into pySim's transport.
|
||||
"""
|
||||
|
||||
def __init__(self, sender):
|
||||
@@ -114,21 +134,47 @@ class GsmtapApduTracer(ApduTracer):
|
||||
self.sender = sender
|
||||
|
||||
def trace_command(self, cmd):
|
||||
if not cmd:
|
||||
return
|
||||
try:
|
||||
self.sender.send_apdu(bytes.fromhex(cmd))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
"""Nothing is sent here: the wire packets need the response."""
|
||||
|
||||
def trace_response(self, cmd, sw, resp):
|
||||
data = (resp or '') + (sw or '')
|
||||
if not data:
|
||||
return
|
||||
try:
|
||||
self.sender.send_apdu(bytes.fromhex(data))
|
||||
raw = bytes.fromhex(cmd or '')
|
||||
resp_bytes = bytes.fromhex(resp or '')
|
||||
sw_bytes = bytes.fromhex(sw or '')
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return
|
||||
|
||||
case = _apdu_case(cmd)
|
||||
if case is None or not raw:
|
||||
# Unparseable APDU: keep the raw command / raw response form.
|
||||
if raw:
|
||||
self.sender.send_apdu(raw)
|
||||
if resp_bytes or sw_bytes:
|
||||
self.sender.send_apdu(resp_bytes + sw_bytes)
|
||||
return
|
||||
|
||||
if case == 4 and len(raw) > 1:
|
||||
# The wire TPDU carries no Le byte for case 4.
|
||||
body = raw[:-1]
|
||||
if not resp_bytes:
|
||||
self.sender.send_apdu(body + sw_bytes)
|
||||
return
|
||||
size = len(resp_bytes)
|
||||
# T=0: "61XX bytes available", then the data via GET RESPONSE.
|
||||
self.sender.send_apdu(body + bytes([0x61, min(size, 0xFF)]))
|
||||
offset = 0
|
||||
while offset < size:
|
||||
chunk = min(size - offset, _GET_RESPONSE_CHUNK)
|
||||
last = offset + chunk >= size
|
||||
self.sender.send_apdu(
|
||||
bytes([0x00, 0xC0, 0x00, 0x00, chunk])
|
||||
+ resp_bytes[offset:offset + chunk]
|
||||
+ (sw_bytes if last else b''))
|
||||
offset += chunk
|
||||
return
|
||||
|
||||
# case 1/2/3: the command TPDU and its response share one packet.
|
||||
self.sender.send_apdu(raw + resp_bytes + sw_bytes)
|
||||
|
||||
|
||||
class FanoutApduTracer(ApduTracer):
|
||||
|
||||
@@ -28,7 +28,7 @@ from osmocom.tlv import BER_TLV_IE
|
||||
from osmocom.utils import rpad
|
||||
|
||||
|
||||
VERSION = '3.1.0'
|
||||
VERSION = '3.1.1'
|
||||
|
||||
MAX_ENVELOPE_SEGMENTS = 5 # max SMS segments for outgoing C-APDU in ENVELOPE
|
||||
|
||||
@@ -2532,34 +2532,10 @@ def _handle_card_disconnect():
|
||||
_reset_proactive_log()
|
||||
|
||||
|
||||
def _send_gsmtap_atr(server):
|
||||
"""Stream the card's ATR as a GSMTAP-SIM packet (--gsmtap only).
|
||||
|
||||
Sent at every equip so a GSMTAP receiver (SIMtrace Analyser, Wireshark)
|
||||
has the session context before the first APDU of the new session."""
|
||||
sender = getattr(server, 'gsmtap', None)
|
||||
if sender is None:
|
||||
return
|
||||
rs = getattr(server, 'rs', None)
|
||||
atr = None
|
||||
if rs is not None:
|
||||
try:
|
||||
atr = (rs.identity or {}).get('ATR')
|
||||
except Exception:
|
||||
atr = None
|
||||
if not atr:
|
||||
return
|
||||
try:
|
||||
sender.send_atr(bytes.fromhex(atr))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
|
||||
def _apply_equipped_card(server):
|
||||
"""Common post-equip state refresh + TERMINAL PROFILE, shared by the
|
||||
/api/command equip branch and the auto-equip worker."""
|
||||
global _CARD_CONNECTED
|
||||
_send_gsmtap_atr(server)
|
||||
server.stk_pending = None
|
||||
server.menu_active = False
|
||||
_cancel_menu_timeout()
|
||||
|
||||
Reference in New Issue
Block a user