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 -----
  • December
  • 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

  • 1 participants
  • 97203 discussions
[L] Change in pysim[master]: ota: CAT_TP / TCP dialect of TS 102 225 secured packet
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43717?usp=email ) Change subject: ota: CAT_TP / TCP dialect of TS 102 225 secured packet ...................................................................... ota: CAT_TP / TCP dialect of TS 102 225 secured packet There are 3 sections: Section 6, CAT_TP: SCP80 secured packets as CAT_TP SDUs over BIP UDP Section 7, TCP/IP: SCP80 secured packets, dropped raw into a TCP stream Section 8, HTTPS = SCP81: no SCP80 packets, prev patchset This covers 6+7 which are identical on the packet level and are basically SCP80 OTA sms without a length limit over a different transport. In practice I don't think anyone ever deployed scp80 over tcp... Change-Id: I122a13000e622f7550468845e8560dec5a3c55a6 --- M pySim/ota.py M tests/unittests/test_ota.py 2 files changed, 262 insertions(+), 1 deletion(-) Approvals: dexter: Looks good to me, approved Jenkins Builder: Verified laforge: Looks good to me, but someone else must approve diff --git a/pySim/ota.py b/pySim/ota.py index 82b1a85..1a44de9 100644 --- a/pySim/ota.py +++ b/pySim/ota.py @@ -23,7 +23,7 @@ from construct import Flag, Padding, Switch, this, PrefixedArray, GreedyRange from construct import Const, Prefixed, Select, Construct, SizeofError, stream_read, stream_write from osmocom.construct import * -from osmocom.tlv import bertlv_encode_len +from osmocom.tlv import bertlv_encode_len, bertlv_parse_len from osmocom.utils import b2h from pySim.sms import UserDataHeader @@ -735,3 +735,162 @@ else: dec = None return (res, dec) + + +class OtaDialectCatTp(OtaDialect): + """TS 102 225 section 6 (CAT_TP) and 7 (TCP/IP), which are identical on the packet level: + CPI '01' / RPI '02', CHI and RHI absent, CPL/CHL/RPL/RHL are BER lengths, and unlike SMS + the CPI+CPL+CHL (RPI+RPL+RHL) are part of the RC/CC/DS. One packet per SDU.""" + CPI = 0x01 # TS 102 225 section 6 + RPI = 0x02 # TS 102 225 section 6 + IDENTIFICATION_PI = 0x03 # TS 102 225 table 6, TCP/IP only + + # field lengths in octets, TS 102 225 table 1 (command packet) and table 3 (response packet) + SPI_LEN = 2 + KIC_LEN = 1 + KID_LEN = 1 + TAR_LEN = 3 + CNTR_LEN = 5 + PCNTR_LEN = 1 + STATUS_LEN = 1 + CMD_HDR_LEN = SPI_LEN + KIC_LEN + KID_LEN + TAR_LEN # between CHL and CNTR + CNTR_PCNTR_LEN = CNTR_LEN + PCNTR_LEN + RESP_HDR_LEN = TAR_LEN + CNTR_LEN + PCNTR_LEN + STATUS_LEN # between RHL and RC/CC/DS + + hdr_construct = Struct('spi'/SPI, 'kic'/KIC, 'kid'/KID_CC, 'tar'/Bytes(TAR_LEN)) + ResponseHead = Struct('tar'/Bytes(TAR_LEN), 'cntr'/Bytes(CNTR_LEN), 'pcntr'/Int8ub, + 'response_status'/ResponseStatus) + + @staticmethod + def _sig(otak: OtaKeyset, rc_cc_ds: str, data: bytes) -> bytes: + if rc_cc_ds == 'cc': + return otak.auth.sign(data) + if rc_cc_ds == 'rc': + return (zlib.crc32(data) & 0xffffffff).to_bytes(4, 'big') + if rc_cc_ds == 'no_rc_cc_ds': + return b'' + raise ValueError("Invalid rc_cc_ds: %s" % rc_cc_ds) + + @staticmethod + def _check_sig(otak: OtaKeyset, rc_cc_ds: str, data: bytes, sig: bytes): + if rc_cc_ds == 'cc': + otak.auth.check_sig(data, sig) + elif rc_cc_ds == 'rc': + expected = (zlib.crc32(data) & 0xffffffff).to_bytes(4, 'big') + if sig != expected: + raise OtaCheckError('Received RC (%s) != Computed RC (%s)' % (b2h(sig), b2h(expected))) + + def encode_cmd(self, otak: OtaKeyset, tar: bytes, spi: dict, + apdu: Union[bytes, List[bytes]], remote_format: str = 'compact') -> bytes: + if remote_format == 'expanded': + apdu = encode_expanded_cmd(apdu) + elif remote_format != 'compact': + raise ValueError("Invalid remote_format: %s" % remote_format) + apdu = bytes(apdu) + len_sig = self._compute_sig_len(spi) + pcntr = 0 + if spi['ciphering']: + # CNTR + PCNTR + RC/CC/DS + data are ciphered, TS 102 225 table 2 note 1 + padding = otak.crypt._get_padding(self.CNTR_PCNTR_LEN + len_sig + len(apdu), + otak.crypt.blocksize) + pcntr = len(padding) + apdu += padding + hdr = self.hdr_construct.build({'spi': spi, 'tar': tar, + 'kic': {'key': otak.kic_idx, 'algo': otak.algo_crypt}, + 'kid': {'key': otak.kid_idx, 'algo': otak.algo_auth}}) + cntr_pcntr = otak.cntr.to_bytes(self.CNTR_LEN, 'big') + bytes([pcntr]) + chl = self.CMD_HDR_LEN + self.CNTR_PCNTR_LEN + len_sig # SPI .. RC/CC/DS + cpl = len(bertlv_encode_len(chl)) + chl + len(apdu) # CHL .. end of data + # the CHI is a null field, TS 102 225 section 6: CHL follows CPL directly + head = bytes([self.CPI]) + bertlv_encode_len(cpl) + bertlv_encode_len(chl) + hdr + sig = self._sig(otak, spi['rc_cc_ds'], head + cntr_pcntr + apdu) + body = cntr_pcntr + sig + apdu + if spi['ciphering']: + body = otak.crypt.encrypt(body) + return head + body + + def decode_cmd(self, otak: OtaKeyset, encoded: bytes) -> Tuple[bytes, dict, bytes]: + """Decode a command packet into (tar, spi, apdu), what the card does.""" + if encoded[0] != self.CPI: + raise ValueError('Unexpected CPI 0x%02x, expected 0x%02x' % (encoded[0], self.CPI)) + cpl, rest = bertlv_parse_len(encoded[1:]) + if len(rest) != cpl: + raise ValueError('CPL %u != %u remaining octets' % (cpl, len(rest))) + # the CHI is a null field, TS 102 225 section 6: CHL follows CPL directly + chl, rest = bertlv_parse_len(rest) + head = encoded[:len(encoded) - len(rest) + self.CMD_HDR_LEN] # CPI .. TAR + hdr = self.hdr_construct.parse(rest[:self.CMD_HDR_LEN]) + spi = hdr['spi'] + body = rest[self.CMD_HDR_LEN:] + if spi['ciphering']: + body = otak.crypt.decrypt(body) + len_sig = self._compute_sig_len(spi) + if chl != self.CMD_HDR_LEN + self.CNTR_PCNTR_LEN + len_sig: + raise ValueError('CHL %u does not match SPI' % chl) + cntr_pcntr = body[:self.CNTR_PCNTR_LEN] + sig = body[self.CNTR_PCNTR_LEN:self.CNTR_PCNTR_LEN + len_sig] + apdu = body[self.CNTR_PCNTR_LEN + len_sig:] + self._check_sig(otak, spi['rc_cc_ds'], head + cntr_pcntr + apdu, sig) + pcntr = cntr_pcntr[self.CNTR_LEN] + return hdr['tar'], spi, apdu[:len(apdu) - pcntr] + + def encode_resp(self, otak: OtaKeyset, spi: dict, tar: bytes, response_status: str = 'por_ok', + data: bytes = b'', cntr: Optional[int] = None) -> bytes: + """Response packet as the card builds it, TS 102 225 5.2, secured per the por_* SPI bits.""" + data = bytes(data) + len_sig = self._compute_sig_len({'rc_cc_ds': spi['por_rc_cc_ds']}) + pcntr = 0 + if spi['por_shall_be_ciphered']: + # CNTR + PCNTR + status + RC/CC/DS + data are ciphered, TS 102 225 table 4 note 1 + padding = otak.crypt._get_padding(self.RESP_HDR_LEN - self.TAR_LEN + len_sig + len(data), + otak.crypt.blocksize) + pcntr = len(padding) + data += padding + cntr = otak.cntr if cntr is None else cntr + hdr = self.ResponseHead.build({'tar': tar, 'cntr': cntr.to_bytes(self.CNTR_LEN, 'big'), + 'pcntr': pcntr, 'response_status': response_status}) + rhl = self.RESP_HDR_LEN + len_sig # TAR .. RC/CC/DS + rpl = len(bertlv_encode_len(rhl)) + rhl + len(data) # RHL .. end of data + # the RHI is a null field, TS 102 225 section 6: RHL follows RPL directly + head = bytes([self.RPI]) + bertlv_encode_len(rpl) + bertlv_encode_len(rhl) + sig = self._sig(otak, spi['por_rc_cc_ds'], head + hdr + data) + body = hdr[self.TAR_LEN:] + sig + data + if spi['por_shall_be_ciphered']: + body = otak.crypt.encrypt(body) + return head + hdr[:self.TAR_LEN] + body + + def decode_resp(self, otak: OtaKeyset, spi: dict, data: bytes, + remote_format: str = 'compact') -> (object, Optional[object]): + if remote_format not in ('compact', 'expanded'): + raise ValueError("Invalid remote_format: %s ?!" % remote_format) + if isinstance(data, str): + data = h2b(data) + if data[0] != self.RPI: + raise ValueError('Unexpected RPI 0x%02x, expected 0x%02x' % (data[0], self.RPI)) + rpl, rest = bertlv_parse_len(data[1:]) + if len(rest) != rpl: + raise ValueError('RPL %u != %u remaining octets' % (rpl, len(rest))) + # the RHI is a null field, TS 102 225 section 6: RHL follows RPL directly + rhl, rest = bertlv_parse_len(rest) + head = data[:len(data) - len(rest)] # RPI .. RHL + tar, body = rest[:self.TAR_LEN], rest[self.TAR_LEN:] + if spi['por_shall_be_ciphered']: + body = otak.crypt.decrypt(body) + len_sig = rhl - self.RESP_HDR_LEN + hdr_rest_len = self.RESP_HDR_LEN - self.TAR_LEN # CNTR + PCNTR + status + hdr = self.ResponseHead.parse(tar + body[:hdr_rest_len]) + sig, secured = body[hdr_rest_len:hdr_rest_len + len_sig], body[hdr_rest_len + len_sig:] + if spi['por_rc_cc_ds'] == 'no_rc_cc_ds' and len_sig: + raise OtaCheckError('No RC/CC/DS requested, but len_sig=%u' % len_sig) + self._check_sig(otak, spi['por_rc_cc_ds'], head + tar + body[:hdr_rest_len] + secured, sig) + if hdr['pcntr']: + secured = secured[:-hdr['pcntr']] + res = Container(rpl=rpl, rhl=rhl, tar=hdr['tar'], cntr=hdr['cntr'], pcntr=hdr['pcntr'], + response_status=hdr['response_status'], cc_rc=sig, secured_data=secured) + dec = None + if res.response_status == 'por_ok' and len(secured): + if remote_format == 'expanded': + dec = decode_expanded_resp(secured) + else: + dec = CompactRemoteResp.parse(secured) + return (res, dec) diff --git a/tests/unittests/test_ota.py b/tests/unittests/test_ota.py index b513355..037e7ee 100644 --- a/tests/unittests/test_ota.py +++ b/tests/unittests/test_ota.py @@ -589,3 +589,105 @@ if __name__ == "__main__": unittest.main() + + +###################################################################### +# CAT_TP / TCP dialect (ETSI TS 102 225 Section 6 + 7) +###################################################################### + +SPI_NONE_POR_NONE = { + 'counter': 'no_counter', 'ciphering': False, 'rc_cc_ds': 'no_rc_cc_ds', + 'por_in_submit': False, 'por_shall_be_ciphered': False, 'por_rc_cc_ds': 'no_rc_cc_ds', + 'por': 'por_required'} + +SPI_RC_POR_RC = dict(SPI_NONE_POR_NONE, rc_cc_ds='rc', por_rc_cc_ds='rc') + + +class CatTpOtaTestCase(OtaTestCase): + APDU = b'\x00\xa4\x00\x04\x02\x3f\x00' + + def setUp(self): + self.dialect = OtaDialectCatTp() + + def test_cmd_plain_golden(self): + # CPI 01, CPL 15, CHL 0d, SPI 0001 KIc 35 KID 35 TAR, CNTR, PCNTR 00, data + outp = self.dialect.encode_cmd(OTA_KEYSET_SJA5_SAMPLES, self.tar, SPI_NONE_POR_NONE, self.APDU) + self.assertEqual(b2h(outp), '01150d00013535b000110000000000' '00' '00a40004023f00') + tar, spi, apdu = self.dialect.decode_cmd(OTA_KEYSET_SJA5_SAMPLES, outp) + self.assertEqual((tar, spi, apdu), (self.tar, SPI_NONE_POR_NONE, self.APDU)) + + def test_cmd_roundtrip(self): + for kset in (OTA_KEYSET_SJA5_SAMPLES, OTA_KEYSET_SJA5_AES128): + for spi in (SPI_CC_POR_CIPHERED_CC, SPI_CC_POR_UNCIPHERED_CC, SPI_RC_POR_RC): + for fmt in ('compact', 'expanded'): + with self.subTest(kset=kset.algo_crypt, spi=spi['rc_cc_ds'], fmt=fmt): + apdu = [self.APDU] if fmt == 'expanded' else self.APDU + outp = self.dialect.encode_cmd(kset, self.tar, spi, apdu, remote_format=fmt) + self.assertEqual(outp[0], 0x01) + if spi['ciphering']: + self.assertEqual((len(outp) - 10) % kset.crypt.blocksize, 0) + tar, dspi, dapdu = self.dialect.decode_cmd(kset, outp) + self.assertEqual(tar, self.tar) + self.assertEqual(dspi, spi) + expected = encode_expanded_cmd(apdu) if fmt == 'expanded' else self.APDU + self.assertEqual(dapdu, expected) + + def test_cmd_tamper_detected(self): + outp = bytearray(self.dialect.encode_cmd(OTA_KEYSET_SJA5_SAMPLES, self.tar, + SPI_CC_POR_UNCIPHERED_CC, self.APDU)) + outp[-1] ^= 0x01 + with self.assertRaises(OtaCheckError): + self.dialect.decode_cmd(OTA_KEYSET_SJA5_SAMPLES, bytes(outp)) + + def test_cmd_long_lengths(self): + # CPL > 127 goes to the 81xx BER form + big = bytes(range(200)) + outp = self.dialect.encode_cmd(OTA_KEYSET_SJA5_SAMPLES, self.tar, SPI_NONE_POR_NONE, big) + self.assertEqual(b2h(outp[:4]), '0181d60d') + self.assertEqual(self.dialect.decode_cmd(OTA_KEYSET_SJA5_SAMPLES, outp)[2], big) + + def test_resp_plain_golden(self): + # RPI 02, RPL 0e, RHL 0a, TAR, CNTR, PCNTR 00, status 00, compact response 01 9000 + resp = self.dialect.encode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_NONE_POR_NONE, self.tar, + data=h2b('019000')) + self.assertEqual(b2h(resp), '020e0ab000110000000000' '00' '00' '019000') + res, dec = self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_NONE_POR_NONE, resp) + self.assertEqual(res.response_status, 'por_ok') + self.assertEqual(dec.last_status_word, '9000') + self.assertEqual(dec.number_of_commands, 1) + + def test_resp_roundtrip(self): + for kset in (OTA_KEYSET_SJA5_SAMPLES, OTA_KEYSET_SJA5_AES128): + for spi in (SPI_CC_POR_CIPHERED_CC, SPI_CC_POR_UNCIPHERED_CC, + SPI_CC_POR_UNCIPHERED_NOCC, SPI_RC_POR_RC): + with self.subTest(kset=kset.algo_crypt, por_cc=spi['por_rc_cc_ds'], + ciph=spi['por_shall_be_ciphered']): + resp = self.dialect.encode_resp(kset, spi, self.tar, data=h2b('01' '6132')) + res, dec = self.dialect.decode_resp(kset, spi, resp) + self.assertEqual(res.response_status, 'por_ok') + self.assertEqual(res.tar, self.tar) + self.assertEqual(dec.last_status_word, '6132') + + def test_resp_error_status_has_no_decoded_part(self): + resp = self.dialect.encode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, self.tar, + response_status='cntr_low') + res, dec = self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, resp) + self.assertEqual(res.response_status, 'cntr_low') + self.assertIsNone(dec) + + def test_resp_expanded(self): + # card answers with a TS 102 226 5.2.2 response scripting template + expanded = h2b('ab0780010123026132') + resp = self.dialect.encode_resp(OTA_KEYSET_SJA5_AES128, SPI_CC_POR_CIPHERED_CC, self.tar, + data=expanded) + res, dec = self.dialect.decode_resp(OTA_KEYSET_SJA5_AES128, SPI_CC_POR_CIPHERED_CC, resp, + remote_format='expanded') + self.assertEqual(res.response_status, 'por_ok') + self.assertEqual(dec.last_status_word, '6132') + + def test_resp_tamper_detected(self): + resp = bytearray(self.dialect.encode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, + self.tar, data=h2b('019000'))) + resp[-1] ^= 0x01 + with self.assertRaises(OtaCheckError): + self.dialect.decode_resp(OTA_KEYSET_SJA5_SAMPLES, SPI_CC_POR_UNCIPHERED_CC, bytes(resp)) -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43717?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I122a13000e622f7550468845e8560dec5a3c55a6 Gerrit-Change-Number: 43717 Gerrit-PatchSet: 3 Gerrit-Owner: 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
[L] Change in pysim[master]: bip: UDP channels for CAT_TP
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43716?usp=email ) Change subject: bip: UDP channels for CAT_TP ...................................................................... bip: UDP channels for CAT_TP Humble beginnings of CAT_TP support: OPEN CHANNEL with "UDP, UICC in client mode, remote connection" gets a datagram socket. SEND DATA without "send immediately" is buffered, TERMINAL PROFILE byte 17 announces our new UDP client mode. ProactChannel becomes the abstract base of ProactTcpChannel and ProactUdpChannel. Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff --- M pySim/bip.py M tests/unittests/test_bip_relay.py 2 files changed, 245 insertions(+), 60 deletions(-) Approvals: Jenkins Builder: Verified laforge: Looks good to me, but someone else must approve dexter: Looks good to me, approved diff --git a/pySim/bip.py b/pySim/bip.py index 1cd3ba0..2c0b244 100644 --- a/pySim/bip.py +++ b/pySim/bip.py @@ -27,7 +27,10 @@ # tp = init_reader(opts, proactive_handler=handler) +import abc +import collections import logging +import select import socket import threading import time @@ -74,16 +77,17 @@ # 13 (class "e" supported bearers): b2 GPRS, and b6..b8 the number of channels. profile[12] = 0x02 | (num_channels << 5) profile[13] = 0x40 | 0x20 # 14: b6 no display capability, b7 no keypad available - profile[16] = 0x01 # 15: b1 TCP, UICC in client mode, remote connection + profile[16] = 0x01 | 0x02 # 17: b1 TCP, b2 UDP, UICC in client mode, remote connection return bytes(profile) -class ProactChannel: - """One BIP channel, TS 102 223 class "e", backed by a blocking TCP socket. +class ProactChannel(abc.ABC): + """One BIP channel, TS 102 223 class "e", backed by a blocking socket. Created by ProactChannels.channel_create(). A reader thread fills the Rx buffer from the socket, the Proact handlers drain it (RECEIVE DATA) and write to it (SEND DATA). Payload - is opaque, TLS or CAT_TP run on the card. + is opaque, TLS or CAT_TP run on the card. ProactTcpChannel and ProactUdpChannel supply the + socket, the reader loop and send(). Args: channels: the owning ProactChannels, notified of data arrival and of close() @@ -98,8 +102,6 @@ # Plain blocking sockets just work: connect() in handle_OpenChannel, send() in # handle_SendData, recv() feeding a buffer for handle_ReceiveData. No need to make it # harder than it has to be to handle the "massive" T0 bandwidth.. - # how much we try to read off the socket per recv() - RECV_CHUNK = 4096 def __init__(self, channels: 'ProactChannels', chan_nr: int): self.channels = channels @@ -114,48 +116,25 @@ self.peer_closed = False def connect(self, host: str, port: int, timeout: float = 10.0): - """Open the blocking TCP socket and start the background Rx reader.""" - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - s.settimeout(timeout) - s.connect((host, port)) - # Back to blocking mode for the reader thread. - # CLOSE CHANNEL unblocks the pending recv() via shutdown(). - s.settimeout(None) - except OSError: - s.close() - raise - self.sock = s + """Open the socket and start the background Rx reader.""" + self.sock = self._open_socket(host, port, timeout) self._reader = threading.Thread(target=self._rx_loop, name='bip-rx-%d' % self.chan_nr, daemon=True) self._reader.start() + @abc.abstractmethod + def _open_socket(self, host: str, port: int, timeout: float) -> socket.socket: + """Return the connected socket, raise OSError if that fails.""" + + @abc.abstractmethod def _rx_loop(self): - """Continuously read from the socket into rx_buf, like a real ME. + """Reader thread: move received data into rx_buf until the channel closes and call + channels.notify_data_available() when data arrives in the empty buffer.""" - TS 102 223 7.5.10.1 says the event is raised 'only if the targeted channel buffer is - empty when new data arrives in it', so the data available hook fires on the - empty->non-empty transition only. That is enough: every RECEIVE DATA response tells - the card how many bytes remain, so it keeps fetching until the buffer is empty, and - the next event restarts it when more data arrives.""" - while not self._closing: - try: - data = self.sock.recv(self.RECV_CHUNK) - except (OSError, ValueError): - break - if not data: - self.peer_closed = True - break - with self._rx_lock: - was_empty = len(self.rx_buf) == 0 - self.rx_buf.extend(data) - if was_empty and not self._closing: - self.channels.notify_data_available(self) - - def send(self, data: bytes): - """Tx, write bytes to the socket == SEND DATA""" - self.sock.sendall(data) + @abc.abstractmethod + def send(self, data: bytes, immediate: bool = True): + """SEND DATA. immediate is bit 1 of the command qualifier, "send immediately" as + opposed to "store in the Tx buffer" (TS 102 223 6.4.30).""" def available_rx(self) -> int: """Number of bytes waiting in the Rx buffer, what RECEIVE DATA can return right now.""" @@ -205,6 +184,118 @@ self._reader.join(timeout=1.0) self.channels.channel_delete(self.chan_nr) + +class ProactTcpChannel(ProactChannel): + """BIP channel on a TCP socket, a byte stream as used by SCP81.""" + # how much we try to read off the socket per recv() + RECV_CHUNK = 4096 + + def _open_socket(self, host: str, port: int, timeout: float) -> socket.socket: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + s.settimeout(timeout) + s.connect((host, port)) + # Back to blocking mode for the reader thread. + # CLOSE CHANNEL unblocks the pending recv() via shutdown(). + s.settimeout(None) + except OSError: + s.close() + raise + return s + + def _rx_loop(self): + """Continuously read from the socket into rx_buf, like a real ME. + + TS 102 223 7.5.10.1 says the event is raised 'only if the targeted channel buffer is + empty when new data arrives in it', so the data available hook fires on the + empty->non-empty transition only. That is enough: every RECEIVE DATA response tells + the card how many bytes remain, so it keeps fetching until the buffer is empty, and + the next event restarts it when more data arrives.""" + while not self._closing: + try: + data = self.sock.recv(self.RECV_CHUNK) + except (OSError, ValueError): + break + if not data: + self.peer_closed = True + break + with self._rx_lock: + was_empty = len(self.rx_buf) == 0 + self.rx_buf.extend(data) + if was_empty and not self._closing: + self.channels.notify_data_available(self) + + def send(self, data: bytes, immediate: bool = True): + # a stream has no SDU boundary to keep, so nothing is held back + self.sock.sendall(data) + + +class ProactUdpChannel(ProactChannel): + """BIP channel on a connected UDP socket, for CAT_TP (TS 102 127 section 6). + + TS 102 223 6.4.29/6.4.30: the Rx buffer holds one datagram SDU at a time, the next one is + inserted only once the card drained it, and the Tx buffer collects SEND DATA until "send + immediately", which emits it as one datagram.""" + RECV_CHUNK = 65535 + + def __init__(self, channels: 'ProactChannels', chan_nr: int): + super().__init__(channels, chan_nr) + self.rx_dgrams = collections.deque() # datagrams waiting behind the current one + self.tx_buf = bytearray() + + def _open_socket(self, host: str, port: int, timeout: float) -> socket.socket: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect((host, port)) + except OSError: + s.close() + raise + return s + + def _rx_loop(self): + """One datagram per recv(). The data available event is raised for the datagram that + lands in an empty buffer, and again when the next queued one moves into the buffer.""" + while not self._closing: + try: + readable, _, _ = select.select([self.sock], [], [], 0.02) + except (OSError, ValueError): + break + if readable: + try: + data = self.sock.recv(self.RECV_CHUNK) + except ConnectionRefusedError: + logger.warning("channel %u: ICMP port unreachable from peer", self.chan_nr) + continue + except (OSError, ValueError): + break + with self._rx_lock: + was_empty = len(self.rx_buf) == 0 + if was_empty: + self.rx_buf.extend(data) + else: + self.rx_dgrams.append(data) + if was_empty and not self._closing: + self.channels.notify_data_available(self) + self._advance() + + def _advance(self): + """Move the next datagram into the drained buffer, from the reader thread so the + notification never runs on the thread that is driving the card.""" + with self._rx_lock: + if self.rx_buf or not self.rx_dgrams: + return + self.rx_buf.extend(self.rx_dgrams.popleft()) + if not self._closing: + self.channels.notify_data_available(self) + + def send(self, data: bytes, immediate: bool = True): + self.tx_buf.extend(data) + if immediate: + self.sock.send(bytes(self.tx_buf)) + self.tx_buf.clear() + + class ProactChannels: """The open BIP channels of one terminal, keyed by channel number. @@ -222,11 +313,16 @@ self.channels = {} self._on_data_available = on_data_available - def channel_create(self) -> ProactChannel: - """Create a new proactive channel, allocating its integer number.""" + def channel_create(self, proto: str = 'tcp') -> ProactChannel: + """Create a new proactive channel, allocating its integer number. + + Args: + proto: 'tcp' for a ProactTcpChannel, 'udp' for a ProactUdpChannel + """ + cls = {'tcp': ProactTcpChannel, 'udp': ProactUdpChannel}[proto] for i in range(1, self.MAX_CHANNELS + 1): if not i in self.channels: - self.channels[i] = ProactChannel(self, i) + self.channels[i] = cls(self, i) return self.channels[i] raise ValueError('Cannot allocate another channel: All channels active') @@ -447,7 +543,8 @@ # UICC/terminal interface transport level is Optional, TS 102 223 6.6.27.x. Absent means # the CAT application runs its own network and transport layer, which we do not do. - if transp_lvl_ie is None or transp_lvl_ie.decoded['protocol_type'] != 'tcp_uicc_client_remote': + protos = {'tcp_uicc_client_remote': 'tcp', 'udp_uicc_client_remote': 'udp'} + if transp_lvl_ie is None or transp_lvl_ie.decoded['protocol_type'] not in protos: logger.warning("OpenChannel: unsupported UICC/terminal interface transport level (%s) " "-> refusing", transp_lvl_ie.decoded if transp_lvl_ie else '(absent)') return refuse('requested_uicc_if_transp_level_not_available') @@ -461,9 +558,10 @@ other_addr_ie.decoded['address'], str) else other_addr_ie.decoded['address'] ipv4_str = '%u.%u.%u.%u' % (addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]) port_nr = transp_lvl_ie.decoded['port_number'] - logger.info("OpenChannel: connecting to %s:%u", ipv4_str, port_nr) + proto = protos[transp_lvl_ie.decoded['protocol_type']] + logger.info("OpenChannel: connecting to %s:%u (%s)", ipv4_str, port_nr, proto) try: - channel = self.channels.channel_create() + channel = self.channels.channel_create(proto) except ValueError: # TS 102 223 6.4.27.2 and 6.4.27.3: no channel left -> BIP error logger.warning("OpenChannel: all %u channels are in use -> refusing", @@ -569,9 +667,8 @@ if isinstance(payload, str): payload = h2b(payload) # command_qualifier bit 1 selects 'send immediately' / Tx-buffer store and forward - # For TCP stream all we have is a socket and TCP takes care of segmentation, - # so just send. - chan.send(payload) + cd_ie = Proact._find_first_element_of_type(pcmd.children, CommandDetails) + chan.send(payload, immediate=bool(cd_ie.decoded['command_qualifier'] & 0x01)) # Terminal Response example: [ # {'command_details': {'command_number': 1, # 'type_of_command': 'send_data', diff --git a/tests/unittests/test_bip_relay.py b/tests/unittests/test_bip_relay.py index 5f72411..b4fe9d4 100644 --- a/tests/unittests/test_bip_relay.py +++ b/tests/unittests/test_bip_relay.py @@ -30,7 +30,7 @@ OtherAddress, ChannelData, ChannelDataLength, ChannelStatus, Result, LocationInformation) -from pySim.bip import Proact, ProactChannels, terminal_profile +from pySim.bip import Proact, ProactChannels, ProactTcpChannel, ProactUdpChannel, terminal_profile class _EchoServer: @@ -71,6 +71,33 @@ pass +class _UdpEchoServer: + """echoes every datagram, and records them so datagram boundaries can be asserted""" + def __init__(self): + self._srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._srv.bind(('127.0.0.1', 0)) + self._srv.settimeout(0.1) + self.port = self._srv.getsockname()[1] + self.datagrams = [] + self._stop = False + threading.Thread(target=self._run, daemon=True).start() + + def _run(self): + while not self._stop: + try: + data, addr = self._srv.recvfrom(65535) + except socket.timeout: + continue + except OSError: + break + self.datagrams.append(data) + self._srv.sendto(data, addr) + + def close(self): + self._stop = True + self._srv.close() + + def _pcmd(children_tlvs): """Assemble D0 proactive-command TLV from child IE bytes, decode it like transport does after a FETCH""" @@ -79,7 +106,7 @@ return ProactiveCommand().from_tlv(pdu) -def _open_channel(port, ip='127.0.0.1', cmd_nr=1): +def _open_channel(port, ip='127.0.0.1', cmd_nr=1, proto='tcp_uicc_client_remote'): a, b, c, d = (int(x) for x in ip.split('.')) return _pcmd([ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'open_channel', @@ -87,8 +114,7 @@ DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': 'terminal'}).to_tlv(), BearerDescription(decoded={'bearer_type': 'default', 'bearer_parameters': b''}).to_tlv(), BufferSize(decoded=1024).to_tlv(), - UiccTransportLevel(decoded={'protocol_type': 'tcp_uicc_client_remote', - 'port_number': port}).to_tlv(), + UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': port}).to_tlv(), OtherAddress(decoded={'type_of_address': 'ipv4', 'address': bytes([a, b, c, d])}).to_tlv(), ]) @@ -105,10 +131,10 @@ ] + extra_ies) -def _send_data(payload, chan='channel_1', cmd_nr=1): +def _send_data(payload, chan='channel_1', cmd_nr=1, immediate=True): return _pcmd([ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'send_data', - 'command_qualifier': 1}).to_tlv(), + 'command_qualifier': 1 if immediate else 0}).to_tlv(), DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': chan}).to_tlv(), ChannelData(decoded=b2h(payload)).to_tlv(), ]) @@ -266,6 +292,68 @@ self.assertEqual(_first(til, ChannelDataLength).decoded, 0) +class ChannelCreateTest(unittest.TestCase): + def test_proto_selects_the_channel_class(self): + channels = ProactChannels() + self.assertIsInstance(channels.channel_create(), ProactTcpChannel) + self.assertIsInstance(channels.channel_create('tcp'), ProactTcpChannel) + self.assertIsInstance(channels.channel_create('udp'), ProactUdpChannel) + self.assertEqual(sorted(channels.channels), [1, 2, 3]) + + +class BipUdpRelayTest(unittest.TestCase): + """UDP channels keep datagram boundaries, TS 102 223 6.4.29 and 6.4.30""" + + def setUp(self): + self.echo = _UdpEchoServer() + self.addCleanup(self.echo.close) + self.events = [] + self.proact = Proact(data_available_sink=self.events.append) + self.addCleanup(lambda: [c.close() for c in list(self.proact.channels.channels.values())]) + til = self.proact.handle_OpenChannel(_open_channel(self.echo.port, proto='udp_uicc_client_remote')) + b''.join(x.to_tlv() for x in til) + self.assertEqual(_first(til, Result).decoded['general_result'], 'performed_successfully') + self.assertEqual(_first(til, ChannelStatus).decoded, '8100') + self.chan = self.proact.channels.channels[1] + + def _wait_events(self, n, timeout=2.0): + deadline = time.monotonic() + timeout + while len(self.events) < n and time.monotonic() < deadline: + time.sleep(0.01) + return len(self.events) + + def test_store_and_forward_is_one_datagram(self): + # two buffered SEND DATA and a final "send immediately" leave as a single datagram + self.proact.handle_SendData(_send_data(b'one', immediate=False)) + self.proact.handle_SendData(_send_data(b'two', immediate=False)) + self.assertEqual(self.echo.datagrams, []) + self.proact.handle_SendData(_send_data(b'three')) + self.assertGreater(self.chan.wait_rx(2.0), 0) + self.assertEqual(self.echo.datagrams, [b'onetwothree']) + + def test_rx_one_sdu_at_a_time(self): + # two datagrams from the peer: RECEIVE DATA never crosses into the second one, and + # the second raises its own data available event once the first is drained + self.proact.handle_SendData(_send_data(b'first')) + self.proact.handle_SendData(_send_data(b'second')) + time.sleep(0.2) + self.assertEqual(self._wait_events(1), 1) + self.assertEqual(self.chan.available_rx(), 5) + til = self.proact.handle_ReceiveData(_receive_data(100)) + self.assertEqual(h2b(_first(til, ChannelData).decoded), b'first') + self.assertEqual(_first(til, ChannelDataLength).decoded, 0) + self.assertEqual(_first(til, Result).decoded['general_result'], + 'performed_with_missing_information') + self.assertEqual(self._wait_events(2), 2) + self.assertEqual(h2b(self.events[1])[-1], 6) # channel data length = len(b'second') + til = self.proact.handle_ReceiveData(_receive_data(3)) + self.assertEqual(h2b(_first(til, ChannelData).decoded), b'sec') + self.assertEqual(_first(til, ChannelDataLength).decoded, 3) + til = self.proact.handle_ReceiveData(_receive_data(3)) + self.assertEqual(h2b(_first(til, ChannelData).decoded), b'ond') + self.assertEqual(_first(til, ChannelDataLength).decoded, 0) + + class OpenChannelRefusalTest(unittest.TestCase): """Refusal is a TERMINAL RESPONSE, not an exception, raising takes the whole proactive session down and leaves the card wondering why""" @@ -296,8 +384,8 @@ def test_transport_level(self): cases = [[self.ADDR.to_tlv()]] # absent, 6.6.27.x Optional - for proto in ('udp_uicc_client_remote', 'tcp_uicc_server', 'udp_uicc_client_local', - 'tcp_uicc_client_local', 'direct_channel'): # not TCP client remote + for proto in ('tcp_uicc_server', 'udp_uicc_client_local', 'tcp_uicc_client_local', + 'direct_channel'): # not client mode remote tl = UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': 1234}) cases.append([tl.to_tlv(), self.ADDR.to_tlv()]) for extra in cases: @@ -375,7 +463,7 @@ self.assertEqual(self.byte(12), 0x1f) # OPEN/CLOSE CHANNEL, RECEIVE/SEND DATA, STATUS self.assertEqual(self.byte(13) >> 5, ProactChannels.MAX_CHANNELS) self.assertEqual(self.byte(14), 0x60) # class ND, class NK - self.assertEqual(self.byte(17), 0x01) # TCP, UICC client mode, remote + self.assertEqual(self.byte(17), 0x03) # TCP + UDP, UICC client mode, remote def test_not_announced(self): self.assertEqual(self.byte(3) & 0x60, 0) # POLL INTERVAL, POLLING OFF -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43716?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff Gerrit-Change-Number: 43716 Gerrit-PatchSet: 3 Gerrit-Owner: 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: TS 102 226 PUSH command and CAT_TP trigger
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43718?usp=email ) ( 1 is the latest approved patch-set. No files were changed between the latest approved patch-set and the submitted one. )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(-) Approvals: dexter: Looks good to me, approved Jenkins Builder: Verified diff --git a/contrib/cattp_trigger.py b/contrib/cattp_trigger.py new file mode 100755 index 0000000..0d7dd7c --- /dev/null +++ b/contrib/cattp_trigger.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""cattp_trigger.py -- build the PUSH APDUs that ask the card to open a CAT_TP link.""" + +# (C) 2026 by sysmocom - s.f.m.c. GmbH +# All Rights Reserved +# +# Author: Eric Wild <ewild(a)sysmocom.de> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# TS 102 226 section 9: two PUSH C-APDUs, "request for BIP channel opening" and "request for +# CAT_TP link establishment", printed one per line for smpp-ota-tool.py -a, compact format, +# sent to the TAR of the application that should open the link. The card answers via the POR +# of the SMS once the link is OPEN, the server side is contrib/cattp_admin_server.py. +# +# example: +# smpp-ota-tool.py ... --tar b00010 $(cattp_trigger.py --ip 10.0.0.1 --port 6001 | sed 's/^/-a /') + +import argparse +import sys + +from osmocom.utils import h2b +from pySim.ota import encode_push_open_channel, encode_push_cattp_link + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--ip", required=True, help="CAT_TP server IPv4 address, OPEN CHANNEL destination") + ap.add_argument("--port", type=int, required=True, help="UDP port of the server, used as CAT_TP port too") + ap.add_argument("--buffer", type=int, default=1024, help="BIP buffer size, bounds the CAT_TP PDU size") + ap.add_argument("--max-sdu", type=int, help="max SDU size the card should announce (default: card decides)") + ap.add_argument("--identification", type=h2b, help="identification for the SYN (hex), default: ICCID") + ap.add_argument("--no-open", action="store_true", help="omit the BIP channel opening PUSH") + args = ap.parse_args() + + apdus = [] + if not args.no_open: + apdus.append(encode_push_open_channel(args.ip, args.port, args.buffer)) + apdus.append(encode_push_cattp_link(args.port, args.max_sdu, args.identification)) + for a in apdus: + print(a.hex()) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pySim/ota.py b/pySim/ota.py index 1a44de9..e25d384 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: merged Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Ib3423c4fe582dbcc9434c8234709a7b845fa6bcd Gerrit-Change-Number: 43718 Gerrit-PatchSet: 3 Gerrit-Owner: 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]: esim.bsp: keep encrypted segments within 1020 bytes
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/44153?usp=email ) Change subject: esim.bsp: keep encrypted segments within 1020 bytes ...................................................................... esim.bsp: keep encrypted segments within 1020 bytes SGP.22 limits a segment to 1020 bytes including tag, length field and MAC, which leaves 1008 bytes for the ciphertext. encrypt_and_mac() cut the plaintext at 1008 bytes; the mandatory '80' padding then added a whole block and the segment got 1036 bytes long. An eUICC that enforces the limit can refuse the first such segment of a profile. Cut encrypted plaintext at 1007 bytes; MAC-only segments keep 1008. The folder osmocom-pysim-bsp-segment-size of hampushellsberg-dev/PySIM-upstream-patches on GitHub has the analysis and a repro. Change-Id: Ie59a8fb3d6cefc079e4e065d8ab9bd9cec886513 Closes: OS#7120 --- M pySim/esim/bsp.py M tests/unittests/test_esim_bsp.py 2 files changed, 37 insertions(+), 3 deletions(-) Approvals: Jenkins Builder: Verified laforge: Looks good to me, approved dexter: Looks good to me, but someone else must approve diff --git a/pySim/esim/bsp.py b/pySim/esim/bsp.py index cd4114f..b08e94c 100644 --- a/pySim/esim/bsp.py +++ b/pySim/esim/bsp.py @@ -235,6 +235,9 @@ TAG_LEN = 1 length_len = len(bertlv_encode_len(MAX_SEGMENT_SIZE)) self.max_payload_size = MAX_SEGMENT_SIZE - TAG_LEN - length_len - self.m_algo.l_mac + # SGP.22 v3.1 2.5.3 NOTE: the '80' padding takes at least one byte of the ciphertext + blocksize = self.c_algo.blocksize + self.max_encrypted_payload_size = self.max_payload_size // blocksize * blocksize - 1 @classmethod def from_kdf(cls, shared_secret: bytes, key_type: int, key_length: int, host_id: bytes, eid: bytes): @@ -245,7 +248,7 @@ def encrypt_and_mac_one(self, tag: int, plaintext:bytes) -> bytes: """Encrypt + MAC a single plaintext TLV. Returns the protected ciphertext.""" assert tag <= 255 - assert len(plaintext) <= self.max_payload_size + assert len(plaintext) <= self.max_encrypted_payload_size # DEBUG: Show what we're processing logger.debug(f"BSP_DEBUG: encrypt_and_mac_one(tag=0x{tag:02x}, plaintext_len={len(plaintext)})") @@ -268,12 +271,12 @@ result = [] while len(remainder): remaining_len = len(remainder) - if remaining_len < self.max_payload_size: + if remaining_len < self.max_encrypted_payload_size: segment_len = remaining_len segment = remainder remainder = b'' else: - segment_len = self.max_payload_size + segment_len = self.max_encrypted_payload_size segment = remainder[0:segment_len] remainder = remainder[segment_len:] result.append(self.encrypt_and_mac_one(tag, segment)) diff --git a/tests/unittests/test_esim_bsp.py b/tests/unittests/test_esim_bsp.py index e8e8131..4580630 100755 --- a/tests/unittests/test_esim_bsp.py +++ b/tests/unittests/test_esim_bsp.py @@ -94,5 +94,36 @@ self.assertEqual(plain_upp, base64.b64decode(original_upp)) +class TestBSPsegmentSize(unittest.TestCase): + """SGP.22 v3.1 2.5.3: a segment has at most 1020 bytes, including tag, length field and MAC.""" + + @staticmethod + def _pair(): + keys = (h2b('00112233445566778899aabbccddeeff'), h2b('ffeeddccbbaa99887766554433221100'), bytes(16)) + return BspInstance(*keys), BspInstance(*keys) + + def test_encrypted_segments(self): + for length in (1, 1006, 1007, 1008, 1009, 2014, 2015, 5000): + tx, rx = self._pair() + plaintext = bytes(i % 251 for i in range(length)) + segments = tx.encrypt_and_mac(0x86, plaintext) + self.assertEqual(len(segments), -(-length // 1007)) + for segment in segments: + self.assertLessEqual(len(segment), MAX_SEGMENT_SIZE) + self.assertEqual(rx.demac_and_decrypt(segments), plaintext) + + def test_full_encrypted_segment(self): + tx, _ = self._pair() + self.assertEqual(tx.max_encrypted_payload_size, 1007) + self.assertEqual(len(tx.encrypt_and_mac_one(0x86, bytes(1007))), MAX_SEGMENT_SIZE) + + def test_mac_only_segments(self): + tx, rx = self._pair() + plaintext = bytes(i % 251 for i in range(2500)) + segments = tx.mac_only(0x88, plaintext) + self.assertEqual([len(x) for x in segments], [MAX_SEGMENT_SIZE, MAX_SEGMENT_SIZE, 496]) + self.assertEqual(rx.demac_only(segments), plaintext) + + if __name__ == "__main__": unittest.main() -- To view, visit https://gerrit.osmocom.org/c/pysim/+/44153?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: Ie59a8fb3d6cefc079e4e065d8ab9bd9cec886513 Gerrit-Change-Number: 44153 Gerrit-PatchSet: 3 Gerrit-Owner: hampushellsberg <hampushellsberg(a)gmail.com> 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]: esim.bsp: keep encrypted segments within 1020 bytes
by laforge 25 Nov '26

25 Nov '26
Attention is currently required from: hampushellsberg. laforge has posted comments on this change by hampushellsberg. ( https://gerrit.osmocom.org/c/pysim/+/44153?usp=email ) Change subject: esim.bsp: keep encrypted segments within 1020 bytes ...................................................................... Patch Set 2: Code-Review+2 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/44153?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Ie59a8fb3d6cefc079e4e065d8ab9bd9cec886513 Gerrit-Change-Number: 44153 Gerrit-PatchSet: 2 Gerrit-Owner: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Attention: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Comment-Date: Wed, 25 Nov 2026 14:02:24 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes
1 0
0 0
[S] Change in pysim[master]: esim/asn1/rsp: add the two types the SGP.32 module imports
by laforge 25 Nov '26

25 Nov '26
Attention is currently required from: dexter, hampushellsberg. laforge has posted comments on this change by hampushellsberg. ( https://gerrit.osmocom.org/c/pysim/+/44008?usp=email ) Change subject: esim/asn1/rsp: add the two types the SGP.32 module imports ...................................................................... Patch Set 3: Code-Review+2 (1 comment) File pySim/esim/asn1/rsp/rsp.asn: https://gerrit.osmocom.org/c/pysim/+/44008/comment/94f33f0a_b437460b?usp=em… : PS2, Line 178: -- module by the SGP.32 v1.3 ASN.1 module (IMPORTS ... OperatorId ... FROM RSPDefinitions) > I would recommend to prefix this comment with "-- workaround:" so that it is clear that this part is […] Done -- To view, visit https://gerrit.osmocom.org/c/pysim/+/44008?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I23d8c7e061a5573caa750fe76a6e8756ddbf0898 Gerrit-Change-Number: 44008 Gerrit-PatchSet: 3 Gerrit-Owner: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Attention: dexter <pmaier(a)sysmocom.de> Gerrit-Attention: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Comment-Date: Wed, 25 Nov 2026 14:02:04 +0000 Gerrit-HasComments: Yes Gerrit-Has-Labels: Yes Comment-In-Reply-To: dexter <pmaier(a)sysmocom.de>
1 0
0 0
[XL] Change in pysim[master]: esim/asn1: add the SGP.22 v3.1 RSPDefinitions module as rsp_v3
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/44007?usp=email ) Change subject: esim/asn1: add the SGP.22 v3.1 RSPDefinitions module as rsp_v3 ...................................................................... esim/asn1: add the SGP.22 v3.1 RSPDefinitions module as rsp_v3 pySim only has the SGP.22 v2 module, so none of the types v3.1 added (EuiccConfiguredData, LoadRpmPackage, ...) can be encoded or decoded. rsp.asn cannot simply be updated: v3.1 renames and drops members that existing callers use, and SGP.32 imports v2 types that v3.1 removed. Add the Annex H module as asn1/rsp_v3, available as rsp.asn1_v3, and compile_asn1_paths() to compile it together with the SAIP and PKIX modules it imports. A module __getattr__ (PEP 562) compiles it on the first access of rsp.asn1_v3, so importing pySim.esim.rsp costs no more than before. The folder osmocom-pysim-rsp-v3-module of hampushellsberg-dev/PySIM-upstream-patches on GitHub has the analysis, the transcription script and a repro. Change-Id: I670ec73f9958882a8d3fe4b589bdafa3fbf702ea --- M pySim/esim/__init__.py A pySim/esim/asn1/rsp_v3/rsp.asn M pySim/esim/rsp.py M setup.py A tests/unittests/test_esim_rsp.py 5 files changed, 1,789 insertions(+), 2 deletions(-) Approvals: dexter: Looks good to me, but someone else must approve Jenkins Builder: Verified laforge: Looks good to me, approved diff --git a/pySim/esim/__init__.py b/pySim/esim/__init__.py index 9bbaf17..a4087d2 100644 --- a/pySim/esim/__init__.py +++ b/pySim/esim/__init__.py @@ -1,5 +1,5 @@ import sys -from typing import Optional, Tuple +from typing import List, Optional, Tuple from importlib import resources class PMO: @@ -62,6 +62,22 @@ #print(resources.read_text(__name__, 'asn1/rsp.asn')) return asn1tools.compile_string(asn_txt, codec=codec) +def compile_asn1_paths(paths: List[str], codec='der'): + """Compile ASN.1 syntax from the given files and subdirs (their .asn files) below asn1/.""" + import asn1tools + asn1_dir = resources.files('pySim.esim').joinpath('asn1') + asn_txt = '' + for path in paths: + entry = asn1_dir.joinpath(path) + if entry.is_dir(): + files = sorted((i for i in entry.iterdir() if i.name.endswith('.asn')), key=lambda i: i.name) + else: + files = [entry] + for i in files: + asn_txt += i.read_text(encoding='utf-8') + asn_txt += "\n" + return asn1tools.compile_string(asn_txt, codec=codec) + class ActivationCode: """SGP.22 section 4.1 Activation Code""" diff --git a/pySim/esim/asn1/rsp_v3/rsp.asn b/pySim/esim/asn1/rsp_v3/rsp.asn new file mode 100644 index 0000000..2f38f02 --- /dev/null +++ b/pySim/esim/asn1/rsp_v3/rsp.asn @@ -0,0 +1,1598 @@ +-- GSMA SGP.22 v3.1, Annex H "ASN.1 Definitions (Normative)", transcribed from the +-- published specification. Comments the PDF wrapped onto a second line are +-- rejoined; the one change to the definitions is described above +-- VendorSpecificExtension. + +RSPDefinitions {joint-iso-itu-t(2) international-organizations(23) gsma(146) rsp(1) +asn1modules(1) sgp22v3(3)} +DEFINITIONS +AUTOMATIC TAGS +EXTENSIBILITY IMPLIED ::= +BEGIN + +IMPORTS Certificate, CertificateList, Time FROM PKIX1Explicit88 {iso(1) identified-organization(3) dod(6) internet(1) security(5) mechanisms(5) pkix(7) id-mod(0) id-pkix1-explicit(18)} +SubjectKeyIdentifier FROM PKIX1Implicit88 {iso(1) identified-organization(3) dod(6) +internet(1) security(5) mechanisms(5) pkix(7) id-mod(0) id-pkix1-implicit(19)} +UICCCapability FROM PEDefinitions {joint-iso-itu-t(2) international-organizations(23) tca(143) euicc-profile(1) spec-version(1) version-three(3)}; +-- The UICCCapability import module version is defined in section 4.3 + +id-rsp OBJECT IDENTIFIER ::= {joint-iso-itu-t(2) international-organizations(23) +gsma(146) rsp(1)} + +-- Basic types, for size constraints +Octet1 ::= OCTET STRING(SIZE(1)) +Octet4 ::= OCTET STRING (SIZE(4)) +Octet8 ::= OCTET STRING (SIZE(8)) +Octet16 ::= OCTET STRING (SIZE(16)) +OctetTo16 ::= OCTET STRING (SIZE(1..16)) +Octet32 ::= OCTET STRING (SIZE(32)) + +VersionType ::= OCTET STRING(SIZE(3)) -- major/minor/revision version are coded as binary value on byte 1/2/3, e.g., '02 00 0C' for v2.0.12. +-- If revision is not used (e.g., v2.1), byte 3 SHALL be set to '00'. +Iccid ::= [APPLICATION 26] OCTET STRING (SIZE(10)) -- ICCID as coded in EFiccid, corresponding tag is '5A' +RemoteOpId ::= [2] INTEGER {installBoundProfilePackage(1)} +TransactionId ::= OCTET STRING (SIZE(1..16)) + +-- Definition of OIDs +id-rsp-cert-objects OBJECT IDENTIFIER ::= {id-rsp 2} + -- value 0 in id-rsp-cert-objects was assigned in SGP.22 v2.x + -- #SupportedOnlyBeforeV3.0.0# + +id-rspRole OBJECT IDENTIFIER ::= {id-rsp-cert-objects 1} + +-- Definition of OIDs for role identification in certificates +id-rspRole-ci OBJECT IDENTIFIER ::= {id-rspRole 0} +id-rspRole-ciSubCa OBJECT IDENTIFIER ::= {id-rspRole-ci 0} + +id-rspRole-eum OBJECT IDENTIFIER ::= {id-rspRole-ciSubCa 0} +id-rspRole-eumSubCa OBJECT IDENTIFIER ::= {id-rspRole-eum 0} +id-rspRole-euicc OBJECT IDENTIFIER ::= {id-rspRole-eumSubCa 0} + +id-rspRole-dpSubCa OBJECT IDENTIFIER ::= {id-rspRole-ciSubCa 1} +id-rspRole-dp-tls OBJECT IDENTIFIER ::= {id-rspRole-dpSubCa 0} +id-rspRole-dp-auth OBJECT IDENTIFIER ::= {id-rspRole-dpSubCa 1} +id-rspRole-dp-pb OBJECT IDENTIFIER ::= {id-rspRole-dpSubCa 2} + +id-rspRole-dsSubCa OBJECT IDENTIFIER ::= {id-rspRole-ciSubCa 2} +id-rspRole-ds-tls OBJECT IDENTIFIER ::= {id-rspRole-dsSubCa 0} +id-rspRole-ds-auth OBJECT IDENTIFIER ::= {id-rspRole-dsSubCa 1} + +-- The following OIDs are used in Variant O and OO Certificates +id-rspRole-euicc-v2 OBJECT IDENTIFIER ::= {id-rspRole 1} +id-rspRole-eum-v2 OBJECT IDENTIFIER ::= {id-rspRole 2} +id-rspRole-dp-tls-v2 OBJECT IDENTIFIER ::= {id-rspRole 3} +id-rspRole-dp-auth-v2 OBJECT IDENTIFIER ::= {id-rspRole 4} +id-rspRole-dp-pb-v2 OBJECT IDENTIFIER ::= {id-rspRole 5} +id-rspRole-ds-tls-v2 OBJECT IDENTIFIER ::= {id-rspRole 6} + +id-rspRole-ds-auth-v2 OBJECT IDENTIFIER ::= {id-rspRole 7} + +-- Definition of OIDs for RSP-specific extensions in Certificates +-- #SupportedFromV3.0.0# +id-rsp-extensions OBJECT IDENTIFIER ::= {id-rsp-cert-objects 2} +id-rsp-extension-permitted-eins OBJECT IDENTIFIER ::= { id-rsp-extensions 0} + +-- The extnValue field of the id-rsp-extension-permitted-eins extension SHALL be of type PermittedEins: +PermittedEins ::= SEQUENCE OF PrintableString + +PprIds ::= BIT STRING {-- Definition of Profile Policy Rules identifiers + pprUpdateControl(0), -- defines how to update PPRs via ES6 + ppr1(1), -- Indicator for PPR1 'Disabling of this Profile is not allowed' + ppr2(2) -- Indicator for PPR2 'Deletion of this Profile is not allowed' +} + +OperatorId ::= SEQUENCE { + mccMnc OCTET STRING (SIZE(3)), -- MCC&MNC coded as 3GPP TS 24.008 + gid1 OCTET STRING OPTIONAL, -- referring to content of EF GID1 (file identifier '6F3E') in 3GPP TS 31.102 [54] + gid2 OCTET STRING OPTIONAL -- referring to content of EF GID2 (file identifier '6F3F') in 3GPP TS 31.102 [54] +} + +RpmConfiguration ::= SEQUENCE { -- #SupportedForRpmV3.0.0# + managingDpList [0] SEQUENCE OF SEQUENCE { + managingDpOid [0] OBJECT IDENTIFIER, -- Managing SM-DP+ OID + rpmType [1] RpmType OPTIONAL, + tagList [APPLICATION 28] OCTET STRING OPTIONAL + }, + pollingAddress [1] UTF8String OPTIONAL, -- Tag '81' + allowedCiPKId [2] SubjectKeyIdentifier OPTIONAL, -- eSIM CA RootCA PKID that is allowed for managing SM-DP+s + profileOwnerOid [3] OBJECT IDENTIFIER +} + +RpmType ::= BIT STRING{ + enable(0), disable(1), delete(2), listProfileInfo(3), contactPcmp(4) +} + +LocalisedTextMessage ::= SEQUENCE { -- #SupportedFromV3.0.0# + languageTag UTF8String DEFAULT "en", -- language tag as defined by RFC 5646 + message UTF8String +} + +LprConfiguration ::= SEQUENCE { -- #SupportedForLpaProxyV3.0.0# + pcmpAddress [0] UTF8String, + dpiEnable [1] UTF8String OPTIONAL, + triggerLprOnEnableProfile [2] NULL OPTIONAL +} + +CertificateChain ::= SEQUENCE OF Certificate -- #SupportedFromV3.0.0# + +EnterpriseConfiguration ::= SEQUENCE { -- #SupportedForEnterpriseV3.0.0# + enterpriseOid [0] OBJECT IDENTIFIER, + enterpriseName [1] UTF8String (SIZE(0..64)), + enterpriseRules [2] SEQUENCE { + enterpriseRuleBits [0] BIT STRING { + referenceEnterpriseRule (0), + priorityEnterpriseProfile (1), + onlyEnterpriseProfilesCanBeInstalled (2) + }, + numberOfNonEnterpriseProfiles [1] INTEGER -- that can be Enabled + } OPTIONAL +} + +-- The published module declares +-- OPENTYPE ::= CLASS { &typeId OBJECT IDENTIFIER, &Type } +-- and types the two fields of VendorSpecificExtension as OPENTYPE.&typeId and +-- OPENTYPE.&Type. asn1tools cannot resolve an information object class, so they +-- are OBJECT IDENTIFIER and ANY here, which encode the same on the wire. + +VendorSpecificExtension ::= SEQUENCE OF SEQUENCE { -- #SupportedFromV2.4.0# + vendorOid [0] OBJECT IDENTIFIER, -- OPENTYPE.&typeId in the published module; OID of the vendor who defined this specific extension + vendorSpecificData [1] ANY -- OPENTYPE.&Type in the published module +} + +DeviceChangeConfiguration ::= CHOICE { -- #SupportedForDcV3.0.0# + requestToDp [0] SEQUENCE { + smdpAddressForDc UTF8String, -- SM-DP+ address that processes the Device Change + allowedCiPKId SubjectKeyIdentifier OPTIONAL, -- PKID allowed for the SM-DP+ address that processes the Device Change + eidRequired NULL OPTIONAL, -- the EID of the new Device is required + tacRequired NULL OPTIONAL -- the TAC of the new Device is required + }, + usingStoredAc [1] SEQUENCE { + activationCodeForDc UTF8String (SIZE(0..255)), -- Activation Code for Device Change of this Profile + deleteOldProfile NULL OPTIONAL -- deletion of this Profile is required before providing the Activation code to the new Device + } +} + +BoundProfilePackage ::= [54] SEQUENCE { -- Tag 'BF36' + initialiseSecureChannelRequest [35] InitialiseSecureChannelRequest, -- Tag 'BF23' + firstSequenceOf87 [0] SEQUENCE OF [7] OCTET STRING, -- sequence of '87' TLVs + sequenceOf88 [1] SEQUENCE OF [8] OCTET STRING, -- sequence of '88' TLVs + secondSequenceOf87 [2] SEQUENCE OF [7] OCTET STRING OPTIONAL, -- sequence of '87' TLVs + sequenceOf86 [3] SEQUENCE OF [6] OCTET STRING -- sequence of '86' TLVs +} + +-- Definition of Profile Installation Result +ProfileInstallationResult ::= [55] SEQUENCE { -- Tag 'BF37' + profileInstallationResultData [39] ProfileInstallationResultData, + euiccSignPIR EuiccSign +} + +ProfileInstallationResultData ::= [39] SEQUENCE { -- Tag 'BF27' + transactionId[0] TransactionId, -- The TransactionID generated by the SM-DP+ + notificationMetadata[47] NotificationMetadata, + smdpOid OBJECT IDENTIFIER, -- SM-DP+ OID (value from CERT.DPpb.SIG) + finalResult [2] CHOICE { + successResult SuccessResult, + errorResult ErrorResult + } +} + +EuiccSign ::= [APPLICATION 55] OCTET STRING -- Tag '5F37', eUICCs signature + +SuccessResult ::= SEQUENCE { + aid [APPLICATION 15] OCTET STRING (SIZE (5..16)), -- AID of ISD-P + ppiResponse OCTET STRING -- contains (multiple) 'EUICCResponse' of the Profile Package Interpreter as defined in [5] +} + +ErrorResult ::= SEQUENCE { + bppCommandId BppCommandId, + errorReason ErrorReason, + ppiResponse OCTET STRING OPTIONAL -- contains (multiple) 'EUICCResponse' of the Profile Package Interpreter as defined in [5] +} + +BppCommandId ::= INTEGER { + initialiseSecureChannel(0), + configureISDP(1), + storeMetadata(2), + storeMetadata2(3), + replaceSessionKeys(4), + loadProfileElements(5) +} + +ErrorReason ::= INTEGER { + incorrectInputValues(1), + invalidSignature(2), + invalidTransactionId(3), + unsupportedCrtValues(4), + unsupportedRemoteOperationType(5), + unsupportedProfileClass(6), + bspStructureError(7), + bspSecurityError(8), + installFailedDueToIccidAlreadyExistsOnEuicc(9), + installFailedDueToInsufficientMemoryForProfile(10), + installFailedDueToInterruption(11), + installFailedDueToPEProcessingError (12), + installFailedDueToDataMismatch(13), + testProfileInstallFailedDueToInvalidNaaKey(14), + pprNotAllowed(15), + enterpriseProfilesNotSupported(17), -- #SupportedForEnterpriseV3.0.0# + enterpriseRulesNotAllowed(18), -- #SupportedForEnterpriseV3.0.0# + enterpriseProfileNotAllowed(19), -- #SupportedForEnterpriseV3.0.0# + enterpriseOidMismatch(20), -- #SupportedForEnterpriseV3.0.0# + enterpriseRulesError(21), -- #SupportedForEnterpriseV3.0.0# + enterpriseProfilesOnly(22), -- #SupportedForEnterpriseV3.0.0# + lprNotSupported(23), -- #SupportedForLpaProxyV3.0.0# + unknownTlvInMetadata(26), -- #SupportedFromV3.0.0# + installFailedDueToUnknownError(127) +} + +RpmPackage ::= SEQUENCE OF RpmCommand -- #SupportedForRpmV3.0.0# + +RpmCommand ::= SEQUENCE { + continueOnFailure [0] NULL OPTIONAL, + rpmCommandDetails CHOICE { + enable [1] SEQUENCE {iccid [APPLICATION 26] Iccid}, + disable [2] SEQUENCE {iccid [APPLICATION 26] Iccid}, + delete [3] SEQUENCE {iccid [APPLICATION 26] Iccid}, + listProfileInfo [4] ListProfileInfo, + updateMetadata [5] SEQUENCE { + iccid [APPLICATION 26] Iccid, + updateMetadataRequest UpdateMetadataRequest + }, + contactPcmp [6] SEQUENCE { + iccid [APPLICATION 26] Iccid, + dpiRpm UTF8String OPTIONAL + } + } +} + +LoadRpmPackageResult ::= [68] CHOICE { -- Tag 'BF44' #SupportedForRpmV3.0.0# + loadRpmPackageResultSigned LoadRpmPackageResultSigned, + loadRpmPackageResultNotSigned LoadRpmPackageResultNotSigned +} + +LoadRpmPackageResultSigned ::= SEQUENCE { + loadRpmPackageResultDataSigned LoadRpmPackageResultDataSigned, + euiccSignRPR EuiccSign +} + +LoadRpmPackageResultDataSigned ::= SEQUENCE { + transactionId [0] TransactionId, + notificationMetadata[47] NotificationMetadata, + smdpOid OBJECT IDENTIFIER, -- SM-DP+ OID (value from CERT.DPauth.SIG) + finalResult [2] CHOICE { + rpmPackageExecutionResult SEQUENCE OF RpmCommandResult, + loadRpmPackageErrorCodeSigned LoadRpmPackageErrorCodeSigned + } +} + +RpmCommandResult ::= SEQUENCE { -- #SupportedForRpmV3.0.0# + iccid [APPLICATION 26] Iccid OPTIONAL, -- SHALL be present, except for listProfileInfoResult and rpmProcessingTerminated + rpmCommandResultData CHOICE { + enableResult [49] EnableProfileResponse, -- ES10c.EnableProfile + disableResult [50] DisableProfileResponse, -- ES10c.DisableProfile + deleteResult [51] DeleteProfileResponse, -- ES10c.DeleteProfile + listProfileInfoResult [45] ProfileInfoListResponse, -- ES10c.GetProfilesInfo + updateMetadataResult [42] UpdateMetadataResponse, -- ES6.UpdateMetadata + contactPcmpResult [0] ContactPcmpResponse, + rpmProcessingTerminated INTEGER { + resultSizeOverflow (1), + unknownOrDamagedCommand (2), + interruption (3), + commandsWithRefreshExceeded (4), + commandAfterContactPcmp (5), + commandPackageTooLarge (6) + } + } +} + +ContactPcmpResponse ::= CHOICE { + contactPcmpResponseOk SEQUENCE { + pcmpAddress UTF8String + }, + contactPcmpResponseError INTEGER { + profileNotEnabled(2), + commandError(7), + noLprConfiguration(13), + undefinedError(127)} +} + +LoadRpmPackageResultNotSigned ::= SEQUENCE { + transactionId [0] TransactionId, + loadRpmPackageErrorCodeNotSigned LoadRpmPackageErrorCodeNotSigned +} + +LoadRpmPackageErrorCodeSigned ::= INTEGER { invalidSignature(2), +invalidTransactionId(5), undefinedError(127)} + +LoadRpmPackageErrorCodeNotSigned ::= INTEGER { noSession(4), undefinedError(127)} + +DeleteNotificationForDc ::= [99] SEQUENCE { -- Tag 'BF63' + notificationMetadata NotificationMetadata, + euiccNotificationSignature EuiccSign +} + +DeviceInfo ::= SEQUENCE { + tac Octet4, + deviceCapabilities DeviceCapabilities, + imei Octet8 OPTIONAL, + preferredLanguages SEQUENCE OF UTF8String OPTIONAL, -- #DeviceInfoExtensibilitySupported# + deviceTestMode NULL OPTIONAL, -- #DeviceInfoExtensibilitySupported# if present the Device is operating in Device Test Mode + lpaRspCapability LpaRspCapability OPTIONAL -- #DeviceInfoExtensibilitySupported# Tag '85' +} + +DeviceCapabilities ::= SEQUENCE { -- Highest fully supported release for each definition + -- The device SHALL set all the capabilities it supports + gsmSupportedRelease VersionType OPTIONAL, + utranSupportedRelease VersionType OPTIONAL, + cdma2000onexSupportedRelease VersionType OPTIONAL, + cdma2000hrpdSupportedRelease VersionType OPTIONAL, + cdma2000ehrpdSupportedRelease VersionType OPTIONAL, + eutranEpcSupportedRelease VersionType OPTIONAL, + contactlessSupportedRelease VersionType OPTIONAL, + rspCrlSupportedVersion VersionType OPTIONAL, -- #SupportedOnlyBeforeV3.0.0# + nrEpcSupportedRelease VersionType OPTIONAL, -- #DeviceInfoExtensibilitySupported# + nr5gcSupportedRelease VersionType OPTIONAL, -- #DeviceInfoExtensibilitySupported# + eutran5gcSupportedRelease VersionType OPTIONAL, -- #DeviceInfoExtensibilitySupported# + lpaSvn VersionType OPTIONAL, -- #DeviceInfoExtensibilitySupported# provided for information only + catSupportedClasses CatSupportedClasses OPTIONAL, -- #DeviceInfoExtensibilitySupported# + euiccFormFactorType EuiccFormFactorType OPTIONAL, -- #DeviceInfoExtensibilitySupported# + deviceAdditionalFeatureSupport DeviceAdditionalFeatureSupport OPTIONAL -- #DeviceInfoExtensibilitySupported# +} + +CatSupportedClasses ::= BIT STRING { + a(0), b(1), c(2), d(3), e(4), f(5), g(6), h(7), i(8), j(9), + k(10), l(11), m(12), n(13), o(14), p(15), q(16), r(17), s(18), t(19), + u(20), v(21), w(22), x(23), y(24), z(25), aa(26), ab(27), ac(28), ad(29), + ae(30), af(31), ag(32), ah(33), ai(34), aj(35), ak(36), al(37), am(38) +} + +-- Definition of EuiccFormFactorType +EuiccFormFactorType ::= INTEGER { + removableEuicc (0), -- eUICC can be removed + nonRemovableEuicc (1) -- eUICC cannot be removed +} + +-- Definition of DeviceAdditionalFeatureSupport +DeviceAdditionalFeatureSupport ::= SEQUENCE { + naiSupport VersionType OPTIONAL -- Device supports Network Access Identifier +} + +-- Definition of LpaRspCapability +LpaRspCapability ::= BIT STRING { + crlStaplingV3Support (0), + certChainV3Support (1), + apduApiSupport (2), + enterpriseCapableDevice (3), + lpaProxySupport (4), + signedSmdsResponseV3Support (5), + euiccCiUpdateSupport (6), + eventCheckingSupport (7), + pushServiceSupport (8), + pendingOperationAlertingSupport (9) +} + +EUICCInfo1 ::= [32] SEQUENCE { -- Tag 'BF20' + lowestSvn [2] VersionType, + euiccCiPKIdListForVerification [9] SEQUENCE OF SubjectKeyIdentifier, -- List of eSIM CA RootCA Public Key Identifiers supported on the eUICC for signature verification + euiccCiPKIdListForSigning [10] SEQUENCE OF SubjectKeyIdentifier, -- List of eSIM CA RootCA Public Key Identifier supported on the eUICC for signature creation that can be verified by a certificate chain Variant O + euiccCiPKIdListForSigningV3 [17] SEQUENCE OF SubjectKeyIdentifier OPTIONAL, -- #SupportedFromV3.0.0# List of eSIM CA RootCA Public Key Identifiers supported on the eUICC for signature creation that can be verified by a certificate chain according to Variant Ov3, A, B or C. + euiccRspCapability [8] EuiccRspCapability OPTIONAL, -- #MandatoryFromV3.0.0# + highestSvn [19] VersionType OPTIONAL -- #SupportedFromV3.0.0# +} + +EUICCInfo2 ::= [34] SEQUENCE { -- Tag 'BF22' + baseProfilePackageVersion [1] VersionType, -- Base eUICC Profile package version supported + lowestSvn [2] VersionType, + euiccFirmwareVersion [3] VersionType, -- eUICC Firmware version + extCardResource [4] OCTET STRING, -- Extended Card Resource Information according to ETSI TS 102 226 + uiccCapability [5] UICCCapability, + ts102241Version [6] VersionType OPTIONAL, + globalplatformVersion [7] VersionType OPTIONAL, -- #MandatoryFromV3.0.0# + euiccRspCapability [8] EuiccRspCapability, + euiccCiPKIdListForVerification [9] SEQUENCE OF SubjectKeyIdentifier, -- List of eSIM CA RootCA Public Key Identifiers supported on the eUICC for signature verification + euiccCiPKIdListForSigning [10] SEQUENCE OF SubjectKeyIdentifier, -- List of eSIM CA RootCA Public Key Identifier supported on the eUICC for signature creation that can be verified by a certificate chain Variant O + euiccCategory [11] INTEGER { + other(0), + basicEuicc(1), + mediumEuicc(2), + contactlessEuicc(3) + } OPTIONAL, -- Deprecated + forbiddenProfilePolicyRules [25] PprIds OPTIONAL, -- Tag '99' + ppVersion VersionType, -- Protection Profile version + sasAcreditationNumber UTF8String (SIZE(0..64)), + certificationDataObject [12] CertificationDataObject OPTIONAL, -- #MandatoryFromV3.0.0# + treProperties [13] BIT STRING { + isDiscrete(0), + isIntegrated(1), + usesRemoteMemory(2) -- refers to the usage of remote memory protected by + -- the Remote Memory Protection Function described in SGP.21 [4] + } OPTIONAL, -- #Mandatory for Integrated eUICC + treProductReference [14] UTF8String OPTIONAL, -- Platform_Label as defined in GlobalPlatform DLOA specification [57] + additionalProfilePackageVersions [15] SEQUENCE OF VersionType OPTIONAL, -- #SupportedFromV3.0.0# + lpaMode [16] LpaMode OPTIONAL, -- #MandatoryFromV3.0.0# active LPA + euiccCiPKIdListForSigningV3 [17] SEQUENCE OF SubjectKeyIdentifier OPTIONAL, -- #SupportedFromV3.0.0# List of eSIM CA RootCA Public Key Identifiers supported on the eUICC for signature creation that can be verified by a certificate chain according to Variant Ov3, A, B or C. + additionalEuiccInfo [18] OCTET STRING (SIZE(0..32)) OPTIONAL, -- #SupportedFromV3.0.0# EUM specific eUICC information + highestSvn [19] VersionType OPTIONAL, -- #SupportedFromV3.0.0# + iotSpecificInfo [20] IoTSpecificInfo OPTIONAL -- reserved for SGP.32 [97] +} + +-- Definition of EuiccRspCapability +EuiccRspCapability ::= BIT STRING { + additionalProfile(0), -- at least one more Profile can be installed + loadCrlSupport(1), -- #SupportedOnlyBeforeV3.0.0# Support for ES10b.LoadCRL + rpmSupport(2), -- Remote Profile Management + testProfileSupport (3), -- support for test profile + deviceInfoExtensibilitySupport (4), -- #SupportedFromV2.2.2# support for ASN.1 extensibility in the Device Info + serviceSpecificDataSupport (5), -- #SupportedFromV2.4.0# support for Service Specific Data in the Profile Metadata + hriServerAddressSupport (6), -- #SupportedFromV3.0.0# support for storing HRI server address + serviceProviderMessageSupport (7), -- #SupportedFromV3.0.0# Service Provider message is allowed within Profile metadata + lpaProxySupport (8), -- #SupportedForLpaProxyV3.0.0# support for LPA Proxy + enterpriseProfilesSupport (9), -- #SupportedForEnterpriseV3.0.0# support for enterprise profiles + serviceDescriptionSupport (10), -- #SupportedFromV3.0.0# support for storing Service Description + deviceChangeSupport (11), -- #SupportedFromV3.0.0# support for Device change + encryptedDeviceChangeDataSupport (12), -- #SupportedFromV3.0.0# support for encrypted Device Change data in Device Change response + estimatedProfileSizeIndicationSupport (13), -- #SupportedFromV3.0.0# support for including estimated profile size + profileSizeInProfilesInfoSupport (14), -- #SupportedFromV3.0.0# support for profile size in GetProfilesInfo + crlStaplingV3Support (15), -- #SupportedFromV3.0.0# support for CRL stapling + certChainV3VerificationSupport (16), -- #SupportedFromV3.0.0# support for certificate chain verification Variant A, B and C + signedSmdsResponseV3Support (17), -- #SupportedFromV3.0.0# support for SM-DS signed response + euiccRspCapInInfo1 (18), -- #SupportedFromV3.0.0# EUICCInfo1 includes euiccRspCapability + osUpdateSupport (19), -- #SupportedFromV3.0.0# support for eUICC OS Update + cancelForEmptySpnPnSupport (20), -- #SupportedFromV3.0.0# support for cancel session reasons empty SPN and empty Profile Name + updateNotifConfigInfoSupport (21), -- #SupportedFromV3.0.0# support for updating NotificationConfigurationInfo as defined in section 5.4.1 + updateMetadataV3Support (22), -- #SupportedFromV3.0.0# support for the modified update metadata mechanism defined in section 5.4.1 + v3ObjectsInCtxParamsCASupport (23), -- #SupportedFromV3.1.0# support for additional elements in CtxParamsForCommonAuthentication + pushServiceRegistrationSupport (24) -- #SupportedForPushServiceV3.1.0# support for CtxParamsForPushServiceRegistration +} + +-- Definition of CertificationDataObject +CertificationDataObject ::= SEQUENCE { + platformLabel UTF8String, -- Platform_Label as defined in GlobalPlatform DLOA specification [57] + discoveryBaseURL UTF8String -- Discovery Base URL of the SE default DLOA Registrar as defined in GlobalPlatform DLOA specification [57] +} + +-- Definition of LpaMode +LpaMode ::= INTEGER { + lpad (0), -- LPAd is active + lpae (1) -- LPAe is active +} + +-- Definition of IoTSpecificInfo +IoTSpecificInfo ::= SEQUENCE { +} + +UpdateMetadataRequest ::= [42] SEQUENCE { -- Tag 'BF2A' + serviceProviderName [17] UTF8String (SIZE(0..32)) OPTIONAL, -- Tag '91' + profileName [18] UTF8String (SIZE(0..64)) OPTIONAL, -- Tag '92' + iconType [19] IconType OPTIONAL, -- Tag '93' + icon [20] OCTET STRING (SIZE(0..1024)) OPTIONAL, -- Tag '94' + profilePolicyRules [25] PprIds OPTIONAL, -- Tag '99' + serviceSpecificDataStoredInEuicc [34] VendorSpecificExtension OPTIONAL, -- #SupportedFromV2.4.0# Tag 'BF22' + notificationConfigurationInfo [22] SEQUENCE OF +NotificationConfigurationInformation OPTIONAL, -- #SupportedFromV3.0.0# Tag 'B6' + tagsForDeletion [APPLICATION 28] OCTET STRING OPTIONAL, -- for tagList #SupportedFromV3.0.0# tag '5C' + rpmConfiguration [26] RpmConfiguration OPTIONAL, -- #SupportedForRpmV3.0.0# Tag 'BA' + hriServerAddress [27] UTF8String OPTIONAL, -- #SupportedFromV3.0.0# Tag '9B' + lprConfiguration [28] LprConfiguration OPTIONAL, -- #SupportedForLpaProxyV3.0.0# Tag 'BC' + enterpriseConfiguration [29] EnterpriseConfiguration OPTIONAL, -- #SupportedForEnterpriseV3.0.0# Tag 'BD' + deviceChangeConfiguration [32] DeviceChangeConfiguration OPTIONAL -- #SupportedForDcV3.0.0# Tag 'BF20' +} + +UpdateMetadataResponse ::= [42] INTEGER { -- #SupportedForRpmV3.0.0# Tag '9F2A' + ok (0), + enterpriseConfigurationNotAllowed (6), -- #SupportedForEnterpriseV3.0.0# + commandError (7), + pprUpdateInvalidSetting (12), + invalidRpmConfiguration (14), + deleteNotAllowed (15), + undefinedError(127) +} + +--Definition of data objects for InitialiseSecureChannel Request +InitialiseSecureChannelRequest ::= [35] SEQUENCE { -- Tag 'BF23' + remoteOpId RemoteOpId, -- Remote Operation Type Identifier (value SHALL be set to installBoundProfilePackage) + transactionId [0] TransactionId, -- The TransactionID generated by the SM-DP+ + controlRefTemplate[6] IMPLICIT ControlRefTemplate, -- Control Reference Template (Key Agreement). Current specification considers a subset of CRT specified in GlobalPlatform Card Specification Amendment F [13] section 6.5.2.3 for the Mutual Authentication Data Field + smdpOtpk [APPLICATION 73] OCTET STRING, -- otPK.DP.KA in accordance with GlobalPlatform Card Specification Amendment F [13] section 6.5.2.3 for ePK.OCE.KA, tag '5F49' + smdpSign [APPLICATION 55] OCTET STRING -- SM-DP's signature, tag '5F37' +} + +ControlRefTemplate ::= SEQUENCE { + keyType[0] Octet1, -- Key type according to GlobalPlatform Card Specification [8] Table 11-16, Tag '80' + keyLen[1] Octet1, -- Key length in number of bytes. Tag '81' + hostId[4] OctetTo16 -- Host ID value , Tag '84' +} + +--Definition of data objects for ConfigureISDPRequest +ConfigureISDPRequest ::= [36] SEQUENCE { -- Tag 'BF24' + dpProprietaryData [24] DpProprietaryData OPTIONAL -- Tag 'B8' +} + +DpProprietaryData ::= SEQUENCE { -- maximum size including tag and length field: 128 bytes + dpOid OBJECT IDENTIFIER -- OID in the tree of the SM-DP+ that created the Profile + -- additional data objects defined by the SM-DP+ MAY follow +} + +StoreMetadataRequest ::= [37] SEQUENCE { -- Tag 'BF25' + iccid Iccid, + serviceProviderName [17] UTF8String (SIZE(0..32)), -- Tag '91' + profileName [18] UTF8String (SIZE(0..64)), -- Tag '92' (corresponds to 'Short Description' defined in SGP.21 [2]) + iconType [19] IconType OPTIONAL, -- Tag '93' (JPG or PNG) + icon [20] OCTET STRING (SIZE(0..1024)) OPTIONAL, -- Tag '94' (Data of the icon. Size 64 x 64 pixel. This field SHALL only be present if iconType is present) + profileClass [21] ProfileClass DEFAULT operational, -- Tag '95' + notificationConfigurationInfo [22] SEQUENCE OF +NotificationConfigurationInformation OPTIONAL, + profileOwner [23] OperatorId OPTIONAL, -- Tag 'B7' + profilePolicyRules [25] PprIds OPTIONAL, -- Tag '99' + serviceSpecificDataStoredInEuicc [34] VendorSpecificExtension OPTIONAL, -- #SupportedFromV2.4.0# Tag 'BF22' + serviceSpecificDataNotStoredInEuicc [35] VendorSpecificExtension OPTIONAL, -- #SupportedFromV2.4.0# Tag 'BF23' + rpmConfiguration [26] RpmConfiguration OPTIONAL, -- #SupportedForRpmV3.0.0# Tag 'BA' + hriServerAddress [27] UTF8String OPTIONAL, -- #SupportedFromV3.0.0# Tag '9B' + serviceProviderMessage [30] LocalisedTextMessage OPTIONAL, -- #SupportedFromV3.0.0# Tag 'BE' + lprConfiguration [28] LprConfiguration OPTIONAL, -- #SupportedForLpaProxyV3.0.0# Tag 'BC' + enterpriseConfiguration [29] EnterpriseConfiguration OPTIONAL, -- #SupportedForEnterpriseV3.0.0# Tag 'BD' + serviceDescription [31] ServiceDescription OPTIONAL, -- #SupportedFromV3.0.0# Tag '9F1F' + deviceChangeConfiguration [32] DeviceChangeConfiguration OPTIONAL, -- #SupportedForDcV3.0.0# Tag 'BF20' + estimatedProfileSize [33] INTEGER OPTIONAL -- #SupportedFromV3.0.0# Tag '9F21' +} + +NotificationEvent ::= BIT STRING { + notificationInstall(0), + notificationLocalEnable(1), + notificationLocalDisable(2), + notificationLocalDelete(3), + notificationRpmEnable(4), -- #SupportedForRpmV3.0.0# + notificationRpmDisable(5), -- #SupportedForRpmV3.0.0# + notificationRpmDelete(6), -- #SupportedForRpmV3.0.0# + loadRpmPackageResult(7) -- #SupportedForRpmV3.0.0# +} + +NotificationConfigurationInformation ::= SEQUENCE { + profileManagementOperation NotificationEvent, + notificationAddress UTF8String -- FQDN to forward the Notification +} + +ServiceDescription ::= BIT STRING { -- 1: service is on, 0: service is off #SupportedFromV3.0.0# + voice (0), -- Operator-provided voice service + data (1) -- Operator-provided data service +} + +-- Definition of request message for command ReplaceSessionKeys +ReplaceSessionKeysRequest ::= [38] SEQUENCE { -- tag 'BF26' +-- The new initial MAC chaining value + initialMacChainingValue OCTET STRING, +-- New session key value for encryption/decryption (PPK-ENC) + ppkEnc OCTET STRING, +-- New session key value of the session key C-MAC computation/verification (PPK- MAC) + ppkCmac OCTET STRING +} + +ISDRProprietaryApplicationTemplate ::= [PRIVATE 0] SEQUENCE { -- Tag 'E0' + lowestSvn [2] VersionType, + euiccConfiguration BIT STRING { + lpaeUsingCatSupported(0), -- LPA in the eUICC using Card Application Toolkit + lpaeUsingScwsSupported(1), -- LPA in the eUICC using Smartcard Web Server + enabledProfile(2), -- eUICC contains an Enabled Profile + lpaeUsingE4Esupported(3) -- LPA in the eUICC using 'E4' ENVELOPEs + } OPTIONAL -- #MandatoryFromV3.0.0# +} + +LpaeActivationRequest ::= [66] SEQUENCE { -- Tag 'BF42' + lpaeOption BIT STRING { + activateCatBasedLpae(0), -- LPAe with LUIe based on CAT + activateScwsBasedLpae(1) -- LPAe with LUIe based on SCWS + } +} + +LpaeActivationResponse ::= [66] SEQUENCE { -- Tag 'BF42' + lpaeActivationResult INTEGER {ok(0), notSupported(1)} +} + +EuiccConfiguredDataRequest ::= [60] SEQUENCE { -- Tag 'BF3C' +} + +EuiccConfiguredDataResponse ::= [60] SEQUENCE { -- Tag 'BF3C' + defaultDpAddress UTF8String OPTIONAL, -- Default SM-DP+ address + rootDsAddress UTF8String, -- Root SM-DS address + additionalRootDsAddresses SEQUENCE OF UTF8String OPTIONAL, -- #SupportedFromV3.0.0# + allowedCiPKId SubjectKeyIdentifier OPTIONAL, -- #SupportedFromV3.0.0# PKID allowed for the Default SM-DP+ + ciList SEQUENCE OF SEQUENCE { -- #SupportedFromV3.0.0# + ciPKId SubjectKeyIdentifier, -- List of eSIM CA RootCA public key identifiers supported + ciName UTF8String -- on the eUICC together with a readable name + } OPTIONAL +} + +SetDefaultDpAddressRequest ::= [63] SEQUENCE { -- Tag 'BF3F' + defaultDpAddress UTF8String, -- Default SM-DP+ address as an FQDN + allowedCiPKId SubjectKeyIdentifier OPTIONAL -- #SupportedFromV3.0.0# PKID allowed for the Default SM-DP+ +} + +SetDefaultDpAddressResponse ::= [63] SEQUENCE { -- Tag 'BF3F' + setDefaultDpAddressResult INTEGER { + ok (0), + unsupportedCiPKId(8), -- #SupportedFromV3.0.0# + undefinedError (127)} +} + +PrepareDownloadRequest ::= [33] SEQUENCE { -- Tag 'BF21' + smdpSigned2 SmdpSigned2, -- Signed information + smdpSignature2 [APPLICATION 55] OCTET STRING, -- tag '5F37' + hashCc Octet32 OPTIONAL, -- Hash of confirmation code + smdpCertificate Certificate -- CERT.DPpb.SIG +} + +SmdpSigned2 ::= SEQUENCE { + transactionId [0] TransactionId, -- The TransactionID generated by the SMDP+ + ccRequiredFlag BOOLEAN, -- Indicates if the Confirmation Code is required + bppEuiccOtpk [APPLICATION 73] OCTET STRING OPTIONAL, -- otPK.EUICC.KA already used for binding the BPP, tag '5F49' + rpmPending NULL OPTIONAL -- #SupportedForRpmV3.0.0# +} + +PrepareDownloadResponse ::= [33] CHOICE { -- Tag 'BF21' + downloadResponseOk PrepareDownloadResponseOk, + downloadResponseError PrepareDownloadResponseError +} + +PrepareDownloadResponseOk ::= SEQUENCE { + euiccSigned2 EUICCSigned2, -- Signed information + euiccSignature2 [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +EUICCSigned2 ::= SEQUENCE { + transactionId [0] TransactionId, + euiccOtpk [APPLICATION 73] OCTET STRING, -- otPK.EUICC.KA, tag '5F49' + hashCc Octet32 OPTIONAL, -- Hash of confirmation code + additionalInformation VendorSpecificExtension OPTIONAL -- #SupportedFromV3.0.0# +} + +PrepareDownloadResponseError ::= SEQUENCE { + transactionId [0] TransactionId, + downloadErrorCode DownloadErrorCode +} + +DownloadErrorCode ::= INTEGER {invalidCertificate(1), invalidSignature(2), +unsupportedCurve(3), noSession(4), invalidTransactionId(5), undefinedError(127)} + +GetEuiccChallengeRequest ::= [46] SEQUENCE { -- Tag 'BF2E' +} + +GetEuiccChallengeResponse ::= [46] SEQUENCE { -- Tag 'BF2E' + euiccChallenge Octet16 -- random eUICC challenge +} + +GetEuiccInfo1Request ::= [32] SEQUENCE { -- Tag 'BF20' +} + +GetEuiccInfo2Request ::= [34] SEQUENCE { -- Tag 'BF22' +} + +ListNotificationRequest ::= [40] SEQUENCE { -- Tag 'BF28' + profileManagementOperation [1] NotificationEvent OPTIONAL +} + +ListNotificationResponse ::= [40] CHOICE { -- Tag 'BF28' + notificationMetadataList SEQUENCE OF NotificationMetadata, + listNotificationsResultError INTEGER {undefinedError(127)} +} + +NotificationMetadata ::= [47] SEQUENCE { -- Tag 'BF2F' + seqNumber [0] INTEGER, + profileManagementOperation [1] NotificationEvent, -- Only one bit SHALL be set to 1 + notificationAddress UTF8String, -- FQDN to forward the Notification + iccid Iccid OPTIONAL +} + +RetrieveNotificationsListRequest ::= [43] SEQUENCE { -- Tag 'BF2B' + searchCriteria CHOICE { + seqNumber [0] INTEGER, + profileManagementOperation [1] NotificationEvent + } OPTIONAL +} + +RetrieveNotificationsListResponse ::= [43] CHOICE { -- Tag 'BF2B' + notificationList SEQUENCE OF PendingNotification, + notificationsListResultError INTEGER { undefinedError(127)} +} + +PendingNotification ::= CHOICE { + profileInstallationResult [55] ProfileInstallationResult, -- tag 'BF37' + otherSignedNotification OtherSignedNotification, + loadRpmPackageResultSigned [1] LoadRpmPackageResultSigned +} + +OtherSignedNotification ::= SEQUENCE { + tbsOtherNotification NotificationMetadata, + euiccNotificationSignature EuiccSign, + euiccCertificate Certificate, -- eUICC Certificate (CERT.EUICC.SIG) + nextCertInChain Certificate, -- The certificate certifying the eUICC Certificate + otherCertsInChain [1] CertificateChain OPTIONAL -- #SupportedFromV3.0.0# Other Certificates in the eUICC certificate chain, if any +} + +NotificationSentRequest ::= [48] SEQUENCE { -- Tag 'BF30' + seqNumber [0] INTEGER +} + +NotificationSentResponse ::= [48] SEQUENCE { -- Tag 'BF30' + deleteNotificationStatus INTEGER {ok(0), nothingToDelete(1), +undefinedError(127)} +} + +AuthenticateServerRequest ::= [56] SEQUENCE { -- Tag 'BF38' + serverSigned1 ServerSigned1, -- Signed information + serverSignature1 [APPLICATION 55] OCTET STRING, -- tag '5F37' + euiccCiPKIdToBeUsed SubjectKeyIdentifier OPTIONAL, -- eSIM CA RootCA Public Key Identifier to be used; MAY also have zero length + serverCertificate Certificate, -- RSP Server Certificate CERT.XXauth.SIG + ctxParams1 CtxParams1, + otherCertsInChain [1] CertificateChain OPTIONAL, -- #SupportedFromV3.0.0# The remaining part of the CERT.XXauth.SIG certificate chain (if any) + crlList [2] SEQUENCE OF CertificateList OPTIONAL -- #SupportedFromV3.0.0# as specified in RFC 5280 +} + +ServerSigned1 ::= SEQUENCE { + transactionId [0] TransactionId, -- The Transaction ID generated by the RSP Server + euiccChallenge [1] Octet16, -- The eUICC Challenge + serverAddress [3] UTF8String, -- The RSP Server address as an FQDN + serverChallenge [4] Octet16, -- The RSP Server Challenge + sessionContext [5] SessionContext OPTIONAL, -- #SupportedFromV3.0.0# + serverRspCapability [6] ServerRspCapability OPTIONAL -- #SupportedFromV3.0.0# +} + +CtxParams1 ::= CHOICE { + ctxParamsForCommonAuthentication[0] CtxParamsForCommonAuthentication, + ctxParamsForDeviceChange [1] CtxParamsForDeviceChange, + ctxParamsForProfileRecovery [2] CtxParamsForProfileRecovery, + ctxParamsForPushServiceRegistration [3] CtxParamsForPushServiceRegistration +-- New contextual data objects MAY be defined for extensibility. +} + +CtxParamsForCommonAuthentication ::= SEQUENCE { + matchingId [0] UTF8String OPTIONAL, -- The MatchingId could be the Activation code token or EventID or empty + deviceInfo [1] DeviceInfo, -- The Device information + operationType [2] OperationType DEFAULT {profileDownload}, -- #SupportedFromV3.0.0# + iccid Iccid OPTIONAL, -- ICCID, tag '5A' #SupportedForRpmV3.0.0# + matchingIdSource [3] MatchingIdSource OPTIONAL, -- #SupportedFromV3.0.0# + vendorSpecificExtension [4] VendorSpecificExtension OPTIONAL -- #SupportedFromV3.0.0# +} + +CtxParamsForDeviceChange ::= SEQUENCE { -- #SupportedForDcV3.0.0# + iccid Iccid, + deviceInfo [1] DeviceInfo, + targetEidValue [APPLICATION 26] Octet16 OPTIONAL, + targetTacValue [2] Octet4 OPTIONAL, + vendorSpecificExtension [3] VendorSpecificExtension OPTIONAL +} + +CtxParamsForProfileRecovery ::= SEQUENCE { -- #SupportedForDcV3.0.0# + iccid Iccid, + deviceInfo [1] DeviceInfo, + vendorSpecificExtension [2] VendorSpecificExtension OPTIONAL +} + +CtxParamsForPushServiceRegistration ::= SEQUENCE { -- #SupportedForPushServiceV3.0.0# + selectedPushService [0] OBJECT IDENTIFIER, + pushToken [1] UTF8String +} + +MatchingIdSource ::= CHOICE { + none [0] NULL, + activationCode [1] NULL, + smdsOid [2] OBJECT IDENTIFIER +} + +OperationType ::= BIT STRING { + profileDownload(0), + rpm(1) +} + +-- Records information agreed along the session +SessionContext ::= SEQUENCE { + serverSvn [0] VersionType, -- RSP Server SVN (provided for information only) + crlStaplingV3Used [1] BOOLEAN, -- Indicates CRLs were attached to the RSP Server response + euiccCiPKIdToBeUsedV3 [2] SubjectKeyIdentifier OPTIONAL, + supportedPushServices [3] SEQUENCE OF OBJECT IDENTIFIER OPTIONAL +} + +-- Definition of ServerRspCapability +ServerRspCapability ::= BIT STRING { + crlStaplingV3Support (0), -- support for CRL stapling + eventListSigningV3Support (1), -- support for Event Record signing + pushServiceV3Support (2), -- support for Push Service + cancelForEmptySpnPnSupport (3), + cancelForSessionAbortedSupport (4) +} + +AuthenticateServerResponse ::= [56] CHOICE { -- Tag 'BF38' + authenticateResponseOk [0] AuthenticateResponseOk, + authenticateResponseError [1] AuthenticateResponseError +} + +AuthenticateResponseOk ::= SEQUENCE { + euiccSigned1 EuiccSigned1, -- Signed information + euiccSignature1 [APPLICATION 55] OCTET STRING, --EUICC_Sign1, tag 5F37 + euiccCertificate Certificate, -- eUICC Certificate (CERT.EUICC.SIG) + nextCertInChain Certificate, -- The Certificate certifying the eUICC Certificate + otherCertsInChain [0] CertificateChain OPTIONAL -- #SupportedFromV3.0.0# Other Certificates in the eUICC certificate chain, if any +} + +EuiccSigned1 ::= SEQUENCE { + transactionId [0] TransactionId, + serverAddress [3] UTF8String, -- The RSP Server address as an FQDN + serverChallenge [4] Octet16, -- The RSP Server Challenge + euiccInfo2 [34] EUICCInfo2, + ctxParams1 CtxParams1 +} + +AuthenticateResponseError ::= SEQUENCE { + transactionId [0] TransactionId, + authenticateErrorCode AuthenticateErrorCode +} + +AuthenticateErrorCode ::= INTEGER {invalidCertificate(1), invalidSignature(2), +unsupportedCurve(3), noSession(4), invalidOid(5), euiccChallengeMismatch(6), +ciPKUnknown(7), +transactionIdError (8), -- #SupportedFromV3.0.0# +missingCrl(9), -- #SupportedFromV3.0.0# +invalidCrlSignature(10), -- #SupportedFromV3.0.0# +revokedCert(11), -- #SupportedFromV3.0.0# +invalidCertOrCrlTime(12), -- #SupportedFromV3.0.0# +invalidCertOrCrlConfiguration(13), -- #SupportedFromV3.0.0# +invalidIccid(14), -- #SupportedForDcV3.0.0# +undefinedError(127)} + +CancelSessionRequest ::= [65] SEQUENCE { -- Tag 'BF41' + transactionId TransactionId, -- The TransactionID generated by the RSP Server + reason CancelSessionReason +} + +CancelSessionReason ::= INTEGER { + endUserRejection(0), + postponed(1), + timeout(2), + pprNotAllowed(3), + metadataMismatch(4), + loadBppExecutionError(5), + sessionAborted(16), -- #SupportedFromV3.0.0# + enterpriseProfilesNotSupported(17), -- #SupportedFromV3.0.0# + enterpriseRulesNotAllowed(18), -- #SupportedForEnterpriseV3.0.0# + enterpriseProfileNotAllowed(19), -- #SupportedForEnterpriseV3.0.0# + enterpriseOidMismatch(20), -- #SupportedForEnterpriseV3.0.0# + enterpriseRulesError(21), -- #SupportedForEnterpriseV3.0.0# + enterpriseProfilesOnly(22), -- #SupportedForEnterpriseV3.0.0# + lprNotSupported(23), -- #SupportedForLpaProxyV3.0.0# + lprNetworkDataNotAllowed(24), -- #SupportedForLpaProxyV3.0.0# + emptyProfileOrSpName(25), -- #SupportedFromV3.0.0# + rpmDisabled(27), -- #SupportedForRpmV3.0.0# + invalidRpmPackage(28), -- #SupportedFromV3.0.0# + loadRpmPackageError(29), -- #SupportedForRpmV3.0.0# + operationAbandoned (30), -- #SupportedForDcV3.1.0# + undefinedReason(127) +} + +CancelSessionResponse ::= [65] CHOICE { -- Tag 'BF41' + cancelSessionResponseOk CancelSessionResponseOk, + cancelSessionResponseError INTEGER {invalidTransactionId(5), +undefinedError(127)} +} + +CancelSessionResponseOk ::= SEQUENCE { + euiccCancelSessionSigned EuiccCancelSessionSigned, -- Signed information + euiccCancelSessionSignature [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +EuiccCancelSessionSigned ::= SEQUENCE { + transactionId TransactionId, + smdpOid OBJECT IDENTIFIER, -- SM-DP+ OID as contained in CERT.DPauth.SIG + reason CancelSessionReason +} + +ProfileInfoListRequest ::= [45] SEQUENCE { -- Tag 'BF2D' + searchCriteria [0] CHOICE { + isdpAid [APPLICATION 15] OctetTo16, -- AID of the ISD-P, tag '4F' + iccid Iccid, -- ICCID, tag '5A' + profileClass [21] ProfileClass -- Tag '95' + } OPTIONAL, + tagList [APPLICATION 28] OCTET STRING OPTIONAL -- tag '5C' +} + +ListProfileInfo ::= [5] SEQUENCE { + searchCriteria [0] CHOICE { + iccid Iccid, + profileOwnerOid [0] OBJECT IDENTIFIER + }, + tagList [APPLICATION 28] OCTET STRING OPTIONAL +} + +-- Definition of ProfileInfoListResponse +ProfileInfoListResponse ::= [45] CHOICE { -- Tag 'BF2D' + profileInfoListOk SEQUENCE OF ProfileInfo, + profileInfoListError ProfileInfoListError +} + +ProfileInfo ::= [PRIVATE 3] SEQUENCE { -- Tag 'E3' + iccid Iccid OPTIONAL, + isdpAid [APPLICATION 15] OctetTo16 OPTIONAL, -- AID of the ISD-P containing the Profile, tag '4F' + profileState [112] ProfileState OPTIONAL, -- Tag '9F70' + profileNickname [16] UTF8String (SIZE(0..64)) OPTIONAL, -- Tag '90' + serviceProviderName [17] UTF8String (SIZE(0..32)) OPTIONAL, -- Tag '91' + profileName [18] UTF8String (SIZE(0..64)) OPTIONAL, -- Tag '92' + iconType [19] IconType OPTIONAL, -- Tag '93' + icon [20] OCTET STRING (SIZE(0..1024)) OPTIONAL, -- Tag '94', + profileClass [21] ProfileClass OPTIONAL, -- Tag '95' + notificationConfigurationInfo [22] SEQUENCE OF +NotificationConfigurationInformation OPTIONAL, -- Tag 'B6' + profileOwner [23] OperatorId OPTIONAL, -- Tag 'B7' + dpProprietaryData [24] DpProprietaryData OPTIONAL, -- Tag 'B8' + profilePolicyRules [25] PprIds OPTIONAL, -- Tag '99' + serviceSpecificDataStoredInEuicc [34] VendorSpecificExtension OPTIONAL, -- #SupportedFromV2.4.0# Tag 'BF22' + rpmConfiguration [26] RpmConfiguration OPTIONAL, -- #SupportedForRpmV3.0.0# Tag 'BA' + hriServerAddress [27] UTF8String OPTIONAL, -- #SupportedFromV3.0.0# Tag '9B' + lprConfiguration [28] LprConfiguration OPTIONAL, -- #SupportedForLpaProxyV3.0.0# Tag 'BC' + enterpriseConfiguration [29] EnterpriseConfiguration OPTIONAL, +-- #SupportedForEnterpriseV3.0.0# Tag 'BD' + serviceDescription [31] ServiceDescription OPTIONAL, -- #SupportedFromV3.0.0# Tag '9F1F' + deviceChangeConfiguration [32] DeviceChangeConfiguration OPTIONAL, -- #SupportedForDcV3.0.0# Tag 'BF20' + enabledOnEsimPort [36] INTEGER OPTIONAL, -- #SupportedForMEPV3.0.0# Tag '9F24' + profileSize [37] INTEGER OPTIONAL -- #SupportedFromV3.0.0# Tag '9F25' +} + +IconType ::= INTEGER {jpg(0), png(1)} +ProfileState ::= INTEGER {disabled(0), enabled(1)} +ProfileClass ::= INTEGER {test(0), provisioning(1), operational(2)} +ProfileInfoListError ::= INTEGER { + incorrectInputValues(1), + profileChangeOngoing (11), -- #SupportedForRpmV3.0.0# + undefinedError(127) +} + +EnableProfileRequest ::= [49] SEQUENCE { -- Tag 'BF31' + profileIdentifier CHOICE { + isdpAid [APPLICATION 15] OctetTo16, -- AID, tag '4F' + iccid Iccid -- ICCID, tag '5A' + }, + refreshFlag BOOLEAN, -- indicating whether REFRESH is required + targetEsimPort INTEGER OPTIONAL-- #SupportedForMEPV3.0.0# +} + +EnableProfileResponse ::= [49] SEQUENCE { -- Tag 'BF31' + enableResult INTEGER { + ok(0), + iccidOrAidNotFound(1), + profileNotInDisabledState(2), + disallowedByPolicy(3), + wrongProfileReenabling(4), + catBusy(5), + disallowedByEnterpriseRule(6), -- #SupportedForEnterpriseV3.0.0# + commandError(7), -- #SupportedFromV3.0.0# + disallowedForRpm(9), -- #SupportedForRpmV3.0.0# + noEsimPortAvailable(10), -- #SupportedForMEPV3.0.0# and + -- #SupportedForRpmV3.0.0# + undefinedError(127) + }, + targetEsimPort INTEGER OPTIONAL -- #SupportedForMEPV3.0.0# +} + +DisableProfileRequest ::= [50] SEQUENCE { -- Tag 'BF32' + profileIdentifier CHOICE { + isdpAid [APPLICATION 15] OctetTo16, -- AID, tag '4F' + iccid Iccid -- ICCID, tag '5A' + }, + refreshFlag BOOLEAN -- indicating whether REFRESH is required +} + +DisableProfileResponse ::= [50] SEQUENCE { -- Tag 'BF32' + disableResult INTEGER { + ok(0), + iccidOrAidNotFound(1), + profileNotInEnabledState(2), + disallowedByPolicy(3), + catBusy(5), + disallowedByEnterpriseRule(6), -- #SupportedForEnterpriseV3.1.0# + commandError(7), -- #SupportedFromV3.0.0# + disallowedForRpm(9), -- #SupportedForRpmV3.0.0# + undefinedError(127) + } +} + +DeleteProfileRequest ::= [51] CHOICE { -- Tag 'BF33' + isdpAid [APPLICATION 15] OctetTo16, -- AID, tag '4F' + iccid Iccid -- ICCID, tag '5A' +} + +DeleteProfileResponse ::= [51] SEQUENCE { -- Tag 'BF33' + deleteResult INTEGER { + ok(0), + iccidOrAidNotFound(1), + profileNotInDisabledState(2), + disallowedByPolicy(3), + disallowedInTestMode(4), -- #SupportedFromV3.0.0# + commandError(7), -- #SupportedFromV3.0.0# + undefinedError(127) + } +} + +EuiccMemoryResetRequest ::= [52] SEQUENCE { -- Tag 'BF34' + resetOptions [2] BIT STRING { + deleteOperationalProfiles(0), + deleteFieldLoadedTestProfiles(1), + resetDefaultSmdpAddress(2), + deletePreLoadedTestProfiles(3), -- #SupportedFromV3.0.0# + deleteProvisioningProfiles(4)} -- #SupportedFromV3.0.0# + -- setting bits 0, 1, 3 and 4 wipes all Profiles +} + +EuiccMemoryResetResponse ::= [52] SEQUENCE { -- Tag 'BF34' + resetResult INTEGER {ok(0), nothingToDelete(1), catBusy(5), undefinedError(127)} +} + +GetEuiccDataRequest ::= [62] SEQUENCE { -- Tag 'BF3E' + tagList [APPLICATION 28] Octet1 -- tag '5C', the value SHALL be set to '5A' +} + +GetEuiccDataResponse ::= [62] SEQUENCE { -- Tag 'BF3E' + eidValue [APPLICATION 26] Octet16 -- tag '5A' +} + +-- Definition of Profile Nickname Information +SetNicknameRequest ::= [41] SEQUENCE { -- Tag 'BF29' + iccid Iccid, + profileNickname [16] UTF8String (SIZE(0..64)) +} + +SetNicknameResponse ::= [41] SEQUENCE { -- Tag 'BF29' + setNicknameResult INTEGER {ok(0), iccidNotFound (1), undefinedError(127)} +} + +GetRatRequest ::= [67] SEQUENCE { -- Tag 'BF43' + -- No input data +} + +GetRatResponse ::= [67] SEQUENCE { -- Tag 'BF43' + rat RulesAuthorisationTable +} + +RulesAuthorisationTable ::= SEQUENCE OF ProfilePolicyAuthorisationRule +ProfilePolicyAuthorisationRule ::= SEQUENCE { + pprIds PprIds, + allowedOperators SEQUENCE OF OperatorId, + pprFlags BIT STRING {consentRequired(0)} +} + +AlertData ::= [74] CHOICE { -- Tag 'BF4A' #SupportedFromV3.0.0# + metadataUpdateEnabledProfile [0] MetadataUpdateEnabledProfile, + pendingOperationAlert [1] ServerWithPendingOperation +} + +MetadataUpdateEnabledProfile ::= SEQUENCE { + iccid Iccid OPTIONAL, + tagList [APPLICATION 28] OCTET STRING -- tag '5C' +} + +ServerWithPendingOperation ::= CHOICE { + pollingAddress [0] NULL, + rootSmds [1] NULL, + defaultSmdp [2] NULL, + explicitAddress [3] UTF8String +} + +VerifySmdsResponseRequest ::= [69] SEQUENCE { -- Tag 'BF45' #SupportedFromV3.0.0# + smdsSigned2 SmdsSigned2, + smdsSignature2 [APPLICATION 55] OCTET STRING +} + +SmdsSigned2 ::= SEQUENCE { + transactionId [0] TransactionId, + requestSpecificData CHOICE { + eventList [0] SEQUENCE { + eventEntries [1] SEQUENCE OF EventRecordV3, + ecId [2] OCTET STRING(SIZE(16..32)) OPTIONAL, -- #SupportedForEventCheckingV3.0.0# Event Checking ID + pushServiceRefreshTime [3] GeneralizedTime OPTIONAL -- #SupportedForPushServiceV3.0.0# date and time to re-register a Push Token to the SM-DS + }, + pushServiceRegistrationResult [1] SEQUENCE { + pushServiceRefreshTime [3] GeneralizedTime OPTIONAL -- #SupportedForPushServiceV3.0.0# date and time to re-register a Push Token to the SM-DS + } + } +} + +EventRecordV3 ::= SEQUENCE { -- #SupportedFromV3.0.0# + eventId UTF8String, + rspServerAddress UTF8String, + eventType INTEGER, -- either 1 (for Profile Download) or 2 (for RPM) + hashedIccids SEQUENCE OF OCTET STRING (SIZE(32)) OPTIONAL, -- hashed ICCID(s) calculated as either SHA256(ICCID) or SHA256(ICCID|Salt) + salt OCTET STRING (SIZE(8..16)) OPTIONAL, -- optional salt to be concatenated with ICCID(s) for hashing + serviceProviderName [17] UTF8String (SIZE(0..32)) OPTIONAL, + operatorId [23] OperatorId OPTIONAL +} + +VerifySmdsResponseResponse ::= [69] CHOICE { -- Tag 'BF45' #SupportedFromV3.0.0# + verifySmdsResponseOk NULL, + verifySmdsResponseError INTEGER { + invalidSignature(2), + noSession(4), + invalidTransactionId(5), + undefinedError(127) + } +} + +LoadRpmPackageRequest ::= [68] SEQUENCE { -- #SupportedForRpmV3.0.0# Tag 'BF44' + smdpSigned3 SmdpSigned3, + smdpSignature3 [APPLICATION 55] OCTET STRING, -- tag '5F37' + targetEsimPort INTEGER OPTIONAL +} + +SmdpSigned3 ::= SEQUENCE { -- #SupportedForRpmV3.0.0# + transactionId [0] TransactionId, -- The TransactionID generated by the SM-DP+ + rpmPackage [1] RpmPackage, + rpmPending [2] NULL OPTIONAL +} + +PrepareDeviceChangeRequest ::= [77] SEQUENCE { -- #SupportedForDcV3.0.0# Tag 'BF4D' + smdpSigned4 SmdpSigned4, -- Signed information + smdpSignature4 [APPLICATION 55] OCTET STRING, -- tag '5F37' + hashCc Octet32 OPTIONAL -- Hash of confirmation code +} + +SmdpSigned4 ::= SEQUENCE { -- #SupportedForDcV3.0.0# + transactionId [0] TransactionId, -- The TransactionID generated by the SMDP+ + ccRequiredFlag BOOLEAN, -- Indicates if the Confirmation Code is required + activationCodeForProfileRecovery [1] UTF8String (SIZE(0..255)) OPTIONAL -- presents only in ES9+.AuthenticateClient response for a profileRecoveryRequest +} + +PrepareDeviceChangeResponse ::= [77] CHOICE { -- #SupportedForDcV3.0.0# Tag 'BF4D' + prepareDeviceChangeResponseOk PrepareDeviceChangeResponseOk, + prepareDeviceChangeResponseError PrepareDeviceChangeResponseError +} + +PrepareDeviceChangeResponseOk ::= SEQUENCE { -- #SupportedForDcV3.0.0# + euiccSigned3 EUICCSigned3, -- Signed information + euiccSignature3 [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +EUICCSigned3 ::= SEQUENCE { -- #SupportedForDcV3.0.0# + transactionId [0] TransactionId, + eacEuiccOtpk [APPLICATION 73] OCTET STRING OPTIONAL, -- otPK.EUICC.KAeac, tag '5F49' + hashCc Octet32 OPTIONAL, -- Hash of confirmation code + additionalInformation VendorSpecificExtension OPTIONAL +} + +PrepareDeviceChangeResponseError ::= SEQUENCE { -- #SupportedForDcV3.0.0# + transactionId [0] TransactionId, + downloadErrorCode DownloadErrorCode +} + +VerifyDeviceChangeRequest ::= [75] SEQUENCE { -- Tag 'BF4B' #SupportedForDcV3.0.0# + smdpSigned5 SmdpSigned5, -- Signed information + smdpSignature5 [APPLICATION 55] OCTET STRING +} + +SmdpSigned5 ::= SEQUENCE { -- #SupportedForDcV3.0.0# + transactionId [0] TransactionId, + deviceChangeResponse [1] DeviceChangeResponse +} + +DeviceChangeResponse ::= CHOICE { + deviceChangeData [0] DeviceChangeData, + encryptedDeviceChangeData [1] EncryptedDeviceChangeData +} + +DeviceChangeData ::= SEQUENCE { -- #SupportedForDcV3.0.0# + iccid Iccid, + activationCodeForDc [0] UTF8String (SIZE(0..255)), + deleteOldProfile [1] NULL OPTIONAL, -- Deletion of the installed Profile required + deleteNotificationForDcSupport [2] NULL OPTIONAL, -- Delete Notification for Device Change supported + notificationAddress [3] UTF8String OPTIONAL, -- FQDN that processes the Delete Notification for Device Change + profileRecoverySupport [4] NULL OPTIONAL, + profileRecoveryValidityPeriod [5] GeneralizedTime OPTIONAL -- Absolute date and time for Profile Recovery +} + +EncryptedDeviceChangeData ::= SEQUENCE { -- #SupportedForDcV3.0.0# + controlRefTemplate [6] IMPLICIT ControlRefTemplate, + eacSmdpOtpk [APPLICATION 73] OCTET STRING, -- okPK.DP.KAeac + sequenceOf87 [1] SEQUENCE OF [7] OCTET STRING -- sequence of '87' TLVs +} + +VerifyDeviceChangeResponse ::= [75] CHOICE { -- Tag 'BF4B' #SupportedForDcV3.0.0# + verifyDeviceChangeOk DeviceChangeData, + verifyDeviceChangeError INTEGER { + invalidSignature(2), + disallowedByPolicy(3), + noSession(4), + invalidTransactionId(5), + unsupportedCrtValues(6), + invalidData(7), + profileNotInDisabledState(8), + undefinedError(127) + } +} + +VerifySmdpResponseRequest ::= [96] SEQUENCE { -- Tag 'BF60' #SupportedForDcV3.1.0# + smdpSigned6 SmdpSigned6, -- Signed information + smdpSignature6 [APPLICATION 55] OCTET STRING +} + +SmdpSigned6 ::= SEQUENCE { -- #SupportedForDcV3.1.0# + transactionId [0] TransactionId, + requestSpecificData CHOICE { + retryData [0] SEQUENCE { + retryDelay [0] INTEGER, -- expected time (in minutes) by when the SM-DP is ready + dcSessionId [1] OCTET STRING (SIZE(1..16)) -- the LPA will use this identifier in the subsequent ES9+.CheckProgress polling(s) + } + } +} + +VerifySmdpResponseResponse ::= [96] CHOICE { -- Tag 'BF60' #SupportedForDcV3.1.0# + verifySmdpResponseOk NULL, + verifySmdpResponseError INTEGER { + invalidSignature(2), + noSession(4), + invalidTransactionId(5), + undefinedError(127) + } +} + +VerifyProfileRecoveryRequest ::= [98] SEQUENCE { -- Tag 'BF62' #SupportedForDcV3.1.0# + smdpSigned4 SmdpSigned4, -- Signed information + smdpSignature4 [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +VerifyProfileRecoveryResponse ::= [98] CHOICE { -- Tag 'BF62' #SupportedForDcV3.1.0# + verifyProfileRecoveryOk NULL, + verifyProfileRecoveryError INTEGER { + invalidSignature(2), + noSession(4), + invalidTransactionId(5), + undefinedError(127) + } +} + +E4ERequest ::= [PRIVATE 4] CHOICE { -- Tag 'E4' + startDownload [0] SEQUENCE { + activationCode [0] UTF8String (SIZE(0..255)) + }, -- Start Download + confirmDownload [1] SEQUENCE { + enable [0] NULL OPTIONAL, -- enable Profile after download + confirmationCode [1] UTF8String OPTIONAL, -- confirmation code + pinCode [2] UTF8String (SIZE(4..8)) OPTIONAL -- LPAe PIN if used + }, -- Confirm Download + listProfiles [2] NULL, -- List Profiles + enableProfile [3] SEQUENCE {iccid [APPLICATION 26] Iccid}, -- Enable Profile + disableProfile [4] SEQUENCE {iccid [APPLICATION 26] Iccid}, -- Disable Profile + deleteProfile [5] SEQUENCE { + iccid [APPLICATION 26] Iccid, + pinCode [1] UTF8String (SIZE(4..8)) OPTIONAL -- LPAe PIN if used + }, -- Delete Profile + euiccMemReset [6] SEQUENCE { + pinCode [0] UTF8String (SIZE(4..8)) OPTIONAL -- LPAe PIN if used + }, -- eUICC Memory Reset + changeConfirmationPin [7] UTF8String (SIZE(9..17)), -- Change confirmation PIN + setRpmAllow [8] BOOLEAN, -- Turn on/off Remote Profile Management + pollRpmPackage [9] SEQUENCE {iccid [APPLICATION 26] Iccid OPTIONAL}, + -- Check for RPM packages for profile with iccid. No iccid means 'Update All' + confirmRpmPackage [10] SEQUENCE { + pinCode [0] UTF8String (SIZE(4..8)) OPTIONAL + -- LPAe PIN, if used, with Strong Confirmation + }, -- Confirms the pending RpmPackage + cancelSession[11] NULL + -- Cancels the pending profile download or RpmPackage execution +} + +E4EResponse ::= [PRIVATE 4] SEQUENCE { -- Tag 'E4' + resultCode [0] E4EResultCode, + resultData [1] CHOICE { + startDownloadResponse [0] SEQUENCE { + serviceProviderName [17] UTF8String (SIZE(0..32)), -- Tag '91' + profileName [18] UTF8String (SIZE(0..64)), -- Tag '92' + ccRequired [0] NULL OPTIONAL -- confirmation code required + }, + listProfilesResponse [3] SEQUENCE OF SEQUENCE { + iccid [APPLICATION 26] Iccid, -- Profile ICCID + profileState [112] ProfileState, -- Tag '9F70' + serviceProviderName [17] UTF8String (SIZE(0..32)), -- Tag '91' + profileName [18] UTF8String (SIZE(0..64)) -- Tag '92' + -- the eUICC MAY truncate these names so that the response fits + -- into one APDU + }, + pollRpmPackageResponse [4] SEQUENCE { + rpmPackage [0] RpmPackage, -- RPM Package to be confirmed by user + rpmPending [1] NULL OPTIONAL -- There are pending RPM Packages after this + }, + confirmDownloadResponse [5] SEQUENCE { + iccid [APPLICATION 26] Iccid -- Profile ICCID + } + } OPTIONAL +} + +E4EResultCode ::= INTEGER { + success (0), + errorBusy (1), -- CAT not available due to another operation + errorComm (2), -- Communication error with server + errorAuth (3), -- Mutual Authentication Error + errorNoProfile (4), -- No Profile available for download at SM-DP+ + errorEligibility (5), -- SM-DP+ rejected download due to Eligibility Check + errorInstall (6), -- Error during Profile installation + errorPin (7), -- Invalid PIN + errorProfileRef (8), -- Referenced Profile does not exist + errorAlreadyEnabled (9), -- Referenced Profile is already enabled + errorAlreadyDisabled (10), -- Referenced Profile is already disabled + errorConfirmationCode (11), -- Invalid Confirmation Code, + errorRpmDisabled (12), -- Cannot pollRpmPackage, RPM is disabled + errorProfileDoesNotExist (13), -- There is no profile with provided ICCID + undefinedError (127) +} + +RemoteProfileProvisioningRequest ::= [2] CHOICE { -- Tag 'A2' + initiateAuthenticationRequest [57] InitiateAuthenticationRequest, -- Tag 'BF39' + authenticateClientRequest [59] AuthenticateClientRequest, -- Tag 'BF3B' + getBoundProfilePackageRequest [58] GetBoundProfilePackageRequest, -- Tag 'BF3A' + cancelSessionRequestEs9 [65] CancelSessionRequestEs9, -- Tag 'BF41' + handleNotification [61] HandleNotification, -- tag 'BF3D' + confirmDeviceChangeRequest [76] ConfirmDeviceChangeRequest, -- Tag 'BF4C' + checkEventRequest [70] CheckEventRequest, -- Tag 'BF46' + checkProgressRequest [97] CheckProgressRequest -- Tag 'BF61' +} + +RemoteProfileProvisioningResponse ::= [2] CHOICE { -- Tag 'A2' + initiateAuthenticationResponse [57] InitiateAuthenticationResponse, -- Tag 'BF39' + authenticateClientResponseEs9 [59] AuthenticateClientResponseEs9, -- Tag 'BF3B' + getBoundProfilePackageResponse [58] GetBoundProfilePackageResponse, -- Tag 'BF3A' + cancelSessionResponseEs9 [65] CancelSessionResponseEs9, -- Tag 'BF41' + authenticateClientResponseEs11 [64] AuthenticateClientResponseEs11, -- Tag 'BF40' + confirmDeviceChangeResponse [76] ConfirmDeviceChangeResponse, -- Tag 'BF4C' + checkEventResponse [70] CheckEventResponse, -- Tag 'BF46' + checkProgressResponse [97] CheckProgressResponse -- Tag 'BF61' +} + +InitiateAuthenticationRequest ::= [57] SEQUENCE { -- Tag 'BF39' + euiccChallenge [1] Octet16, -- random eUICC challenge + smdpAddress [3] UTF8String, + euiccInfo1 EUICCInfo1, + lpaRspCapability [5] LpaRspCapability OPTIONAL -- #SupportedFromV3.0.0# Tag 'B5' +} + +InitiateAuthenticationResponse ::= [57] CHOICE { -- Tag 'BF39' + initiateAuthenticationOk InitiateAuthenticationOkEs9, + initiateAuthenticationError INTEGER { + invalidDpAddress(1), + euiccVersionNotSupportedByDp(2), -- #SupportedOnlyBeforeV3.0.0# + ciPKIdNotSupported(3), + invalidInputData(124), -- #SupportedFromV3.0.0# + missingInputData(125), -- #SupportedFromV3.0.0# + functionProviderBusy(126), -- #SupportedFromV3.0.0# + undefinedError(127) -- #SupportedFromV3.0.0# + } +} + +InitiateAuthenticationOkEs9 ::= SEQUENCE { + transactionId [0]TransactionId, -- The TransactionID generated by the SM-DP+ + serverSigned1 ServerSigned1, -- Signed information + serverSignature1 [APPLICATION 55] OCTET STRING, -- Server Sign1, tag '5F37' + euiccCiPKIdToBeUsed SubjectKeyIdentifier OPTIONAL, -- The CI Public Key to be used as required by ES10b.AuthenticateServer + serverCertificate Certificate, + otherCertsInChain [1] CertificateChain OPTIONAL, -- #SupportedFromV3.0.0# + crlList [2] SEQUENCE OF CertificateList OPTIONAL -- #SupportedFromV3.0.0# From RFC 5280 +} + +AuthenticateClientRequest ::= [59] SEQUENCE { -- Tag 'BF3B' + transactionId [0] TransactionId, + authenticateServerResponse [56] AuthenticateServerResponse, -- This is the response from ES10b.AuthenticateServer, Tag 'BF38' + deleteNotificationForDc DeleteNotificationForDc OPTIONAL -- #SupportedForDcV3.0.0# Delete Notification for Device Change, see section 4.1.3 +} + +AuthenticateClientResponseEs9 ::= [59] CHOICE { -- Tag 'BF3B' + authenticateClientOk AuthenticateClientOk, + authenticateClientError INTEGER { + eumCertificateInvalid(1), + eumCertificateExpired(2), + euiccCertificateInvalid(3), + euiccCertificateExpired(4), + euiccSignatureInvalid(5), + matchingIdRefused(6), + eidMismatch(7), + noEligibleProfile(8), + ciPKUnknown(9), + invalidTransactionId(10), + insufficientMemory(11), + ciPKMismatch(12), -- #SupportedFromV3.0.0# + euiccRspCapabilityHasChanged(13), -- #SupportedFromV3.0.0# + lpaRspCapabilityHasChanged(14), -- #SupportedFromV3.0.0# + deviceChangeNotSupported(15), -- #SupportedForDcV3.0.0# + deviceChangeNotAllowed(16), -- #SupportedForDcV3.0.0# + iccidUnkwon(17), -- #SupportedForDcV3.0.0# + invalidInputData(124), -- #SupportedFromV3.0.0# + missingInputData(125), -- #SupportedFromV3.0.0# + functionProviderBusy(126), -- #SupportedFromV3.0.0# + undefinedError(127) + }, + authenticateClientOkRpm AuthenticateClientOkRpm, -- #SupportedForRpmV3.0.0# + authenticateClientOkDeviceChange AuthenticateClientOkDeviceChange, -- #SupportedForDcV3.0.0# + authenticateClientOkDelayedDeviceChange AuthenticateClientOkDelayedDeviceChange +-- #SupportedForDcV3.1.0# +} + +AuthenticateClientOk ::= SEQUENCE { + transactionId [0] TransactionId, + profileMetadata [37] StoreMetadataRequest, -- tag 'BF25' + smdpSigned2 SmdpSigned2, -- Signed information + smdpSignature2 [APPLICATION 55] OCTET STRING, -- tag '5F37' + smdpCertificate Certificate -- CERT.DPpb.SIG +} + +AuthenticateClientOkRpm ::= SEQUENCE { + transactionId [0] TransactionId, + smdpSigned3 SmdpSigned3, + smdpSignature3 [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +AuthenticateClientOkDeviceChange ::= SEQUENCE { + transactionId [0] TransactionId, + smdpSigned4 SmdpSigned4, -- Signed information + smdpSignature4 [APPLICATION 55] OCTET STRING, -- tag '5F37' + serviceProviderMessageForDc [1] LocalisedTextMessage OPTIONAL -- Service Provider Message For Device Change +} + +AuthenticateClientOkDelayedDeviceChange ::= SEQUENCE { + transactionId [0] TransactionId, + smdpSigned6 SmdpSigned6, -- Signed information + smdpSignature6 [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +GetBoundProfilePackageRequest ::= [58] SEQUENCE { -- Tag 'BF3A' + transactionId [0] TransactionId, + prepareDownloadResponse [33] PrepareDownloadResponse -- Tag 'BF21' +} + +GetBoundProfilePackageResponse ::= [58] CHOICE { -- Tag 'BF3A' + getBoundProfilePackageOk GetBoundProfilePackageOk, + getBoundProfilePackageError INTEGER { + euiccSignatureInvalid(1), + confirmationCodeMissing(2), + confirmationCodeRefused(3), + confirmationCodeRetriesExceeded(4), + bppRebindingRefused(5), + downloadOrderExpired(6), + invalidTransactionId(95), + invalidInputData(124), -- #SupportedFromV3.0.0# + missingInputData(125), -- #SupportedFromV3.0.0# + functionProviderBusy(126), -- #SupportedFromV3.0.0# + undefinedError(127) + } +} + +GetBoundProfilePackageOk ::= SEQUENCE { + transactionId [0] TransactionId, + boundProfilePackage [54] BoundProfilePackage -- Tag 'BF36' +} + +HandleNotification ::= [61] SEQUENCE { -- Tag 'BF3D' + pendingNotification PendingNotification +} + +CancelSessionRequestEs9 ::= [65] SEQUENCE { -- Tag 'BF41' + transactionId TransactionId, + cancelSessionResponse CancelSessionResponse -- data structure defined for ES10b.CancelSession function +} + +CancelSessionResponseEs9 ::= [65] CHOICE { -- Tag 'BF41' + cancelSessionOk CancelSessionOk, + cancelSessionError INTEGER { + invalidTransactionId(1), + euiccSignatureInvalid(2), + invalidInputData(124), -- #SupportedFromV3.0.0# + missingInputData(125), -- #SupportedFromV3.0.0# + functionProviderBusy(126), -- #SupportedFromV3.0.0# + undefinedError(127) + } +} + +CancelSessionOk ::= SEQUENCE { -- This function has no output data +} + +AuthenticateClientResponseEs11 ::= [64] CHOICE { -- Tag 'BF40' + authenticateClientOk AuthenticateClientOkEs11V2, -- #SupportedOnlyBeforeV3.0.0# + authenticateClientError INTEGER { + eumCertificateInvalid(1), + eumCertificateExpired(2), + euiccCertificateInvalid(3), + euiccCertificateExpired(4), + euiccSignatureInvalid(5), + eventIdUnknown(6), + invalidTransactionId(7), + ciPKUnknown(8), -- #SupportedFromV3.0.0# + ciPKMismatch(9), -- #SupportedFromV3.0.0# + euiccRspCapabilityHasChanged(10), -- #SupportedFromV3.0.0# + lpaRspCapabilityHasChanged(11), -- #SupportedFromV3.0.0# + pushServiceNotSupport(12), -- #SupportedForPushServiceV3.0.0# + pushServiceRegistrationNotSupported(13), -- #SupportedForPushServiceV3.0.0# + invalidInputData(124), -- #SupportedFromV3.0.0# + missingInputData(125), -- #SupportedFromV3.0.0# + functionProviderBusy(126), -- #SupportedFromV3.0.0# + undefinedError(127) + }, + authenticateClientOkV3 AuthenticateClientOkEs11V3 -- #SupportedFromV3.0.0# +} + +AuthenticateClientOkEs11V2 ::= SEQUENCE { -- #SupportedOnlyBeforeV3.0.0# + transactionId [0] TransactionId, + eventEntries [1] SEQUENCE OF EventRecord +} + +EventRecord ::= SEQUENCE { -- #SupportedOnlyBeforeV3.0.0# + eventId UTF8String, + rspServerAddress UTF8String +} + +AuthenticateClientOkEs11V3 ::= SEQUENCE { + transactionId [0] TransactionId, + smdsSigned2 SmdsSigned2, + smdsSignature2 [APPLICATION 55] OCTET STRING -- tag '5F37' +} + +CheckEventRequest ::= [70] SEQUENCE { -- #SupportedForEventCheckingV3.0.0# Tag 'BF46' + ecId [0] OCTET STRING(SIZE(16..32)), -- Event Checking Identifier + smdsAddress [1] UTF8String +} + +CheckEventResponse ::= [70] CHOICE { -- #SupportedForEventCheckingV3.0.0# Tag 'BF46' + checkEventOk CheckEventOk, + checkEventError INTEGER { + invalidDsAddress(1), + eventCheckingNotSupported(2), + expiredEcid(3), + unknownEcid(4), + invalidInputData(124), + missingInputData(125), + functionProviderBusy(126), + undefinedError(127) + } +} + +CheckEventOk ::= SEQUENCE { + isPendingEvent [0] BOOLEAN -- Indicates if an Event Record corresponding to the received ECID exists +} + +ConfirmDeviceChangeRequest ::= [76] SEQUENCE { -- #SupportedForDcV3.0.0# Tag 'BF4C' + transactionId [0] TransactionId, + prepareDeviceChangeResponse PrepareDeviceChangeResponse +} + +ConfirmDeviceChangeResponse ::= [76] CHOICE { -- #SupportedForDcV3.0.0# Tag 'BF4C' + confirmDeviceChangeOk ConfirmDeviceChangeOk, + confirmDeviceChangeError INTEGER { + invalidTransactionId(1), + euiccSignatureInvalid(2), + confirmationCodeMissing(3), + confirmationCodeRefused(4), + confirmationCodeInvalidMatch(5), + confirmationCodeRetriesExceeded(6), + invalidInputData(124), + missingInputData(125), + functionProviderBusy(126), + undefinedError(127) + } +} + +ConfirmDeviceChangeOk ::= SEQUENCE { + transactionId [0] TransactionId, + smdpSigned5 SmdpSigned5, + smdpSignature5 [APPLICATION 55] OCTET STRING +} + +CheckProgressRequest ::= [97] SEQUENCE { -- #SupportedForDcV3.1.0# Tag 'BF61' + dcSessionId [0] OCTET STRING(SIZE(1..16)) -- Device Change Session ID +} + +CheckProgressResponse ::= [97] CHOICE { -- #SupportedForDcV3.1.0# Tag 'BF61' + checkProgressOk CheckProgressOk, + checkProgressError INTEGER { + unknowndcSessionId(4), + invalidInputData(124), + missingInputData(125), + functionProviderBusy(126), + undefinedError(127) + } +} + +CheckProgressOk ::= SEQUENCE { + retryDelay [0] INTEGER OPTIONAL -- Time interval (in minutes) expected by the SM-DP+ to finish the relevant Profile preparation +} + + +END diff --git a/pySim/esim/rsp.py b/pySim/esim/rsp.py index bab9123..ff4ac4d 100644 --- a/pySim/esim/rsp.py +++ b/pySim/esim/rsp.py @@ -25,10 +25,22 @@ from osmocom.utils import b2h from osmocom.tlv import bertlv_parse_one_rawtag, bertlv_return_one_rawtlv -from pySim.esim import compile_asn1_subdir +from pySim.esim import compile_asn1_subdir, compile_asn1_paths +# SGP.22 v2 RSPDefinitions, used by all RSP code in pySim asn1 = compile_asn1_subdir('rsp') +def __getattr__(name): + """Module attribute 'asn1_v3' (PEP 562): the SGP.22 v3.1 RSPDefinitions module (Annex H), + compiled on first access instead of at import, and kept as a global from then on. + v3.1 renames and drops members of the v2 types, so it is kept apart from 'asn1'; + it imports UICCCapability from the SAIP module.""" + if name == 'asn1_v3': + spec = compile_asn1_paths(['rsp/PKIX1Explicit88.asn', 'rsp/PKIX1Implicit88.asn', 'saip', 'rsp_v3']) + globals()[name] = spec + return spec + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + class RspSessionState: """Encapsulates the state of a RSP session. It is created during the initiateAuthentication and subsequently used by further API calls using the same transactionId. The session state diff --git a/setup.py b/setup.py index 20feba4..31f839b 100644 --- a/setup.py +++ b/setup.py @@ -45,6 +45,7 @@ 'pySim.esim': [ 'asn1/rsp/*.asn', + 'asn1/rsp_v3/*.asn', 'asn1/saip/*.asn', ], }, diff --git a/tests/unittests/test_esim_rsp.py b/tests/unittests/test_esim_rsp.py new file mode 100644 index 0000000..553c63b --- /dev/null +++ b/tests/unittests/test_esim_rsp.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 + +# (C) 2026 by Hampus Hellsberg <hampushellsberg(a)gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import unittest +import asn1tools +from osmocom.utils import h2b + +import pySim.esim.rsp as rsp + +SKI_V2 = '11' * 20 +SKI_V3 = '22' * 20 + +def tlv(tag: str, value_hex: str) -> str: + """Hex of a DER TLV (length below 256), for building the test vectors by hand.""" + length = len(value_hex) // 2 + assert length < 0x100 + if length < 0x80: + return tag + '%02x' % length + value_hex + return tag + '81%02x' % length + value_hex + +# EUICCInfo1 as an SGP.22 v3.1 eUICC returns it (SGP.22 v3.1 Annex H) +EUICC_INFO1_V3 = tlv('bf20', + tlv('82', '030100') + # lowestSvn [2] (svn in v2) + tlv('a9', tlv('04', SKI_V2)) + # euiccCiPKIdListForVerification [9] + tlv('aa', tlv('04', SKI_V2)) + # euiccCiPKIdListForSigning [10] + tlv('b1', tlv('04', SKI_V3)) + # euiccCiPKIdListForSigningV3 [17] + tlv('88', '05900020') + # euiccRspCapability [8]: bits 0, 3, 18 + tlv('93', '030100')) # highestSvn [19] + +TID = h2b('0102030405060708') +SIG = h2b('00' * 64) +ICCID = h2b('98880221436587092143') +NOTIF_METADATA = {'seqNumber': 1, 'profileManagementOperation': (h2b('40'), 2), + 'notificationAddress': 'smdp.example.com', 'iccid': ICCID} + +# The BF-tagged types SGP.22 v3.1 added: ES10 (sections 5.7.3, 5.7.23-5.7.29), ES9+ (5.6.6, +# 5.6.7), ES11 (5.8.3) and DeleteNotificationForDc of AuthenticateClientRequest (5.6.3) +TYPES_V3 = [ + ('EuiccConfiguredDataRequest', 'bf3c', {}), + ('EuiccConfiguredDataResponse', 'bf3c', { + 'defaultDpAddress': 'smdp.example.com', 'rootDsAddress': 'smds.example.com', + 'allowedCiPKId': h2b(SKI_V3), 'ciList': [{'ciPKId': h2b(SKI_V3), 'ciName': 'Test CI'}]}), + ('LoadRpmPackageRequest', 'bf44', { + 'smdpSigned3': {'transactionId': TID, + 'rpmPackage': [{'rpmCommandDetails': ('enable', {'iccid': ICCID})}]}, + 'smdpSignature3': SIG, 'targetEsimPort': 1}), + ('LoadRpmPackageResult', 'bf44', ('loadRpmPackageResultNotSigned', { + 'transactionId': TID, 'loadRpmPackageErrorCodeNotSigned': 4})), + ('VerifySmdsResponseRequest', 'bf45', { + 'smdsSigned2': {'transactionId': TID, 'requestSpecificData': ('pushServiceRegistrationResult', {})}, + 'smdsSignature2': SIG}), + ('VerifySmdsResponseResponse', 'bf45', ('verifySmdsResponseOk', None)), + ('CheckEventRequest', 'bf46', {'ecId': bytes(range(16)), 'smdsAddress': 'smds.example.com'}), + ('CheckEventResponse', 'bf46', ('checkEventOk', {'isPendingEvent': True})), + ('AlertData', 'bf4a', ('pendingOperationAlert', ('defaultSmdp', None))), + ('VerifyDeviceChangeRequest', 'bf4b', { + 'smdpSigned5': {'transactionId': TID, 'deviceChangeResponse': ('deviceChangeData', { + 'iccid': ICCID, 'activationCodeForDc': '1$smdp.example.com$ABC'})}, + 'smdpSignature5': SIG}), + ('VerifyDeviceChangeResponse', 'bf4b', ('verifyDeviceChangeError', 8)), + ('ConfirmDeviceChangeRequest', 'bf4c', { + 'transactionId': TID, 'prepareDeviceChangeResponse': ('prepareDeviceChangeResponseError', { + 'transactionId': TID, 'downloadErrorCode': 127})}), + ('ConfirmDeviceChangeResponse', 'bf4c', ('confirmDeviceChangeError', 3)), + ('PrepareDeviceChangeRequest', 'bf4d', { + 'smdpSigned4': {'transactionId': TID, 'ccRequiredFlag': False}, 'smdpSignature4': SIG}), + ('PrepareDeviceChangeResponse', 'bf4d', ('prepareDeviceChangeResponseError', { + 'transactionId': TID, 'downloadErrorCode': 127})), + ('VerifySmdpResponseRequest', 'bf60', { + 'smdpSigned6': {'transactionId': TID, 'requestSpecificData': ('retryData', { + 'retryDelay': 5, 'dcSessionId': h2b('01')})}, + 'smdpSignature6': SIG}), + ('VerifySmdpResponseResponse', 'bf60', ('verifySmdpResponseOk', None)), + ('CheckProgressRequest', 'bf61', {'dcSessionId': h2b('0102')}), + ('CheckProgressResponse', 'bf61', ('checkProgressOk', {'retryDelay': 10})), + ('VerifyProfileRecoveryRequest', 'bf62', { + 'smdpSigned4': {'transactionId': TID, 'ccRequiredFlag': True, + 'activationCodeForProfileRecovery': '1$smdp.example.com$XYZ'}, + 'smdpSignature4': SIG}), + ('VerifyProfileRecoveryResponse', 'bf62', ('verifyProfileRecoveryOk', None)), + ('DeleteNotificationForDc', 'bf63', { + 'notificationMetadata': NOTIF_METADATA, 'euiccNotificationSignature': SIG}), +] + + +class TestRspV3Module(unittest.TestCase): + """The SGP.22 v3.1 module next to the v2 one.""" + + def test_compiled_on_first_access(self): + vars(rsp).pop('asn1_v3', None) + spec = rsp.asn1_v3 + self.assertIs(vars(rsp)['asn1_v3'], spec) + self.assertIs(rsp.asn1_v3, spec) + self.assertFalse(hasattr(rsp, 'asn1_v4')) + + def test_bf_tagged_v3_types(self): + for type_name, tag, value in TYPES_V3: + with self.subTest(type_name): + self.assertNotIn(type_name, rsp.asn1.types) + enc = rsp.asn1_v3.encode(type_name, value) + self.assertEqual(enc[:2], h2b(tag)) + self.assertEqual(rsp.asn1_v3.decode(type_name, enc), value) + + def test_v3_member_names(self): + dec_v2 = rsp.asn1.decode('EUICCInfo1', h2b(EUICC_INFO1_V3)) + dec_v3 = rsp.asn1_v3.decode('EUICCInfo1', h2b(EUICC_INFO1_V3)) + self.assertEqual(dec_v2['svn'], dec_v3['lowestSvn']) + self.assertEqual(dec_v3['highestSvn'], h2b('030100')) + self.assertEqual(rsp.asn1_v3.encode('EUICCInfo1', dec_v3), h2b(EUICC_INFO1_V3)) + + def test_device_capabilities_tag_88_differs(self): + # same bytes, different member: the reason v3.1 is not merged into the v2 module + enc = h2b('30058803020000') + self.assertEqual(rsp.asn1.decode('DeviceCapabilities', enc), + {'rspRpmSupportedVersion': h2b('020000')}) + self.assertEqual(rsp.asn1_v3.decode('DeviceCapabilities', enc), + {'nrEpcSupportedRelease': h2b('020000')}) + + def test_smdp_oid_mandatory_in_v3(self): + pir = {'transactionId': TID, 'notificationMetadata': NOTIF_METADATA, + 'finalResult': ('errorResult', {'bppCommandId': 1, 'errorReason': 1})} + enc = rsp.asn1.encode('ProfileInstallationResultData', pir) + self.assertEqual(rsp.asn1.decode('ProfileInstallationResultData', enc)['transactionId'], TID) + with self.assertRaises(asn1tools.DecodeError): + rsp.asn1_v3.decode('ProfileInstallationResultData', enc) + pir['smdpOid'] = '1.2.3.4' + enc = rsp.asn1.encode('ProfileInstallationResultData', pir) + self.assertEqual(rsp.asn1_v3.decode('ProfileInstallationResultData', enc)['smdpOid'], + '1.2.3.4') + + def test_unchanged_encodings_match(self): + server_signed1 = {'transactionId': TID, 'euiccChallenge': bytes(16), + 'serverAddress': 'smdp.example.com', 'serverChallenge': bytes(range(16))} + ctx = {'matchingId': 'ABC', 'deviceInfo': {'tac': h2b('35230145'), 'deviceCapabilities': {}}} + for type_name, value in (('ServerSigned1', server_signed1), + ('CtxParamsForCommonAuthentication', ctx)): + with self.subTest(type_name): + self.assertEqual(rsp.asn1.encode(type_name, value), rsp.asn1_v3.encode(type_name, value)) + # operationType [2] DEFAULT {profileDownload}: absent on the wire, filled in on decode + dec = rsp.asn1_v3.decode('CtxParamsForCommonAuthentication', + rsp.asn1.encode('CtxParamsForCommonAuthentication', ctx)) + self.assertEqual(dec['operationType'], (h2b('80'), 1)) + + +if __name__ == "__main__": + unittest.main() -- To view, visit https://gerrit.osmocom.org/c/pysim/+/44007?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: I670ec73f9958882a8d3fe4b589bdafa3fbf702ea Gerrit-Change-Number: 44007 Gerrit-PatchSet: 2 Gerrit-Owner: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1 0
0 0
[XL] Change in pysim[master]: esim/asn1: add the SGP.22 v3.1 RSPDefinitions module as rsp_v3
by laforge 25 Nov '26

25 Nov '26
Attention is currently required from: hampushellsberg. laforge has posted comments on this change by hampushellsberg. ( https://gerrit.osmocom.org/c/pysim/+/44007?usp=email ) Change subject: esim/asn1: add the SGP.22 v3.1 RSPDefinitions module as rsp_v3 ...................................................................... Patch Set 2: Code-Review+2 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/44007?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I670ec73f9958882a8d3fe4b589bdafa3fbf702ea Gerrit-Change-Number: 44007 Gerrit-PatchSet: 2 Gerrit-Owner: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Attention: hampushellsberg <hampushellsberg(a)gmail.com> Gerrit-Comment-Date: Wed, 25 Nov 2026 14:00:36 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes
1 0
0 0
[XS] Change in libosmocore[master]: cbsp: narrow the HAVE_SYS_SOCKET_H guard to osmo_cbsp_recv_buffered()
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/libosmocore/+/44165?usp=email ) Change subject: cbsp: narrow the HAVE_SYS_SOCKET_H guard to osmo_cbsp_recv_buffered() ...................................................................... cbsp: narrow the HAVE_SYS_SOCKET_H guard to osmo_cbsp_recv_buffered() Only osmo_cbsp_recv_buffered() uses recv() and thus requires <sys/socket.h>. However, the guard is extended to the end of the file, also covering osmo_cbsp_segmentation_cb() and osmo_cbsp_cause_names[], which have no socket dependencies. Change-Id: Ibaf89d14dafdec431dafbf2202e0f5bb145aac6c --- M src/gsm/cbsp.c 1 file changed, 1 insertion(+), 2 deletions(-) Approvals: laforge: Looks good to me, approved Jenkins Builder: Verified pespin: Looks good to me, but someone else must approve diff --git a/src/gsm/cbsp.c b/src/gsm/cbsp.c index b1d0d2f..18b8226 100644 --- a/src/gsm/cbsp.c +++ b/src/gsm/cbsp.c @@ -1588,6 +1588,7 @@ msgb_free(msg); return rc; } +#endif /* HAVE_SYS_SOCKET_H */ /*! call-back function to segment the data at message boundaries. * Returns the size of the next message. If it returns -EAGAIN or a value larger than msgb_length() (message @@ -1629,5 +1630,3 @@ { OSMO_CBSP_CAUSE_LAI_OR_LAC_NOT_VALID, "LAI-or-LAC-not-valid"}, { 0, NULL } }; - -#endif /* HAVE_SYS_SOCKET_H */ -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44165?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ibaf89d14dafdec431dafbf2202e0f5bb145aac6c Gerrit-Change-Number: 44165 Gerrit-PatchSet: 2 Gerrit-Owner: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de>
1 0
0 0
[XS] Change in libosmocore[master]: cbsp: cbsp_decode_cell_list(): check *buf/len
by laforge 25 Nov '26

25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/libosmocore/+/44159?usp=email ) Change subject: cbsp: cbsp_decode_cell_list(): check *buf/len ...................................................................... cbsp: cbsp_decode_cell_list(): check *buf/len The callers of this function pass *buf/len as follows: cbsp_decode_cell_list(..., TLVP_VAL(tp, CBSP_IEI_CELL_LIST), TLVP_LEN(tp, CBSP_IEI_CELL_LIST)); so the *buf is NULL if the Cell List IE is not present. The IE length is also not guaranteed to be valid: it can be 0. Thus we should not be dereferencing the *buf unconditionally. Change-Id: I31c66fad36f380fb6706a935df412fd6114f4cd9 Fixes: OS#7097 --- M src/gsm/cbsp.c 1 file changed, 8 insertions(+), 0 deletions(-) Approvals: laforge: Looks good to me, approved Jenkins Builder: Verified diff --git a/src/gsm/cbsp.c b/src/gsm/cbsp.c index bc8bc4f..b355eef 100644 --- a/src/gsm/cbsp.c +++ b/src/gsm/cbsp.c @@ -509,6 +509,14 @@ const uint8_t *cur = buf; int rc; + if (buf == NULL) { + osmo_cbsp_errstr = "cell list: missing mandatory IE"; + return -ENOENT; + } else if (len < 1) { + osmo_cbsp_errstr = "cell list: too short"; + return -EINVAL; + } + cl->id_discr = *cur++; while (cur < buf + len) { -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44159?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: I31c66fad36f380fb6706a935df412fd6114f4cd9 Gerrit-Change-Number: 44159 Gerrit-PatchSet: 2 Gerrit-Owner: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-CC: pespin <pespin(a)sysmocom.de>
1 0
0 0
  • ← Newer
  • 1
  • ...
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • ...
  • 9721
  • Older →

HyperKitty Powered by HyperKitty version 1.3.12.