def auth(request, slot): """REST API endpoint for performing authentication against a USIM. Expects a JSON body containing RAND and AUTN. Returns a JSON body containing RES, CK, IK and Kc.""" try: # there are two hex-string JSON parameters in the body: rand and autn content = json.loads(request.content.read()) rand = content['rand'] autn = content['autn'] except: request.setResponseCode(400) return "Malformed Request" try: tp = PcscSimLink(slot, apdu_tracer=ApduPrintTracer()) tp.connect() except ReaderError: request.setResponseCode(404) return "Specified SIM Slot doesn't exist" except ProtocolError: request.setResponseCode(500) return "Error" except NoCardError: request.setResponseCode(410) return "No SIM card inserted in slot" scc = SimCardCommands(tp) card = UsimCard(scc) # this should be part of UsimCard, but FairewavesSIM breaks with that :/ scc.cla_byte = "00" scc.sel_ctrl = "0004" try: card.read_aids() card.select_adf_by_aid(adf='usim') res, sw = scc.authenticate(rand, autn) except SwMatchError as e: request.setResponseCode(500) return "Communication Error %s" % e tp.disconnect() return json.dumps(res, indent=4)