def fuzzFile(self, observer=False): self.cardrequest = CardRequest(timeout=5, cardType=AnyCardType()) self.cardservice = self.cardrequest.waitforcard() if observer: obs = ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(obs) self.cardservice.connection.connect() self.c = self.cardservice.connection print("ATR... : %s" % self.cardservice.connection.getATR()) print("Brute forcing...") out = "" for i in range(0, 0xFF): for x in range(0, 0xFF): response, sw1, sw2 = self.cardservice.connection.transmit( [0x00, 0xA4, 0x08, 0x04, 0x02, i, x]) if sw1 == 0x61: out += "Valid APDU from MF: %02x::%02x\n" % (i, x) return out
def requestByATR(atr): print('\n========== REQUEST BY ATR ==========\n') # example: ATR of German ID Card, only works with ISO 14443 devices # cardtype = ATRCardType(toBytes("3B 88 80 01 00 00 00 00 00 00 00 00 09")) cardtype = ATRCardType(toBytes(atr)) # also supports masks # cardtype = ATRCardType( toBytes( "3B 15 94 20 02 01 00 00 0F" ), toBytes( "00 00 FF FF FF FF FF FF 00" ) ) cardrequest = CardRequest(timeout=1, cardType=cardtype) try: cardservice = cardrequest.waitforcard() print('Card detected successfully') return True except smartcard.Exceptions.CardRequestTimeoutException: print('Wrong card type') return False cardservice.connection.connect() print(toHexString(cardservice.connection.getATR()))
def main(): mainCardType = AnyCardType() mainCardRequest = CardRequest(timeout=1, cardType=mainCardType) # Introduction print("Bad Reader, PoC") print("By Heartbroken-Dev, licensed under Apache-2.0") while True: # Pseudo do: .. while() # Attempt to connect to a card mainCardService = attemptConnection(mainCardRequest) promptStatus = enterPrompt(mainCardService) if promptStatus == utils.const.STATUS_PROMPT_EXITING: break
def connect(self, timeout=1, new_card_only=True): """Returns a connection if possible, otherwise returns None""" card_request = CardRequest(readers=[self.reader], timeout=timeout, newcardonly=new_card_only) card_service = card_request.waitforcard() try: # Establish reader-centric connection connection = self.reader.createConnection() connection.connect() self.process_atr(connection.getATR()) # Load keys if need be self.card_authentication = None if self.key_load_pending and self.card_authable: self._load_keys(connection) return connection except (CardConnectionException, NoCardException): return None
def initialize(card_type=""): if card_type == "": cardtype = AnyCardType() # for accepting any type of card else: cardtype = ATRCardType(card_type) cardrequest = CardRequest(timeout=1, cardType=cardtype) # print("Waiting for card") cardservice = cardrequest.waitforcard() # print("Card found") # connecting to card cardservice.connection.connect() reader = cardservice.connection.getReader() print(f"Success: NFC Connection established on reader {reader}") # set up object nfc_connection = NFCconnection( cardservice=cardservice, metadata={}, ) # add reader info to object nfc_connection.metadata['reader'] = reader # to make next command more robust sleep(0.1) # get metadata nfc_connection.get_card_atr_info() nfc_connection.get_card_uid() nfc_connection.get_card_size() uid = nfc_connection.metadata["UID"] size = nfc_connection.metadata["Size"] card_type = nfc_connection.metadata['ATR']['card_type'] card_subtype = nfc_connection.metadata['ATR']['card_subtype'] print( f"Success: NFC Connection identified as {uid} with size {size},card:{card_type}/{card_subtype}" ) return nfc_connection
def run(self): """Runs until stopEvent is notified, and notify observers of all card insertion/removal. """ self.cardrequest = CardRequest(timeout=0.1) while self.stopEvent.isSet() != 1: try: currentcards = self.cardrequest.waitforcardevent() addedcards = [] for card in currentcards: if not self.cards.__contains__(card): addedcards.append(card) removedcards = [] for card in self.cards: if not currentcards.__contains__(card): removedcards.append(card) if addedcards != [] or removedcards != []: self.cards = currentcards self.observable.setChanged() self.observable.notifyObservers( (addedcards, removedcards)) # when CardMonitoringThread.__del__() is invoked in # response to shutdown, e.g., when execution of the # program is done, other globals referenced by the # __del__() method may already have been deleted. # this causes ReaderMonitoringThread.run() to except # with a TypeError or AttributeError except TypeError: pass except AttributeError: pass except: try: import sys print sys.exc_info()[1] print sys.exc_info()[2] print sys.exc_info()[0] except: pass
def run(self): """Runs until stopEvent is notified, and notify observers of all card insertion/removal. """ self.cardrequest = CardRequest(timeout=0.1) while self.stopEvent.isSet() != 1: try: currentcards = self.cardrequest.waitforcardevent() addedcards = [] for card in currentcards: if not self.cards.__contains__(card): addedcards.append(card) removedcards = [] for card in self.cards: if not currentcards.__contains__(card): removedcards.append(card) if addedcards != [] or removedcards != []: self.cards = currentcards self.observable.setChanged() self.observable.notifyObservers( (addedcards, removedcards)) # when CardMonitoringThread.__del__() is invoked in # response to shutdown, e.g., when execution of the # program is done, other globals referenced by the # __del__() method may already have been deleted. # this causes ReaderMonitoringThread.run() to except # with a TypeError or AttributeError except TypeError: pass except AttributeError: pass except: # FIXME Tighten the exceptions caught by this block traceback.print_exc() # Most likely raised during interpreter shutdown due # to unclean exit which failed to remove all observers. # To solve this, we set the stop event and pass the # exception to let the thread finish gracefully. self.stopEvent.set()
def detect_smartcard_reader(self): _logger.info(f"[SatochipPlugin] detect_smartcard_reader")#debugSatochip self.cardtype = AnyCardType() try: cardrequest = CardRequest(timeout=5, cardType=self.cardtype) cardservice = cardrequest.waitforcard() return [Device(path="/satochip", interface_number=-1, id_="/satochip", product_key=(SATOCHIP_VID,SATOCHIP_PID), usage_page=0, transport_ui_string='ccid')] except CardRequestTimeoutException: _logger.info(f'time-out: no card inserted during last 5s') return [] except Exception as exc: _logger.info(f"Error during connection:{str(exc)}") return [] return []
def enable_card_listener(self, card_type=AnyCardType()): # Check if resetting vars is required and if so, do so self.__reset_local_vars() try: # Setup a cardRequest: waiting infinitely for any card type self.__request = CardRequest(timeout=INFINITE, cardType=card_type) # Once a card is presented, initialize variables to setup connection self.__service = self.__request.waitforcard() self.__on_card_presented() except CardRequestTimeoutException as e: Logger.critical( "This should not happen: Timelimit reached for card presenting" ) os._exit(1) except EstablishContextException as e2: # There is no smartcard reader found so we just ignore it. pass
def verificar_eID_en_lector(self): ''' Verifica que la tarjeta esté puesta en el lector :return: True si está puesta, False en caso contrario. ''' print('insert a card (SIM card if possible) within 10s') try: cardrequest = CardRequest(timeout=10, cardType=self.cardtype) self.cardservice = cardrequest.waitforcard() # attach the console tracer observer = ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(observer) self.cardservice.connection.connect() return True except CardRequestTimeoutException: print('time-out: no card inserted during last 10s') return False
def connect_to_chip(timeout, card_type=AnyCardType()): """ Establish a connection with the first chip presented to the reader before the timeout. :param timeout: The number of seconds for a chip before timing out :param card_type: The card type to wait for :return: A connection to the chip or false if it the read times out. """ try: _logger.debug('Entering SmartCard.connect_to_chip function.') connection = CardRequest( timeout=timeout, cardType=card_type).waitforcard().connection connection.connect() return connection except CardRequestTimeoutException as e: _logger.debug('Card connection timed out after {timeout} seconds.') return False except Exception as e: raise Exception('Card connection failed unexpectedly.') from e
def testcase_CardRequestAnyCardTypeAnyReaderPassThru(self): """Test smartcard.AnyCardType.""" for reader in expectedReaders: atr = expectedATRinReader[reader] if [] != atr: ct = AnyCardType() cardservice = smartcard.PassThruCardService.PassThruCardService cr = CardRequest(timeout=10.6, readers=[reader], cardType=ct, cardServiceClass=cardservice) cs = cr.waitforcard() cs.connection.connect() self.assertEqual( cs.__class__, smartcard.PassThruCardService.PassThruCardService) self.assertEqual(atr, cs.connection.getATR()) self.assertEqual(cs.connection.getReader(), expectedReaderForATR[toHexString(atr)])
def do_connect (self, args): """ Waits until a smartcard is present and initializes everything that's needed. """ print ("Trying to connect...") try: cardtype = AnyCardType () cardrequest = CardRequest (timeout = 10, cardType = cardtype) cardservice = cardrequest.waitforcard () # self.observer has been initialized when calling 'init ()' cardservice.connection.addObserver (self.observer) cardservice.connection.connect () self.sc_reader = cardservice except Exception as e: print ("ERROR: " + str (e)) return None
def detect_smartcard_reader(self): self.print_error("detect_smartcard_reader")#debugSatochip self.cardtype = AnyCardType() try: cardrequest = CardRequest(timeout=0.1, cardType=self.cardtype) cardservice = cardrequest.waitforcard() self.print_error("detect_smartcard_reader: found card!")#debugSatochip return [Device(path="/satochip", interface_number=-1, id_="/satochip", product_key=(SATOCHIP_VID,SATOCHIP_PID), usage_page=0)] #transport_ui_string='ccid')] except CardRequestTimeoutException: self.print_error('time-out: no card found') return [] except Exception as exc: self.print_error("Error during connection:", repr(exc), f"\n{traceback.format_exc()}") return [] return []
def french_apdu(self,rand=None,autn=None,debug=False,trigger=None): # trigger.disarm() self.cardrequest = CardRequest(timeout=5,cardType=AnyCardType()) self.cardservice = self.cardrequest.waitforcard() if debug: obs = ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(obs) self.cardservice.connection.connect() self.c = self.cardservice.connection # print(" !!! USING SHORTER SSTIC2018 PAPER APDU SEQUENCE !!!") r,sw1,sw2 = self.c.transmit([0x00, 0xa4, 0x08, 0x04, 0x02, 0x2f, 0x00]) r,sw1,sw2 = self.c.transmit([0x00,0xC0,0x00,0x00] + [sw2]) r,sw1,sw2 = self.c.transmit([0x00,0xB2,0x01,0x04] + [r[7]]) r,sw1,sw2 = self.c.transmit([0x00,0xA4,0x04,0x04] + list(r[3:4 + r[3]])) r,sw1,sw2 = self.c.transmit([0x00,0xC0,0x00,0x00] + [sw2]) if rand is None and autn is None: authcmd = [0x00, 0x88, 0x00, 0x81, 0x22, 0x10] + [0xaa] * 16 + [0x10] + [0xbb] * 16 else: authcmd = [0x00, 0x88, 0x00, 0x81, 0x22, 0x10] + rand + [0x10] + autn # trigger.arm() r,sw1,sw2 = self.c.transmit(authcmd)
def run(self): from smartcard.CardRequest import CardRequest from smartcard.Exceptions import NoCardException, CardConnectionException from smartcard.util import toHexString super().run() self.logger.info( 'Initialized smart card reader backend - ATR filter: {}'.format( self.ATRs)) prev_atr = None reader = None while not self.should_stop(): try: cardrequest = CardRequest(timeout=None, cardType=self.cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() reader = cardservice.connection.getReader() atr = toHexString(cardservice.connection.getATR()) if atr != prev_atr: self.logger.info( 'Smart card detected on reader {}, ATR: {}'.format( reader, atr)) self.bus.post( SmartCardDetectedEvent(atr=atr, reader=reader)) prev_atr = atr except Exception as e: if isinstance(e, NoCardException) or isinstance( e, CardConnectionException): self.bus.post( SmartCardRemovedEvent(atr=prev_atr, reader=reader)) else: self.logger.exception(e) prev_atr = None
def cardConnect(self, time=10, cardtype=None): try: # request card insertion print 'insert a card (SIM card if possible) within 10s' cardrequest = CardRequest(timeout=time, cardType=cardtype) self.cardservice = cardrequest.waitforcard() # attach the console tracer observer = ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(observer) # connect to the card and perform a few transmits self.cardservice.connection.connect() response, sw1, sw2 = self.cardservice.connection.transmit( self.get_tag_apdu) if sw1 == 0x90: self.get_tag(response) else: print "Get Tag Apdu transmit işlemi basarısız" sys.exit() except CardRequestTimeoutException: print 'time-out: no card inserted during last 10s'
def testcase_CardRequestNewCardAnyCardTypeInfiniteTimeOut(self): """Test smartcard.CardRequest for any new card without time-out.""" self.removeAllCards() cardtype = AnyCardType() cardrequest = CardRequest( timeout=None, cardType=cardtype, newcardonly=True) print('re-insert any combination of cards six time') count = 0 for i in range(0, 6): cardservice = cardrequest.waitforcard() try: cardservice.connection.connect() print(toHexString( cardservice.connection.getATR()), \ 'in', cardservice.connection.getReader()) except CardConnectionException: # card was removed too fast pass cardservice.connection.disconnect() count += 1 self.assertEqual(6, count)
def testcase_CardRequestNewCardAnyCardTypeFiniteTimeOutNoInsertion(self): """Test smartcard.CardRequest for new card with time-out and no insertion before time-out.""" self.removeAllCards() # make sure we have 6 time-outs cardtype = AnyCardType() cardrequest = CardRequest( timeout=1, cardType=cardtype, newcardonly=True) count = 0 for i in range(0, 6): try: before = time.time() cardservice = cardrequest.waitforcard() except CardRequestTimeoutException as e: elapsed = int(10 * (time.time() - before)) print('.', end=' ') self.assertTrue(elapsed >= 10 and elapsed <= 11.) count += 1 print('\n') self.assertEqual(6, count)
def nextg_apdu(self, rand=None, autn=None, debug=False, trigger=None, scope=None): if trigger is not None: trigger.disarm() self.cardrequest = CardRequest(timeout=5, cardType=AnyCardType()) self.cardservice = self.cardrequest.waitforcard() if debug: obs = ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(obs) self.cardservice.connection.connect() self.c = self.cardservice.connection # print("ATR... : %s" % self.cardservice.connection.getATR()) r, sw1, sw2 = self.c.transmit( [0x00, 0xa4, 0x08, 0x04, 0x02, 0x2f, 0x00]) r, sw1, sw2 = self.c.transmit([0x00, 0xc0, 0x00, 0x00, sw2]) r, sw1, sw2 = self.c.transmit([0x00, 0xb2, 0x01, 0x04, r[7]]) r, sw1, sw2 = self.c.transmit([0x00, 0xA4, 0x04, 0x04] + list(r[3:4 + r[3]])) r, sw1, sw2 = self.c.transmit([0x00, 0xC0, 0x00, 0x00] + [sw2]) r, sw1, sw2 = self.c.transmit( [0x00, 0xA4, 0x00, 0x04, 0x02, 0x6F, 0x07]) r, sw1, sw2 = self.c.transmit([0x00, 0xc0, 0x00, 0x00, sw2]) # r,sw1,sw2 = self.c.transmit([0x00, 0xb0, 0x00, 0x00, r[7]]) # r,sw1,sw2 = # r,sw1,sw2 = self.c.transmit([0x00, 0xb2, 0x01, 0x04, r[7]]) if rand is None and autn is None: authcmd = [0x00, 0x88, 0x00, 0x81, 0x22, 0x10 ] + [0xaa] * 16 + [0x10] + [0xbb] * 16 else: authcmd = [0x00, 0x88, 0x00, 0x81, 0x22, 0x10] + rand + [0x10 ] + autn if trigger is not None: trigger.arm() scope.arm() r, sw1, sw2 = self.c.transmit(authcmd)
def __init__(self, client_key, client_cert, tp_key, tp_cert, key_transport=False, mutual_auth=True, cert_verif=True, debug=False, chan=0, vuln=True): self.vuln = vuln if chan > 3 or chan < 0: raise ValueError("Logical channel number must be in [0, 3]") self.cla = self.DEFAULT_CLA + chan self.security_lvl = 0x42 # ANY_AUTHENTICATED + C_DECRYPTION self.client_key = RsaKeyHolder(client_key) self.client_cert = CVCertificate(client_cert) self.tp_key = RsaKeyHolder(tp_key) self.tp_cert = CVCertificate(tp_cert) self.card_key = None self.card_cert = None self.key_transport = key_transport self.mutual_auth = mutual_auth self.cert_verif = cert_verif self.session_keys = [] self.session_ivs = [] self.client_secret = [] self.card_secret = [] # Wait for any card to be put on a reader, and initiate a connection card_type = AnyCardType() card_request = CardRequest(timeout=None, cardType=card_type) self.card = card_request.waitforcard() self.card.connection.connect() error_chain = [] error_chain = [ErrorCheckingChain(error_chain, ISO7816_4ErrorChecker())] self.card.connection.setErrorCheckingChain(error_chain) # Set an observer for debugging if debug: observer = SCP10Observer() self.card.connection.addObserver(observer)
def readUID(self, ATR, apdu): cardtype = ATRCardType(toBytes(ATR)) cardrequest = CardRequest(timeout=None, cardType=cardtype) cardservice = cardrequest.waitforcard() try: cardservice.connection.connect() response, sw1, sw2 = cardservice.connection.transmit(apdu) except CardConnectionException: return None ## print toHexString(cardservice.connection.getATR()) print "%x %x" % (sw1, sw2) print "%x, %x, %x, %x" % (response[0], response[1], response[2], response[3]) if sw1 == 0x90 and sw2 == 0x00: #check if UID was read successfully UID = str(hex(response[0])) + str(hex(response[1])) + str( hex(response[2])) + str(hex(response[3])) return UID.replace("0x", "") return None
def testcase_CardRequestNewCardAnyCardTypeFiniteTimeOutInsertion(self): """Test smartcard.CardRequest for new card with time-out and insertion before time-out.""" self.removeAllCards() # make sure insertion is within 5s cardtype = AnyCardType() cardrequest = CardRequest( timeout=5, cardType=cardtype, newcardonly=True) count = 0 for i in range(0, 6): try: print('re-insert any card within the next 5 seconds') before = time.time() cardservice = cardrequest.waitforcard() count += 1 elapsed = int(10 * (time.time() - before)) self.assertTrue(elapsed <= 55.) except CardRequestTimeoutException as e: print('too slow... Test will show a failure') print('\n') self.assertEqual(6, count)
def testcase_CardRequestNewCardATRCardTypeInfiniteTimeOut(self): """Test smartcard.CardRequest for new card with given ATR without time-out.""" self.removeAllCards() count = 0 for i in range(0, 6): card = random.choice(cardz) cardtype = ATRCardType(card.atr) cardrequest = CardRequest( timeout=None, cardType=cardtype, newcardonly=True) print('re-insert card', toHexString(card.atr), 'into', card.reader) cardservice = cardrequest.waitforcard() print('ok') try: cardservice.connection.connect() self.assertEqual(cardservice.connection.getATR(), card.atr) except CardConnectionException: # card was removed too fast pass cardservice.connection.disconnect() count += 1 self.assertEqual(6, count)
def french_apdu(self, rand=None, autn=None, scope=None, debug=False): self.cardrequest = CardRequest(timeout=5, cardType=AnyCardType()) self.cardservice = self.cardrequest.waitforcard() if debug: obs = ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(obs) self.cardservice.connection.connect() self.c = self.cardservice.connection r, sw1, sw2 = self.c.transmit( [0x00, 0xa4, 0x08, 0x04, 0x02, 0x2f, 0x00]) r, sw1, sw2 = self.c.transmit([0x00, 0xC0, 0x00, 0x00] + [sw2]) r, sw1, sw2 = self.c.transmit([0x00, 0xB2, 0x01, 0x04] + [r[7]]) r, sw1, sw2 = self.c.transmit([0x00, 0xA4, 0x04, 0x04] + list(r[3:4 + r[3]])) scope.arm() r, sw1, sw2 = self.c.transmit([0x00, 0xC0, 0x00, 0x00] + [sw2]) if rand is None and autn is None: authcmd = [0x00, 0x88, 0x00, 0x81, 0x22, 0x10 ] + [0xaa] * 16 + [0x10] + [0xbb] * 16 else: authcmd = [0x00, 0x88, 0x00, 0x81, 0x22, 0x10] + rand + [0x10 ] + autn r, sw1, sw2 = self.c.transmit(authcmd)
def main(): global ATRS get_smartcards_list() cardtype = AnyCardType() while True: cardrequest = CardRequest(timeout=120, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() atrBytes = cardservice.connection.getATR() atr = ATR(atrBytes) print(atr) print('historical bytes: ', toHexString(atr.getHistoricalBytes())) print('checksum: ', "0x%X" % atr.getChecksum()) print('checksum OK: ', atr.checksumOK) print('T0 supported: ', atr.isT0Supported()) print('T1 supported: ', atr.isT1Supported()) print('T15 supported: ', atr.isT15Supported()) if (ATRS[toHexString(atrBytes)]): print(ATRS[toHexString(atrBytes)]) print(cardservice.connection) send(cardservice.connection) sleep(5) return 0
def __init__(self): """ Generic constructor """ cardtype = AnyCardType() cardrequest = CardRequest(timeout=3, cardType=cardtype) self.seq = None self.kSessEnc = None self.kSessMac = None self.index = 0 # Wait for the card #print('Waiting for the CIE...') try: self.cardservice = cardrequest.waitforcard() except CardRequestTimeoutException: raise Exception('Card not found') # Connect to the card if found self.cardservice.connection.connect()
class printobserver(CardObserver): """A simple card observer that is notified when cards are inserted/removed from the system and prints its uids. The code is not pretty but it works! """ def update(self, observable, (addedcards, removedcards)): apdu = [0xff, 0xca, 0, 0, 0] try: cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() response, sw1, sw2 = cardservice.connection.transmit(apdu) tagid = toHexString(response).replace(' ', '') response = {} response['status'] = 200 response['tagid'] = tagid print json.dumps(response) #urllib2.urlopen("http://your_web_servers_waiting_for_card_data/?uid=%s" % tagid, None, 3) except Exception as e: response = {} response['status'] = 400 response['error'] = 'Please place the card in the reader.' print json.dumps(response)
def card_transmit(self, apdu): try: (response, sw1, sw2) = self.cardservice.connection.transmit(apdu) if (sw1 == 0x9C) and (sw2 == 0x06): (response, sw1, sw2) = self.card_verify_PIN() (response, sw1, sw2) = self.cardservice.connection.transmit(apdu) return (response, sw1, sw2) except CardConnectionException: # may be the card has been removed try: self.cardrequest = CardRequest(timeout=10, cardType=self.cardtype) self.cardservice = self.cardrequest.waitforcard() # attach the console tracer self.observer = LogCardConnectionObserver( ) #ConsoleCardConnectionObserver() self.cardservice.connection.addObserver(self.observer) # connect to the card and perform a few transmits self.cardservice.connection.connect() except CardRequestTimeoutException: _logger.exception('time-out: no card inserted during last 10s') except Exception as exc: _logger.exception("Error during connection: {str(exc)}")
sys.exit(True) PIN = '' if args: if not args[0].isdigit(): print 'Invalid PIN', args[0] sys.exit(True) else: PIN = args[0] try: # request any card type cardtype = AnyCardType() # request card insertion print 'insert a card within 10s' cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() # attach the console tracer if Debug: observer = ConsoleCardConnectionObserver() cardservice.connection.addObserver(observer) # connect to the card cardservice.connection.connect(Protocol) #get_challenge(0) # try to select PSE apdu = SELECT + [len(DF_PSE)] + DF_PSE response, sw1, sw2 = send_apdu(apdu)