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