def main(): known_ids = {} cardtype = AnyCardType() #times out every 0.5 seconds cardrequest = CardRequest( timeout=0.5, cardType=cardtype ) while True: try: # try to connect to a card, if the process # times out, continue cardservice = cardrequest.waitforcard() cardservice.connection.connect() # compare ATRs if ATR == cardservice.connection.getATR(): response, sw1, sw2 = \ cardservice.connection.transmit( APDU ) tagid = toHexString(response).replace(' ','') if tagid in known_ids: print "found uid" print tagid else: known_ids[tagid] = True print "new uid" print tagid # do appropriate things post_to_server(tagid) play_sound() except: continue
def update(self, observable, actions): try: readers = self._list() self.reader_name = readers[0] except: print_error("Error retreiving the reader") try: (addedcards, removedcards) = actions for card in addedcards: print_info(f"Reader 0: {self.reader_name}") print_ok_raw(f"Card State: Card inserted") print("ATR: ", toHexString(card.atr)) atr = ATR(card.atr) if (self.verbose): atr.dump() print() print_info( "Possible identified card (using _smartcard_list.txt)") self.search_in_txt('utildata/_smartcard_list.txt', toHexString(card.atr)) for card in removedcards: print_info(f"Reader 0: {self.reader_name}") print_error_raw(f"Card State: Card removed") print("ATR: ", toHexString(card.atr)) except Exception as e: pass
def sendisplay(self, apdudata, msg='', **kwargs): # 发送指令处理状态 status = label_pass try: response, sw1, sw2 = self.connection.transmit(toBytes(apdudata)) rtn_data = toHexString(response, PACK) rtn_sw = toHexString([sw1, sw2], PACK) # TODO 需要删除该语句 # self._showapdu(apdudata, rtn_data, kwargs['expectData'], rtn_sw, kwargs['SW']) except Exception: raise DeviceError('Send APDU Failed') else: if 'expect_data' in kwargs.keys(): expect_data = kwargs['expect_data'] else: expect_data = '' if 'sw' in kwargs.keys(): expect_sw = kwargs['sw'] else: expect_sw = '' if not self.checkdata(rtn_sw, expect_sw, rtn_data, expect_data): status = label_fail return rtn_data, rtn_sw, status
def read(self): # keyword to ask card id SELECT = [0xFF, 0xCA, 0x00, 0x00, 0x00] if debug: print "reading data" try: self.connection.connect() data, sw1, sw2 = self.connection.transmit( SELECT ) if debug: print "%x %x" % (sw1, sw2) #90 0 if debug: print data if format == 'hex' and reverse == 0: cardid = toHexString(data).replace(' ','') elif format == 'hex' and reverse == 1: cardid = toHexString(data[::-1]).replace(' ','') elif format == 'dec' and reverse == 0: cardid = toHexString(data).replace(' ','') cardid = int(cardid, 16) elif format == 'dec' and reverse == 1: cardid = toHexString(data[::-1]).replace(' ','') cardid = int(cardid, 16) if debug: print "cardid: %s" % cardid return cardid except: if debug: print "no card data" return False
def _process_card(self, connection): """This is where the magic happens""" self.reader.busy_signal(connection) self.logger.info(self.reader.card_description + ' card detected') self.logger.debug('ATR: ' + toHexString(self.reader.card_ATR)) card_serial_number = self.reader.get_serial_number(connection) if card_serial_number: self.logger.debug('UID: ' + toHexString(card_serial_number)) else: card_serial_number = [] self.logger.warn('No UID read!') # parse data definition and read data accordingly data_list = self._read_defined_data(connection) output_string = self.head + self.start1 + self.track1 + self.end if self.track2 != "": output_string += self.start2 + self.track2 + self.end if self.track3 != "": output_string += self.start3 + self.track3 + self.end output_string += self.tail self.key_stroker.send_string( self._process_output_string(output_string, card_serial_number, data_list)) self.reader.ready_signal(connection) connection.disconnect()
def update(self, observable, actions): global gCard (addedcards, removedcards) = actions for card in addedcards: if checkAtrMatch(card.atr): card.connection = card.createConnection() card.connection.connect() if VERBOSE: card.connection.addObserver(self.observer) response, sw1, sw2 = card.connection.transmit(SELECT) if sw1 == 0x61: second, sw1, sw2 = card.connection.transmit( GET_RESPONSE + [sw2]) response += second if sw1 == 0x90 and sw2 == 0x00: card.connection.setErrorCheckingChain(gErrorchain) gCard = card print('card added :', toHexString(card.atr).lower()) print('card reader:', card.connection.getReader()) # autoStartCard() will be called after 4 seconds Timer(4, lambda: autoStartCard()).start() break # just select first expected card for card in removedcards: if checkAtrMatch(card.atr): if gCard: print('card removed:', toHexString(card.atr).lower()) gCard = None
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: logger.info("+ Inserted: %s", toHexString(card.atr)) connection = card.createConnection() connection.connect() card.connection = connection.component # This will log raw card traffic to console connection.addObserver(ConsoleCardConnectionObserver()) # connection object itself is CardConnectionDecorator wrapper # and we need to address the underlying connection object # directly logger.debug("Opened connection %s", connection.component) desfire = DESFire(PCSCDevice(connection.component)) applications = desfire.get_applications() if FOOBAR_APP_ID in applications: consumer.attach_card(card) else: logger.warn( "DESFire card doesn't have the required application. Maybe not properly formatted?" ) for card in removedcards: logger.info("- Removed: %s", toHexString(card.atr)) consumer.detach_card(card)
def getApplications(self): # Select IPAY-application, find out what is listed. #response, sw1, sw2 = self.connection.transmit(SELECT + [len(IPAY)] + IPAY) response, sw1, sw2 = self.selectApplication(IPAY) print toHexString(response) if ((sw1 == 0x90) and (sw2 == 0x00)): # Find SFI (0x88) firstPSE = uglyParse(TAG_SFI, response) print "[!] First PSE Record at: ", toHexString(firstPSE) SFI = [((firstPSE[0] << 3) | 4)] print "SFI: ", SFI #record #1, for some "apparant" response, sw1, sw2 = self.readRecord([0x01] + SFI) offset = 0 answers = [] aid = uglyParse(TAG_AID, response, offset) al = uglyParse(TAG_AL, response, offset) while (len(aid) > 1): answers += [[aid, al]] offset += 1 aid = uglyParse(TAG_AID, response, offset) al = uglyParse(TAG_AL, response, offset) return answers return []
def get_card_id(connection): 'Get user card id ,But that could go wrong' global cardid CARDID1 = [0x00,0xb2,0x01,0x14,0x00] CARDID2 = [0x00,0xb2,0x01,0x0c,0x00] card,sw1,sw2 = connection.transmit(CARDID1) show_something(show_flag,'SEND INFORMATION',str(CARDID1)) card = toHexString(card) show_something(show_flag,'WAIT INFORMATION NOW',card) card = card.split(' ') for i in range(len(card)-1): if card[i] == '5A': for j in range(int(card[i+1],16)): cardid += card[i+2+j] cardid = cardid.replace('F','') break if len(cardid) < 8: card,sw1,sw2 = connection.transmit(CARDID2) show_something(show_flag,'SEND INFORMATION',str(CARDID2)) card = toHexString(card) print card show_something(show_flag,'WAIT INFORMATION NOW',card) card = card.split(' ') for i in range(len(card)-1): if card[i] == '57': for j in range(10): cardid += card[i+2+j] cardid = cardid.replace('D','') break
def scanButton(self): self.displayScan = Label(self.master, text="Scanning card...") self.displayScan.pack() self.cr = CardRequest(timeout=None, newcardonly=True) self.cardtype = "3B 8F 80 01 80 4F 0C A0 00 00 03 06 40 00 00 00 00 00 00 28" self.length = 10 self.cs = self.cr.waitforcard() self.cs.connection.connect() self.cs.card = toHexString(self.cs.connection.getATR()) self.SELECT = [0xFF, 0xCA, 0x00, 0x00, 0x00] self.response, self.sw1, self.sw2 = self.cs.connection.transmit( self.SELECT) self.texting = toHexString(self.response).replace(' ', '') self.word_len = len(self.texting) #print("Success!") if self.cs.card == self.cardtype and self.length == self.word_len: header() self.a = search_Student(self.texting) self.student = Label(self.master, text=self.a) self.student.pack() self.cs.connection.disconnect() formular() else: self.cs = self.cr.waitforcard() self.cs.connection.disconnect()
def send_to_tag(self, tag, apdu): if tag is not None: raise ValueError('Multiple tags not supported') HResult(smartcard.scard.SCardBeginTransaction(self.hcard)) if DEBUG: print('> %s' % toHexString(list(apdu))) response = HResult(smartcard.scard.SCardTransmit(self.hcard, smartcard.scard.SCARD_PCI_T0, list(apdu))) if DEBUG: print('< %s' % toHexString(response)) sw1, sw2 = response[0:2] if sw1 == 0x61: # More data apdu2 = APDU(0, 0xc0, lc=sw2) if DEBUG: print('> %s' % toHexString(list(apdu2))) response = HResult(smartcard.scard.SCardTransmit(self.hcard, smartcard.scard.SCARD_PCI_T0, list(apdu2))) if DEBUG: print('< %s' % toHexString(response)) HResult(smartcard.scard.SCardEndTransaction(self.hcard, smartcard.scard.SCARD_LEAVE_CARD)) return response
def __transmit(self, arg_apdu_cmd): log.debug(self.__class__.__name__, "TX> %s" % (toHexString(arg_apdu_cmd))) response, sw1, sw2 = self.__connection.transmit(arg_apdu_cmd) log.debug(self.__class__.__name__, "RX< %s, %02X %02X" % (toHexString(response), sw1, sw2)) return (response, sw1, sw2)
def run(self): found= False for reader in readers(): try: connection = reader.createConnection() connection.connect() ATR = toHexString(connection.getATR()) APDU = [0xFF,0xCA,0x00,0x00,0x00] data, sw1, sw2 = connection.transmit(APDU) UID= toHexString(data) except NoCardException: print(reader, 'no card inserted') except: self.signals.error.emit((reader, 'error !!')) else: found= True self.signals.result.emit(UID) finally: QThread.sleep(2) if(found): self.signals.finished.emit() else: self.signals.error.emit((reader,'aucune carte à proximité ou insérée !!!'))
def _readRecordApdu(self, sfi, record): #00B2020C00 #READ_RECORD={CLA:00, INS:B2, P1:02, P2:0C, Lc:00} record 02 form SFI 1 lst = [record] P1 = toHexString(lst) lst = [sfi << 3 | 1 << 2] P2 = toHexString(lst) return "00B2" + P1 + P2 + "00"
def run(self): while self.alive: # List of cards where we have lost connetion remove_cards = [] for card in self.cards: card_id = toHexString(card.atr) desfire = DESFire(PCSCDevice(card.connection)) try: desfire.select_application(FOOBAR_APP_ID) value = desfire.get_value(FOOBAR_STORED_VALUE_FILE_ID) if value > 0: logger.info("Card: %s value left: %d", card_id, value) desfire.debit_value(FOOBAR_STORED_VALUE_FILE_ID, 1) desfire.commit() else: logger.info("No value left on card: %s", card_id) except CardConnectionException: # Lost the card in the middle of transit logger.warn("Consumer lost the card %s", card_id) remove_cards.append(card) finally: pass for c in remove_cards: card_id = toHexString(card.atr) logger.debug("Consumer removing a bad card from itself: %s", card_id) self.detach_card(c) time.sleep(1)
def testcase_CardRequestNewCardInReaderNotPresentInfiniteTimeOut(self): """Test smartcard.CardRequest for any new card in a specific reader not present without time-out.""" print 'please remove a smart card reader' _readerz = readers() while True: readerz = readers() if len(_readerz) > len(readerz): break time.sleep(.1) for reader in readerz: _readerz.remove(reader) cardtype = AnyCardType() cardrequest = CardRequest( timeout=None, readers=[_readerz[0]], cardType=cardtype, newcardonly=True) print 'Re-insert reader ', _readerz[0], 'with a card inside' cardservice = cardrequest.waitforcard() cardservice.connection.connect() print toHexString( cardservice.connection.getATR()), \ 'in', cardservice.connection.getReader() cardservice.connection.disconnect()
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: self.flagk = "Tap" print("+Inserted: ", toHexString(card.atr)) card.connection = card.createConnection() card.connection.connect() card.connection.addObserver(self.observer) cmdott = [0xFF, 0x88, 0x00, Mifare1k[0], 0x60, 0x00] cmdbaca = [0xFF, 0xB0, 0x00, Mifare1k[0], 0x10] response, sw1, sw2 = card.connection.transmit(cmdott) print("Select Ott: %02X %02X" % (sw1, sw2)) if hex(sw1) == hex(144): # apdu = GET_RESPONSE + [sw2] data, sw1, sw2 = card.connection.transmit(cmdbaca) print("Select Baca: %02X %02X" % (sw1, sw2)) if hex(sw1) == hex(144): # InsertPresensi(toASCIIString(data)) # InsertTap(toASCIIString(data)) # UpdateTap("tap") print(toASCIIString(data)) for card in removedcards: self.flagk = "Remove" # UpdateTap("remove") print("-Removed: ", toHexString(card.atr))
def read_fp_from_card(): sc_readers = readers() print(sc_readers) # create a connection to the first reader first_reader = sc_readers[0] connection = first_reader.createConnection() # get ready for a command get_uid = util.toBytes("FF 20 00 00 02 FF FF") try: # send the command and capture the response data and status connection.connect() data, sw1, sw2 = connection.transmit(get_uid) # print the response uid = util.toHexString(data) status = util.toHexString([sw1, sw2]) print("UID = {}\tstatus = {}".format(uid, status)) read_payload = [] for i in range(0, 512, 64): read_command = [0xFF, 0xB0, i / 64, 0x00, 0x40] #get_uid = util.toBytes("FF B0 00 00 40") data, sw1, sw2 = connection.transmit(read_command) read_payload = read_payload + data print("UID = {}\tstatus = {}".format(util.toHexString(data), util.toHexString([sw1, sw2]))) print(read_payload) return read_payload except NoCardException: print("ERROR: Card not present") raise Exception("ERROR: Card not present")
def case_2e(self, full): # gets (1 to 256) data from the card # > 80 00 04 2A 00 00 07 # < 2A 2A 2A 2A 2A 2A 2A 90 0 magic_value = 42 CASE_2 = toBytes("80 00 04 00 00 00 00") CASE_2[3] = magic_value print "Case 2 extended" print # ATRs of the Athena test cards Athena_ATRs = ["3B D6 18 00 80 B1 80 6D 1F 03 80 51 00 61 10 30 9E", "3F 96 18 80 01 80 51 00 61 10 30 9F"] if toHexString(self.ATR) not in Athena_ATRs: print_error("Wrong card inserted!") print "Got ATR:", toHexString(self.ATR) return step = 100 end = 65535 if full: start = 1 else: start = end for length in range(start, end + 1, step): print self.BOL, "length:", length APDU = list(CASE_2) APDU[5] = (length & 0xFF00) >> 8 APDU[6] = length & 0x00FF expected = ([magic_value] * length, 0x90, 0x00) self.transmitAndCompare(APDU, expected)
def case_3e(self, full): # send data to the card # > 80 12 01 80 00 00 07 00 01 02 03 04 05 06 # < [] 90 0 CASE_3 = toBytes("80 12 01 80 00 00 00") print "Case 3 extended" print if toHexString(self.ATR) != "3B D6 18 00 81 B1 80 7D 1F 03 80 51 00 61 10 30 8F": print_error("Wrong card inserted!") print "Got ATR:", toHexString(self.ATR) return end = 65535 step = 100 if full: start = 1 else: start = end expected = ([], 0x90, 0x00) for length in range(start, end + 1, step): print self.BOL, "length:", length APDU = list(CASE_3) APDU[5] = (length & 0xFF00) >> 8 APDU[6] = length & 0x00FF APDU += [i for i in range(0, length)] self.transmitAndCompare(APDU, expected)
def set_trig_mode(trig_mode_c4=0x00, trig_mode_c8=0x00): print("Set Trig mode") # build complete Read APDU l_APDUSOSSEAESSetTrigMode_complete = [] l_APDUSOSSEAESSetTrigMode_complete += l_APDUSOSSEAESSetTrigMode # unused P1 l_APDUSOSSEAESSetTrigMode_complete.append(0) # unused P2 l_APDUSOSSEAESSetTrigMode_complete.append(0) # Trig mode length l_APDUSOSSEAESSetTrigMode_complete.append(0x02) # Trig mode values (for C4 and C8 pins) l_APDUSOSSEAESSetTrigMode_complete.append(trig_mode_c4) l_APDUSOSSEAESSetTrigMode_complete.append(trig_mode_c8) print("send APDU: %s" % toHexString(l_APDUSOSSEAESSetTrigMode_complete)) if USE_LEIA == True: r = reader.send_APDU(sl.create_APDU_from_bytes(l_APDUSOSSEAESSetTrigMode_complete)) response = r.data sw1 = r.sw1 sw2 = r.sw2 else: response,sw1,sw2 = o_deviceConnection.transmit(l_APDUSOSSEAESSetTrigMode_complete) print("data: %s" % toHexString(response)) print("sw : %s" % toHexString([sw1]) + toHexString([sw2]))
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: atr = toHexString(card.atr) print("+Inserted: ", atr) added_card = self.get_cardtype(atr, "added") if isinstance(added_card, StudentCard): self.read_uid(added_card) print("uid", added_card.uid) z = self.api_client.send_event("card", added_card.uid) print(z) elif isinstance(added_card, RaspiTag): self.read_uid(added_card) print("uid", added_card.uid) self.api_client.send_event("tag", added_card.uid) elif added_card is None: print("Insert valid student card or scan a Raspberry Board RFID Tag") for card in removedcards: atr = toHexString(card.atr) print("-Removed: ", atr) removed_card = self.get_cardtype(atr, "removed") if isinstance(removed_card, StudentCard): pass elif isinstance(removed_card, RaspiTag): pass elif removed_card is None: print("Goog bye stranger")
def parseEventLog(cardservice,event_file,record_number): command = toBytes("00 A4 00 00 02 " + event_file + " 19") res,sw1,sw2 = cardservice.connection.transmit(command) if(toHexString([sw1,sw2]) == "90 00"): command = toBytes("00 B2 " + record_number + "04 1D") res,sw1,sw2 = cardservice.connection.transmit(command) if(toHexString([sw1,sw2]) == "90 00"): eventInfo = {} EPOCH = mktime(datetime.datetime(1997,1,1).timetuple()) hexResponse = toHexString(res).replace(" ","") response = bin(int(hexResponse,16))[2:].zfill(232) issuer = parse_issuer_code(str(int(response[3:11],2))) eventInfo['Issuer'] = issuer Line_Type = parse_line_types_code(str(int(response[15:19],2))) eventInfo['LineType'] = Line_Type evenType = parse_event_type_code(str(int(response[19:23],2))) eventInfo['EventType'] = evenType evenTime = (datetime.datetime.fromtimestamp(int(response[23:53],2) + EPOCH) + datetime.timedelta(hours=2)).strftime("%d/%m/%Y %H:%M:%S") eventInfo['EventTime'] = evenTime locationBitMap = str(int(response[116:123],2)) if(locationBitMap & 1 > 0): if(issuer == 'Israel Railways'): railStation = return eventInfo else: print(RED + "[x] Failed to Read Event Log Record" + ENDC) else: print(RED + "[x] Failed to Select Event Log File" + ENDC)
def execute(self, arg_components: components, arg_arguments=''): log.debug(self.__class__.__name__, "ENTER") uicc: uicc = arg_components.modeler.uicc set_content = None dict_args = convert_arguments_to_dict(arg_arguments) for key, value in dict_args.items(): if key == "set": set_content = value uicc_resp: uicc_sel_resp = uicc.select(UICC_FILE.ICCID) read_resp = uicc.read_binary(uicc_resp) if read_resp != None: print(self.get_res("original").format(convert_bcd_to_string(read_resp), toHexString(read_resp))) if set_content != None and self.is_update_require_adm == uicc.adm_verified: original = convert_bcd_to_string(read_resp) update_content = set_content + original[len(set_content):] if uicc.update_binary(convert_string_to_bcd(update_content)) == ERROR.NONE: print(self.get_res("updated").format(update_content, toHexString(convert_string_to_bcd(update_content)))) else: print(self.get_res("update_error")) else: print(self.get_res("read_error")) log.debug(self.__class__.__name__, "EXIT")
def send_to_tag(self, tag, apdu): if tag is not None: raise ValueError('Multiple tags not supported') HResult(smartcard.scard.SCardBeginTransaction(self.hcard)) if DEBUG: print '> %s' % toHexString(list(apdu)) response = HResult(smartcard.scard.SCardTransmit(self.hcard, smartcard.scard.SCARD_PCI_T0, list(apdu))) if DEBUG: print '< %s' % toHexString(response) sw1, sw2 = response[0:2] if sw1 == 0x61: # More data apdu2 = APDU(0, 0xc0, lc=sw2) if DEBUG: print '> %s' % toHexString(list(apdu2)) response = HResult(smartcard.scard.SCardTransmit(self.hcard, smartcard.scard.SCARD_PCI_T0, list(apdu2))) if DEBUG: print '< %s' % toHexString(response) HResult(smartcard.scard.SCardEndTransaction(self.hcard, smartcard.scard.SCARD_LEAVE_CARD)) return response
def print_details(debug, apdu, result, t, n): (data, sw1, sw2) = result if debug == 1: print "C =", toHexString(apdu) print "D =",toHexString(data) print "R = %x %x" % (sw1, sw2) print '%s took %0.3f ms.' % (n, t*1000.)
def printExchange(query, response, sw1, sw2): """Prints an APDU exchange (query-response).""" print ">> ", if type(query) is types.ListType: print toHexString(query) else: print query print "<< ", toHexString(response), " / ", "%x %x" % (sw1, sw2)
def printExchange(query, response, sw1, sw2): """Affiche un échange query-response.""" print ">> ", if type(query) == type([]): print toHexString(query) else: print query print "<< ", toHexString(response), " / ", "%x %x" % (sw1, sw2)
def update(self, observable, actions): (addedcards, removedcards) = actions data, sw1, sw2 = connection.transmit([0xFF, 0xCA, 0x00, 0x00, 0x00]) for card in addedcards: print "getuid:" + toHexString(data) #print("+Inserted: ", toHexString(card.atr)) for card in removedcards: print("-Removed: ", toHexString(data))
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: print("+Inserted: ", toHexString(card.atr)) self.Tap = "Tap" for card in removedcards: print("-Removed: ", toHexString(card.atr)) self.Tap = "Remove"
def enumerate_CLAs(cardservice): array = [] for i in range(0x00, 0xFF + 1): message = toBytes("A4 04 00") message.insert(0, i) res, sw1, sw2 = cardservice.connection.transmit(message) if (toHexString([sw1]) != '6E' and toHexString([sw1]) != '68'): array.append(toHexString([i])) return array
def execute(self, arg_components: components, arg_arguments=''): log.debug(self.__class__.__name__, "ENTER") uicc_resp: uicc_sel_resp = None uicc: uicc = arg_components.modeler.uicc set_content = None dict_args = convert_arguments_to_dict(arg_arguments) for key, value in dict_args.items(): if key == "set": set_content = value # read EF_IMSI uicc_resp = uicc.select(UICC_FILE.IMSI) read_resp = uicc.read_binary(uicc_resp) if read_resp == None: print(self.get_res("read_error")) return # RAW IMSI: 08 09 10 10 10 32 54 76 98 # - -------------------- # Convert 09 10 10 10 32 54 76 98 => 9001010123456789 # Ignore 1st char, and just use '001010123456789' print( self.get_res("original").format( convert_bcd_to_string(read_resp[1:])[1:], toHexString(read_resp))) if set_content != None and self.is_update_require_adm == uicc.adm_verified: imsi_update_content = read_resp[:] for i in range(len(set_content)): if i == 15: break Idx_of_PayLoad = int(((i + 1) / 2) + 1) Mod_Value = (i % 2) if Mod_Value == 0: imsi_update_content[Idx_of_PayLoad] = ( imsi_update_content[Idx_of_PayLoad] & 0x0F) + (int(set_content[i]) << 4) else: imsi_update_content[Idx_of_PayLoad] = ( imsi_update_content[Idx_of_PayLoad] & 0xF0) + int( set_content[i]) if uicc.update_binary(imsi_update_content) != ERROR.NONE: print(self.get_res("update_error")) return print( self.get_res("updated").format( convert_bcd_to_string(imsi_update_content[1:])[1:], toHexString(imsi_update_content))) log.debug(self.__class__.__name__, "EXIT")
def update(self, observable, actions): (addedcards, removedcards) = actions foundcards = {} self.testcase.assertEqual(removedcards, []) for card in addedcards: foundcards[toHexString(card.atr)] = 1 for atr in expectedATRs: if [] != atr and {} != foundcards: self.testcase.assertTrue(toHexString(atr) in foundcards)
def on_response(_, ccevent): response_meaning = '' try: hex_result = convert_int_2_hex_str(ccevent.args[-2:][0]) response_meaning = response_map[hex_result] except KeyError: pass print('<', toHexString(ccevent.args[0]), ' | ', 'SW: ' + toHexString(ccevent.args[-2:]), ' | ', response_meaning)
def commandToReader(self, bytearray, ToHex=True): # transmit to reader, ToHex - just for comfortable reading, default - TRUE convert to Hex print '-> To Reader', utils.toHexString(bytearray) readeranswer, sw1, sw2 = self.connectToCurrentReader.transmit( bytearray) if (ToHex): return utils.toHexString(readeranswer), self.convertToHex(sw1, sw2) else: return readeranswer, sw1, sw2
def on_command(_, ccevent): str_ = toHexString(ccevent.args[0]) command = toHexString(ccevent.args[0])[0:5] try: print('*' * 100) print(command_map[command]) except KeyError: print(f'Undefined command "{command}"') print('>', str_)
def _send_apdu(self, apdu): if self.debug == True: print("--> {0}".format(toHexString(apdu))) data, sw1, sw2 = self.connection.transmit(apdu) self.last_sent = apdu self.last_received = data + [sw1, sw2] if self.debug == True: print("<-- {0}".format(toHexString(data))) print("<-- {0}".format(toHexString([sw1, sw2]))) print("") return data, sw1, sw2
def evtLogKeyDown(self, event): code = event.GetKeyCode() if wx.WXK_RETURN == code or wx.WXK_NUMPAD_ENTER == code: linenum = len(self.txtLog.GetRange(0, self.txtLog.GetInsertionPoint()).split("\n")) linetext = self.txtLog.GetLineText(linenum - 1) self.history.append(linetext) self.history_index = len(self.history) cmd = map(ord, linetext.decode("hex")) self.txtLog.AppendText("\n") if self.card: try: data, sw1, sw2 = self.card.transmit(cmd) except Exceptions.CardConnectionException as ex: self.txtLog.SetDefaultStyle(wx.TextAttr("RED")) self.txtLog.AppendText("{0}\n\n".format(ex.message)) self.txtLog.SetDefaultStyle(wx.TextAttr("BLACK")) if sw1 == 0x61: data, sw1, sw2 = self.card.transmit([0x00, 0xC0, 0x00, 0x00, sw2]) self.txtLog.SetDefaultStyle(wx.TextAttr("BROWN")) if data: self.txtLog.AppendText("> Data:\n") for octet in [data[i : i + 8] for i in xrange(0, len(data), 8)]: txtform = "".join(map(logchr, octet)) txtform = "{0}{1}{2}\n".format(toHexString(octet), " " * ((8 - len(octet)) * 3 + 5), txtform) self.txtLog.AppendText(txtform) self.txtLog.SetDefaultStyle(wx.TextAttr("BLUE")) self.txtLog.AppendText("> SW: " + toHexString([sw1, sw2]) + "\n\n") self.txtLog.SetDefaultStyle(wx.TextAttr("BLACK")) self.lastpos = self.txtLog.GetLastPosition() elif wx.WXK_UP == code: if not len(self.history): return if self.history_index: self.history_index -= 1 self.txtLog.Remove(self.lastpos, self.txtLog.GetLastPosition()) self.txtLog.SetInsertionPoint(self.lastpos) self.txtLog.WriteText(self.history[self.history_index]) elif wx.WXK_DOWN == code: if not len(self.history): return if self.history_index + 1 < len(self.history): self.history_index += 1 self.txtLog.Remove(self.lastpos, self.txtLog.GetLastPosition()) self.txtLog.SetInsertionPoint(self.lastpos) self.txtLog.WriteText(self.history[self.history_index]) elif wx.WXK_BACK == code: if self.lastpos < self.txtLog.GetInsertionPoint(): event.Skip() else: event.Skip() return
def _card_connection_observer_update(self, card_connection, event): """CardConnectionObserver interface implementation""" if 'connect' == event.type: print 'Card inserted\n' elif 'disconnect' == event.type: print 'Card removed\n' elif 'command' == event.type: print '> ', toHexString(event.args[0]) elif 'response' == event.type: print '< ', '[{}]\n< {:02X} {:02X}\n'.format(toHexString(event.args[0]), *event.args[1:])
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: print("+Inserted: ", toHexString(card.atr)) card.connection = card.createConnection() card.connection.connect() card.connection.addObserver(self.observer) apdu = SELECT + DF_TELECOM response, sw1, sw2 = card.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] response, sw1, sw2 = card.connection.transmit(apdu) for card in removedcards: print("-Removed: ", toHexString(card.atr))
def get_smartcard_atr(): """return the atr of the current device""" try: # ottengo la lista dei lettori readers_list = smartcard.System.readers() except smartcard.pcsc.PCSCExceptions.EstablishContextException: # il lettore di smartcard potrebbe non essere inserito return None, "demone pcscd not attivo\n" # non sono riuscito a trovare nessun lettore if len(readers_list) == 0: return None, "nessun lettore riconosciuto\n" # di default prendo il primo lettore reader = readers_list[0] connection = reader.createConnection() try: # Mi connetto e ottengo l'ATR dalla carta connection.connect() atr_str = toHexString(connection.getATR()).replace(" ", ":").lower() connection.disconnect() except smartcard.Exceptions.CardConnectionException, e: return None, "smartcard non inserita\n"
def entersafe_manage_select_file(response, sw1, sw2): # there is a OK if sw1 == SW1_EXPECTED: print 'Selected file is', toHexString(response) else: print 'Not mapped response (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')'
def get_smartcard_atr(logger): """return the atr of the current device""" if logger is None: raise AttributeError try: readers_list = smartcard.System.readers() # ottengo la lista dei lettori except pcsc.PCSCExceptions.EstablishContextException: logger.error("demone pcscd not attivo") # il lettore di smartcard potrebbe non essere inserito return None # non sono riuscito a trovare nessun lettore if len(readers_list) == 0: logger.error("nessun lettore riconosciuto") return None reader = readers_list[0] # di default prendo il primo lettore connection = reader.createConnection() try: # Mi connetto e ottengo l'ATR dalla carta connection.connect() atr_str = toHexString(connection.getATR()).replace(" ", ":").lower() connection.disconnect() except smartcard.Exceptions.CardConnectionException, errmsg: logger.error(errmsg) return None
def update(self, cardconnection, ccevent): if 'connect' == ccevent.type: print 'connecting to ' + cardconnection.getReader() elif 'disconnect' == ccevent.type: print 'disconnecting from ' + cardconnection.getReader() elif 'command' == ccevent.type: print '> ', toHexString(ccevent.args[0]) elif 'response' == ccevent.type: if [] == ccevent.args[0]: print '< [] ', "%-2X %-2X" % tuple(ccevent.args[-2:]) else: print '< ', toHexString(ccevent.args[0]), "%-2X %-2X" % tuple(ccevent.args[-2:])
def connect(self): print "== Available readers:" self.connected = False rl = smartcard.System.readers() i = 0 for r in rl: print str(i) + ") " + r.name i = i + 1 if len(rl) == 0: raise Exception("No readers available") print " Connecting to first reader ... " try: self.c = r.createConnection() self.c.connect() print " ATR: " + toHexString(self.c.getATR()) except Exception: raise Exception("Communication error") # select app SELECT = [0x00, 0xA4, 0x04, 0x00, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08] response, sw1, sw2 = self.c.transmit(SELECT) if sw1 == 0x90 and sw2 == 0x00: print " App selected" self.connected = True else: raise Exception("App select failed")
def entersafe_manage_select_file(response, sw1, sw2): # there is a OK if sw1 == SW1_EXPECTED: print "Selected file is", toHexString(response) print "Archivo Correcto..." else: if sw1 == 0x62: if sw2 == 0x83: print "Archivo seleccionado invalido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" else: print "Error desconocido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw1 == 0x69: if sw2 == 0x85: print "Condicion insuficiente para uso del comando (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" else: print "Error desconocido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw1 == 0x6A: if sw2 == 0x81: print "Funcion no soportada (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw2 == 0x82: print "Archivo no encontrado (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw2 == 0x86: print "P1 y/o P2 invalidos (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw2 != 0x82 and sw2 != 0x81 and sw2 != 0x86: print "Error desconocido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw1 == 0x6E: if sw2 == 0x00: print "CLA invalido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw2 != 0x00: print "Error desconocido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")" if sw1 != 0x62 and sw1 != 0x69 and sw1 != 0x6A and sw1 != 0x6E: print "Error desconocido (sw1,sw2)=(", hex(sw1), ",", hex(sw2), ")"
def main(fileid, is_update, data, passwd): gnuk = GnukToken() gnuk.connection.connect() print "Token:", gnuk.connection.getReader() print "ATR:", toHexString( gnuk.connection.getATR() ) gnuk.cmd_verify(BY_ADMIN, passwd) gnuk.cmd_write_binary(fileid, data, is_update) gnuk.cmd_select_openpgp() if fileid == 0: data_in_device = gnuk.cmd_get_data(0x00, 0x4f) for d in data_in_device: print "%02x" % d, print compare(data, data_in_device[8:]) elif fileid >= 1 and fileid <= 4: data_in_device = gnuk.cmd_read_binary(fileid) compare(data, data_in_device) elif fileid == 5: data_in_device = gnuk.cmd_get_data(0x7f, 0x21) compare(data, data_in_device) gnuk.connection.disconnect() return 0
def entersafe_manage_select_file(response, sw1, sw2): # there is a OK if sw1 == SW1_EXPECTED: print 'Selected file is', toHexString(response) print 'Archivo Correcto...' else: if sw1 == 0x6C: if sw2 == 0x10: print 'Error de longitud LE (se esperaba 10) (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw2 != 0x10: print 'Error desconocido (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw1 == 0x69: if sw2 == 0x85: print 'Condicion insuficiente para uso del comando (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' else: print 'Error desconocido (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw1 == 0x6A: if sw2 == 0x81: print 'Funcion no soportada (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw2 == 0x82: print 'Archivo no encontrado (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw2 == 0x86: print 'P1 y/o P2 invalidos (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw2 != 0x82 and sw2 != 0x81 and sw2 != 0x86: print 'Error desconocido (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw1 == 0x6E: if sw2 == 0x00: print 'CLA invalido (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw2 != 0x00: print 'Error desconocido (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')' if sw1 != 0x6C and sw1 != 0x69 and sw1 != 0x6A and sw1 !=0x6E: print 'Error desconocido (sw1,sw2)=(', hex(sw1), ',', hex(sw2), ')'
def _process_output_string(self, output_string, uid_bytes, data_list=None): if data_list is None: data_list = ["", "", "", "", "", "", "", ""] if uid_bytes is None: uidlen = "0" uidint = "" uid = "" else: uidlen = str(len(uid_bytes)) uidint = str(self._little_endian_value(uid_bytes)) uid = toHexString(uid_bytes, PACK) return output_string.format(UIDLEN=uidlen, TYPE=self.reader.card_type, SUBTYPE=self.reader.card_subtype, UIDINT=uidint, UID=uid, CR=os.linesep, DATA=data_list[0], DATA0=data_list[0], DATA1=data_list[1], DATA2=data_list[2], DATA3=data_list[3], DATA4=data_list[4], DATA5=data_list[5], DATA6=data_list[6], DATA7=data_list[7])
def analyse_return(response, sw1, sw2): print 'response: ', toHexString(response), ' status words: ', "%x %x" % (sw1, sw2) if sw1 == 0x90 and sw2 == 0 and response[-1] != 0: try: print "Desfire: " + hex(response[-1]) + " " + sw2_error_codes[response[-1]] except KeyError: # not in table pass
def getATR(self): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() return toHexString(cardservice.connection.getATR())
def OnAddCards(self, addedcards): """Called when a card is inserted. Adds a smart card to the smartcards tree.""" parentnode = self.root for cardtoadd in addedcards: childCard = self.AppendItem(parentnode, toHexString(cardtoadd.atr)) self.SetItemText(childCard, toHexString(cardtoadd.atr)) self.SetPyData(childCard, cardtoadd) self.SetItemImage( childCard, self.cardimageindex, wx.TreeItemIcon_Normal) self.SetItemImage( childCard, self.cardimageindex, wx.TreeItemIcon_Expanded) self.Expand(childCard) self.Expand(self.root) self.EnsureVisible(self.root) self.Repaint()
def getATR(self): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() atr = toHexString(cardservice.connection.getATR()) self.writeToLog("ATR: {0}".format(atr))
def get_uid(self): d = self.read_block(0) d = d+ self.read_block(1) uid = toHexString(d).replace(" ", "")[:16] return uid
def _decode_error_response(self, sw1, sw2): if sw1 == 0x64 and sw2 == 0x00: raise MaximException("Read not allowed on interface.") elif sw1 == 0x64 and sw2 == 0x01: raise MaximException("Write not allowed on interface.") elif sw1 == 0x64 and sw2 == 0x02: raise MaximException("Interface is disabled.") elif sw1 == 0x65 and sw2 == 0x00: raise MaximException("Read timeout on interface {0}.".format(toHexString([sw2]))) elif sw1 == 0x6A and sw2 == 0x80: raise MaximException("Malformed command.") elif sw1 == 0x6A: raise MaximException("Unrecognized interface: {0}".format(toHexString([sw2]))) elif sw1 == 0x6F and sw2 == 0x00: raise MaximException("Interface error.") else: raise MaximException("Unrecognized return code: %s %s." % (toHexString([sw1]), toHexString([sw2])))