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

June 2024

  • 1 participants
  • 1566 discussions
[S] Change in pysim[master]: esim.saip: Introduce ProfileElement.identification property
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/37009?usp=email ) Change subject: esim.saip: Introduce ProfileElement.identification property ...................................................................... esim.saip: Introduce ProfileElement.identification property Change-Id: I6525bb78619e574296488843e021d505e0632d99 --- M pySim/esim/saip/__init__.py 1 file changed, 16 insertions(+), 0 deletions(-) Approvals: fixeria: Looks good to me, but someone else must approve laforge: Looks good to me, approved Jenkins Builder: Verified osmith: Looks good to me, but someone else must approve diff --git a/pySim/esim/saip/__init__.py b/pySim/esim/saip/__init__.py index e5b99e7..9fa568c 100644 --- a/pySim/esim/saip/__init__.py +++ b/pySim/esim/saip/__init__.py @@ -198,6 +198,13 @@ return self.decoded.get(self.header_name, None) @property + def identification(self): + if self.header: + return self.header['identification'] + else: + return None + + @property def templateID(self): """Return the decoded templateID used by this profile element (if any).""" return self.decoded.get('templateID', None) -- To view, visit https://gerrit.osmocom.org/c/pysim/+/37009?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I6525bb78619e574296488843e021d505e0632d99 Gerrit-Change-Number: 37009 Gerrit-PatchSet: 4 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: osmith <osmith(a)sysmocom.de> Gerrit-MessageType: merged
1 0
0 0
[S] Change in pysim[master]: http_json_api / es9p: Add User-Agent header
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/37007?usp=email ) Change subject: http_json_api / es9p: Add User-Agent header ...................................................................... http_json_api / es9p: Add User-Agent header ES9+ (And ES11) require the use of User-Agent, while ES2+ not. Change-Id: Iffe64d82087940a82fbfa73bf5d2b7e864ae5d67 --- M pySim/esim/es9p.py M pySim/esim/http_json_api.py 2 files changed, 22 insertions(+), 4 deletions(-) Approvals: fixeria: Looks good to me, but someone else must approve laforge: Looks good to me, approved osmith: Looks good to me, but someone else must approve Jenkins Builder: Verified diff --git a/pySim/esim/es9p.py b/pySim/esim/es9p.py index e923709..0315850 100644 --- a/pySim/esim/es9p.py +++ b/pySim/esim/es9p.py @@ -74,6 +74,7 @@ # ES9+ InitiateAuthentication function (SGP.22 section 6.5.2.6) class InitiateAuthentication(Es9PlusApiFunction): path = '/gsma/rsp2/es9plus/initiateAuthentication' + extra_http_req_headers = { 'User-Agent': 'gsma-rsp-lpad' } input_params = { 'euiccChallenge': ApiParamBase64, 'euiccInfo1': param.EuiccInfo1, @@ -94,6 +95,7 @@ # ES9+ GetBoundProfilePackage function (SGP.22 section 6.5.2.7) class GetBoundProfilePackage(Es9PlusApiFunction): path = '/gsma/rsp2/es9plus/getBoundProfilePackage' + extra_http_req_headers = { 'User-Agent': 'gsma-rsp-lpad' } input_params = { 'transactionId': param.TransactionId, 'prepareDownloadResponse': param.PrepareDownloadResponse, @@ -109,6 +111,7 @@ # ES9+ AuthenticateClient function (SGP.22 section 6.5.2.8) class AuthenticateClient(Es9PlusApiFunction): path= '/gsma/rsp2/es9plus/authenticateClient' + extra_http_req_headers = { 'User-Agent': 'gsma-rsp-lpad' } input_params = { 'transactionId': param.TransactionId, 'authenticateServerResponse': param.AuthenticateServerResponse, @@ -128,6 +131,7 @@ # ES9+ HandleNotification function (SGP.22 section 6.5.2.9) class HandleNotification(Es9PlusApiFunction): path = '/gsma/rsp2/es9plus/handleNotification' + extra_http_req_headers = { 'User-Agent': 'gsma-rsp-lpad' } input_params = { 'pendingNotification': param.PendingNotification, } @@ -136,6 +140,7 @@ # ES9+ CancelSession function (SGP.22 section 6.5.2.10) class CancelSession(Es9PlusApiFunction): path = '/gsma/rsp2/es9plus/cancelSession' + extra_http_req_headers = { 'User-Agent': 'gsma-rsp-lpad' } input_params = { 'transactionId': param.TransactionId, 'cancelSessionResponse': param.CancelSessionResponse, diff --git a/pySim/esim/http_json_api.py b/pySim/esim/http_json_api.py index d396b46..7d40f88 100644 --- a/pySim/esim/http_json_api.py +++ b/pySim/esim/http_json_api.py @@ -174,6 +174,7 @@ expected_http_status = 200 # the HTTP method used (GET, OPTIONS, HEAD, POST, PUT, PATCH or DELETE) http_method = 'POST' + extra_http_req_headers = {} def __init__(self, url_prefix: str, func_req_id: str, session: requests.Session): self.url_prefix = url_prefix @@ -232,19 +233,20 @@ is returned as json-deserialized dict.""" url = self.url_prefix + self.path encoded = json.dumps(self.encode(data, func_call_id)) - headers = { + req_headers = { 'Content-Type': 'application/json', 'X-Admin-Protocol': 'gsma/rsp/v2.5.0', } + req_headers.update(self.extra_http_req_headers) - logger.debug("HTTP REQ %s - '%s'" % (url, encoded)) - response = self.session.request(self.http_method, url, data=encoded, headers=headers, timeout=timeout) + logger.debug("HTTP REQ %s - hdr: %s '%s'" % (url, req_headers, encoded)) + response = self.session.request(self.http_method, url, data=encoded, headers=req_headers, timeout=timeout) logger.debug("HTTP RSP-STS: [%u] hdr: %s" % (response.status_code, response.headers)) logger.debug("HTTP RSP: %s" % (response.content)) if response.status_code != self.expected_http_status: raise HttpStatusError(response) - if not response.headers.get('Content-Type').startswith(headers['Content-Type']): + if not response.headers.get('Content-Type').startswith(req_headers['Content-Type']): raise HttpHeaderError(response) if not response.headers.get('X-Admin-Protocol', 'gsma/rsp/v2.unknown').startswith('gsma/rsp/v2.'): raise HttpHeaderError(response) -- To view, visit https://gerrit.osmocom.org/c/pysim/+/37007?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Iffe64d82087940a82fbfa73bf5d2b7e864ae5d67 Gerrit-Change-Number: 37007 Gerrit-PatchSet: 4 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: osmith <osmith(a)sysmocom.de> Gerrit-MessageType: merged
1 0
0 0
[L] Change in pysim[master]: add contrib/es9p_client: Perform ES9+ client functions like LPA+eUICC
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/36974?usp=email ) Change subject: add contrib/es9p_client: Perform ES9+ client functions like LPA+eUICC ...................................................................... add contrib/es9p_client: Perform ES9+ client functions like LPA+eUICC This tool can be used to test the SM-DP+. It implements the full dance of all HTTPs API operations to get to the downloadProfile, and will decrypt the BPP to the UPP, which is then subsequently stored as file on disk. Needless to say, this will only work if you have an eUICC certificate + private key that is compatible with the CI of your SM-DP+. Change-Id: Idf8881e82f9835f5221c58b78ced9937cf5fb520 --- A contrib/es9p_client.py M pySim/esim/es8p.py 2 files changed, 337 insertions(+), 1 deletion(-) Approvals: laforge: Looks good to me, approved Jenkins Builder: Verified diff --git a/contrib/es9p_client.py b/contrib/es9p_client.py new file mode 100755 index 0000000..09ae7cd --- /dev/null +++ b/contrib/es9p_client.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 + +# (C) 2024 by Harald Welte <laforge(a)osmocom.org> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import os +import sys +import argparse +import logging +import hashlib + +from typing import List +from urllib.parse import urlparse + +from cryptography import x509 +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from cryptography.hazmat.primitives.asymmetric import ec + +import pySim.esim.rsp as rsp +from pySim.esim import es9p +from pySim.utils import h2b, b2h, swap_nibbles, bertlv_parse_one_rawtag, bertlv_return_one_rawtlv +from pySim.esim.x509_cert import CertAndPrivkey +from pySim.esim.es8p import BoundProfilePackage + +logging.basicConfig(level=logging.DEBUG) + +parser = argparse.ArgumentParser(description=""" +Utility to manually issue requests against the ES9+ API of an SM-DP+ according to GSMA SGP.22.""") +parser.add_argument('--url', required=True, help='Base URL of ES9+ API endpoint') +parser.add_argument('--id', default='osmocom pySim', help='Entity identifier passed to SM-DP+') +parser.add_argument('--server-ca-cert', help="""X.509 CA certificates acceptable for the server side. In + production use cases, this would be the GSMA Root CA (CI) certificate.""") +subparsers = parser.add_subparsers(dest='command',help="The command (API function) to call", required=True) + +parser_dl = subparsers.add_parser('download', help="ES9+ download") +parser_dl.add_argument('--certificate-path', default='.', + help="Path in which to look for certificate and key files.") +parser_dl.add_argument('--euicc-certificate', default='CERT_EUICC_ECDSA_NIST.der', + help="File name of DER-encoded eUICC certificate file.") +parser_dl.add_argument('--euicc-private-key', default='SK_EUICC_ECDSA_NIST.pem', + help="File name of PEM-format eUICC secret key file.") +parser_dl.add_argument('--eum-certificate', default='CERT_EUM_ECDSA_NIST.der', + help="File name of DER-encoded EUM certificate file.") +parser_dl.add_argument('--ci-certificate', default='CERT_CI_ECDSA_NIST.der', + help="File name of DER-encoded CI certificate file.") +parser_dl.add_argument('--matchingId', required=True, + help='MatchingID that shall be used by profile download') +parser_dl.add_argument('--output-path', default='.', + help="Path to which the output files will be written.") +parser_dl.add_argument('--confirmation-code', + help="Confirmation Code for the eSIM download") + + +def do_download(opts): + + cert_and_key = CertAndPrivkey() + cert_and_key.cert_from_der_file(os.path.join(opts.certificate_path, opts.euicc_certificate)) + cert_and_key.privkey_from_pem_file(os.path.join(opts.certificate_path, opts.euicc_private_key)) + + with open(os.path.join(opts.certificate_path, opts.eum_certificate), 'rb') as f: + eum_cert = x509.load_der_x509_certificate(f.read()) + + with open(os.path.join(opts.certificate_path, opts.ci_certificate), 'rb') as f: + ci_cert = x509.load_der_x509_certificate(f.read()) + subject_exts = list(filter(lambda x: isinstance(x.value, x509.SubjectKeyIdentifier), ci_cert.extensions)) + subject_pkid = subject_exts[0].value + ci_pkid = subject_pkid.key_identifier + + print("EUICC: %s" % cert_and_key.cert.subject) + print("EUM: %s" % eum_cert.subject) + print("CI: %s" % ci_cert.subject) + + eid = cert_and_key.cert.subject.get_attributes_for_oid(x509.oid.NameOID.SERIAL_NUMBER)[0].value + print("EID: %s" % eid) + print("CI PKID: %s" % b2h(ci_pkid)) + print() + + peer = es9p.Es9pApiClient(opts.url, opts.id, server_cert_verify=opts.server_ca_cert) + + print("Step 1: InitiateAuthentication...") + + euiccInfo1 = { + 'svn': b'\x02\x04\x00', + 'euiccCiPKIdListForVerification': [ + ci_pkid, + ], + 'euiccCiPKIdListForSigning': [ + ci_pkid, + ], + } + + data = { + 'euiccChallenge': os.urandom(16), + 'euiccInfo1': euiccInfo1, + 'smdpAddress': urlparse(opts.url).netloc, + } + init_auth_res = peer.call_initiateAuthentication(data) + print(init_auth_res) + + print("Step 2: AuthenticateClient...") + + #res['serverSigned1'] + #res['serverSignature1'] + print("TODO: verify serverSignature1 over serverSigned1") + #res['transactionId'] + print("TODO: verify transactionId matches the signed one in serverSigned1") + #res['euiccCiPKIdToBeUsed'] + # TODO: select eUICC certificate based on CI + #res['serverCertificate'] + # TODO: verify server certificate against CI + + euiccInfo2 = { + 'profileVersion': b'\x02\x03\x01', + 'svn': euiccInfo1['svn'], + 'euiccFirmwareVer': b'\x23\x42\x00', + 'extCardResource': b'\x81\x01\x00\x82\x04\x00\x04\x9ch\x83\x02"#', + 'uiccCapability': (b'k6\xd3\xc3', 32), + 'javacardVersion': b'\x11\x02\x00', + 'globalplatformVersion': b'\x02\x03\x00', + 'rspCapability': (b'\x9c', 6), + 'euiccCiPKIdListForVerification': euiccInfo1['euiccCiPKIdListForVerification'], + 'euiccCiPKIdListForSigning': euiccInfo1['euiccCiPKIdListForSigning'], + #'euiccCategory': + #'forbiddenProfilePolicyRules': + 'ppVersion': b'\x01\x00\x00', + 'sasAcreditationNumber': 'OSMOCOM-TEST-1', #TODO: make configurable + #'certificationDataObject': + } + + euiccSigned1 = { + 'transactionId': h2b(init_auth_res['transactionId']), + 'serverAddress': init_auth_res['serverSigned1']['serverAddress'], + 'serverChallenge': init_auth_res['serverSigned1']['serverChallenge'], + 'euiccInfo2': euiccInfo2, + 'ctxParams1': + ('ctxParamsForCommonAuthentication', { + 'matchingId': opts.matchingId, + 'deviceInfo': { + 'tac': b'\x00'*8, + 'deviceCapabilities': {}, + #imei: + } + }), + } + euiccSigned1_bin = rsp.asn1.encode('EuiccSigned1', euiccSigned1) + euiccSignature1 = cert_and_key.ecdsa_sign(euiccSigned1_bin) + auth_clnt_req = { + 'transactionId': init_auth_res['transactionId'], + 'authenticateServerResponse': + ('authenticateResponseOk', { + 'euiccSigned1': euiccSigned1, + 'euiccSignature1': euiccSignature1, + 'euiccCertificate': rsp.asn1.decode('Certificate', cert_and_key.get_cert_as_der()), + 'eumCertificate': rsp.asn1.decode('Certificate', eum_cert.public_bytes(Encoding.DER)) + }) + } + auth_clnt_res = peer.call_authenticateClient(auth_clnt_req) + print(auth_clnt_res) + #auth_clnt_res['transactionId'] + print("TODO: verify transactionId matches previous ones") + #auth_clnt_res['profileMetadata'] + # TODO: what's in here? + #auth_clnt_res['smdpSigned2']['bppEuiccOtpk'] + #auth_clnt_res['smdpSignature2'] + print("TODO: verify serverSignature2 over smdpSigned2") + + smdp_cert = x509.load_der_x509_certificate(auth_clnt_res['smdpCertificate']) + + print("Step 3: GetBoundProfilePackage...") + # Generate a one-time ECKA key pair (ot{PK,SK}.DP.ECKA) using the curve indicated by the Key Parameter + # Reference value of CERT.DPpb.ECDSA + euicc_ot = ec.generate_private_key(smdp_cert.public_key().public_numbers().curve) + + # extract the public key in (hopefully) the right format for the ES8+ interface + euicc_otpk = euicc_ot.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) + + euiccSigned2 = { + 'transactionId': h2b(auth_clnt_res['transactionId']), + 'euiccOtpk': euicc_otpk, + #hashCC + } + # check for smdpSigned2 ccRequiredFlag, and send it in PrepareDownloadRequest hashCc + if auth_clnt_res['smdpSigned2']['ccRequiredFlag']: + if not opts.confirmation_code: + raise ValueError('Confirmation Code required but not provided') + cc_hash = hashlib.sha256(opts.confirmation_code.encode('ascii')).digest() + euiccSigned2['hashCc'] = hashlib.sha256(cc_hash + euiccSigned2['transactionId']).digest() + euiccSigned2_bin = rsp.asn1.encode('EUICCSigned2', euiccSigned2) + euiccSignature2 = cert_and_key.ecdsa_sign(euiccSigned2_bin + auth_clnt_res['smdpSignature2']) + gbp_req = { + 'transactionId': auth_clnt_res['transactionId'], + 'prepareDownloadResponse': + ('downloadResponseOk', { + 'euiccSigned2': euiccSigned2, + 'euiccSignature2': euiccSignature2, + }) + } + gbp_res = peer.call_getBoundProfilePackage(gbp_req) + print(gbp_res) + #gbp_res['transactionId'] + # TODO: verify transactionId + print("TODO: verify transactionId matches previous ones") + bpp_bin = gbp_res['boundProfilePackage'] + print("TODO: verify boundProfilePackage smdpSignature") + + bpp = BoundProfilePackage() + upp_bin = bpp.decode(euicc_ot, eid, bpp_bin) + + iccid = swap_nibbles(b2h(bpp.storeMetadataRequest['iccid'])) + base_name = os.path.join(opts.output_path, '%s' % iccid) + + print("SUCCESS: Storing files as %s.*.der" % base_name) + + # write various output files + with open(base_name+'.upp.der', 'wb') as f: + f.write(bpp.upp) + with open(base_name+'.isdp.der', 'wb') as f: + f.write(bpp.encoded_configureISDPRequest) + with open(base_name+'.smr.der', 'wb') as f: + f.write(bpp.encoded_storeMetadataRequest) + + +if __name__ == '__main__': + opts = parser.parse_args() + + if opts.command == 'download': + do_download(opts) diff --git a/pySim/esim/es8p.py b/pySim/esim/es8p.py index 81b0fc9..ff266ce 100644 --- a/pySim/esim/es8p.py +++ b/pySim/esim/es8p.py @@ -17,7 +17,11 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. from typing import Dict, List, Optional -from pySim.utils import b2h, h2b, bertlv_encode_tag, bertlv_encode_len + +from cryptography.hazmat.primitives.asymmetric import ec + +from pySim.utils import b2h, h2b, bertlv_encode_tag, bertlv_encode_len, bertlv_parse_one_rawtag +from pySim.utils import bertlv_return_one_rawtlv import pySim.esim.rsp as rsp from pySim.esim.bsp import BspInstance @@ -183,3 +187,79 @@ # manual DER encode: wrap in outer SEQUENCE return bertlv_encode_tag(0xbf36) + bertlv_encode_len(len(bpp_seq)) + bpp_seq + + def decode(self, euicc_ot, eid: str, bpp_bin: bytes): + """Decode a BPP into the PPP and subsequently UPP. This is what happens inside an eUICC.""" + + def split_bertlv_sequence(sequence: bytes) -> List[bytes]: + remainder = sequence + ret = [] + while remainder: + _tag, _l, tlv, remainder = bertlv_return_one_rawtlv(remainder) + ret.append(tlv) + return ret + + # we don't use rsp.asn1.decode('boundProfilePackage') here, as the BSP needs + # fully encoded + MACed TLVs including their tag + length values. + #bpp = rsp.asn1.decode('BoundProfilePackage', bpp_bin) + + tag, _l, v, _remainder = bertlv_parse_one_rawtag(bpp_bin) + if len(_remainder): + raise ValueError('Excess data at end of TLV') + if tag != 0xbf36: + raise ValueError('Unexpected outer tag: %s' % tag) + + # InitialiseSecureChannelRequest + tag, _l, iscr_bin, remainder = bertlv_return_one_rawtlv(v) + iscr = rsp.asn1.decode('InitialiseSecureChannelRequest', iscr_bin) + + # configureIsdpRequest + tag, _l, firstSeqOf87, remainder = bertlv_parse_one_rawtag(remainder) + if tag != 0xa0: + raise ValueError("Unexpected 'firstSequenceOf87' tag: %s" % tag) + firstSeqOf87 = split_bertlv_sequence(firstSeqOf87) + + # storeMetadataRequest + tag, _l, seqOf88, remainder = bertlv_parse_one_rawtag(remainder) + if tag != 0xa1: + raise ValueError("Unexpected 'sequenceOf88' tag: %s" % tag) + seqOf88 = split_bertlv_sequence(seqOf88) + + tag, _l, tlv, remainder = bertlv_parse_one_rawtag(remainder) + if tag == 0xa2: + secondSeqOf87 = split_bertlv_sequence(tlv) + tag2, _l, seqOf86, remainder = bertlv_parse_one_rawtag(remainder) + if tag2 != 0xa3: + raise ValueError("Unexpected 'sequenceOf86' tag: %s" % tag) + seqOf86 = split_bertlv_sequence(seqOf86) + elif tag == 0xa3: + secondSeqOf87 = None + seqOf86 = split_bertlv_sequence(tlv) + else: + raise ValueError("Unexpected 'secondSequenceOf87' tag: %s" % tag) + + # extract smdoOtpk from initialiseSecureChannel + smdp_otpk = iscr['smdpOtpk'] + + # Generate Session Keys using the CRT, opPK.DP.ECKA and otSK.EUICC.ECKA according to annex G + smdp_public_key = ec.EllipticCurvePublicKey.from_encoded_point(euicc_ot.curve, smdp_otpk) + self.shared_secret = euicc_ot.exchange(ec.ECDH(), smdp_public_key) + + crt = iscr['controlRefTemplate'] + bsp = BspInstance.from_kdf(self.shared_secret, int.from_bytes(crt['keyType'], 'big'), int.from_bytes(crt['keyLen'], 'big'), crt['hostId'], h2b(eid)) + + self.encoded_configureISDPRequest = bsp.demac_and_decrypt(firstSeqOf87) + self.configureISDPRequest = rsp.asn1.decode('ConfigureISDPRequest', self.encoded_configureISDPRequest) + + self.encoded_storeMetadataRequest = bsp.demac_only(seqOf88) + self.storeMetadataRequest = rsp.asn1.decode('StoreMetadataRequest', self.encoded_storeMetadataRequest) + + if secondSeqOf87 != None: + rsk_bin = bsp.demac_and_decrypt(secondSeqOf87) + rsk = rsp.asn1.decode('ReplaceSessionKeysRequest', rsk_bin) + # process replace_session_keys! + bsp = BspInstance(rsk['ppkEnc'], rsk['ppkCmac'], rsk['initialMacChainingValue']) + self.replaceSessionKeysRequest = rsk + + self.upp = bsp.demac_and_decrypt(seqOf86) + return self.upp -- To view, visit https://gerrit.osmocom.org/c/pysim/+/36974?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Idf8881e82f9835f5221c58b78ced9937cf5fb520 Gerrit-Change-Number: 36974 Gerrit-PatchSet: 5 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-CC: osmith <osmith(a)sysmocom.de> Gerrit-MessageType: merged
1 0
0 0
[M] Change in pysim[master]: esim.es9p: Suppress sending requestHeader on ES9+
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/37008?usp=email ) Change subject: esim.es9p: Suppress sending requestHeader on ES9+ ...................................................................... esim.es9p: Suppress sending requestHeader on ES9+ SGP.22 states that ES9+ should not include a requestHeader Change-Id: Ic9aa874a82241d7b26e2bcb0423961173e103020 --- M contrib/es9p_client.py M pySim/esim/es9p.py M pySim/esim/http_json_api.py 3 files changed, 34 insertions(+), 28 deletions(-) Approvals: osmith: Looks good to me, but someone else must approve fixeria: Looks good to me, but someone else must approve laforge: Looks good to me, approved Jenkins Builder: Verified diff --git a/contrib/es9p_client.py b/contrib/es9p_client.py index 09ae7cd..a221035 100755 --- a/contrib/es9p_client.py +++ b/contrib/es9p_client.py @@ -39,7 +39,6 @@ parser = argparse.ArgumentParser(description=""" Utility to manually issue requests against the ES9+ API of an SM-DP+ according to GSMA SGP.22.""") parser.add_argument('--url', required=True, help='Base URL of ES9+ API endpoint') -parser.add_argument('--id', default='osmocom pySim', help='Entity identifier passed to SM-DP+') parser.add_argument('--server-ca-cert', help="""X.509 CA certificates acceptable for the server side. In production use cases, this would be the GSMA Root CA (CI) certificate.""") subparsers = parser.add_subparsers(dest='command',help="The command (API function) to call", required=True) @@ -87,7 +86,7 @@ print("CI PKID: %s" % b2h(ci_pkid)) print() - peer = es9p.Es9pApiClient(opts.url, opts.id, server_cert_verify=opts.server_ca_cert) + peer = es9p.Es9pApiClient(opts.url, server_cert_verify=opts.server_ca_cert) print("Step 1: InitiateAuthentication...") diff --git a/pySim/esim/es9p.py b/pySim/esim/es9p.py index 0315850..41f2eeb 100644 --- a/pySim/esim/es9p.py +++ b/pySim/esim/es9p.py @@ -148,35 +148,29 @@ input_mandatory = ['transactionId', 'cancelSessionResponse'] class Es9pApiClient: - def __init__(self, url_prefix:str, func_req_id:str, server_cert_verify: str = None): - self.func_id = 0 + def __init__(self, url_prefix:str, server_cert_verify: str = None): self.session = requests.Session() self.session.verify = False # FIXME HACK if server_cert_verify: self.session.verify = server_cert_verify - self.initiateAuthentication = InitiateAuthentication(url_prefix, func_req_id, self.session) - self.authenticateClient = AuthenticateClient(url_prefix, func_req_id, self.session) - self.getBoundProfilePackage = GetBoundProfilePackage(url_prefix, func_req_id, self.session) - self.handleNotification = HandleNotification(url_prefix, func_req_id, self.session) - self.cancelSession = CancelSession(url_prefix, func_req_id, self.session) - - def _gen_func_id(self) -> str: - """Generate the next function call id.""" - self.func_id += 1 - return 'FCI-%u-%u' % (time.time(), self.func_id) + self.initiateAuthentication = InitiateAuthentication(url_prefix, '', self.session) + self.authenticateClient = AuthenticateClient(url_prefix, '', self.session) + self.getBoundProfilePackage = GetBoundProfilePackage(url_prefix, '', self.session) + self.handleNotification = HandleNotification(url_prefix, '', self.session) + self.cancelSession = CancelSession(url_prefix, '', self.session) def call_initiateAuthentication(self, data: dict) -> dict: - return self.initiateAuthentication.call(data, self._gen_func_id()) + return self.initiateAuthentication.call(data) def call_authenticateClient(self, data: dict) -> dict: - return self.authenticateClient.call(data, self._gen_func_id()) + return self.authenticateClient.call(data) def call_getBoundProfilePackage(self, data: dict) -> dict: - return self.getBoundProfilePackage.call(data, self._gen_func_id()) + return self.getBoundProfilePackage.call(data) def call_handleNotification(self, data: dict) -> dict: - return self.handleNotification.call(data, self._gen_func_id()) + return self.handleNotification.call(data) def call_cancelSession(self, data: dict) -> dict: - return self.cancelSession.call(data, self._gen_func_id()) + return self.cancelSession.call(data) diff --git a/pySim/esim/http_json_api.py b/pySim/esim/http_json_api.py index 7d40f88..377faea 100644 --- a/pySim/esim/http_json_api.py +++ b/pySim/esim/http_json_api.py @@ -19,6 +19,7 @@ import requests import logging import json +from typing import Optional import base64 logger = logging.getLogger(__name__) @@ -176,19 +177,20 @@ http_method = 'POST' extra_http_req_headers = {} - def __init__(self, url_prefix: str, func_req_id: str, session: requests.Session): + def __init__(self, url_prefix: str, func_req_id: Optional[str], session: requests.Session): self.url_prefix = url_prefix self.func_req_id = func_req_id self.session = session - def encode(self, data: dict, func_call_id: str) -> dict: + def encode(self, data: dict, func_call_id: Optional[str] = None) -> dict: """Validate an encode input dict into JSON-serializable dict for request body.""" - output = { - 'header': { - 'functionRequesterIdentifier': self.func_req_id, - 'functionCallIdentifier': func_call_id - } - } + output = {} + if func_call_id: + output['header'] = { + 'functionRequesterIdentifier': self.func_req_id, + 'functionCallIdentifier': func_call_id + } + for p in self.input_mandatory: if not p in data: raise ValueError('Mandatory input parameter %s missing' % p) @@ -227,7 +229,7 @@ output[p] = p_class.decode(v) return output - def call(self, data: dict, func_call_id:str, timeout=10) -> dict: + def call(self, data: dict, func_call_id: Optional[str] = None, timeout=10) -> dict: """Make an API call to the HTTP API endpoint represented by this object. Input data is passed in `data` as json-serializable dict. Output data is returned as json-deserialized dict.""" -- To view, visit https://gerrit.osmocom.org/c/pysim/+/37008?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Ic9aa874a82241d7b26e2bcb0423961173e103020 Gerrit-Change-Number: 37008 Gerrit-PatchSet: 4 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: osmith <osmith(a)sysmocom.de> Gerrit-MessageType: merged
1 0
0 0
[M] Change in pysim[master]: add pySim.esim.es9p with definitions of the ES9+ HTTP Interface
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/36973?usp=email ) Change subject: add pySim.esim.es9p with definitions of the ES9+ HTTP Interface ...................................................................... add pySim.esim.es9p with definitions of the ES9+ HTTP Interface Let's use the infrastructure of pySim.esim.http_json_api to define the ES9+ API Functions. This can in turn be used by clients or even osmo-smdpp can be ported over to using this infratructure rather than open-coding a lot of the encoding/decoding of API request/response parameters. Change-Id: I194ef1d186391f36245c099cc70a4813185ecf9c --- A pySim/esim/es9p.py 1 file changed, 192 insertions(+), 0 deletions(-) Approvals: laforge: Looks good to me, approved Jenkins Builder: Verified diff --git a/pySim/esim/es9p.py b/pySim/esim/es9p.py new file mode 100644 index 0000000..e923709 --- /dev/null +++ b/pySim/esim/es9p.py @@ -0,0 +1,177 @@ +"""GSMA eSIM RSP ES9+ interface according ot SGP.22 v2.5""" + +# (C) 2024 by Harald Welte <laforge(a)osmocom.org> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import requests +import logging +import time + +import pySim.esim.rsp as rsp +from pySim.esim.http_json_api import * + +logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + +class param: + class RspAsn1Par(ApiParamBase64): + """Generalized RSP ASN.1 parameter: base64-wrapped ASN.1 DER. Derived classes must provide + the asn1_type class variable to indicate the name of the ASN.1 type to use for encode/decode.""" + asn1_type = None # must be overridden by derived class + + @classmethod + def _decode(cls, data): + data = ApiParamBase64.decode(data) + return rsp.asn1.decode(cls.asn1_type, data) + + @classmethod + def _encode(cls, data): + data = rsp.asn1.encode(cls.asn1_type, data) + return ApiParamBase64.encode(data) + + class EuiccInfo1(RspAsn1Par): + asn1_type = 'EUICCInfo1' + + class ServerSigned1(RspAsn1Par): + asn1_type = 'ServerSigned1' + + class PrepareDownloadResponse(RspAsn1Par): + asn1_type = 'PrepareDownloadResponse' + + class AuthenticateServerResponse(RspAsn1Par): + asn1_type = 'AuthenticateServerResponse' + + class SmdpSigned2(RspAsn1Par): + asn1_type = 'SmdpSigned2' + + class StoreMetadataRequest(RspAsn1Par): + asn1_type = 'StoreMetadataRequest' + + class PendingNotification(RspAsn1Par): + asn1_type = 'PendingNotification' + + class CancelSessionResponse(RspAsn1Par): + asn1_type = 'CancelSessionResponse' + + class TransactionId(ApiParamString): + pass + +class Es9PlusApiFunction(JsonHttpApiFunction): + pass + +# ES9+ InitiateAuthentication function (SGP.22 section 6.5.2.6) +class InitiateAuthentication(Es9PlusApiFunction): + path = '/gsma/rsp2/es9plus/initiateAuthentication' + input_params = { + 'euiccChallenge': ApiParamBase64, + 'euiccInfo1': param.EuiccInfo1, + 'smdpAddress': SmdpAddress, + } + input_mandatory = ['euiccChallenge', 'euiccInfo1', 'smdpAddress'] + output_params = { + 'header': JsonResponseHeader, + 'transactionId': param.TransactionId, + 'serverSigned1': param.ServerSigned1, + 'serverSignature1': ApiParamBase64, + 'euiccCiPKIdToBeUsed': ApiParamBase64, + 'serverCertificate': ApiParamBase64, + } + output_mandatory = ['header', 'transactionId', 'serverSigned1', 'serverSignature1', + 'euiccCiPKIdToBeUsed', 'serverCertificate'] + +# ES9+ GetBoundProfilePackage function (SGP.22 section 6.5.2.7) +class GetBoundProfilePackage(Es9PlusApiFunction): + path = '/gsma/rsp2/es9plus/getBoundProfilePackage' + input_params = { + 'transactionId': param.TransactionId, + 'prepareDownloadResponse': param.PrepareDownloadResponse, + } + input_mandatory = ['transactionId', 'prepareDownloadResponse'] + output_params = { + 'header': JsonResponseHeader, + 'transactionId': param.TransactionId, + 'boundProfilePackage': ApiParamBase64, + } + output_mandatory = ['header', 'transactionId', 'boundProfilePackage'] + +# ES9+ AuthenticateClient function (SGP.22 section 6.5.2.8) +class AuthenticateClient(Es9PlusApiFunction): + path= '/gsma/rsp2/es9plus/authenticateClient' + input_params = { + 'transactionId': param.TransactionId, + 'authenticateServerResponse': param.AuthenticateServerResponse, + } + input_mandatory = ['transactionId', 'authenticateServerResponse'] + output_params = { + 'header': JsonResponseHeader, + 'transactionId': param.TransactionId, + 'profileMetadata': param.StoreMetadataRequest, + 'smdpSigned2': param.SmdpSigned2, + 'smdpSignature2': ApiParamBase64, + 'smdpCertificate': ApiParamBase64, + } + output_mandatory = ['header', 'transactionId', 'profileMetadata', 'smdpSigned2', + 'smdpSignature2', 'smdpCertificate'] + +# ES9+ HandleNotification function (SGP.22 section 6.5.2.9) +class HandleNotification(Es9PlusApiFunction): + path = '/gsma/rsp2/es9plus/handleNotification' + input_params = { + 'pendingNotification': param.PendingNotification, + } + input_mandatory = ['pendingNotification'] + +# ES9+ CancelSession function (SGP.22 section 6.5.2.10) +class CancelSession(Es9PlusApiFunction): + path = '/gsma/rsp2/es9plus/cancelSession' + input_params = { + 'transactionId': param.TransactionId, + 'cancelSessionResponse': param.CancelSessionResponse, + } + input_mandatory = ['transactionId', 'cancelSessionResponse'] + +class Es9pApiClient: + def __init__(self, url_prefix:str, func_req_id:str, server_cert_verify: str = None): + self.func_id = 0 + self.session = requests.Session() + self.session.verify = False # FIXME HACK + if server_cert_verify: + self.session.verify = server_cert_verify + + self.initiateAuthentication = InitiateAuthentication(url_prefix, func_req_id, self.session) + self.authenticateClient = AuthenticateClient(url_prefix, func_req_id, self.session) + self.getBoundProfilePackage = GetBoundProfilePackage(url_prefix, func_req_id, self.session) + self.handleNotification = HandleNotification(url_prefix, func_req_id, self.session) + self.cancelSession = CancelSession(url_prefix, func_req_id, self.session) + + def _gen_func_id(self) -> str: + """Generate the next function call id.""" + self.func_id += 1 + return 'FCI-%u-%u' % (time.time(), self.func_id) + + def call_initiateAuthentication(self, data: dict) -> dict: + return self.initiateAuthentication.call(data, self._gen_func_id()) + + def call_authenticateClient(self, data: dict) -> dict: + return self.authenticateClient.call(data, self._gen_func_id()) + + def call_getBoundProfilePackage(self, data: dict) -> dict: + return self.getBoundProfilePackage.call(data, self._gen_func_id()) + + def call_handleNotification(self, data: dict) -> dict: + return self.handleNotification.call(data, self._gen_func_id()) + + def call_cancelSession(self, data: dict) -> dict: + return self.cancelSession.call(data, self._gen_func_id()) -- To view, visit https://gerrit.osmocom.org/c/pysim/+/36973?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I194ef1d186391f36245c099cc70a4813185ecf9c Gerrit-Change-Number: 36973 Gerrit-PatchSet: 6 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: osmith <osmith(a)sysmocom.de> Gerrit-MessageType: merged
1 0
0 0
[S] Change in pysim[master]: pySim/cat: Fix "Decode the "Type of Comand" from numeric value to a s...
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/37136?usp=email ) Change subject: pySim/cat: Fix "Decode the "Type of Comand" from numeric value to a string" ...................................................................... pySim/cat: Fix "Decode the "Type of Comand" from numeric value to a string" This fixes a bug introduced in Change-Id: I833ec02bf281fe49de2be326018e91f521de52c0 Change-Id: I8b466c123173a5be335df3e1d77ef1c5f717a7d9 --- M pySim/cat.py 1 file changed, 12 insertions(+), 1 deletion(-) Approvals: Jenkins Builder: Verified laforge: Looks good to me, approved diff --git a/pySim/cat.py b/pySim/cat.py index 875806c..bfd22b4 100644 --- a/pySim/cat.py +++ b/pySim/cat.py @@ -1191,7 +1191,7 @@ pcmd.from_tlv(binary) cmd_details = pcmd.find_cmd_details() # then do a second decode stage for the specific - cmd_type = cmd_details.decoded['type_of_command'] + cmd_type = TypeOfCommand.encmapping[cmd_details.decoded['type_of_command']] if cmd_type in self.members_by_tag: cls = self.members_by_tag[cmd_type] inst = cls() -- To view, visit https://gerrit.osmocom.org/c/pysim/+/37136?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I8b466c123173a5be335df3e1d77ef1c5f717a7d9 Gerrit-Change-Number: 37136 Gerrit-PatchSet: 1 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-MessageType: merged
1 0
0 0
[L] Change in pysim[master]: esim.es2p: Split generic part of HTTP/REST API from ES2+
by laforge 09 Jun '24

09 Jun '24
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/36972?usp=email ) ( 5 is the latest approved patch-set. No files were changed between the latest approved patch-set and the submitted one. )Change subject: esim.es2p: Split generic part of HTTP/REST API from ES2+ ...................................................................... esim.es2p: Split generic part of HTTP/REST API from ES2+ This way we can reuse it for other eSIM RSP HTTP interfaces like ES9+, ES11, ... Change-Id: I468041da40a88875e8df15b04d3ad508e06f16f7 --- M pySim/esim/es2p.py A pySim/esim/http_json_api.py 2 files changed, 275 insertions(+), 234 deletions(-) Approvals: fixeria: Looks good to me, approved Jenkins Builder: Verified osmith: Looks good to me, but someone else must approve diff --git a/pySim/esim/es2p.py b/pySim/esim/es2p.py index fa21d2c..a73dd0c 100644 --- a/pySim/esim/es2p.py +++ b/pySim/esim/es2p.py @@ -15,98 +15,16 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -import abc import requests import logging -import json from datetime import datetime import time -import base64 + +from pySim.esim.http_json_api import * logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) -class ApiParam(abc.ABC): - """A class reprsenting a single parameter in the ES2+ API.""" - @classmethod - def verify_decoded(cls, data): - """Verify the decoded reprsentation of a value. Should raise an exception if somthing is odd.""" - pass - - @classmethod - def verify_encoded(cls, data): - """Verify the encoded reprsentation of a value. Should raise an exception if somthing is odd.""" - pass - - @classmethod - def encode(cls, data): - """[Validate and] Encode the given value.""" - cls.verify_decoded(data) - encoded = cls._encode(data) - cls.verify_decoded(encoded) - return encoded - - @classmethod - def _encode(cls, data): - """encoder function, typically [but not always] overridden by derived class.""" - return data - - @classmethod - def decode(cls, data): - """[Validate and] Decode the given value.""" - cls.verify_encoded(data) - decoded = cls._decode(data) - cls.verify_decoded(decoded) - return decoded - - @classmethod - def _decode(cls, data): - """decoder function, typically [but not always] overridden by derived class.""" - return data - -class ApiParamString(ApiParam): - """Base class representing an API parameter of 'string' type.""" - pass - - -class ApiParamInteger(ApiParam): - """Base class representing an API parameter of 'integer' type.""" - @classmethod - def _decode(cls, data): - return int(data) - - @classmethod - def _encode(cls, data): - return str(data) - - @classmethod - def verify_decoded(cls, data): - if not isinstance(data, int): - raise TypeError('Expected an integer input data type') - - @classmethod - def verify_encoded(cls, data): - if isinstance(data, int): - return - if not data.isdecimal(): - raise ValueError('integer (%s) contains non-decimal characters' % data) - assert str(int(data)) == data - -class ApiParamBoolean(ApiParam): - """Base class representing an API parameter of 'boolean' type.""" - @classmethod - def _encode(cls, data): - return bool(data) - -class ApiParamFqdn(ApiParam): - """String, as a list of domain labels concatenated using the full stop (dot, period) character as - separator between labels. Labels are restricted to the Alphanumeric mode character set defined in table 5 - of ISO/IEC 18004""" - @classmethod - def verify_encoded(cls, data): - # FIXME - pass - class param: class Iccid(ApiParamString): """String representation of 19 or 20 digits, where the 20th digit MAY optionally be the padding @@ -172,9 +90,6 @@ class SmdsAddress(ApiParamFqdn): pass - class SmdpAddress(ApiParamFqdn): - pass - class ReleaseFlag(ApiParamBoolean): pass @@ -197,150 +112,12 @@ class NotificationPointStatus(ApiParam): pass - class ResultData(ApiParam): - @classmethod - def _decode(cls, data): - return base64.b64decode(data) + class ResultData(ApiParamBase64): + pass - @classmethod - def _encode(cls, data): - return base64.b64encode(data) - - class JsonResponseHeader(ApiParam): - """SGP.22 section 6.5.1.4.""" - @classmethod - def verify_decoded(cls, data): - fe_status = data.get('functionExecutionStatus') - if not fe_status: - raise ValueError('Missing mandatory functionExecutionStatus in header') - status = fe_status.get('status') - if not status: - raise ValueError('Missing mandatory status in header functionExecutionStatus') - if status not in ['Executed-Success', 'Executed-WithWarning', 'Failed', 'Expired']: - raise ValueError('Unknown/unspecified status "%s"' % status) - - -class HttpStatusError(Exception): - pass - -class HttpHeaderError(Exception): - pass - -class Es2PlusApiError(Exception): - """Exception representing an error at the ES2+ API level (status != Executed).""" - def __init__(self, func_ex_status: dict): - self.status = func_ex_status['status'] - sec = { - 'subjectCode': None, - 'reasonCode': None, - 'subjectIdentifier': None, - 'message': None, - } - actual_sec = func_ex_status.get('statusCodeData', None) - sec.update(actual_sec) - self.subject_code = sec['subjectCode'] - self.reason_code = sec['reasonCode'] - self.subject_id = sec['subjectIdentifier'] - self.message = sec['message'] - - def __str__(self): - return f'{self.status}("{self.subject_code}","{self.reason_code}","{self.subject_id}","{self.message}")' - -class Es2PlusApiFunction(abc.ABC): +class Es2PlusApiFunction(JsonHttpApiFunction): """Base classs for representing an ES2+ API Function.""" - # the below class variables are expected to be overridden in derived classes - - path = None - # dictionary of input parameters. key is parameter name, value is ApiParam class - input_params = {} - # list of mandatory input parameters - input_mandatory = [] - # dictionary of output parameters. key is parameter name, value is ApiParam class - output_params = {} - # list of mandatory output parameters (for successful response) - output_mandatory = [] - # expected HTTP status code of the response - expected_http_status = 200 - # the HTTP method used (GET, OPTIONS, HEAD, POST, PUT, PATCH or DELETE) - http_method = 'POST' - - def __init__(self, url_prefix: str, func_req_id: str, session): - self.url_prefix = url_prefix - self.func_req_id = func_req_id - self.session = session - - def encode(self, data: dict, func_call_id: str) -> dict: - """Validate an encode input dict into JSON-serializable dict for request body.""" - output = { - 'header': { - 'functionRequesterIdentifier': self.func_req_id, - 'functionCallIdentifier': func_call_id - } - } - for p in self.input_mandatory: - if not p in data: - raise ValueError('Mandatory input parameter %s missing' % p) - for p, v in data.items(): - p_class = self.input_params.get(p) - if not p_class: - logger.warning('Unexpected/unsupported input parameter %s=%s', p, v) - output[p] = v - else: - output[p] = p_class.encode(v) - return output - - - def decode(self, data: dict) -> dict: - """[further] Decode and validate the JSON-Dict of the respnse body.""" - output = {} - # let's first do the header, it's special - if not 'header' in data: - raise ValueError('Mandatory output parameter "header" missing') - hdr_class = self.output_params.get('header') - output['header'] = hdr_class.decode(data['header']) - - if output['header']['functionExecutionStatus']['status'] not in ['Executed-Success','Executed-WithWarning']: - raise Es2PlusApiError(output['header']['functionExecutionStatus']) - # we can only expect mandatory parameters to be present in case of successful execution - for p in self.output_mandatory: - if p == 'header': - continue - if not p in data: - raise ValueError('Mandatory output parameter "%s" missing' % p) - for p, v in data.items(): - p_class = self.output_params.get(p) - if not p_class: - logger.warning('Unexpected/unsupported output parameter "%s"="%s"', p, v) - output[p] = v - else: - output[p] = p_class.decode(v) - return output - - def call(self, data: dict, func_call_id:str, timeout=10) -> dict: - """Make an API call to the ES2+ API endpoint represented by this object. - Input data is passed in `data` as json-serializable dict. Output data - is returned as json-deserialized dict.""" - url = self.url_prefix + self.path - encoded = json.dumps(self.encode(data, func_call_id)) - headers = { - 'Content-Type': 'application/json', - 'X-Admin-Protocol': 'gsma/rsp/v2.5.0', - } - - logger.debug("HTTP REQ %s - '%s'" % (url, encoded)) - response = self.session.request(self.http_method, url, data=encoded, headers=headers, timeout=timeout) - logger.debug("HTTP RSP-STS: [%u] hdr: %s" % (response.status_code, response.headers)) - logger.debug("HTTP RSP: %s" % (response.content)) - - if response.status_code != self.expected_http_status: - raise HttpStatusError(response) - if not response.headers.get('Content-Type').startswith(headers['Content-Type']): - raise HttpHeaderError(response) - if not response.headers.get('X-Admin-Protocol', 'gsma/rsp/v2.unknown').startswith('gsma/rsp/v2.'): - raise HttpHeaderError(response) - - return self.decode(response.json()) - + pass # ES2+ DownloadOrder function (SGP.22 section 5.3.1) class DownloadOrder(Es2PlusApiFunction): @@ -351,7 +128,7 @@ 'profileType': param.ProfileType } output_params = { - 'header': param.JsonResponseHeader, + 'header': JsonResponseHeader, 'iccid': param.Iccid, } output_mandatory = ['header', 'iccid'] @@ -369,10 +146,10 @@ } input_mandatory = ['iccid', 'releaseFlag'] output_params = { - 'header': param.JsonResponseHeader, + 'header': JsonResponseHeader, 'eid': param.Eid, 'matchingId': param.MatchingId, - 'smdpAddress': param.SmdpAddress, + 'smdpAddress': SmdpAddress, } output_mandatory = ['header', 'matchingId'] @@ -387,7 +164,7 @@ } input_mandatory = ['finalProfileStatusIndicator', 'iccid'] output_params = { - 'header': param.JsonResponseHeader, + 'header': JsonResponseHeader, } output_mandatory = ['header'] @@ -399,7 +176,7 @@ } input_mandatory = ['iccid'] output_params = { - 'header': param.JsonResponseHeader, + 'header': JsonResponseHeader, } output_mandatory = ['header'] diff --git a/pySim/esim/http_json_api.py b/pySim/esim/http_json_api.py new file mode 100644 index 0000000..d396b46 --- /dev/null +++ b/pySim/esim/http_json_api.py @@ -0,0 +1,252 @@ +"""GSMA eSIM RSP HTTP/REST/JSON interface according to SGP.22 v2.5""" + +# (C) 2024 by Harald Welte <laforge(a)osmocom.org> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import abc +import requests +import logging +import json +import base64 + +logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + +class ApiParam(abc.ABC): + """A class reprsenting a single parameter in the API.""" + @classmethod + def verify_decoded(cls, data): + """Verify the decoded reprsentation of a value. Should raise an exception if somthing is odd.""" + pass + + @classmethod + def verify_encoded(cls, data): + """Verify the encoded reprsentation of a value. Should raise an exception if somthing is odd.""" + pass + + @classmethod + def encode(cls, data): + """[Validate and] Encode the given value.""" + cls.verify_decoded(data) + encoded = cls._encode(data) + cls.verify_decoded(encoded) + return encoded + + @classmethod + def _encode(cls, data): + """encoder function, typically [but not always] overridden by derived class.""" + return data + + @classmethod + def decode(cls, data): + """[Validate and] Decode the given value.""" + cls.verify_encoded(data) + decoded = cls._decode(data) + cls.verify_decoded(decoded) + return decoded + + @classmethod + def _decode(cls, data): + """decoder function, typically [but not always] overridden by derived class.""" + return data + +class ApiParamString(ApiParam): + """Base class representing an API parameter of 'string' type.""" + pass + + +class ApiParamInteger(ApiParam): + """Base class representing an API parameter of 'integer' type.""" + @classmethod + def _decode(cls, data): + return int(data) + + @classmethod + def _encode(cls, data): + return str(data) + + @classmethod + def verify_decoded(cls, data): + if not isinstance(data, int): + raise TypeError('Expected an integer input data type') + + @classmethod + def verify_encoded(cls, data): + if isinstance(data, int): + return + if not data.isdecimal(): + raise ValueError('integer (%s) contains non-decimal characters' % data) + assert str(int(data)) == data + +class ApiParamBoolean(ApiParam): + """Base class representing an API parameter of 'boolean' type.""" + @classmethod + def _encode(cls, data): + return bool(data) + +class ApiParamFqdn(ApiParam): + """String, as a list of domain labels concatenated using the full stop (dot, period) character as + separator between labels. Labels are restricted to the Alphanumeric mode character set defined in table 5 + of ISO/IEC 18004""" + @classmethod + def verify_encoded(cls, data): + # FIXME + pass + +class ApiParamBase64(ApiParam): + @classmethod + def _decode(cls, data): + return base64.b64decode(data) + + @classmethod + def _encode(cls, data): + return base64.b64encode(data).decode('ascii') + +class SmdpAddress(ApiParamFqdn): + pass + +class JsonResponseHeader(ApiParam): + """SGP.22 section 6.5.1.4.""" + @classmethod + def verify_decoded(cls, data): + fe_status = data.get('functionExecutionStatus') + if not fe_status: + raise ValueError('Missing mandatory functionExecutionStatus in header') + status = fe_status.get('status') + if not status: + raise ValueError('Missing mandatory status in header functionExecutionStatus') + if status not in ['Executed-Success', 'Executed-WithWarning', 'Failed', 'Expired']: + raise ValueError('Unknown/unspecified status "%s"' % status) + + +class HttpStatusError(Exception): + pass + +class HttpHeaderError(Exception): + pass + +class ApiError(Exception): + """Exception representing an error at the API level (status != Executed).""" + def __init__(self, func_ex_status: dict): + self.status = func_ex_status['status'] + sec = { + 'subjectCode': None, + 'reasonCode': None, + 'subjectIdentifier': None, + 'message': None, + } + actual_sec = func_ex_status.get('statusCodeData', None) + sec.update(actual_sec) + self.subject_code = sec['subjectCode'] + self.reason_code = sec['reasonCode'] + self.subject_id = sec['subjectIdentifier'] + self.message = sec['message'] + + def __str__(self): + return f'{self.status}("{self.subject_code}","{self.reason_code}","{self.subject_id}","{self.message}")' + +class JsonHttpApiFunction(abc.ABC): + """Base classs for representing an HTTP[s] API Function.""" + # the below class variables are expected to be overridden in derived classes + + path = None + # dictionary of input parameters. key is parameter name, value is ApiParam class + input_params = {} + # list of mandatory input parameters + input_mandatory = [] + # dictionary of output parameters. key is parameter name, value is ApiParam class + output_params = {} + # list of mandatory output parameters (for successful response) + output_mandatory = [] + # expected HTTP status code of the response + expected_http_status = 200 + # the HTTP method used (GET, OPTIONS, HEAD, POST, PUT, PATCH or DELETE) + http_method = 'POST' + + def __init__(self, url_prefix: str, func_req_id: str, session: requests.Session): + self.url_prefix = url_prefix + self.func_req_id = func_req_id + self.session = session + + def encode(self, data: dict, func_call_id: str) -> dict: + """Validate an encode input dict into JSON-serializable dict for request body.""" + output = { + 'header': { + 'functionRequesterIdentifier': self.func_req_id, + 'functionCallIdentifier': func_call_id + } + } + for p in self.input_mandatory: + if not p in data: + raise ValueError('Mandatory input parameter %s missing' % p) + for p, v in data.items(): + p_class = self.input_params.get(p) + if not p_class: + logger.warning('Unexpected/unsupported input parameter %s=%s', p, v) + output[p] = v + else: + output[p] = p_class.encode(v) + return output + + def decode(self, data: dict) -> dict: + """[further] Decode and validate the JSON-Dict of the respnse body.""" + output = {} + # let's first do the header, it's special + if not 'header' in data: + raise ValueError('Mandatory output parameter "header" missing') + hdr_class = self.output_params.get('header') + output['header'] = hdr_class.decode(data['header']) + + if output['header']['functionExecutionStatus']['status'] not in ['Executed-Success','Executed-WithWarning']: + raise ApiError(output['header']['functionExecutionStatus']) + # we can only expect mandatory parameters to be present in case of successful execution + for p in self.output_mandatory: + if p == 'header': + continue + if not p in data: + raise ValueError('Mandatory output parameter "%s" missing' % p) + for p, v in data.items(): + p_class = self.output_params.get(p) + if not p_class: + logger.warning('Unexpected/unsupported output parameter "%s"="%s"', p, v) + output[p] = v + else: + output[p] = p_class.decode(v) + return output + + def call(self, data: dict, func_call_id:str, timeout=10) -> dict: + """Make an API call to the HTTP API endpoint represented by this object. + Input data is passed in `data` as json-serializable dict. Output data + is returned as json-deserialized dict.""" + url = self.url_prefix + self.path + encoded = json.dumps(self.encode(data, func_call_id)) + headers = { + 'Content-Type': 'application/json', + 'X-Admin-Protocol': 'gsma/rsp/v2.5.0', + } + + logger.debug("HTTP REQ %s - '%s'" % (url, encoded)) + response = self.session.request(self.http_method, url, data=encoded, headers=headers, timeout=timeout) + logger.debug("HTTP RSP-STS: [%u] hdr: %s" % (response.status_code, response.headers)) + logger.debug("HTTP RSP: %s" % (response.content)) + + if response.status_code != self.expected_http_status: + raise HttpStatusError(response) + if not response.headers.get('Content-Type').startswith(headers['Content-Type']): + raise HttpHeaderError(response) + if not response.headers.get('X-Admin-Protocol', 'gsma/rsp/v2.unknown').startswith('gsma/rsp/v2.'): + raise HttpHeaderError(response) + + return self.decode(response.json()) -- To view, visit https://gerrit.osmocom.org/c/pysim/+/36972?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I468041da40a88875e8df15b04d3ad508e06f16f7 Gerrit-Change-Number: 36972 Gerrit-PatchSet: 6 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: osmith <osmith(a)sysmocom.de> Gerrit-MessageType: merged
1 0
0 0
[L] Change in pysim[master]: add contrib/es9p_client: Perform ES9+ client functions like LPA+eUICC
by laforge 09 Jun '24

09 Jun '24
Attention is currently required from: dexter, fixeria, osmith. laforge has posted comments on this change. ( https://gerrit.osmocom.org/c/pysim/+/36974?usp=email ) Change subject: add contrib/es9p_client: Perform ES9+ client functions like LPA+eUICC ...................................................................... Patch Set 5: Code-Review+2 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/36974?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Idf8881e82f9835f5221c58b78ced9937cf5fb520 Gerrit-Change-Number: 36974 Gerrit-PatchSet: 5 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-CC: osmith <osmith(a)sysmocom.de> Gerrit-Attention: osmith <osmith(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: dexter <pmaier(a)sysmocom.de> Gerrit-Comment-Date: Sun, 09 Jun 2024 10:20:13 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes Gerrit-MessageType: comment
1 0
0 0
[M] Change in pysim[master]: add pySim.esim.es9p with definitions of the ES9+ HTTP Interface
by laforge 09 Jun '24

09 Jun '24
Attention is currently required from: dexter, fixeria, osmith. laforge has posted comments on this change. ( https://gerrit.osmocom.org/c/pysim/+/36973?usp=email ) Change subject: add pySim.esim.es9p with definitions of the ES9+ HTTP Interface ...................................................................... Patch Set 6: Code-Review+2 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/36973?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I194ef1d186391f36245c099cc70a4813185ecf9c Gerrit-Change-Number: 36973 Gerrit-PatchSet: 6 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de> Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: osmith <osmith(a)sysmocom.de> Gerrit-Attention: osmith <osmith(a)sysmocom.de> Gerrit-Attention: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Attention: dexter <pmaier(a)sysmocom.de> Gerrit-Comment-Date: Sun, 09 Jun 2024 10:20:04 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes Gerrit-MessageType: comment
1 0
0 0
[S] Change in pysim[master]: pySim/cat: Fix "Decode the "Type of Comand" from numeric value to a s...
by laforge 09 Jun '24

09 Jun '24
laforge has posted comments on this change. ( https://gerrit.osmocom.org/c/pysim/+/37136?usp=email ) Change subject: pySim/cat: Fix "Decode the "Type of Comand" from numeric value to a string" ...................................................................... Patch Set 1: Code-Review+2 -- To view, visit https://gerrit.osmocom.org/c/pysim/+/37136?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I8b466c123173a5be335df3e1d77ef1c5f717a7d9 Gerrit-Change-Number: 37136 Gerrit-PatchSet: 1 Gerrit-Owner: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-CC: Jenkins Builder Gerrit-Comment-Date: Sun, 09 Jun 2024 10:19:53 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: Yes Gerrit-MessageType: comment
1 0
0 0
  • ← Newer
  • 1
  • ...
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • ...
  • 157
  • Older →

HyperKitty Powered by HyperKitty version 1.3.12.