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
示例#2
0
    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]
示例#3
0
 def __init__(self):
     self.readerList = readers()
     self.cardtype = AnyCardType()
     self.cardrequest = CardRequest(readers=self.readerList,
                                    timeout=7000,
                                    cardType=self.cardtype)
     self.cardservice = self.cardrequest.waitforcard()
示例#4
0
    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
示例#5
0
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 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 []
示例#7
0
 def french_apdu(self,
                 rand=None,
                 autn=None,
                 scope=None,
                 debug=False,
                 trigger=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
     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
     if trigger is not None:
         trigger.arm()
     scope.arm()
     r, sw1, sw2 = self.c.transmit(authcmd)
 def nextg_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("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
   trigger.arm()
   print("Arming")
   r,sw1,sw2 = self.c.transmit(authcmd)
示例#9
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:
            print('Card not found, exiting')
            sys.exit(1)

        # Connect to the card if found
        self.cardservice.connection.connect()
        print('Connected!')
示例#10
0
    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()
示例#11
0
 def __init__(self, filename="aid_list.txt"):
     self._cardtype = AnyCardType()
     self._cardrequest = CardRequest(timeout=10, cardType=self._cardtype)
     self._cardservice = self._cardrequest.waitforcard()
     self._cardservice.connection.connect()
     #print toHexString(self._cardservice.connection.getATR())
     self.aids = self._getAids(filename)
示例#12
0
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")
示例#13
0
 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 
示例#14
0
    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
示例#16
0
 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:
         # maybe 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()
             # retransmit apdu
             (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 CardRequestTimeoutException:
             self.print_error('time-out: no card inserted during last 10s')
         except Exception as exc:
             self.print_error("Error during connection:", repr(exc),
                              traceback.format_exc())
示例#17
0
 def __init__(self, client):
     # request any card type
     #self.print_error("** client", client, " ** handler", client.handler)
     self.client = client
     self.parser = client.parser
     self.cardtype = AnyCardType()
     self.needs_2FA = None
     try:
         # request card insertion
         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)
         # attach the card removal observer
         self.cardmonitor = CardMonitor()
         self.cardobserver = RemovalObserver(self)
         self.cardmonitor.addObserver(self.cardobserver)
         # connect to the card and perform a few transmits
         self.cardservice.connection.connect()
         # cache PIN
         self.pin_nbr = None
         self.pin = None
     except CardRequestTimeoutException:
         self.print_error('time-out: no card inserted during last 10s')
     except Exception as exc:
         self.print_error("Error during connection:", repr(exc),
                          traceback.format_exc())
示例#18
0
 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)
示例#19
0
    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()
示例#20
0
 def __init__(self, client):
     # request any card type
     self.client = client
     self.parser = client.parser
     self.cardtype = AnyCardType()
     try:
         # request card insertion
         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)
         # attach the card removal observer
         self.cardmonitor = CardMonitor()
         self.cardobserver = RemovalObserver(self)
         self.cardmonitor.addObserver(self.cardobserver)
         # connect to the card and perform a few transmits
         self.cardservice.connection.connect()
         # cache PIN
         self.pin_nbr = None
         self.pin = None
     except CardRequestTimeoutException:
         _logger.exception('time-out: no card inserted during last 10s')
     except Exception as exc:
         _logger.exception("Error during connection: {str(exc)}")
示例#21
0
    def getATR(self):
        cardtype = AnyCardType()
        cardrequest = CardRequest(timeout=1, cardType=cardtype)
        cardservice = cardrequest.waitforcard()

        cardservice.connection.connect()
        return toHexString(cardservice.connection.getATR())
示例#22
0
    def getATR(self):
        cardtype = AnyCardType()
        cardrequest = CardRequest(timeout=1, cardType=cardtype)
        cardservice = cardrequest.waitforcard()

        cardservice.connection.connect()
        return toHexString(cardservice.connection.getATR())
示例#23
0
    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 __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
示例#25
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
示例#26
0
    def __init__(self, srv, db, user, pwd):
        # this will wait until card inserted in any reader
        self.channel = CardRequest(
            timeout=10, cardType=AnyCardType()).waitforcard().connection

        # using T=0 for compatibility (i.e., DigiID) and simplicity
        self.channel.connect()
        print "[+] Leitor:", self.channel.getReader()

        # Card Results
        self.card_results()

        # Odoo connection
        common = xmlrpclib.ServerProxy('%s/xmlrpc/2/common' % (srv))
        self.api = xmlrpclib.ServerProxy('%s/xmlrpc/2/object' % (srv))
        self.uid = common.authenticate(db, user, pwd, {})
        self.pwd = pwd
        self.db = db
        self.model = 'res.partner'

        toaster.show_toast(
            "CART\xc3O DO CIDAD\xc3O",
            "A ligar ao odoo!",
            icon_path="custom.ico",
            duration=0,
        )

        # Insert in Odoo
        #a = self.get()
        id = self.set()
        print "/n>>> Registo inserido no odoo/n"

        url = 'http://odoo9-cartaocidadao-pedroposeiro.c9users.io/web#id=%s&view_type=form&model=res.partner' % (
            id)
        webbrowser.open_new(url)
示例#27
0
	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()
示例#28
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))
示例#29
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
示例#31
0
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
示例#32
0
 def removeAllCards(self):
     print('please remove all inserted smart cards')
     cardrequest = CardRequest()
     while True:
         cards = cardrequest.waitforcardevent()
         if 0 == len(cards):
             break
         time.sleep(.3)
     print('ok')
示例#33
0
 def removeAllCards(self):
     print 'please remove all inserted smart cards'
     cardrequest = CardRequest()
     while True:
         cards = cardrequest.waitforcardevent()
         if 0 == len(cards):
             break
         time.sleep(.3)
     print 'ok'
示例#34
0
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
示例#35
0
    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)
示例#36
0
	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
示例#37
0
    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()
示例#39
0
 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
示例#40
0
    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()
示例#41
0
    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)])
示例#42
0
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
示例#43
0
def receiveCard():
	cardtype = AnyCardType()
	cardrequest = CardRequest(timeout = 120, cardType = cardtype)
	
	while (1):
		try:
			cardservice = cardrequest.waitforcard()
			
		except CardRequestTimeoutException:
			continue
			
			
		return cardservice.connection
示例#44
0
    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 )
示例#46
0
    class __CardMonitoringThreadSingleton(Thread):
        """The real card monitoring thread class.

        A single instance of this class is created
        by the public CardMonitoringThread class.
        """

        def __init__(self, observable):
            Thread.__init__(self)
            self.observable = observable
            self.stopEvent = Event()
            self.stopEvent.clear()
            self.cards = []
            self.setDaemon(True)

        # the actual monitoring thread
        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()

        # stop the thread by signaling stopEvent
        def stop(self):
            self.stopEvent.set()
    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)
示例#48
0
    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
示例#49
0
 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)
示例#50
0
    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)
示例#52
0
    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...")
示例#53
0
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
示例#54
0
    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        
示例#55
0
        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 SmartcardException as exc:
                    # 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.
                    if exc.hresult == SCARD_E_NO_SERVICE:
                        self.stopEvent.set()
示例#56
0
        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
示例#57
0
	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 )
示例#58
0
 def __init__(self):
     cardtype = AnyCardType()
     cardrequest = CardRequest(timeout=1, cardType=cardtype)
     cardservice = cardrequest.waitforcard()
     self.connection = cardservice.connection
示例#59
0
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()
示例#60
0
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()