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 wait_for_card(self, timeout=None, newcardonly=False): cr = CardRequest(readers=[self._reader], timeout=timeout, newcardonly=newcardonly) try: cr.waitforcard() except CardRequestTimeoutException: raise NoCardError() self.connect()
def __send_intro_message(self, waiting): """ sends introduction message and returns active connection to device """ logging.debug('Initialized communication. waiting for device...') if waiting: cardrequest = CardRequest(timeout=3000) cardrequest.waitforcard() r = readers() reader = r[0] connection = reader.createConnection() connection.connect() logging.debug('Connected to device. ') logging.debug('Sending initial message with AID.') # Send introductory message with AID from configuration file intro_message = APDUMessage(APDUHeader.SELECT_AID, config.AID).convertToByteArray() data, sw1, sw2 = connection.transmit(intro_message) logging.debug('Got response: %02X %02X' % (sw1, sw2)) # Return active connection that is later used to communicate with device return connection
class SIMController: def __init__(self): self.c = None # f**k pyscard. seriously. pass def nextg_apdu(self, rand=None, autn=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 # 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, 0x28]) r, sw1, sw2 = self.c.transmit([0x00, 0xb2, 0x01, 0x04, 0x26]) r, sw1, sw2 = self.c.transmit([ 0x00, 0xa4, 0x04, 0x04, 0x10, 0xa0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02, 0xff, 0x33, 0xff, 0xff, 0x89, 0x01, 0x01, 0x01, 0x00 ]) r, sw1, sw2 = self.c.transmit([0x00, 0xc0, 0x00, 0x00, 0x3e]) r, sw1, sw2 = self.c.transmit( [0x00, 0xa4, 0x00, 0x04, 0x02, 0x6f, 0x07]) r, sw1, sw2 = self.c.transmit([0x00, 0xc0, 0x00, 0x00, 0x25]) r, sw1, sw2 = self.c.transmit([0x00, 0xb0, 0x00, 0x00, 0x09]) 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 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 __init__(self, threadindex): '''Connect to a card with an ExclusiveTransmitCardConnection.''' threading.Thread.__init__(self) self.threadindex = threadindex # request any card type cardtype = AnyCardType() cardrequest = CardRequest(timeout=5, cardType=cardtype) cardservice = cardrequest.waitforcard() # attach our decorator cardservice.connection = ExclusiveTransmitCardConnection( cardservice.connection) # uncomment to attach the console tracer #observer=ConsoleCardConnectionObserver() #cardservice.connection.addObserver(observer) # connect to the card cardservice.connection.connect() self.cardservice = cardservice # this event will signal the end of the thread self.evtStop = threading.Event() # this timer will set the event stop event in 30s timer = threading.Timer(30, signalEvent, [self.evtStop]) timer.start() self.countTransmitted = 0
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 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={}, ) # 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"] print(f"Success: NFC Connection identified as {uid} with size {size}") return nfc_connection
def detect_smartcard_reader(self): print_error("[satochip] SatochipPlugin: detect_smartcard_reader" ) #debugSatochip self.cardtype = AnyCardType() try: cardrequest = CardRequest(timeout=5, cardType=self.cardtype) cardservice = cardrequest.waitforcard() print_error( "[satochip] SatochipPlugin: 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: print('time-out: no card inserted during last 5s') return [] except Exception as exc: print("Error during connection:", exc) return [] return []
def connectionObserver(): # request any card type cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() observer = ConsoleCardConnectionObserver() cardservice.connection.addObserver(observer) cardservice.connection.connect() print('ATR: ' + toHexString(cardservice.connection.getATR())) # get reader used for the connection # device = cardservice.connection.getReader() GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] apdu = SELECT + DF_TELECOM response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] response, sw1, sw2 = cardservice.connection.transmit(apdu) else: print('no DF_TELECOM')
def __init__(self): cardtype = AnyCardType() self.resetCmd = [0x0, 0xA4, 0x4, 0x0, 0x8, 0xA0, 0x0, 0x0, 0x0, 0x54, 0x48, 0x0, 0x1] self.resetCmd1 = [0x0, 0xC0, 0x0, 0x0, 0xA] self.citizenCmd = [0x80, 0xB0, 0x0, 0x4, 0x2, 0x0, 0xD] self.citizenResponse = [0x0, 0xC0, 0x0, 0x0, 0xD] try: # request card insertion cardrequest = CardRequest(timeout=5, 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() except CardRequestTimeoutException: print 'time-out: no card inserted during last 5s' except: import sys print sys.exc_info()[1]
def getATR(self): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() return toHexString(cardservice.connection.getATR())
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: print('Card not found, exiting') sys.exit(1) # Connect to the card if found self.cardservice.connection.connect() print('Connected!')
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 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()
class SIMController: def __init__(self): self.c = None # f**k pyscard. seriously. pass 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 writeTag(value): page = 4 cardtype = AnyCardType() cardreq = CardRequest(timeout=100, cardType=cardtype) cardservice = cardreq.waitforcard() cardservice.connection.connect() print(toHexString(cardservice.connection.getATR())) WRITE_COMMAND = [ 0xFF, 0xD6, 0x00, 0x04, 0x04, int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16), int(value[6:8], 16) ] print(WRITE_COMMAND) #[0xFF, 0xD6, 0x00, int(page), 0x04, int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16), int(value[6:8], 16)] #Let's write a page Page 9 is usually 00000000 #resp = cardservice.connection.transmit(AUTHENTICATE_COMMAND) #print(resp) resp = cardservice.connection.transmit(WRITE_COMMAND) print(resp) if resp[1] == 144: print("Wrote " + str(value)) else: print("Error occured during write operation")
def __init__(self): cardtype = AnyCardType() self.resetCmd = [ 0x0, 0xA4, 0x4, 0x0, 0x8, 0xA0, 0x0, 0x0, 0x0, 0x54, 0x48, 0x0, 0x1 ] self.resetCmd1 = [0x0, 0xC0, 0x0, 0x0, 0xA] self.citizenCmd = [0x80, 0xB0, 0x0, 0x4, 0x2, 0x0, 0xD] self.citizenResponse = [0x0, 0xC0, 0x0, 0x0, 0xD] try: # request card insertion cardrequest = CardRequest(timeout=5, 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() except CardRequestTimeoutException: print 'time-out: no card inserted during last 5s' except: import sys print sys.exc_info()[1]
def __init__(self, threadindex): '''Connect to a card with an ExclusiveTransmitCardConnection.''' threading.Thread.__init__(self) self.threadindex = threadindex # request any card type cardtype = AnyCardType() cardrequest = CardRequest(timeout=5, cardType=cardtype) cardservice = cardrequest.waitforcard() # attach our decorator cardservice.connection = ExclusiveTransmitCardConnection(cardservice.connection) # uncomment to attach the console tracer #observer=ConsoleCardConnectionObserver() #cardservice.connection.addObserver(observer) # connect to the card cardservice.connection.connect() self.cardservice = cardservice # this event will signal the end of the thread self.evtStop = threading.Event() # this timer will set the event stop event in 30s timer = threading.Timer(30, signalEvent, [self.evtStop]) timer.start() self.countTransmitted = 0
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 getCard(): try: cardrequest = CardRequest(timeout=60) cardservice = cardrequest.waitforcard() cardservice.connection.connect() return cardservice except Exception: return None
def get_photo_byte(): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) try: cardservice = cardrequest.waitforcard() except: resultdict = { 'status': 'inactive' } return json.dumps(resultdict) cardservice.connection.connect() REQ_PHOTO_P1 = [0x80, 0xB0, 0x01, 0x7B, 0x02, 0x00, 0xFF] REQ_PHOTO_P2 = [0x80, 0xB0, 0x02, 0x7A, 0x02, 0x00, 0xFF] REQ_PHOTO_P3 = [0x80, 0xB0, 0x03, 0x79, 0x02, 0x00, 0xFF] REQ_PHOTO_P4 = [0x80, 0xB0, 0x04, 0x78, 0x02, 0x00, 0xFF] REQ_PHOTO_P5 = [0x80, 0xB0, 0x05, 0x77, 0x02, 0x00, 0xFF] REQ_PHOTO_P6 = [0x80, 0xB0, 0x06, 0x76, 0x02, 0x00, 0xFF] REQ_PHOTO_P7 = [0x80, 0xB0, 0x07, 0x75, 0x02, 0x00, 0xFF] REQ_PHOTO_P8 = [0x80, 0xB0, 0x08, 0x74, 0x02, 0x00, 0xFF] REQ_PHOTO_P9 = [0x80, 0xB0, 0x09, 0x73, 0x02, 0x00, 0xFF] REQ_PHOTO_P10 = [0x80, 0xB0, 0x0A, 0x72, 0x02, 0x00, 0xFF] REQ_PHOTO_P11 = [0x80, 0xB0, 0x0B, 0x71, 0x02, 0x00, 0xFF] REQ_PHOTO_P12 = [0x80, 0xB0, 0x0C, 0x70, 0x02, 0x00, 0xFF] REQ_PHOTO_P13 = [0x80, 0xB0, 0x0D, 0x6F, 0x02, 0x00, 0xFF] REQ_PHOTO_P14 = [0x80, 0xB0, 0x0E, 0x6E, 0x02, 0x00, 0xFF] REQ_PHOTO_P15 = [0x80, 0xB0, 0x0F, 0x6D, 0x02, 0x00, 0xFF] REQ_PHOTO_P16 = [0x80, 0xB0, 0x10, 0x6C, 0x02, 0x00, 0xFF] REQ_PHOTO_P17 = [0x80, 0xB0, 0x11, 0x6B, 0x02, 0x00, 0xFF] REQ_PHOTO_P18 = [0x80, 0xB0, 0x12, 0x6A, 0x02, 0x00, 0xFF] REQ_PHOTO_P19 = [0x80, 0xB0, 0x13, 0x69, 0x02, 0x00, 0xFF] REQ_PHOTO_P20 = [0x80, 0xB0, 0x14, 0x68, 0x02, 0x00, 0xFF] PHOTO = [REQ_PHOTO_P1, REQ_PHOTO_P2, REQ_PHOTO_P3, REQ_PHOTO_P4, REQ_PHOTO_P5, REQ_PHOTO_P6, REQ_PHOTO_P7, REQ_PHOTO_P8, REQ_PHOTO_P9, REQ_PHOTO_P10, REQ_PHOTO_P11, REQ_PHOTO_P12, REQ_PHOTO_P13, REQ_PHOTO_P14, REQ_PHOTO_P15, REQ_PHOTO_P16, REQ_PHOTO_P17, REQ_PHOTO_P18, REQ_PHOTO_P19, REQ_PHOTO_P20] photobytearray = bytearray() apdu = SELECT+THAI_ID_CARD response, sw1, sw2 = cardservice.connection.transmit(apdu) # custom fphoto = open("photos/current.jpeg", "wb") for d in PHOTO: response, sw1, sw2 = cardservice.connection.transmit(d) if sw1 == 0x61: GET_RESPONSE = [0X00, 0XC0, 0x00, 0x00] apdu = GET_RESPONSE + [sw2] response, sw1, sw2 = cardservice.connection.transmit(apdu) photobytearray.extend(bytearray(response)) # custom fphoto.write(bytearray(response)) return photobytearray
def __init__(self, clientkey_enc, clientcert_enc, clientkey_sig, clientcert_sig, 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.clientKey_enc = RsaKeyHolder(clientkey_enc) self.clientCert_enc = CVCertificate(clientcert_enc) self.clientKey_sig = RsaKeyHolder(clientkey_sig) self.clientCert_sig = CVCertificate(clientcert_sig) self.tp_key = RsaKeyHolder(tp_key) self.tp_cert = CVCertificate(tp_cert) self.cardKey_enc = None self.cardCert_enc = None self.cardKey_sig = None self.cardCert_sig = 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 connect_to_smartcard(verbose=True): cardtype = AnyCardType() cardrequest = CardRequest(timeout=.2, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() atr = cardservice.connection.getATR() if verbose == True: print("ATR: " + toHexString(atr)) return cardservice
def __init__(self): cardtype = AnyCardType() cardrequest = CardRequest(timeout=10, cardType=cardtype) self.card = cardrequest.waitforcard() self.card.connection.connect() self.ins_db = [] self.ins_db_update(INS_DB) self.log = [] self.auto_get_response = True
def connect(): try: cardtype = AnyCardType() cardrequest = CardRequest(cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() return cardservice except: print(RED + "[x] please enter your card" + ENDC) sys.exit()
def readTag(): cardtype = AnyCardType() cardrequest = CardRequest( timeout=10, cardType=cardtype ) cardservice = cardrequest.waitforcard() cardservice.connection.connect() COMMAND = [0xFF, 0xCA, 0x00, 0x00, 0x00] #cmd necessari per inicialitzar la transmissió de dades tagID, sw1, sw2 = cardservice.connection.transmit(COMMAND) #retorna 3 dades print("\t>>> Your UID is: ") print("\t>>> 0x{}".format(listenToString(toHexString(tagID))))
class SmartCardReader(object): def __init__(self): self.cardtype = AnyCardType() def is_card_inserted(self, timeout=1): self.cardrequest = CardRequest( timeout=timeout, cardType=self.cardtype ) try: self.cardservice = self.cardrequest.waitforcard() except CardRequestTimeoutException: return False return True
def request_any_card(cardtype): cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() atr = ATR(cardservice.connection.getATR()) atr_hex = toHexString(cardservice.connection.getATR()) # print_atr_info(atr) return atr_hex, atr
def __init__(self, add_a_byte, pinmin, pinmax, fixed): cardtype = AnyCardType() cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() self.connection = cardservice.connection self.verify_ioctl = -1 self.modify_ioctl = -1 self.another_byte = add_a_byte self.pinmin = pinmin self.pinmax = pinmax self.fixed = fixed
def get_photo_json(): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() REQ_PHOTO_P1 = [0x80, 0xB0, 0x01, 0x7B, 0x02, 0x00, 0xFF] REQ_PHOTO_P2 = [0x80, 0xB0, 0x02, 0x7A, 0x02, 0x00, 0xFF] REQ_PHOTO_P3 = [0x80, 0xB0, 0x03, 0x79, 0x02, 0x00, 0xFF] REQ_PHOTO_P4 = [0x80, 0xB0, 0x04, 0x78, 0x02, 0x00, 0xFF] REQ_PHOTO_P5 = [0x80, 0xB0, 0x05, 0x77, 0x02, 0x00, 0xFF] REQ_PHOTO_P6 = [0x80, 0xB0, 0x06, 0x76, 0x02, 0x00, 0xFF] REQ_PHOTO_P7 = [0x80, 0xB0, 0x07, 0x75, 0x02, 0x00, 0xFF] REQ_PHOTO_P8 = [0x80, 0xB0, 0x08, 0x74, 0x02, 0x00, 0xFF] REQ_PHOTO_P9 = [0x80, 0xB0, 0x09, 0x73, 0x02, 0x00, 0xFF] REQ_PHOTO_P10 = [0x80, 0xB0, 0x0A, 0x72, 0x02, 0x00, 0xFF] REQ_PHOTO_P11 = [0x80, 0xB0, 0x0B, 0x71, 0x02, 0x00, 0xFF] REQ_PHOTO_P12 = [0x80, 0xB0, 0x0C, 0x70, 0x02, 0x00, 0xFF] REQ_PHOTO_P13 = [0x80, 0xB0, 0x0D, 0x6F, 0x02, 0x00, 0xFF] REQ_PHOTO_P14 = [0x80, 0xB0, 0x0E, 0x6E, 0x02, 0x00, 0xFF] REQ_PHOTO_P15 = [0x80, 0xB0, 0x0F, 0x6D, 0x02, 0x00, 0xFF] REQ_PHOTO_P16 = [0x80, 0xB0, 0x10, 0x6C, 0x02, 0x00, 0xFF] REQ_PHOTO_P17 = [0x80, 0xB0, 0x11, 0x6B, 0x02, 0x00, 0xFF] REQ_PHOTO_P18 = [0x80, 0xB0, 0x12, 0x6A, 0x02, 0x00, 0xFF] REQ_PHOTO_P19 = [0x80, 0xB0, 0x13, 0x69, 0x02, 0x00, 0xFF] REQ_PHOTO_P20 = [0x80, 0xB0, 0x14, 0x68, 0x02, 0x00, 0xFF] PHOTO = [ REQ_PHOTO_P1, REQ_PHOTO_P2, REQ_PHOTO_P3, REQ_PHOTO_P4, REQ_PHOTO_P5, REQ_PHOTO_P6, REQ_PHOTO_P7, REQ_PHOTO_P8, REQ_PHOTO_P9, REQ_PHOTO_P10, REQ_PHOTO_P11, REQ_PHOTO_P12, REQ_PHOTO_P13, REQ_PHOTO_P14, REQ_PHOTO_P15, REQ_PHOTO_P16, REQ_PHOTO_P17, REQ_PHOTO_P18, REQ_PHOTO_P19, REQ_PHOTO_P20 ] resultdict = dict() photobytearray = list() apdu = SELECT + THAI_ID_CARD response, sw1, sw2 = cardservice.connection.transmit(apdu) for d in PHOTO: response, sw1, sw2 = cardservice.connection.transmit(d) if sw1 == 0x61: GET_RESPONSE = [0X00, 0XC0, 0x00, 0x00] apdu = GET_RESPONSE + [sw2] response, sw1, sw2 = cardservice.connection.transmit(apdu) for i in response: photobytearray.append(i) resultdict = {'status': 'active', 'photo': photobytearray} return Response(json.dumps(resultdict), mimetype='application/json')
def testcase_CardRequestATRCardType(self): """Test smartcard.AnyCardType.""" for atr in expectedATRs: if [] != atr: ct = ATRCardType(atr) cr = CardRequest(timeout=10, cardType=ct) cs = cr.waitforcard() cs.connection.connect() self.assertEquals(atr, cs.connection.getATR()) self.assertEquals(cs.connection.getReader(), expectedReaderForATR[toHexString(atr)]) cs.connection.disconnect()
def testcase_CardRequestAnyCardTypeInSelectedReader(self): """Test smartcard.AnyCardType.""" for reader in expectedReaders: atr = expectedATRinReader[reader] if [] != atr: ct = AnyCardType() cr = CardRequest(timeout=10.6, readers=[reader], cardType=ct) cs = cr.waitforcard() cs.connection.connect() self.assertEquals(atr, cs.connection.getATR()) self.assertEquals(cs.connection.getReader(), expectedReaderForATR[toHexString(atr)])
def get_status(): ##header("Content-type: application/json") cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) try: cardservice = cardrequest.waitforcard() except: resultdict = {'status': 'inactive'} return json.dumps(resultdict) resultdict = {'status': 'active'} return Response(json.dumps(resultdict), mimetype='application/json')
def connect_to_card(): cardtype = AnyCardType() cardrequest = CardRequest(timeout=None, cardType=cardtype, newcardonly=True) print("Waiting for card insertion...") cardservice = cardrequest.waitforcard() cardservice.connection.connect() print("Card ATR: %s" % toHexString(cardservice.connection.getATR())) return cardservice
def run(): global cardservice try: cardtype = AnyCardType() cardreq = CardRequest(timeout=30,cardType=cardtype) cardservice = cardreq.waitforcard() cardservice.connection.setErrorCheckingChain(errorchain) cardservice.connection.connect() print "ATR = ", toHexString(cardservice.connection.getATR()) except SWException, e: print str(e) return False
def run(): global cardservice try: cardtype = AnyCardType() cardreq = CardRequest(timeout=30, cardType=cardtype) cardservice = cardreq.waitforcard() cardservice.connection.setErrorCheckingChain(errorchain) cardservice.connection.connect() print "ATR = ", toHexString(cardservice.connection.getATR()) except SWException, e: print str(e) return False
def get_data(): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) try: cardservice = cardrequest.waitforcard() except: resultdict = { 'status': 'inactive' } return json.dumps(resultdict) stat = cardservice.connection.connect() REQ_CID = [0x80, 0xb0, 0x00, 0x04, 0x02, 0x00, 0x0d] REQ_THAI_NAME = [0x80, 0xb0, 0x00, 0x11, 0x02, 0x00, 0x64] REQ_ENG_NAME = [0x80, 0xb0, 0x00, 0x75, 0x02, 0x00, 0x64] REQ_GENDER = [0x80, 0xb0, 0x00, 0xE1, 0x02, 0x00, 0x01] REQ_DOB = [0x80, 0xb0, 0x00, 0xD9, 0x02, 0x00, 0x08] REQ_ADDRESS = [0x80, 0xb0, 0x15, 0x79, 0x02, 0x00, 0x64] REQ_ISSUE_EXPIRE = [0x80, 0xb0, 0x01, 0x67, 0x02, 0x00, 0x0C] DATA = [REQ_CID, REQ_THAI_NAME, REQ_ENG_NAME, REQ_GENDER, REQ_DOB, REQ_ADDRESS, REQ_ISSUE_EXPIRE] apdu = SELECT+THAI_ID_CARD response, sw1, sw2 = cardservice.connection.transmit(apdu) resultlist = list() for d in DATA: response, sw1, sw2 = cardservice.connection.transmit(d) if sw1 == 0x61: GET_RESPONSE = [0X00, 0XC0, 0x00, 0x00] apdu = GET_RESPONSE + [sw2] response, sw1, sw2 = cardservice.connection.transmit(apdu) result = '' for i in response: result = result + tis620encoding[i] resultlist.append(result) resultdict = { 'status': 'active', 'idnumber': resultlist[0], 'thainame': resultlist[1], 'englishname': resultlist[2], 'gender': resultlist[3], 'dob': resultlist[4], 'address': resultlist[5], 'issueexpire': resultlist[6], } return Response(json.dumps(resultdict), mimetype='application/json')
def receiveCard(): cardtype = AnyCardType() cardrequest = CardRequest(timeout = 120, cardType = cardtype) while (1): try: cardservice = cardrequest.waitforcard() except CardRequestTimeoutException: continue return cardservice.connection
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.assertEquals(cs.__class__, smartcard.PassThruCardService.PassThruCardService) self.assertEquals(atr, cs.connection.getATR()) self.assertEquals(cs.connection.getReader(), expectedReaderForATR[toHexString(atr)])
def sc_connect(): global cardservice # detect the smart card based on the content of the ATR (card-centric approach) print('Initializing card connection...') try: cardtype = ATRCardType( toBytes( "3B 90 11 00" ) ) cardrequest = CardRequest( timeout=5, cardType=cardtype ) cardservice = cardrequest.waitforcard() print('Card connection established correctly') except: print('ERROR: Timeout exceeded') sys.exit(0) # connect to the card using T0 protocol. cardservice.connection.connect( CardConnection.T0_protocol )
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, e: elapsed = int(10 * (time.time() - before)) print '.', self.assert_(elapsed >= 10 and elapsed <= 11.) count += 1
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: try: cardType = ATRCardType( toBytes( "%s" %toHexString(card.atr) )) cardRequest = CardRequest(timeout = 1, cardType = cardType) cardService = cardRequest.waitforcard() cardService.connection.connect() SELECT = [0xFF, 0xCA, 0x00, 0x00, 0x00] apdu = SELECT #print ("sending" + toHexString(apdu)) response, sw1, sw2 = cardService.connection.transmit( apdu ) #print ('response: ', response, ' status words: ', "%x %x" % (sw1, sw2)) hexUID = self.getParseHexUID(response) #print (hexUID) self.process(hexUID) # id = tagid # print ("UID is",id) except Exception as e: print (e)
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.assert_(elapsed <= 55.) except CardRequestTimeoutException, e: print 'too slow... Test will show a failure'
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 main(): """ Retrieves the ID of the attached Card and returns it as keyboard-presses """ while True: try: # define the apdus used in this script apdu = [0xFF, 0xCA, 0x00, 0x00, 0x00] # request card insertion card_request = CardRequest(timeout=None, cardType=AnyCardType(), newcardonly=True) card_service = card_request.waitforcard() # connect to the card and perform a few transmits card_service.connection.connect() response, sw1, sw2 = card_service.connection.transmit(apdu) rfid_string = '_'.join([str(id_val) for id_val in response]) keyboard = PyKeyboard() keyboard.type_string('<U>RFID_ID_'+rfid_string) except: continue
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 )
def run(self): ### INIT GPS SUPPORT ### if pysharegpsloaded: logging.info("gps support enabling...") gpsProxy = sharedGpsClient() if gpsProxy.isInit(): logging.info("gps support enabled") else: logging.info("gps support not enabled. retry later.") else: logging.warning("gps support not installed") gpsProxy = None ### INIT SMARTCARD ### while True: #sometime, pcscd take time to start try: from smartcard.CardType import AnyCardType from smartcard.CardRequest import CardRequest from smartcard.scard import INFINITE from smartcard.Exceptions import CardConnectionException #card type cardtype = AnyCardType() #card request cardrequest = CardRequest(timeout=INFINITE, newcardonly=True,cardType=cardtype ) break except Exception as ex: logging.exception("failed to load smartcard : "+str(ex)) logging.shutdown() time.sleep(2) continue logging.info("smartcard loaded") ### DUMP PROCESS ### while True: logging.info("wait card") try: cardservice = cardrequest.waitforcard() except Exception as cte: logging.exception("wait card Exception : "+str(cte)) time.sleep(2) continue logging.info("new card") currentDump = None fileName = None try: #init dump recording currentDump = dump() #and new dump object ## dump the tag ## try: cardservice.connection.connect()#connect to the card dumpSkipass(cardservice.connection, currentDump) cardservice.connection.disconnect()## disconnect dump except CardConnectionException as cce: logging.exception("CardConnectionException : "+str(cce)) except Exception as e: logging.exception("save dump exception : "+str(e)) ## recolt and process env info ## #build a first simple file name dtime = datetime.datetime.now() fileName = str(dtime).replace(" ","_").replace(":","_").replace(".","_")+".txt" currentDump.setCurrentDatetime() currentDump.setExtraInformation("DumpProcessLogId",self.localid) nextDumpID = getLogNextId(MAINREP) fileName = str(nextDumpID)+"_"+fileName currentDump.setExtraInformation("DumpFileId",nextDumpID) logging.info("DumpFileId : "+str(nextDumpID)) ## UID management ## #uid is the minimal information needed to save a dump, if it is not available, not saved #a tag has always an uid, if it is not set, the connection had been broke before to read it uid = None if len(currentDump.getUID()) == 0: logging.warning("empty uid") else: # update path name uid = currentDump.getUIDString().replace(" ","") fileName = uid+"_"+fileName if uid in owners: currentDump.setOwner(owners[uid]) else: currentDump.setOwner("unknown") logging.warning("uid not in the owner list") logging.info("dump uid: "+uid) ## gps management ## if gpsProxy != None: #is there gps support ? if gpsProxy.isInit(): position = gpsProxy.getSharedObject().getPosition() print position currentDump.setPosition(*position) print gpsProxy.getSharedObject().getAltitude() currentDump.setAltitude(*gpsProxy.getSharedObject().getAltitude()) place = gpsProxy.getSharedObject().getPlace() if place[4] != None: currentDump.setLocation(*place) currentDump.setExtraInformation("GpsLogId",gpsProxy.getSharedObject().getGpsLogId()) if uid != None: gpsProxy.getSharedObject().addPointOfInterest(position[0], position[1], uid, "dump of "+uid+" at "+dtime.isoformat()+" (file key ="+str(nextDumpID)+")") else: currentDump.setExtraInformation("gps","gps support does not work") logging.warning("need to re init pyro") gpsProxy.reInit() else: currentDump.setExtraInformation("gps","gps support is not supported") except Exception as ex: logging.exception("dump exception : "+str(ex)) if self.debug: exit() time.sleep(2) #wait two secs to allow the system to stabilyse if the environment is not ready #and also to prevent a log rush if the problem is still present at the next iteration finally: ## save the dump ## if currentDump == None or fileName == None: logging.critical("Can't save the dump, currentDump or fileName is None") else: try: saveDump(currentDump, MAINREP+"dump_"+fileName) except Exception as e: logging.exception("save dump exception : "+str(e))
if ret == True: readafl() readcardinfo() readhist() printcardinfo() printtranshist() ''' apdu = readrecord(0xC, 0x1) resp = transmit(apdu) gotresp(resp) apdu = selectcmd('a0 00 00 03 33 01 01 01') resp = transmit(apdu) print toHexString(apdu) gotresp(resp) apdu = gpo('600000000000000000000000000000000156000000000001561309250000000000') resp = transmit(apdu) gotresp(resp) ''' cardtype = AnyCardType() cardrequest = CardRequest( timeout=10, cardType=cardtype ) card = cardrequest.waitforcard() card.connection.connect() logic() #transhist()
def __init__(self): cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() self.connection = cardservice.connection
def __enter__(self): """Set up context with a connection to the card.""" cr = CardRequest(timeout=self._timeout, cardType=self._card_type) self.cardservice = cr.waitforcard() self.cardservice.connection.connect() return self
class ReaderPCSC(ReaderTemplate): _name = "PC/SC Reader" def __init__(self): ReaderTemplate.__init__(self) self.timeoutTimer = timer.Timer() self.timeoutTimer.timeout.connect(self.timeoutFired) self.timeoutTimer.setInterval(2000) self.getParams().addChildren([ {'name':'Keep-Alive Interval (off=0)', 'type':'int', 'value':2, 'set':self.setKeepalive} ]) @setupSetParam("Keep-Alive Interval (off=0)") def setKeepalive(self, kinterval): self.timeoutTimer.setInterval(kinterval*1000) def timeoutFired(self): self.scserv.connection.connect() def sendAPDU(self, cla, ins, p1, p2, txdata=None, rxdatalen=0): """Send APDU to SmartCard, get Response""" data = [cla,ins, p1, p2] if txdata is not None: txdatalen = len(txdata) data.append(txdatalen) else: txdatalen = 0 if (txdata is None) & (rxdatalen == 0): data.append(0) # Append payload if txdata is not None: for b in txdata: data.append(b) if rxdatalen != 0: data.append(rxdatalen) response, sw1, sw2 = self.scserv.connection.transmit(data , CardConnection.T0_protocol) status = (sw1 << 8) | sw2 if rxdatalen > 0: return (status, response) return status def con(self, scope=None): """Connect to reader. scope parameter is OpenADC/ChipWhisperer hardware, only used to integrated readers""" try: self.sccard = AnyCardType() self.screq = CardRequest(timeout=1, cardType=self.sccard) self.scserv = self.screq.waitforcard() if not self.timeoutTimer.isActive(): self.timeoutTimer.start() print "SCARD: Connected..." except Exception: raise Exception("SCARD: Failed to connect...") def flush(self): """Discard all input buffers""" pass def reset(self): """Reset card & save the ATR""" pass def getATR(self): """Get the ATR from the SmartCard. Reads a saved value, user reset() to actually reset card.""" pass def dis(self): self.scserv.connection.disconnect() self.timeoutTimer.stop()
class ReaderPCSC(ReaderTemplate): def __init__(self, console=None, showScriptParameter=None): super(ReaderPCSC, self).__init__(console, showScriptParameter) if AnyCardType is None: raise ImportError("smartcard libraries missing") def setupParameters(self): ssParams = [{'name':'Keep-Alive Interval (off=0)', 'type':'int', 'value':2, 'set':self.setKeepalive} ] self.params = Parameter.create(name='Target Connection', type='group', children=ssParams) ExtendedParameter.setupExtended(self.params, self) self.timeoutTimer = QTimer() self.timeoutTimer.timeout.connect(self.timeoutFired) self.timeoutTimer.setInterval(2000) def setKeepalive(self, kinterval): self.timeoutTimer.setInterval(kinterval*1000) def timeoutFired(self): self.scserv.connection.connect() def sendAPDU(self, cla, ins, p1, p2, txdata=None, rxdatalen=0): """Send APDU to SmartCard, get Response""" data = [cla,ins, p1, p2] if txdata is not None: txdatalen = len(txdata) data.append(txdatalen) else: txdatalen = 0 if (txdata is None) & (rxdatalen == 0): data.append(0) #Append payload if txdata is not None: for b in txdata: data.append(b) if rxdatalen != 0: data.append(rxdatalen) response, sw1, sw2 = self.scserv.connection.transmit(data , CardConnection.T1_protocol) status = (sw1 << 8) | sw2; if rxdatalen > 0: return (status, response) return status def con(self, oa=None): """Connect to reader. oa parameter is OpenADC/ChipWhisperer hardware, only used to integrated readers""" try: self.sccard = AnyCardType() self.screq = CardRequest(timeout=1, cardType=self.sccard) self.scserv = self.screq.waitforcard() #observer = ConsoleCardConnectionObserver() #self.scserv.connection.addObserver( observer ) if not self.timeoutTimer.isActive(): self.timeoutTimer.start() except CardRequestTimeoutException: return False return True def flush(self): """Discard all input buffers""" pass def reset(self): """Reset card & save the ATR""" pass def getATR(self): """Get the ATR from the SmartCard. Reads a saved value, user reset() to actually reset card.""" pass def dis(self): self.scserv.connection.disconnect() self.timeoutTimer.stop()