laforge submitted this change.

View Change

Approvals: Jenkins Builder: Verified laforge: Looks good to me, approved dexter: Looks good to me, but someone else must approve
esim.saip: keep keyAccess and keyCounterValue of security domain keys

SecurityDomainKey only stored the usage qualifier, KID, KVN and key
components, and ProfileElementSD._pre_encode() rebuilds keyList from
it, so a non-default keyAccess and any keyCounterValue were lost on
re-encode. Store both. keyAccess is only written if it is not '00'.

The counter is an integer, encoded with the length of the protocol the
KVN is reserved for (SAIP section 8.6.3: 2, 3 and 5 bytes for SCP02,
SCP03 and SCP80, on the KVN ranges listed in global_platform/uicc.py),
also when it was decoded with another length. A counter on any other
KVN raises ValueError.

The folder osmocom-pysim-saip-sd-key-access-counter of
hampushellsberg-dev/PySIM-upstream-patches on GitHub has the analysis
and a repro.

Change-Id: I7df8ef6f2c81cd8544a04dbf7ff5d096685103e3
---
M pySim/esim/saip/__init__.py
M tests/unittests/test_esim_saip.py
2 files changed, 70 insertions(+), 6 deletions(-)

diff --git a/pySim/esim/saip/__init__.py b/pySim/esim/saip/__init__.py
index 5966897..e18ac8a 100644
--- a/pySim/esim/saip/__init__.py
+++ b/pySim/esim/saip/__init__.py
@@ -1153,11 +1153,28 @@
class SecurityDomainKey:
"""Representation of a key used for SCP access to a security domain."""
def __init__(self, key_version_number: int, key_id: int, key_usage_qualifier: dict,
- key_components: List[SecurityDomainKeyComponent]):
+ key_components: List[SecurityDomainKeyComponent], key_access: int = 0,
+ key_counter_value: Optional[int] = None):
self.key_usage_qualifier = key_usage_qualifier
self.key_identifier = key_id
self.key_version_number = key_version_number
self.key_components = key_components
+ self.key_access = key_access
+ self.key_counter_value = key_counter_value
+
+ @staticmethod
+ def counter_len_for_kvn(kvn: int) -> int:
+ """Return the counter length of the protocol a KVN is reserved for (see the KVN table in
+ pySim.global_platform.uicc). Raises ValueError if that is not SCP80, SCP02 or SCP03."""
+ # SAIP section 8.6.3: the default counter is '0000' for SCP02, '000000' for SCP03 and
+ # '0000000000' for SCP80
+ if kvn in range(0x01, 0x10):
+ return 5 # SCP80
+ if kvn in range(0x20, 0x30) or kvn == 0xff:
+ return 2 # SCP02
+ if kvn in range(0x30, 0x40):
+ return 3 # SCP03
+ raise ValueError('KVN 0x%02x is not reserved for SCP80, SCP02 or SCP03, its key counter length is unknown' % kvn)

def __repr__(self) -> str:
return 'SdKey(KVN=0x%02x, ID=0x%02x, Usage=0x%x, Comp=%s)' % (self.key_version_number,
@@ -1168,18 +1185,32 @@
@classmethod
def from_saip_dict(cls, saip: dict) -> 'SecurityDomainKey':
"""Construct instance from the dict as generated by SAIP asn.1 decoder."""
+ counter = saip.get('keyCounterValue', None)
inst = cls(int.from_bytes(saip['keyVersionNumber'], "big"),
int.from_bytes(saip['keyIdentifier'], "big"),
KeyUsageQualifier.parse(saip['keyUsageQualifier']),
- [SecurityDomainKeyComponent.from_saip_dict(x) for x in saip['keyComponents']])
+ [SecurityDomainKeyComponent.from_saip_dict(x) for x in saip['keyComponents']],
+ key_access=int.from_bytes(saip.get('keyAccess', b'\x00'), "big"),
+ key_counter_value=int.from_bytes(counter, "big") if counter is not None else None)
return inst

def to_saip_dict(self) -> dict:
"""Express instance in the dict format required by SAIP asn.1 encoder."""
- return {'keyUsageQualifier': KeyUsageQualifier.build(self.key_usage_qualifier),
- 'keyIdentifier': bytes([self.key_identifier]),
- 'keyVersionNumber': bytes([self.key_version_number]),
- 'keyComponents': [k.to_saip_dict() for k in self.key_components]}
+ ret = {'keyUsageQualifier': KeyUsageQualifier.build(self.key_usage_qualifier),
+ 'keyIdentifier': bytes([self.key_identifier]),
+ 'keyVersionNumber': bytes([self.key_version_number]),
+ 'keyComponents': [k.to_saip_dict() for k in self.key_components]}
+ # keyAccess is DEFAULT '00', keyCounterValue OPTIONAL
+ if self.key_access:
+ ret['keyAccess'] = bytes([self.key_access])
+ if self.key_counter_value is not None:
+ counter_len = self.counter_len_for_kvn(self.key_version_number)
+ try:
+ ret['keyCounterValue'] = self.key_counter_value.to_bytes(counter_len, "big")
+ except OverflowError as e:
+ raise ValueError('key counter %d of KVN 0x%02x does not fit in %d bytes'
+ % (self.key_counter_value, self.key_version_number, counter_len)) from e
+ return ret

def get_key_component(self, key_type):
for kc in self.key_components:
diff --git a/tests/unittests/test_esim_saip.py b/tests/unittests/test_esim_saip.py
index 4a02b71..50cb9d5 100755
--- a/tests/unittests/test_esim_saip.py
+++ b/tests/unittests/test_esim_saip.py
@@ -63,6 +63,39 @@
pes = ProfileElementSequence.from_der(der)
self.assertEqual(pes.to_der(), der)

+ def test_sd_key_access_and_counter(self):
+ """Test that keyAccess and keyCounterValue of a security domain key survive a re-encode."""
+ decoded = copy.deepcopy(self.pes.get_pe_for_type('securityDomain').decoded)
+ # KVN 0x01: SCP80 keyset, five byte counter
+ decoded['keyList'][0]['keyAccess'] = b'\x01'
+ decoded['keyList'][0]['keyCounterValue'] = h2b('0000000001')
+ der = asn1.encode('ProfileElement', ('securityDomain', decoded))
+ pe = ProfileElement.from_der(der)
+ self.assertEqual(pe.keys[0].key_access, 1)
+ self.assertEqual(pe.keys[0].key_counter_value, 1)
+ self.assertEqual(pe.to_der(), der)
+
+ def test_sd_key_counter_len(self):
+ """Test that a key counter is encoded with the length of the protocol its KVN is reserved for."""
+ key = self.pes.get_pe_for_type('securityDomain').keys[0]
+ def counter(kvn: int, value: int = 1) -> str:
+ sd_key = SecurityDomainKey(kvn, key.key_identifier, key.key_usage_qualifier, key.key_components,
+ key_counter_value=value)
+ return b2h(sd_key.to_saip_dict()['keyCounterValue'])
+ self.assertEqual(counter(0x01), '0000000001') # SCP80
+ self.assertEqual(counter(0x20), '0001') # SCP02
+ self.assertEqual(counter(0xff), '0001') # SCP02
+ self.assertEqual(counter(0x30), '000001') # SCP03
+ # KVN 0x70 is not reserved for SCP80, SCP02 or SCP03; 0x1000000 needs more than 3 bytes
+ for kvn, value in ((0x70, 1), (0x30, 0x1000000)):
+ with self.assertRaises(ValueError):
+ counter(kvn, value)
+ # a decoded counter of another length re-encodes with the length of its KVN
+ decoded = copy.deepcopy(self.pes.get_pe_for_type('securityDomain').decoded)
+ decoded['keyList'][3]['keyCounterValue'] = h2b('0001') # KVN 0x02: SCP80
+ pe = ProfileElement.from_der(asn1.encode('ProfileElement', ('securityDomain', decoded)))
+ self.assertEqual(pe.keys[3].to_saip_dict()['keyCounterValue'], h2b('0000000001'))
+
def test_sequence_helpers(self):
"""Verify that the convenience helpers worked as expected."""
self.assertEqual([x.type for x in self.pes.pe_list], self.expected_pet_list)

To view, visit change 44011. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I7df8ef6f2c81cd8544a04dbf7ff5d096685103e3
Gerrit-Change-Number: 44011
Gerrit-PatchSet: 3
Gerrit-Owner: hampushellsberg <hampushellsberg@gmail.com>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier@sysmocom.de>
Gerrit-Reviewer: laforge <laforge@osmocom.org>
Gerrit-Reviewer: lynxis lazus <lynxis@fe80.eu>