[M] Change in pysim[master]: global_platform: add tracked security domain selection
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43724?usp=email ) Change subject: global_platform: add tracked security domain selection ...................................................................... global_platform: add tracked security domain selection select_security_domain <aid> does SELECT by AID and models the result as an ADF_SD, so the GP commands, prompt and CardKeyProvider identity work. Plain select cannot do this: probe_file() classifies by the ISO FCP, an application answers with a GP FCI, and whether that FCI belongs to a Security Domain is not obvious (GPC 11.9.3.1 table 11-56 tag 73 is optional, the sysmoEUICC1 omits it). The CardKeyProvider identity (ICCID vs EID) used for csv lookup of credentials is (obviously) not part of the answer at all. This new command makes using the eUICC with MNO-SDs and SSDs easier, because so far we only had raw apdus to select those that led to a confused internal pysim state, i.e. install_cap after selecting like that would try to install to the ISD-R. Change-Id: I7c6dda0f11dc6bb175f05b3832cf49691089c297 --- M docs/put_key-tutorial.rst M docs/shell.rst M pySim/global_platform/__init__.py M tests/unittests/test_globalplatform.py 4 files changed, 221 insertions(+), 12 deletions(-) Approvals: laforge: Looks good to me, but someone else must approve Jenkins Builder: Verified dexter: Looks good to me, approved diff --git a/docs/put_key-tutorial.rst b/docs/put_key-tutorial.rst index fe49729..8585167 100644 --- a/docs/put_key-tutorial.rst +++ b/docs/put_key-tutorial.rst @@ -44,10 +44,10 @@ `MNO-SD` is either the default AID for the Issuer Security Domain (see also GlobalPlatform, section H.1.3) or a different value specified by the provider of the eSIM profile. -Since the AID of the `MNO-SD` is not a fixed value, it is not known by `pySim-shell`. This means there will be no -`ADF.ISD` file shown in the file system, but we can simply select the `ADF.ISD-R` first and then select the `MNO-SD` -using a raw APDU. In the following example we assume that the default AID (``a000000151000000``) is used The APDU -would look like this: ``00a4040408`` + ``a000000151000000`` + ``00`` +Since the AID of the `MNO-SD` is not a fixed value, it is not part of pySim's static card profile. Select a known +Security Domain such as `ADF.ISD-R` first to make the GlobalPlatform commands available, then use +``select_security_domain`` with the MNO-SD AID. Do not select it with a raw ``apdu``, that desyncs pySim's internal +card model. In the following example we assume that the default AID (``a000000151000000``) is used. :: @@ -61,14 +61,55 @@ "supported_version_number": "020300" } } - pySIM-shell (00:MF/ADF.ISD-R)> apdu 00a4040408a00000015100000000 - SW: 9000, RESP: 6f108408a000000151000000a5049f6501ff + pySIM-shell (00:MF/ADF.ISD-R)> select_security_domain a000000151000000 + CardKeyProvider identity: ICCID + { + "application_id": "a000000151000000", + "proprietary_data": { + "maximum_length_of_data_field_in_command_message": 255 + } + } -After that, the prompt will still show the `ADF.ISD-R`, but we are actually in `ADF.ISD` and the standard GlobalPlatform -operations like `establish_scpXX`, `get_data`, and `put_key` should work. By doing this, we simply have tricked -`pySim-shell` into making the GlobalPlatform related commands available for some other Security Domain we are not -interested in. With the raw APDU we then have swapped out the Security Domain under the hood. The same workaround can -be applied to any Security Domain, provided that the AID is known to the user. +The dynamically discovered Security Domain uses the profile ICCID for CardKeyProvider lookup by default, which is +appropriate for an MNO-SD. Use ``--key-provider-identity EID`` for an eUICC-global Security Domain instead. The command +must be used before establishing SCP; use ``release_scp`` before switching away from a Security Domain with an active +SCP session. If the enabled profile changes during the shell session, re-equip the card before selecting its MNO-SD; +different profiles commonly reuse the same MNO-SD AID, while their key lookup is tied to the profile ICCID. + +Selecting a Supplementary Security Domain (SSD) +------------------------------------------------ + +``select_security_domain`` is not limited to an MNO-SD. It can also select a Supplementary Security Domain (SSD), +provided that the SSD is in a selectable life-cycle state. An SSD frequently has no filesystem alias and need not be +listed in ``EF.DIR``; select it using its instance AID. + +The SSD AID can be obtained from the profile or installation data. It can also be discovered with +``get_status applications`` while operating through its controlling Security Domain. Look for an application registry +entry with the ``security_domain`` privilege and a selectable life-cycle state. + +The following example assumes that an SSD with AID ``a000000151000042`` was created beneath the active profile's +MNO-SD. Any SCP session with the MNO-SD must first be released. Selecting the SSD does not carry the parent's secure +channel into the SSD: establish a new secure channel using the SSD's own keyset afterwards. + +:: + + pySIM-shell (SCP03[03]:00:MF/ADF.SD-A000000151000000)> get_status applications + # Locate the selectable registry entry with the security_domain privilege. + pySIM-shell (SCP03[03]:00:MF/ADF.SD-A000000151000000)> release_scp + pySIM-shell (00:MF/ADF.SD-A000000151000000)> select_security_domain a000000151000042 + CardKeyProvider identity: ICCID + { + "application_id": "a000000151000042" + } + pySIM-shell (00:MF/ADF.SD-A000000151000042)> establish_scp03 --key-ver 1 --key-enc <SSD-ENC> --key-mac <SSD-MAC> --key-dek <SSD-DEK> --security-level 3 + +For a newly installed SSD, ``install_for_install --privilege security_domain --make-selectable`` creates it as a +selectable Security Domain. If SELECT-by-AID fails because the SSD is not selectable, it must first be moved to the +appropriate life-cycle state through its controlling Security Domain. Remote administration that targets an SSD by +AID (for example through SCP81) is a separate mechanism and does not imply that contact-interface SELECT is enabled. + +As with an MNO-SD, profile-scoped SSD key lookup normally uses the default ``ICCID`` identity. Use +``--key-provider-identity EID`` only when the SSD's keys are associated with the eUICC rather than the enabled profile. Establishing a secure channel @@ -135,7 +176,7 @@ :: - pySIM-shell (00:MF/ADF.ISD-R)> establish_scp03 --key-enc 63af517c29ad6ac6fcadfe6ac8a3c8a041d8141c7eb845ef1cba6112a325e430 --key-mac 54b9ad6713ae922f54014ed762132e7b59bdcd2a2a6beba98fb9afe6b4df27e1 --key-dek cbb933ba2389da93c86c112739cd96389139f16c6f80f7d16bf3593e407ca893 --key-ver 48 --security-level 3 + pySIM-shell (00:MF/ADF.SD-A000000151000000)> establish_scp03 --key-enc 63af517c29ad6ac6fcadfe6ac8a3c8a041d8141c7eb845ef1cba6112a325e430 --key-mac 54b9ad6713ae922f54014ed762132e7b59bdcd2a2a6beba98fb9afe6b4df27e1 --key-dek cbb933ba2389da93c86c112739cd96389139f16c6f80f7d16bf3593e407ca893 --key-ver 48 --security-level 3 Successfully established a SCP03[03] secure channel diff --git a/docs/shell.rst b/docs/shell.rst index 0dc00ba..53e55d1 100644 --- a/docs/shell.rst +++ b/docs/shell.rst @@ -1030,6 +1030,12 @@ pySim-shell has only the mots rudimentary support for GlobalPlatform at this point. Please use dedicated projects like GlobalPlatformPro meanwhile. +select_security_domain +~~~~~~~~~~~~~~~~~~~~~~ +.. argparse:: + :module: pySim.global_platform + :func: ADF_SD.AddlShellCommands.select_sd_parser + get_data ~~~~~~~~ .. argparse:: diff --git a/pySim/global_platform/__init__.py b/pySim/global_platform/__init__.py index 9600c7c..854e73b 100644 --- a/pySim/global_platform/__init__.py +++ b/pySim/global_platform/__init__.py @@ -609,6 +609,57 @@ @with_default_category('Application-Specific Commands') class AddlShellCommands(CommandSet): + select_sd_parser = argparse.ArgumentParser() + select_sd_parser.add_argument('aid', type=is_hexstr, + help='AID of the Security Domain') + select_sd_parser.add_argument('--key-provider-identity', choices=['ICCID', 'EID'], + help='CardKeyProvider identity for this Security Domain; ' + 'default: retain it for a known SD, otherwise ICCID') + + @cmd2.with_argparser(select_sd_parser) + def do_select_security_domain(self, opts): + """Select a Security Domain by AID, e.g. the MNO-SD of an eUICC profile, and + add it to the runtime card model so the GP commands and key lookup follow.""" + # select() unregisters this CommandSet, self._cmd is gone afterwards + cmd_app = self._cmd + lchan = cmd_app.lchan + if lchan.scc.scp: + raise RuntimeError('Cannot select another Security Domain while an SCP session is active; ' + 'use release_scp first') + + aid = opts.aid.lower() + if not 10 <= len(aid) <= 32: + raise ValueError('A Security Domain AID must be between 5 and 16 bytes') + mf = cmd_app.rs.mf + adf = mf.applications.get(aid) + added = False + if adf is None: + app = CardApplicationSD(aid=aid, + name='ADF.SD-' + aid.upper(), + desc='Runtime-discovered Security Domain') + adf = app.adf + adf.scp_key_identity = opts.key_provider_identity or 'ICCID' + mf.add_application_df(adf) + added = True + elif not isinstance(adf, ADF_SD): + raise ValueError('Application %s is already known, but is not modelled as a Security Domain' % aid) + + try: + fcp_dec = lchan.select(aid, cmd_app) + except Exception: + if added: + # clean up on rejected select + mf.applications.pop(aid, None) + adf.parent = None + raise + + if not added and opts.key_provider_identity: + adf.scp_key_identity = opts.key_provider_identity + cmd_app.update_prompt() + cmd_app.poutput('CardKeyProvider identity: %s' % + (adf.scp_key_identity or 'not configured')) + cmd_app.poutput_json(fcp_dec) + get_data_parser = argparse.ArgumentParser() get_data_parser.add_argument('data_object_name', type=str, help='Name of the data object to be retrieved from the card') diff --git a/tests/unittests/test_globalplatform.py b/tests/unittests/test_globalplatform.py index d329c45..67c07a9 100644 --- a/tests/unittests/test_globalplatform.py +++ b/tests/unittests/test_globalplatform.py @@ -31,6 +31,117 @@ KIK = h2b('102102030405060708090a0b0c0d0e0f') # DEK ck_3des_70 = GpCardKeyset(0x20, KIC, KID, KIK) + +class SelectSecurityDomain_Test(unittest.TestCase): + class _FakeMf: + def __init__(self): + self.applications = {} + + def add_application_df(self, adf): + if adf.aid in self.applications: + raise ValueError('duplicate AID') + self.applications[adf.aid] = adf + adf.parent = self + + class _FakeLchan: + def __init__(self, mf, fail_select=False): + self.rs = SimpleNamespace(mf=mf) + self.scc = SimpleNamespace(scp=None) + self.fail_select = fail_select + self.select_calls = [] + self.selected_file = None + self.selected_adf = None + self.selected_file_fcp = None + + def select(self, aid, cmd): + self.select_calls.append((aid, cmd)) + if self.fail_select: + raise RuntimeError('SELECT failed') + self.selected_file = self.rs.mf.applications[aid] + self.selected_adf = self.selected_file + self.selected_file_fcp = {'application_id': aid} + return self.selected_file_fcp + + def _run(self, aid='a000000151000000', key_provider_identity=None, + mf=None, fail_select=False, scp=None, lose_selector_cmd=False): + mf = mf or self._FakeMf() + lchan = self._FakeLchan(mf, fail_select=fail_select) + lchan.scc.scp = scp + output = [] + cmd = SimpleNamespace( + lchan=lchan, + rs=lchan.rs, + update_prompt=lambda: output.append(('prompt',)), + poutput=lambda value: output.append(('text', value)), + poutput_json=lambda value: output.append(('json', value)), + ) + if lose_selector_cmd: + # make sure cmd survives unregistering + class Selector(ADF_SD.AddlShellCommands): + @property + def _cmd(self): + if lchan.selected_file is not None: + raise RuntimeError('CommandSet was unregistered') + return cmd + else: + Selector = type('Selector', (ADF_SD.AddlShellCommands,), {'_cmd': cmd}) + selector = Selector.__new__(Selector) + opts = SimpleNamespace(aid=aid, key_provider_identity=key_provider_identity) + # the undecorated method, set by functools.wraps in cmd2.with_argparser + # pylint: disable-next=no-member + ADF_SD.AddlShellCommands.do_select_security_domain.__wrapped__(selector, opts) + return mf, lchan, output + + def test_new_security_domain_is_selected_and_tracked(self): + mf, lchan, output = self._run() + adf = mf.applications['a000000151000000'] + self.assertIsInstance(adf, ADF_SD) + self.assertEqual(adf.scp_key_identity, 'ICCID') + self.assertIs(lchan.selected_file, adf) + self.assertIs(lchan.selected_adf, adf) + self.assertEqual(output[-1], ('json', {'application_id': 'a000000151000000'})) + + def test_success_survives_executing_command_set_being_unregistered(self): + _mf, lchan, output = self._run(lose_selector_cmd=True) + self.assertEqual(lchan.selected_file_fcp, + {'application_id': 'a000000151000000'}) + self.assertEqual(output[-1], ('json', lchan.selected_file_fcp)) + + def test_explicit_key_provider_identity(self): + mf, _lchan, _output = self._run(key_provider_identity='EID') + self.assertEqual(mf.applications['a000000151000000'].scp_key_identity, 'EID') + + def test_known_security_domain_retains_identity_by_default(self): + mf = self._FakeMf() + app = CardApplicationSD('a000000151000000', 'ADF.TEST-SD', 'Test SD') + app.adf.scp_key_identity = 'EID' + mf.add_application_df(app.adf) + self._run(mf=mf) + self.assertEqual(app.adf.scp_key_identity, 'EID') + + def test_active_scp_is_rejected(self): + mf = self._FakeMf() + with self.assertRaisesRegex(RuntimeError, 'release_scp'): + self._run(mf=mf, scp=object()) + self.assertEqual(mf.applications, {}) + + def test_invalid_aid_length_is_rejected(self): + with self.assertRaisesRegex(ValueError, 'between 5 and 16 bytes'): + self._run(aid='01020304') + + def test_failed_select_is_not_retained(self): + mf = self._FakeMf() + with self.assertRaises(RuntimeError): + self._run(mf=mf, fail_select=True) + self.assertEqual(mf.applications, {}) + + def test_parser_accepts_security_domain_aid(self): + opts = ADF_SD.AddlShellCommands.select_sd_parser.parse_args( + ['a000000151000000', '--key-provider-identity', 'EID']) + self.assertEqual(opts.aid, 'a000000151000000') + self.assertEqual(opts.key_provider_identity, 'EID') + + class SCP02_Auth_Test(unittest.TestCase): host_challenge = h2b('40A62C37FA6304F8') init_update_resp = h2b('00000000000000000000700200016B4524ABEE7CF32EA3838BC148F3') -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43724?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: I7c6dda0f11dc6bb175f05b3832cf49691089c297 Gerrit-Change-Number: 43724 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild@sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier@sysmocom.de> Gerrit-Reviewer: laforge <laforge@osmocom.org>
participants (1)
-
laforge