def get_tag(): context = nfc.init() pnd = nfc.open(context) if pnd is None: print('ERROR: Unable to open NFC device.') exit() if nfc.initiator_init(pnd) < 0: nfc.perror(pnd, "nfc_initiator_init") print('ERROR: Unable to init NFC device.') exit() # Declare modulations nmMifare = nfc.modulation() nmMifare.nmt = nfc.NMT_ISO14443A nmMifare.nbr = nfc.NBR_106 nt = nfc.target() # Wait for tag ret = nfc.initiator_select_passive_target(pnd, nmMifare, 0, 0, nt) # Convert raw uid to hex, then trim to length (2*nt.nti.nai.szUidLen) tag = ''.join(format(x, '02x') for x in nt.nti.nai.abtUid)[:2*nt.nti.nai.szUidLen] nfc.close(pnd) nfc.exit(context) # Return UID return tag
def run(self): if debug: print("started thread") nms = [] nm = nfc.modulation() nm.nmt = nfc.NMT_ISO14443A nm.nbr = nfc.NBR_106 nms.append(nm) while self.running: sleep(0.1) # Python doesn't have a yield function, this is to make sure that other threads also have time to serve requests target = nfc.target() status = nfc.initiator_poll_target(self.pnd, nm, 1, 0x01, 0x02, target) if status > 0: uid = ":".join(["{:0>2x}".format(target.nti.nai.abtUid[i]) for i in range(target.nti.nai.szUidLen)]) atqa = ":".join(["{:0>2x}".format(target.nti.nai.abtAtqa[i]) for i in range(2)]) sak = "{:0>2x}".format(target.nti.nai.btSak) if debug: print(uid, atqa, sak) self.callback(uid, atqa, sak)
def run(self): if debug: print("started thread") nms = [] nm = nfc.modulation() nm.nmt = nfc.NMT_ISO14443A nm.nbr = nfc.NBR_106 nms.append(nm) while self.running: sleep( 0.1 ) # Python doesn't have a yield function, this is to make sure that other threads also have time to serve requests target = nfc.target() status = nfc.initiator_poll_target(self.pnd, nm, 1, 0x01, 0x02, target) if status > 0: uid = ":".join([ "{:0>2x}".format(target.nti.nai.abtUid[i]) for i in range(target.nti.nai.szUidLen) ]) atqa = ":".join([ "{:0>2x}".format(target.nti.nai.abtAtqa[i]) for i in range(2) ]) sak = "{:0>2x}".format(target.nti.nai.btSak) if debug: print(uid, atqa, sak) self.callback(uid, atqa, sak)
def block_for_card(device, target_type=None, nbr=None): """Block (wait) until a card is detected, then return its info. """ modul = nfc.modulation() modul.nmt = target_type if target_type is not None else _target_type modul.nbr = nbr if nbr is not None else _nbr target = nfc.target() # this blocks retval = nfc.initiator_select_passive_target(device, modul, 0, 0, target) if not retval: raise NFCError('Couldn\'t establish initial connection with card', { 'retval': retval, 'target_type': modul.nmt, 'nbr': modul.nbr }) return target
def get_id(self): self.open_device() uid = None modulation = nfc.modulation() modulation.nmt = nfc.NMT_ISO14443A modulation.nbr = nfc.NBR_106 # List ISO14443A targets target = nfc.target() target_count = nfc.initiator_poll_target(self.device, modulation, 1, 30, 1, target) if(target_count >= 0): if (verbose): print(target_count, 'ISO14443A passive target(s) found') nfc.print_nfc_target(target, verbose) uid_len = target.nti.nai.szUidLen uid = target.nti.nai.abtUid[:uid_len] print("UID byte: {}".format(uid)) uid = str(int.from_bytes(uid, byteorder='little')) print("UID int: {}".format(uid)) return uid
def try_read(): if nfc.initiator_select_passive_target(pnd, nmMifare, 0, 0, nt) > -1: return read_sector(7) @atexit.register def close(): nfc.close(pnd) nfc.exit(context) accessBits = compute_access_bits(c1, c2, c3) context = nfc.init() pnd = nfc.open(context) if pnd is None: raise Exception('ERROR: Unable to open NFC device.') if nfc.initiator_init(pnd) < 0: nfc.perror(pnd, "nfc_initiator_init") raise Exception('ERROR: Unable to init NFC device.') print('NFC reader: %s opened' % nfc.device_get_name(pnd)) nmMifare = nfc.modulation() nmMifare.nmt = nfc.NMT_ISO14443A nmMifare.nbr = nfc.NBR_106 nt = nfc.target()
def nfcProtocol(): """ NFC Protocol """ global pnd, nt, context nmMifare = nfc.modulation() nmMifare.nmt = nfc.NMT_ISO14443A nmMifare.nbr = nfc.NBR_106 print("Polling for target...\n"); nt = nfc.target() ret = nfc.initiator_select_passive_target(pnd, nmMifare, 0, 0, nt) print("Target detected!\n"); # Select application pbtTx = DoorProtocol['APDU'] szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_HELLO']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) print("Application selected!"); print("REC: " + rapdu) if rapdu != DoorProtocol['DOOR_HELLO']: print("** Opss ** I'm expecting HELLO msg, but card sent to me: %s. len: %d\n" % (rapdu, len(rapdu))) sys.exit(1) # FIDO Auth Request Message print("Doing AuthRequest to FIDO UAF Server\n"); UAFurl = fido_server['AUTH_REQUEST_MSG'] % (fido_server['SCHEME'], fido_server['HOSTNAME'], fido_server['PORT'], fido_server['AUTH_REQUEST_ENDPOINT']) try: r = requests.get(UAFurl) r.raise_for_status() except requests.exceptions.RequestException as e: # This is the correct syntax print(e) sys.exit(1) if (r.status_code != 200): print("** Opss ** Error to connect to FIDO Server") pbtTx = DoorProtocol['ERROR'] szTx = len(pbtTx) szRx = len(DoorProtocol['ERROR']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) sys.exit(1) content = r.content blocks = (len(content) / BLOCK_SIZE) + 1 pbtTx = "BLOCK:%s" % blocks print("Sending number of blocks: %s " % pbtTx); szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_NEXT']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) print("REC: " + rapdu) if rapdu != DoorProtocol['DOOR_NEXT']: print("Error to send number of blocks") sys.exit(1) # Sending UAFRequestMessage to card chunks = len(content) msg_packages = ([ content[i:i + BLOCK_SIZE] for i in range(0, chunks, BLOCK_SIZE) ]) for pack, index in zip(msg_packages, range(1, chunks+1)): print("Seding package %s..." % index) pbtTx = pack szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_OK']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) if rapdu != DoorProtocol['DOOR_OK']: print("** Opss ** I'm expecting OK msg, but card sent to me: %s. len: %s" % (rapdu, len(rapdu))) sys.exit(1) print("REC: " + rapdu) print("\nSending READY!") pbtTx = DoorProtocol['DOOR_READY'] szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_WAIT']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) if rapdu != DoorProtocol['DOOR_WAIT']: print("** Opss ** I'm expecting WAIT msg, but card sent to me: %s. len: %s" % (rapdu, len(rapdu))) sys.exit(1) print("REC: " + rapdu) print("\nWaiting...\n") time.sleep(5) while rapdu == DoorProtocol['DOOR_WAIT']: szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_DONE']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) print("SEND: " + pbtTx) if rapdu != DoorProtocol['DOOR_DONE'] and rapdu != DoorProtocol['DOOR_WAIT']: print("** Opss ** I'm expecting DONE or WAIT msg, but card sent to me: %s. len: %s" % (rapdu, len(rapdu))) sys.exit(1) print("REC: " + rapdu) if (rapdu == DoorProtocol['DOOR_DONE']): print("Sending RESPONSE!") pbtTx = DoorProtocol['DOOR_RESPONSE'] szTx = len(pbtTx) szRx = len("BLOCK: ") res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) if not "BLOCK" in rapdu: print("** Opss ** I'm expecting RESPONSE msg, but card sent to me: %s. len: %s" % (rapdu, len(rapdu))) sys.exit(1) print("REC: " + rapdu) r_decode = rapdu.decode('utf-8') blocks = re.search(r'\d+', r_decode) blocks = blocks.group() blocks = int(blocks) print("\nBLOCKS:%s" % blocks) UAFmsg = '\0' for block in range(0, blocks): print("receiving block --> %s" % block) pbtTx = DoorProtocol['DOOR_NEXT'] szTx = len(pbtTx) szRx = BLOCK_SIZE res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) UAFmsg += rapdu UAFmsg = "".join(map(chr, UAFmsg)) UAFmsg = bytearry2json(UAFmsg) # FIDO Auth Request Message print("Forwarding card response to FIDO UAF Server: \n") UAFurl = fido_server['AUTH_REQUEST_MSG'] % (fido_server['SCHEME'], fido_server['HOSTNAME'], fido_server['PORT'], fido_server['AUTH_RESPONSE_ENDPOINT']) headers = { 'Accept': 'application/json', 'Content-Type': 'application/json'} r = requests.post(UAFurl, data=UAFmsg, headers=headers) response = json.loads(r.text) if response[0]["status"] == "SUCCESS": pbtTx = DoorProtocol['DOOR_GRANTED'] szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_BYE']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) print("Access granted!"); # ligar led verde response = saml_request() print(etree.tostring(response)) else: pbtTx = DoorProtocol['DOOR_DENY'] szTx = len(pbtTx) szRx = len(DoorProtocol['DOOR_BYE']) res, rapdu = cardTransmit(pnd, pbtTx, szTx, szRx) print("Access denied!"); # ligar led vermelho if (rapdu == DoorProtocol['DOOR_BYE']): print("bye!") else: print(":-(") return
output('libnfc version: ' + nfc.__version__) context = nfc.init() pnd = nfc.open(context) if pnd is None: output('ERROR: Unable to detect RFID sensor (run this as root).') exit() if nfc.initiator_init(pnd) < 0: nfc.perror(pnd, "nfc_initiator_init") output('ERROR: Unable to init RFID sensor.') exit() output('NFC reader: ' + nfc.device_get_name(pnd) + 'opened') nmMifare = nfc.modulation() nmMifare.nmt = nfc.NMT_ISO14443A nmMifare.nbr = nfc.NBR_106 nt = nfc.target() admin_switch = False while True: if not admin_switch: GPIO.cleanup() # Wait for tag ret = nfc.initiator_select_passive_target(pnd, nmMifare, 0, 0, nt)
if szDeviceFound == 0: print("No NFC device found.") for i in range(szDeviceFound): pnd = nfc.open(context, connstrings[i]); if pnd is None: continue if(nfc.initiator_init(pnd)<0): nfc.perror(pnd, "nfc_initiator_init") nfc.close(pnd) nfc.exit(context) exit() print("NFC reader:", nfc.device_get_name(pnd), "opened") nm = nfc.modulation() if mask & 0x1: nm.nmt = nfc.NMT_ISO14443A nm.nbr = nfc.NBR_106 # List ISO14443A targets res, ant = nfc.initiator_list_passive_targets(pnd, nm, max_target_count) if (res >= 0): if (verbose or (res > 0)): print(res, 'ISO14443A passive target(s) found') for n in range(res): nfc.print_nfc_target(ant[n], verbose) print('') nfc.close(pnd) nfc.exit(context)
is_linux = (system() == "Linux") yes_confirm_options = ["yes", "y"] if is_linux: """ Determine if the device this is running on is a linux device and if so, attempt to import necessary nfc modules and prepare for later use of the reader. """ import nfc context = nfc.init() reader = nfc.list_devices(context, 2)[0] listener = nfc.open(context, reader) modulation = nfc.modulation() modulation.nmt = nfc.NMT_ISO14443A modulation.nbr = nfc.NBR_106 def parse_nfc_uid(device): """ Parses from the string returned from nfc.str_nfc_target and just returns the uid. :param device: An object of the card class from nfc's implementation. Get this from initiator_list_passive_targets :return: The uid of the given object. """ num, string = nfc.str_nfc_target(device, False) str_list = string.split("\n") uid = str_list[2].strip().replace(" ", " ") uid = uid[uid.index(": ") + 2:]