예제 #1
1
int NFC_Mifare_Classic(int argc, const char *argv[]) //! Lecture - Écriture d'une carte MIFARE Classic
{
    action_t atAction = ACTION_USAGE;
    uint8_t *pbtUID;
    int    unlock = 0;
    if (argc < 2)
    {
        sprintf(message_erreur,"Syntaxe incorrecte !");
        return EXIT_FAILURE; //! Échec !
    }
    const char *command = argv[1];
    if (strcmp(command, "r") == 0 || strcmp(command, "R") == 0)
    {
        if (argc < 4)
        {
            sprintf(message_erreur,"Syntaxe incorrecte !");
            return EXIT_FAILURE; //! Échec !
        }
        atAction = ACTION_READ;
        if (strcmp(command, "R") == 0)
        {
            unlock = 1;
        }
        bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a';
        bTolerateFailures = tolower((int)((unsigned char) * (argv[2]))) != (int)((unsigned char) * (argv[2]));
        bUseKeyFile = (argc > 4);
        bForceKeyFile = ((argc > 5) && (strcmp((char *)argv[5], "f") == 0));
    }
    else if (strcmp(command, "w") == 0 || strcmp(command, "W") == 0)
    {
        if (argc < 4)
        {
            sprintf(message_erreur,"Syntaxe incorrecte !");
            return EXIT_FAILURE; //! Échec !
        }
        atAction = ACTION_WRITE;
        if (strcmp(command, "W") == 0)
        {
            unlock = 1;
        }
        bUseKeyA = tolower((int)((unsigned char) * (argv[2]))) == 'a';
        bTolerateFailures = tolower((int)((unsigned char) * (argv[2]))) != (int)((unsigned char) * (argv[2]));
        bUseKeyFile = (argc > 4);
        bForceKeyFile = ((argc > 5) && (strcmp((char *)argv[5], "f") == 0));
    }
    if (atAction == ACTION_USAGE)
    {
        sprintf(message_erreur,"Syntaxe incorrecte !");
        return EXIT_FAILURE; //! Échec !
    }
    //! We don't know yet the card size so let's read only the UID from the keyfile for the moment
    if (bUseKeyFile)
    {
        FILE *pfKeys = fopen(argv[4], "rb");
        if (pfKeys == NULL)
        {
            sprintf(message_erreur,"Could not open keys file: %s\n", argv[4]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtKeys, 1, 4, pfKeys) != 4)
        {
            sprintf(message_erreur,"Could not read UID from key file: %s !", argv[4]);
            fclose(pfKeys);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfKeys);
    }
    nfc_init(&context);
    if (context == NULL)
    {
        sprintf(message_erreur,"Unable to init libnfc (malloc) !");
        return EXIT_FAILURE; //! Échec !
    }
    //! Try to open the NFC reader
    pnd = nfc_open(context, NULL);
    if (pnd == NULL)
    {
        sprintf(message_erreur,"Error opening NFC reader !");
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    if (nfc_initiator_init(pnd) < 0)
    {
        nfc_perror(pnd, "nfc_initiator_init");
        nfc_strerror_r(pnd, message_erreur, TAILLE_MESSAGE_ERREUR);
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    };
    //! Let the reader only try once to find a tag
    if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0)
    {
        nfc_perror(pnd, "nfc_device_set_property_bool");
        nfc_strerror_r(pnd, message_erreur, TAILLE_MESSAGE_ERREUR);
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    //! Disable ISO14443-4 switching in order to read devices that emulate Mifare Classic with ISO14443-4 compliance.
    nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false);
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"NFC reader: %s opened\n", nfc_device_get_name(pnd));
    #endif
    //! Try to find a MIFARE Classic tag
    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0)
    {
        sprintf(message_erreur,"Error: no tag was found !");
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    //! Test if we are dealing with a MIFARE compatible tag
    if ((nt.nti.nai.btSak & 0x08) == 0)
    {
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"Warning: tag is probably not a MFC !");
        #endif
    }
    //! Get the info from the current tag
    pbtUID = nt.nti.nai.abtUid;
    if (bUseKeyFile)
    {
        uint8_t fileUid[4];
        memcpy(fileUid, mtKeys.amb[0].mbm.abtUID, 4);
        //! Compare if key dump UID is the same as the current tag UID, at least for the first 4 bytes
        if (memcmp(pbtUID, fileUid, 4) != 0)
        {
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Expected MIFARE Classic card with UID starting as: %02x%02x%02x%02x\n", fileUid[0], fileUid[1], fileUid[2], fileUid[3]);
            fprintf(stderr,"Got card with UID starting as:                     %02x%02x%02x%02x\n", pbtUID[0], pbtUID[1], pbtUID[2], pbtUID[3]);
            #endif
            if (! bForceKeyFile)
            {
                sprintf(message_erreur,"Aborting !");
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
        }
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"Found MIFARE Classic card:\n");
    #endif
    print_nfc_target(&nt, false);
    //! Guessing size
    if ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x02)
        //! 4K
        uiBlocks = 0xff;
    else if ((nt.nti.nai.btSak & 0x01) == 0x01)
        //! 320b
        uiBlocks = 0x13;
    else
        //! 1K/2K, checked through RATS
        uiBlocks = 0x3f;
    //! Testing RATS
    int res;
    if ((res = get_rats()) > 0)
    {
        if ((res >= 10) && (abtRx[5] == 0xc1) && (abtRx[6] == 0x05) && (abtRx[7] == 0x2f) && (abtRx[8] == 0x2f) && ((nt.nti.nai.abtAtqa[1] & 0x02) == 0x00))
        {
            //! MIFARE Plus 2K
            uiBlocks = 0x7f;
        }
        //! Chinese magic emulation card, ATS=0978009102:dabc1910
        if ((res == 9)  && (abtRx[5] == 0xda) && (abtRx[6] == 0xbc) && (abtRx[7] == 0x19) && (abtRx[8] == 0x10))
        {
            magic2 = true;
        }
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"Guessing size: seems to be a %i-byte card\n", (uiBlocks + 1) * 16);
    #endif
    if (bUseKeyFile)
    {
        FILE *pfKeys = fopen(argv[4], "rb");
        if (pfKeys == NULL)
        {
            sprintf(message_erreur,"Could not open keys file: %s !", argv[4]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtKeys, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfKeys) != (uiBlocks + 1) * sizeof(mifare_classic_block))
        {
            sprintf(message_erreur,"Could not read keys file: %s !", argv[4]);
            fclose(pfKeys);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfKeys);
    }
    if (atAction == ACTION_READ)
    {
        memset(&mtDump, 0x00, sizeof(mtDump));
    }
    else
    {
        FILE *pfDump = fopen(argv[3], "rb");
        if (pfDump == NULL)
        {
            sprintf(message_erreur,"Could not open dump file: %s !", argv[3]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtDump, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfDump) != (uiBlocks + 1) * sizeof(mifare_classic_block))
        {
            sprintf(message_erreur,"Could not read dump file: %s !", argv[3]);
            fclose(pfDump);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfDump);
    }
    if (atAction == ACTION_READ)
    {
        if (read_card(unlock))
        {
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Writing data to file: %s ...", argv[3]);
            #endif
            fflush(stdout);
            FILE *pfDump = fopen(argv[3], "wb");
            if (pfDump == NULL)
            {
                sprintf(message_erreur,"Could not open dump file: %s !", argv[3]);
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
            if (fwrite(&mtDump, 1, (uiBlocks + 1) * sizeof(mifare_classic_block), pfDump) != ((uiBlocks + 1) * sizeof(mifare_classic_block)))
            {
                sprintf(message_erreur,"\nCould not write to file: %s !", argv[3]);
                fclose(pfDump);
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Done.\n");
            #endif
            fclose(pfDump);
        }
        else
        {
            nfc_close(pnd);
            nfc_exit(context);
            return EXIT_FAILURE;
        }
    }
    else if (atAction == ACTION_WRITE)
    {
        write_card(unlock);
    }
    nfc_close(pnd);
    nfc_exit(context);
    return EXIT_SUCCESS; //! Succès !
}
예제 #2
0
static int list_passive_targets(nfc_device *_pnd)
{
  int res = 0;

  nfc_target ant[MAX_TARGET_COUNT];

  if (nfc_initiator_init(_pnd) < 0) {
    return -EXIT_FAILURE;
  }

  if ((res = nfc_initiator_list_passive_targets(_pnd, nmMifare, ant, MAX_TARGET_COUNT)) >= 0) {
    int i;

    if (res > 0)
      printf("%d ISO14443A passive target(s) found:\n", res);

    for (i = 0; i < res; i++) {
      size_t  szPos;

      printf("\t");
      for (szPos = 0; szPos < ant[i].nti.nai.szUidLen; szPos++) {
        printf("%02x", ant[i].nti.nai.abtUid[szPos]);
      }
      printf("\n");
    }

  }

  return 0;
}
예제 #3
0
파일: nfc.c 프로젝트: cybrairai/nfc
static PyObject * my_nfc_open() //PyObject *self, PyObject *args)
{
	// Initialize libnfc and set the nfc_context
	nfc_init(&context);
	if (context == NULL) {
		printf("Unable to init libnfc (malloc)\n");
		exit(EXIT_FAILURE);
	}

	// Open, using the first available NFC device which can be in order of selection:
	//   - default device specified using environment variable or
	//   - first specified device in libnfc.conf (/etc/nfc) or
	//   - first specified device in device-configuration directory (/etc/nfc/devices.d) or
	//   - first auto-detected (if feature is not disabled in libnfc.conf) device
	pnd = nfc_open(context, NULL);

	if (pnd == NULL) {
		printf("ERROR: %s\n", "Unable to open NFC device.");
		exit(EXIT_FAILURE);
	}
	// Set opened NFC device to initiator mode
	if (nfc_initiator_init(pnd) < 0) {
		nfc_perror(pnd, "nfc_initiator_init");
		exit(EXIT_FAILURE);
	}

	//printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
	return Py_BuildValue("");
}
예제 #4
0
bool verification_lecteur_context(nfc_context**context, nfc_device **pnd, QLabel* label_conf_lecteur, QLabel* Message_utilisateur){

     Message_utilisateur->setText("Detecting reader !");
        bool res=1;
        *pnd = nfc_open(*context, NULL);

        if (*pnd == NULL) {
            Message_utilisateur->setText("Pas de lecteur détécté !");
            label_conf_lecteur->setText("Non détécté");
            label_conf_lecteur->setStyleSheet("background-color: red;");
            res =0;
        }
        // Set opened NFC device to initiator mode
        else {
          if (nfc_initiator_init(*pnd) < 0) {
              Message_utilisateur->setText("Détécté mais non utilisable!");
              label_conf_lecteur->setText("Non utilisable");
              label_conf_lecteur->setStyleSheet("background-color: orange;");
              res =0;
            }
          else {
              Message_utilisateur->setText("lecteur detecte");
              QString message ="";
              message += nfc_device_get_name(*pnd);
              label_conf_lecteur->setText(message);
              label_conf_lecteur->setStyleSheet("background-color: green;");
          }
    }

    return res;

    }
예제 #5
0
/*
 * Get a list of the MIFARE targets near to the provided NFC initiator.
 *
 * The list has to be freed using the freefare_free_tags() function.
 */
MifareTag *
freefare_get_tags (nfc_device *device)
{
    MifareTag *tags = NULL;
    int tag_count = 0;

    nfc_initiator_init(device);

    // Drop the field for a while
    nfc_device_set_property_bool(device,NP_ACTIVATE_FIELD,false);

    // Configure the CRC and Parity settings
    nfc_device_set_property_bool(device,NP_HANDLE_CRC,true);
    nfc_device_set_property_bool(device,NP_HANDLE_PARITY,true);
    nfc_device_set_property_bool(device,NP_AUTO_ISO14443_4,true);

    // Enable field so more power consuming cards can power themselves up
    nfc_device_set_property_bool(device,NP_ACTIVATE_FIELD,true);

    // Poll for a ISO14443A (MIFARE) tag
    nfc_target *candidates = pvPortMalloc(MAX_CANDIDATES*sizeof(nfc_target));
    int candidates_count;
    nfc_modulation modulation = {
	.nmt = NMT_ISO14443A,
	.nbr = NBR_106
    };
    if ((candidates_count = nfc_initiator_list_passive_targets(device, modulation, candidates, MAX_CANDIDATES)) < 0)
    {
    	vPortFree(candidates);
    	return NULL;

    }
    tags = pvPortMalloc(MAX_CANDIDATES*sizeof (void *));
    if(!tags)
   	{
    	vPortFree(candidates);
    	return NULL;
    }
    memset (tags,0,MAX_CANDIDATES*sizeof (void *));

    for (int c = 0; c < candidates_count; c++) {
		MifareTag t;
		if ((t = freefare_tag_new(device, candidates[c].nti.nai))) {
			/* (Re)Allocate memory for the found MIFARE targets array */
	/*		MifareTag *p = pvPortRealloc (tags, (tag_count + 2) * sizeof (MifareTag));
			if (p)
			tags = p;
			else
			{
				vPortFree(candidates);
				return tags; // FAIL! Return what has been found so far.
			}*/
			tags[tag_count++] = t;
//			tags[tag_count] = NULL;
		}
    }
	vPortFree(candidates);

    return tags;
}
예제 #6
0
int
main(int argc, const char *argv[])
{
  nfc_device *pnd;
  nfc_target nt;

  // Allocate only a pointer to nfc_context
  nfc_context *context;

  // Initialize libnfc and set the nfc_context
  nfc_init(&context);

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version();
  printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);

  // Open, using the first available NFC device which can be in order of selection:
  //   - default device specified using environment variable or
  //   - first specified device in libnfc.conf (/etc/nfc) or
  //   - first specified device in device-configuration directory (/etc/nfc/devices.d) or
  //   - first auto-detected (if feature is not disabled in libnfc.conf) device
  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    warnx("ERROR: %s", "Unable to open NFC device.");
    return EXIT_FAILURE;
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));

  // Poll for a ISO14443A (MIFARE) tag
  const nfc_modulation nmMifare = {
    .nmt = NMT_ISO14443A,
    .nbr = NBR_106,
  };
  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
    printf("The following (NFC) ISO14443A tag was found:\n");
    printf("    ATQA (SENS_RES): ");
    print_hex(nt.nti.nai.abtAtqa, 2);
    printf("       UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
    print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
    printf("      SAK (SEL_RES): ");
    print_hex(&nt.nti.nai.btSak, 1);
    if (nt.nti.nai.szAtsLen) {
      printf("          ATS (ATR): ");
      print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
    }
  }
  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  return EXIT_SUCCESS;
}
예제 #7
0
void TagInit(ReaderTag *rt){
    
  
  nfc_init(&rt->context);
  if (rt->context == NULL) {
    ERR("Unable to init libnfc (malloc)");
    exit(EXIT_FAILURE);
  }

  // Try to open the NFC device
  rt->device = nfc_open(rt->context, NULL);
  if (rt->device == NULL) {
    ERR("Error opening NFC device");
    nfc_exit(rt->context);
    exit(EXIT_FAILURE);
  }

  if (nfc_initiator_init(rt->device) < 0) {
    nfc_perror(rt->device, "nfc_initiator_init");
    nfc_close(rt->device);
    nfc_exit(rt->context);
    exit(EXIT_FAILURE);
  }

  // Scan until the cows come home, or the tag, which ever comes first.
  if (nfc_device_set_property_bool(rt->device, NP_INFINITE_SELECT, true) < 0) {
    nfc_perror(rt->device, "nfc_device_set_property_bool");
    nfc_close(rt->device);
    nfc_exit(rt->context);
    exit(EXIT_FAILURE);
  }

  printf("NFC device: %s opened\n", nfc_device_get_name(rt->device));
  printf("\nWaiting for tag\n");

  // Try to find a MIFARE Ultralight tag
  if (nfc_initiator_select_passive_target(rt->device, nmMifare, NULL, 0, &rt->nt) <= 0) {
    ERR("no tag was found\n");
    nfc_close(rt->device);
    nfc_exit(rt->context);
    exit(EXIT_FAILURE);
  }
  // Test if we are dealing with a MIFARE compatible tag

  if (rt->nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(rt->device);
    nfc_exit(rt->context);
    exit(EXIT_FAILURE);
  }
  // Get the info from the current tag
  printf("Found MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < rt->nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", rt->nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");
}
예제 #8
0
silvia_nfc_card_monitor::silvia_nfc_card_monitor()
{
	nfc_init(&context);
	device = nfc_open(context, NULL);
	
	if (device != NULL)
	{
		nfc_initiator_init(device);
	}
}
예제 #9
0
파일: nfc_device.c 프로젝트: rubenrails/nfc
/*
 * call-seq:
 *  connect
 *
 * Connect to the NFC device
 */
static VALUE connect(VALUE klass)
{
  nfc_device_t * dev = nfc_open(NULL);
  if(!dev)
    rb_raise(rb_eRuntimeError, "could not find NFC device");

  if(!nfc_initiator_init(dev))
    rb_raise(rb_eRuntimeError, "oh snap, could not init");

  return Data_Wrap_Struct(klass, 0, 0, dev);
}
예제 #10
0
int
main(int argc, const char *argv[])
{

  nfc_device *pnd;
  nfc_target nt;
  nfc_context *context;
  nfc_init(&context);
  if (context == NULL) {
    printf("Unable to init libnfc (malloc)\n");
    exit(EXIT_FAILURE);
  }
  const char *acLibnfcVersion = nfc_version();
  (void)argc;

  printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    printf("ERROR: %s\n", "Unable to open NFC device.");
    exit(EXIT_FAILURE);
  }
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));

  for( ; ; ){
    const nfc_modulation nmMifare = {
      .nmt = NMT_ISO14443A,
      .nbr = NBR_106,
    };
    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
      printf("The following (NFC) ISO14443A tag was found:\n");
      printf("    ATQA (SENS_RES): ");
      print_hex(nt.nti.nai.abtAtqa, 2);
      printf("       UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
      print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
      printf("      SAK (SEL_RES): ");
      print_hex(&nt.nti.nai.btSak, 1);
      if (nt.nti.nai.szAtsLen) {
        printf("          ATS (ATR): ");
        print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
      }
      sleep(3);
    }
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
예제 #11
0
nfc_device *rfid_init(void) {
	nfc_init(&nfc_ctx);
	if(!nfc_ctx) {
		log("initializing libnfc failed");
		return NULL;
	}

	door_aid = mifare_desfire_aid_new(0x2305CA);

	nfc_connstring devices[NFC_MAX_DEVICES];
	int device_count = nfc_list_devices(nfc_ctx, devices, NFC_MAX_DEVICES);
	if(device_count <= 0) {
		log("no NFC devices found");
		return NULL;
	}

	log("found %u NFC devices:", device_count);
	for(int i = 0; i < device_count; i++)
		log(" - %s", devices[i]);

	int selected_device = -1;
	const char *conf_connstring = getenv("RFID_CONNSTRING");
	if(conf_connstring) {
		for(int i = 0; i < device_count; i++)
			if(strstr(devices[i], conf_connstring)) {
				selected_device = i;
				break;
			}
	} else {
		log("no connection string supplied, using first device");
		selected_device = 0;
	}

	if(selected_device == -1) {
		log("could not find requested device");
		return NULL;
	}

	log("using device %s", devices[selected_device]);

	nfc_device *dev = nfc_open(nfc_ctx, devices[selected_device]);
	if(!dev) {
		log("opening NFC device failed");
		return NULL;
	}

	if(nfc_initiator_init(dev) < 0) {
		nfc_perror(dev, "configuring NFC device as initiator failed");
		return NULL;
	}

	return dev;
}
예제 #12
0
파일: nfcc001.c 프로젝트: oldu73/sblh
int
main(int argc, const char *argv[])
{
  system("clear");
  
  nfc_device *pnd;
  nfc_target nt;

  // Allocate only a pointer to nfc_context
  nfc_context *context;

  // Initialize libnfc and set the nfc_context
  nfc_init(&context);

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version();
  printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);

  // Open, using the first available NFC device.
  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    warnx("ERROR: %s", "Unable to open NFC device.");
    return EXIT_FAILURE;
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
  printf("...\n", nfc_device_get_name(pnd));
  
  while (true){
    // Poll for a ISO14443A (MIFARE) tag
    const nfc_modulation nmMifare = {
      .nmt = NMT_ISO14443A,
      .nbr = NBR_106,
    };
    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
      print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
    }
    sleep(1);
  }
    
    // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  return EXIT_SUCCESS;
}
예제 #13
0
void nfcInitListen() {
    const char *acLibnfcVersion = nfc_version();
    pnd = nfc_open(context, NULL);
    if (pnd == NULL) {
        printf("ERROR: %s", "Unable to open NFC device.");
        exit(EXIT_FAILURE);
    }
    if (nfc_initiator_init(pnd) < 0) {
        nfc_perror(pnd, "nfc_initiator_init");
        exit(EXIT_FAILURE);
    }
    printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
}
예제 #14
0
int
main (int argc, const char *argv[])
{
  nfc_device *pnd;
  nfc_target nt;
  
  nfc_init (NULL);

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version ();
  printf ("%s uses libnfc %s\n", argv[0], acLibnfcVersion);

  // Open, using the first available NFC device
  pnd = nfc_open (NULL, NULL);

  if (pnd == NULL) {
    ERR ("%s", "Unable to open NFC device.");
    return EXIT_FAILURE;
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init (pnd) < 0) {
    nfc_perror (pnd, "nfc_initiator_init");
    exit (EXIT_FAILURE);    
  }

  printf ("NFC reader: %s opened\n", nfc_device_get_name (pnd));

  // Poll for a ISO14443A (MIFARE) tag
  const nfc_modulation nmMifare = {
    .nmt = NMT_ISO14443A,
    .nbr = NBR_106,
  };
  if (nfc_initiator_select_passive_target (pnd, nmMifare, NULL, 0, &nt) > 0) {
    printf ("The following (NFC) ISO14443A tag was found:\n");
    printf ("    ATQA (SENS_RES): ");
    print_hex (nt.nti.nai.abtAtqa, 2);
    printf ("       UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
    print_hex (nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
    printf ("      SAK (SEL_RES): ");
    print_hex (&nt.nti.nai.btSak, 1);
    if (nt.nti.nai.szAtsLen) {
      printf ("          ATS (ATR): ");
      print_hex (nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
    }
  }
  // Close NFC device
  nfc_close (pnd);
  nfc_exit (NULL);
  return EXIT_SUCCESS;
}
예제 #15
0
int
main(int argc, const char *argv[])
{
  nfc_device *pnd;
  nfc_target nt;

  // Allocate only a pointer to nfc_context
  nfc_context *context;

  // Initialize libnfc and set the nfc_context
  nfc_init(&context);
  if (context == NULL) {
    exit(EXIT_FAILURE);
  }

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version();
  (void)argc;

  // Open, using the first available NFC device which can be in order of selection:
  //   - default device specified using environment variable or
  //   - first specified device in libnfc.conf (/etc/nfc) or
  //   - first specified device in device-configuration directory (/etc/nfc/devices.d) or
  //   - first auto-detected (if feature is not disabled in libnfc.conf) device
  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    exit(EXIT_FAILURE);
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }


  // Poll for a ISO14443A (MIFARE) tag
  nfc_modulation nmMifare;
  nmMifare.nmt = NMT_ISO14443A;
  nmMifare.nbr = NBR_106;
  
  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0)
    print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
예제 #16
0
int main(int argc, const char *argv[]) {
    pinMode(LED_R, OUTPUT); 	// Set PWM LED as PWM output
    pinMode(LED_G, OUTPUT);     // Set regular LED as output
    pinMode(LED_B, OUTPUT);

    pinMode(DOOR, OUTPUT);		//tür öffner

    // nfc initiiere
    nfc_init(&context);
    if (context == NULL) {
        printf("ERROR: fehler beim dev init\n");
        exit(EXIT_FAILURE);
    }

    while (true) {
        doorCode = 0;
        // öffnet verbindung zum token
        pnd = nfc_open(context, NULL);

        led(1,1,0); //Gelb an

        if (pnd == NULL) {
            printf("ERROR: fehler beim öffnen.\n");
            exit(EXIT_FAILURE);
        }

        if (nfc_initiator_init(pnd) < 0) {
            nfc_perror(pnd, "nfc_initiator_init");
            exit(EXIT_FAILURE);
        }

        const nfc_modulation nmMifare = {
            .nmt = NMT_ISO14443A,
            .nbr = NBR_106,
        };
        if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
            toTokenKey(nt.nti.nai.abtUid);
            printf("%s\n",tokenKey);
            checkToken();
        }

        // TODO checken ob offen ist oder nicht um dann blau oder black zu zeigen

        nfc_close(pnd);
    }
    nfc_exit(context);
    exit(EXIT_SUCCESS);
}
예제 #17
0
//Not really useful for now but will be more interesting when we'll handle multiple devices
nfc_device *edgehog_nfc_get_reader_device(nfc_context* context, const nfc_connstring conn_string)
{
    nfc_device *pnd = nfc_open(context, conn_string);
    if(pnd == NULL)
    {
        return NULL;
    }

    if (nfc_initiator_init(pnd) < 0)
    {
        //NOTE: free pnd ?
        return NULL;
    }

    return pnd;
}
int main(int argc, const char *argv[])
{
    nfc_device *pnd;
    nfc_target nt;

    nfc_context *context;

    nfc_init(&context);
    if(context == NULL) {
        printf("unable to init (malloc)\n");
        exit(EXIT_FAILURE);
    }

    pnd = nfc_open(context, NULL);

    if (pnd == NULL) {
        printf("ERROR: %s\n", "Unable to open NFC Device.");
        exit(EXIT_FAILURE);
    }

    if (nfc_initiator_init(pnd) < 0) {
        nfc_perror(pnd, "nfc_initiator_init");
        exit(EXIT_FAILURE);
    }

    printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));

    const nfc_modulation nmMifare = {
        .nmt = NMT_ISO14443A,
        .nbr = NBR_106,
    };

    for(int i = 0; i < 24; i++) {
        if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
            printf("The following (NFC) card was found:\n");
            print_card(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
        }
        while (0 == nfc_initiator_target_is_present(pnd, NULL)){}
    }

    nfc_close(pnd);

    nfc_exit(context);

    exit(EXIT_SUCCESS);   
}
예제 #19
0
bool silvia_nfc_card_monitor::wait_for_card(silvia_nfc_card** card)
{
	assert(card != NULL);
	
	if (device == NULL)
	{
		device = nfc_open(context, NULL);
	
		if (device == NULL)
		{
			return false;
		}
		
		nfc_initiator_init(device);
	}
	
	// CAVEAT: only tested with PN533
	const nfc_modulation modulation = { NMT_ISO14443A, NBR_106 };
	
	// Poll for a card
	int rv = 0;
	nfc_target target;
	
	while ((rv = nfc_initiator_select_passive_target(device, modulation, NULL, 0, &target)) == 0)
	{
		usleep(10000);
	}
	
	if (rv < 0)
	{
		return false;
	}
	
	*card = new silvia_nfc_card(device, target, "NFC reader");
	
	return true;
}
예제 #20
0
파일: context.c 프로젝트: Elmuch/nfc
static VALUE open_dev(VALUE self, VALUE name)
{
  nfc_context * ctx;
  nfc_device * dev;
  VALUE device;

  Data_Get_Struct(self, nfc_context, ctx);

  if (NIL_P(name)) {
    dev = nfc_open(ctx, NULL);
  } else {
    dev = nfc_open(ctx, StringValuePtr(name));
  }

  if (NULL == dev)
    rb_raise(rb_eRuntimeError, "Unable to open the device");

  if(nfc_initiator_init(dev) < 0)
    rb_raise(rb_eRuntimeError, "Could not initialize device");

  device = Data_Wrap_Struct(cNfcDevice, 0, nfc_close, dev);
  rb_iv_set(device, "@context", self);
  return device;
}
int
main (int argc, char *argv[])
{
  int     arg;

  // Get commandline options
  for (arg = 1; arg < argc; arg++) {
    if (0 == strcmp (argv[arg], "-h")) {
      print_usage (argv);
      exit(EXIT_SUCCESS);
    } else if (0 == strcmp (argv[arg], "-q")) {
      quiet_output = true;
    } else {
      ERR ("%s is not supported option.", argv[arg]);
      print_usage (argv);
      exit(EXIT_FAILURE);
    }
  }

  // Try to open the NFC reader
  pnd = nfc_connect (NULL);

  if (!pnd) {
    printf ("Error connecting NFC reader\n");
    exit(EXIT_FAILURE);
  }

  // Initialise NFC device as "initiator"
  nfc_initiator_init (pnd);

  // Drop the field for a while
  if (!nfc_configure (pnd, NDO_ACTIVATE_FIELD, false)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }

  // Configure the CRC
  if (!nfc_configure (pnd, NDO_HANDLE_CRC, false)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  // Configure parity settings
  if (!nfc_configure (pnd, NDO_HANDLE_PARITY, true)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  // Use raw send/receive methods
  if (!nfc_configure (pnd, NDO_EASY_FRAMING, false)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  // Disable 14443-4 autoswitching
  if (!nfc_configure (pnd, NDO_AUTO_ISO14443_4, false)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }
  // Force 14443-A mode
  if (!nfc_configure (pnd, NDO_FORCE_ISO14443_A, true)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }

  // Enable field so more power consuming cards can power themselves up
  if (!nfc_configure (pnd, NDO_ACTIVATE_FIELD, true)) {
    nfc_perror (pnd, "nfc_configure");
    exit (EXIT_FAILURE);
  }

  printf ("Connected to NFC reader: %s\n\n", pnd->acName);

  // Send the 7 bits request command specified in ISO 14443A (0x26)
  if (!transmit_bits (abtReqa, 7)) {
    printf ("Error: No tag available\n");
    nfc_disconnect (pnd);
    return 1;
  }
  memcpy (abtAtqa, abtRx, 2);

  // Anti-collision
  transmit_bytes (abtSelectAll, 2);

  // Check answer
  if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
    printf("WARNING: BCC check failed!\n");
  }

  // Save the UID CL1
  memcpy (abtRawUid, abtRx, 4);

  //Prepare and send CL1 Select-Command
  memcpy (abtSelectTag + 2, abtRx, 5);
  iso14443a_crc_append (abtSelectTag, 7);
  transmit_bytes (abtSelectTag, 9);
  abtSak = abtRx[0];

  // Test if we are dealing with a CL2
  if (abtSak & CASCADE_BIT) {
    szCL = 2;//or more
    // Check answer
    if (abtRawUid[0] != 0x88) {
      printf("WARNING: Cascade bit set but CT != 0x88!\n");
    }
  }

  if(szCL == 2) {
    // We have to do the anti-collision for cascade level 2

    // Prepare CL2 commands
    abtSelectAll[0] = 0x95;

    // Anti-collision
    transmit_bytes (abtSelectAll, 2);

    // Check answer
    if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
      printf("WARNING: BCC check failed!\n");
    }

    // Save UID CL2
    memcpy (abtRawUid + 4, abtRx, 4);

    // Selection
    abtSelectTag[0] = 0x95;
    memcpy (abtSelectTag + 2, abtRx, 5);
    iso14443a_crc_append (abtSelectTag, 7);
    transmit_bytes (abtSelectTag, 9);
    abtSak = abtRx[0];

    // Test if we are dealing with a CL3
    if (abtSak & CASCADE_BIT) {
      szCL = 3;
      // Check answer
      if (abtRawUid[0] != 0x88) {
        printf("WARNING: Cascade bit set but CT != 0x88!\n");
      }
    }

    if ( szCL == 3) {
      // We have to do the anti-collision for cascade level 3

      // Prepare and send CL3 AC-Command
      abtSelectAll[0] = 0x97;
      transmit_bytes (abtSelectAll, 2);

      // Check answer
      if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
        printf("WARNING: BCC check failed!\n");
      }

      // Save UID CL3
      memcpy (abtRawUid + 8, abtRx, 4);

      // Prepare and send final Select-Command
      abtSelectTag[0] = 0x97;
      memcpy (abtSelectTag + 2, abtRx, 5);
      iso14443a_crc_append (abtSelectTag, 7);
      transmit_bytes (abtSelectTag, 9);
      abtSak = abtRx[0];
    }
  }

  // Request ATS, this only applies to tags that support ISO 14443A-4
  if (abtRx[0] & SAK_FLAG_ATS_SUPPORTED) {
    iso14443a_crc_append(abtRats, 2);
    transmit_bytes (abtRats, 4);
  }

  // Done, halt the tag now
  iso14443a_crc_append(abtHalt, 2);
  transmit_bytes (abtHalt, 4);

  printf ("\nFound tag with\n UID: ");
  switch (szCL) {
    case 1:
      printf ("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]);
    break;
    case 2:
      printf ("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
      printf ("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]);
    break;
    case 3:
      printf ("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
      printf ("%02x%02x%02x", abtRawUid[5], abtRawUid[6], abtRawUid[7]);
      printf ("%02x%02x%02x%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]);
    break;
  }
  printf("\n");
  printf("ATQA: %02x%02x\n SAK: %02x\n", abtAtqa[1], abtAtqa[0], abtSak);

  nfc_disconnect (pnd);
  return 0;
}
예제 #22
0
int main(int argc, char **argv) {
    nfc_device *pnd;
    nfc_target nt;

    // Allocate only a pointer to nfc_context
    nfc_context *context;

    byte_t abtRx[MAX_FRAME_LEN];
    byte_t abtTx[MAX_FRAME_LEN];
    size_t szRx = sizeof(abtRx);
	size_t szTx;

	byte_t START_14443A[] = {0x4A, 0x01, 0x00};
	byte_t SELECT_APP[] = {0x40,0x01,0x00,0xA4,0x04,0x00,0x07,0xA0,0x00,0x00,0x00,0x42,0x10,0x10,0x00};
	byte_t READ_RECORD_VISA[] = {0x40, 0x01, 0x00, 0xB2, 0x02, 0x0C, 0x00, 0x00};
	byte_t READ_RECORD_MC[] = {0x40, 0x01, 0x00, 0xB2, 0x01, 0x14, 0x00, 0x00};
	byte_t READ_PAYLOG_VISA[] = {0x40, 0x01, 0x00, 0xB2, 0x01, 0x8C, 0x00, 0x00};
	byte_t READ_PAYLOG_MC[] = {0x40, 0x01, 0x00, 0xB2, 0x01, 0x5C, 0x00, 0x00};

	unsigned char *res, output[50], c, amount[10],msg[100];
	unsigned int i, j, expiry;

    // Initialize the libnfc and set the nfc_context
    nfc_init(&context);
    if (context == NULL) {
        printf("Unable to init libnfc(malloc)\n");
        return 1;
    }typedef unsigned char byte;

    // Open first available device
    pnd = nfc_open(context, NULL);
	if (pnd == NULL) {
		printf("Unable to connect to NFC device.\n");
		return(1);
	}
	//printf("Connected to NFC reader: %s\n", pnd->acName);
	nfc_initiator_init(pnd);

	while(1) {

		szRx = sizeof(abtRx);
        if (!nfc_initiator_transceive_bytes(pnd, START_14443A, sizeof(START_14443A), abtRx, szRx, 0)) {
				nfc_perror(pnd, "START_14443A");
				return(1);
		}
		//show(szRx, abtRx);

		szRx = sizeof(abtRx);
        if (!nfc_initiator_transceive_bytes(pnd, SELECT_APP, sizeof(SELECT_APP), abtRx, szRx, 0)) {
				nfc_perror(pnd, "SELECT_APP");
				return(1);
		}
		//show(szRx, abtRx);

		szRx = sizeof(abtRx);
        if (!nfc_initiator_transceive_bytes(pnd, READ_RECORD_VISA, sizeof(READ_RECORD_VISA), abtRx, szRx, 0)) {
				nfc_perror(pnd, "READ_RECORD");
				return(1);
		}
		//show(szRx, abtRx);

		/* Look for cardholder name */
		res = abtRx;
		for(i=0;i<(unsigned int) szRx-1;i++) {
				if(*res==0x5f&&*(res+1)==0x20) {
					strncpy(output, res+3, (int) *(res+2));
					output[(int) *(res+2)]=0;
					printf("Cardholder name: %s\n",output);
					break;			
				}
				res++;
		}

		/* Look for PAN & Expiry date */
		res = abtRx;
		for(i=0;i<(unsigned int) szRx-1;i++) {
				if(*res==0x4d&&*(res+1)==0x57) {
					strncpy(output, res+3, 13);
					output[11]=0;
					printf("PAN:");
					
					for(j=0;j<8;j++) {
						if(j%2==0) printf(" ");
						c=output[j];
						if(MASKED&j>=2&j<=5) {
							printf("**");
						}
						else {
							printf("%02x",c&0xff);
						}
					}
					printf("\n");
					expiry = (output[10]+(output[9]<<8)+(output[8]<<16))>>4;
					printf("Expiration date: %02x/20%02x\n\n",(expiry&0xff),((expiry>>8)&0xff));
					break;			
				}
				res++;
		}

		szRx = sizeof(abtRx);
        if (!nfc_initiator_transceive_bytes(pnd, READ_RECORD_MC, sizeof(READ_RECORD_MC), abtRx, szRx, 0)) {
				nfc_perror(pnd, "READ_RECORD");
				return(1);
		}
		//show(szRx, abtRx);

		/* Look for cardholder name */
		res = abtRx;
		for(i=0;i<(unsigned int) szRx-1;i++) {
				if(*res==0x5f&&*(res+1)==0x20) {
					strncpy(output, res+3, (int) *(res+2));
					output[(int) *(res+2)]=0;
					printf("Cardholder name: %s\n",output);
					break;			
				}
				res++;
		}

		/* Look for PAN & Expiry date */
		res = abtRx;
		for(i=0;i<(unsigned int) szRx-1;i++) {
				if(*res==0x9c&&*(res+1)==0x57) {
					strncpy(output, res+3, 13);
					output[11]=0;
					printf("PAN:");
					
					for(j=0;j<8;j++) {
						if(j%2==0) printf(" ");
						c=output[j];
						if(MASKED&j>=2&j<=5) {
							printf("**");
						}
						else {
							printf("%02x",c&0xff);
						}
					}
					printf("\n");
					expiry = (output[10]+(output[9]<<8)+(output[8]<<16))>>4;
					printf("Expiration date: %02x/20%02x\n\n",(expiry&0xff),((expiry>>8)&0xff));
					break;			
				}
				res++;
		}
예제 #23
0
/*
 * Get a list of the MIFARE targets near to the provided NFC initiator.
 *
 * The list has to be freed using the freefare_free_tags() function.
 */
MifareTag *
freefare_get_tags (nfc_device_t *device)
{
    MifareTag *tags = NULL;
    int tag_count = 0;

    nfc_initiator_init(device);

    // Drop the field for a while
    nfc_configure(device,NDO_ACTIVATE_FIELD,false);

    // Let the reader only try once to find a tag
    nfc_configure(device,NDO_INFINITE_SELECT,false);

    // Configure the CRC and Parity settings
    nfc_configure(device,NDO_HANDLE_CRC,true);
    nfc_configure(device,NDO_HANDLE_PARITY,true);

    // Enable field so more power consuming cards can power themselves up
    nfc_configure(device,NDO_ACTIVATE_FIELD,true);

    // Poll for a ISO14443A (MIFARE) tag
    nfc_target_info_t target_info;

    tags = malloc(sizeof (void *));
    if(!tags) return NULL;
    tags[0] = NULL;
    
    while (nfc_initiator_select_passive_target(device,NM_ISO14443A_106,NULL,0,&target_info)) {

		bool found = false;
		struct supported_tag *tag_info;

		for (size_t i = 0; i < sizeof (supported_tags) / sizeof (struct supported_tag); i++) {
			if (((target_info.nai.szUidLen == 4) || (target_info.nai.abtUid[0] == NXP_MANUFACTURER_CODE)) &&
			(target_info.nai.btSak == supported_tags[i].SAK) &&
			(target_info.nai.szAtsLen == supported_tags[i].ATS_length) &&
			(0 == memcmp (target_info.nai.abtAts, supported_tags[i].ATS, supported_tags[i].ATS_length))) {

			tag_info = &(supported_tags[i]);
			found = true;
			break;
			}
		}

		if (!found)
			goto deselect;

		tag_count++;

		/* (Re)Allocate memory for the found MIFARE targets array */
		MifareTag *p = realloc (tags, (tag_count + 1) * sizeof (MifareTag));
		if (p)
			tags = p;
		else
			return tags; // FAIL! Return what has been found so far.

		/* Allocate memory for the found MIFARE target */
		switch (tag_info->type) {
			case CLASSIC_1K:
			case CLASSIC_4K:
			tags[tag_count-1] = mifare_classic_tag_new ();
			break;
			case DESFIRE:
			tags[tag_count-1] = mifare_desfire_tag_new (0); //JIM
			break;
			case ULTRALIGHT:
			tags[tag_count-1] = mifare_ultralight_tag_new ();
			break;
		}

		if (!tags[tag_count-1])
			return tags; // FAIL! Return what has been found before.

		/*
		 * Initialize common fields
		 * (Target specific fields are initialized in mifare_*_tag_new())
		 */
		(tags[tag_count-1])->device = device;
		(tags[tag_count-1])->info = target_info.nai;
		(tags[tag_count-1])->active = 0;
		(tags[tag_count-1])->tag_info = tag_info;
		tags[tag_count] = NULL;

deselect:
		nfc_initiator_deselect_target (device);
    }

    return tags;
}
예제 #24
0
int
main(int argc, char *argv[])
{
  int     arg;
  const char *acLibnfcVersion = nfc_version();
  nfc_target ntRealTarget;

  // Get commandline options
  for (arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "-h")) {
      print_usage(argv);
      exit(EXIT_SUCCESS);
    } else if (0 == strcmp(argv[arg], "-q")) {
      quiet_output = true;
    } else if (0 == strcmp(argv[arg], "-t")) {
      printf("INFO: %s\n", "Target mode only.");
      initiator_only_mode = false;
      target_only_mode = true;
    } else if (0 == strcmp(argv[arg], "-i")) {
      printf("INFO: %s\n", "Initiator mode only.");
      initiator_only_mode = true;
      target_only_mode = false;
    } else if (0 == strcmp(argv[arg], "-s")) {
      printf("INFO: %s\n", "Swapping devices.");
      swap_devices = true;
    } else if (0 == strcmp(argv[arg], "-n")) {
      if (++arg == argc || (sscanf(argv[arg], "%10i", &waiting_time) < 1)) {
        ERR("Missing or wrong waiting time value: %s.", argv[arg]);
        print_usage(argv);
        exit(EXIT_FAILURE);
      }
      printf("Waiting time: %i secs.\n", waiting_time);
    } else {
      ERR("%s is not supported option.", argv[arg]);
      print_usage(argv);
      exit(EXIT_FAILURE);
    }
  }

  // Display libnfc version
  printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);

#ifdef WIN32
  signal(SIGINT, (void (__cdecl *)(int)) intr_hdlr);
#else
  signal(SIGINT, intr_hdlr);
#endif

  nfc_context *context;
  nfc_init(&context);
  if (context == NULL) {
    ERR("Unable to init libnfc (malloc)");
    exit(EXIT_FAILURE);
  }

  nfc_connstring connstrings[MAX_DEVICE_COUNT];
  // List available devices
  size_t szFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT);

  if (initiator_only_mode || target_only_mode) {
    if (szFound < 1) {
      ERR("No device found");
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    if ((fd3 = fdopen(3, "r")) == NULL) {
      ERR("Could not open file descriptor 3");
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    if ((fd4 = fdopen(4, "r")) == NULL) {
      ERR("Could not open file descriptor 4");
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
  } else {
    if (szFound < 2) {
      ERR("%" PRIdPTR " device found but two opened devices are needed to relay NFC.", szFound);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
  }

  if (!target_only_mode) {
    // Try to open the NFC reader used as initiator
    // Little hack to allow using initiator no matter if
    // there is already a target used locally or not on the same machine:
    // if there is more than one readers opened we open the second reader
    // (we hope they're always detected in the same order)
    if ((szFound == 1) || swap_devices) {
      pndInitiator = nfc_open(context, connstrings[0]);
    } else {
      pndInitiator = nfc_open(context, connstrings[1]);
    }

    if (pndInitiator == NULL) {
      printf("Error opening NFC reader\n");
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }

    printf("NFC reader device: %s opened\n", nfc_device_get_name(pndInitiator));

    if (nfc_initiator_init(pndInitiator) < 0) {
      printf("Error: fail initializing initiator\n");
      nfc_close(pndInitiator);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }

    // Try to find a ISO 14443-4A tag
    nfc_modulation nm = {
      .nmt = NMT_ISO14443A,
      .nbr = NBR_106,
    };
    if (nfc_initiator_select_passive_target(pndInitiator, nm, NULL, 0, &ntRealTarget) <= 0) {
      printf("Error: no tag was found\n");
      nfc_close(pndInitiator);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }

    printf("Found tag:\n");
    print_nfc_target(&ntRealTarget, false);
    if (initiator_only_mode) {
      if (print_hex_fd4(ntRealTarget.nti.nai.abtUid, ntRealTarget.nti.nai.szUidLen, "UID") < 0) {
        fprintf(stderr, "Error while printing UID to FD4\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (print_hex_fd4(ntRealTarget.nti.nai.abtAtqa, 2, "ATQA") < 0) {
        fprintf(stderr, "Error while printing ATQA to FD4\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (print_hex_fd4(&(ntRealTarget.nti.nai.btSak), 1, "SAK") < 0) {
        fprintf(stderr, "Error while printing SAK to FD4\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (print_hex_fd4(ntRealTarget.nti.nai.abtAts, ntRealTarget.nti.nai.szAtsLen, "ATS") < 0) {
        fprintf(stderr, "Error while printing ATS to FD4\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
    }
  }
  if (initiator_only_mode) {
    printf("Hint: tag <---> *INITIATOR* (relay) <-FD3/FD4-> target (relay) <---> original reader\n\n");
  } else if (target_only_mode) {
    printf("Hint: tag <---> initiator (relay) <-FD3/FD4-> *TARGET* (relay) <---> original reader\n\n");
  } else {
    printf("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n");
  }
  if (!initiator_only_mode) {
    nfc_target ntEmulatedTarget = {
      .nm = {
        .nmt = NMT_ISO14443A,
        .nbr = NBR_106,
      },
    };
    if (target_only_mode) {
      size_t foo;
      if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtUid, &(ntEmulatedTarget.nti.nai.szUidLen), "UID") < 0) {
        fprintf(stderr, "Error while scanning UID from FD3\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAtqa, &foo, "ATQA") < 0) {
        fprintf(stderr, "Error while scanning ATQA from FD3\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (scan_hex_fd3(&(ntEmulatedTarget.nti.nai.btSak), &foo, "SAK") < 0) {
        fprintf(stderr, "Error while scanning SAK from FD3\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (scan_hex_fd3(ntEmulatedTarget.nti.nai.abtAts, &(ntEmulatedTarget.nti.nai.szAtsLen), "ATS") < 0) {
        fprintf(stderr, "Error while scanning ATS from FD3\n");
        nfc_close(pndInitiator);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
    } else {
      ntEmulatedTarget.nti = ntRealTarget.nti;
    }
    // We can only emulate a short UID, so fix length & ATQA bit:
    ntEmulatedTarget.nti.nai.szUidLen = 4;
    ntEmulatedTarget.nti.nai.abtAtqa[1] &= (0xFF - 0x40);
    // First byte of UID is always automatically replaced by 0x08 in this mode anyway
    ntEmulatedTarget.nti.nai.abtUid[0] = 0x08;
    // ATS is always automatically replaced by PN532, we've no control on it:
    // ATS = (05) 75 33 92 03
    //       (TL) T0 TA TB TC
    //             |  |  |  +-- CID supported, NAD supported
    //             |  |  +----- FWI=9 SFGI=2 => FWT=154ms, SFGT=1.21ms
    //             |  +-------- DR=2,4 DS=2,4 => supports 106, 212 & 424bps in both directions
    //             +----------- TA,TB,TC, FSCI=5 => FSC=64
    // It seems hazardous to tell we support NAD if the tag doesn't support NAD but I don't know how to disable it
    // PC/SC pseudo-ATR = 3B 80 80 01 01 if there is no historical bytes

    // Creates ATS and copy max 48 bytes of Tk:
    uint8_t *pbtTk;
    size_t szTk;
    pbtTk = iso14443a_locate_historical_bytes(ntEmulatedTarget.nti.nai.abtAts, ntEmulatedTarget.nti.nai.szAtsLen, &szTk);
    szTk = (szTk > 48) ? 48 : szTk;
    uint8_t pbtTkt[48];
    memcpy(pbtTkt, pbtTk, szTk);
    ntEmulatedTarget.nti.nai.abtAts[0] = 0x75;
    ntEmulatedTarget.nti.nai.abtAts[1] = 0x33;
    ntEmulatedTarget.nti.nai.abtAts[2] = 0x92;
    ntEmulatedTarget.nti.nai.abtAts[3] = 0x03;
    ntEmulatedTarget.nti.nai.szAtsLen = 4 + szTk;
    memcpy(&(ntEmulatedTarget.nti.nai.abtAts[4]), pbtTkt, szTk);

    printf("We will emulate:\n");
    print_nfc_target(&ntEmulatedTarget, false);

    // Try to open the NFC emulator device
    if (swap_devices) {
      pndTarget = nfc_open(context, connstrings[1]);
    } else {
      pndTarget = nfc_open(context, connstrings[0]);
    }
    if (pndTarget == NULL) {
      printf("Error opening NFC emulator device\n");
      if (!target_only_mode) {
        nfc_close(pndInitiator);
      }
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }

    printf("NFC emulator device: %s opened\n", nfc_device_get_name(pndTarget));
    if (nfc_target_init(pndTarget, &ntEmulatedTarget, abtCapdu, sizeof(abtCapdu), 0) < 0) {
      ERR("%s", "Initialization of NFC emulator failed");
      if (!target_only_mode) {
        nfc_close(pndInitiator);
      }
      nfc_close(pndTarget);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    printf("%s\n", "Done, relaying frames now!");
  }
예제 #25
0
// main entry point
int main(int argc, const char *argv[])
{
  init_leds();

  nfc_device *device_1;
  nfc_target target_1;
  nfc_context *context_1;

  nfc_device *device_2;
  nfc_target target_2;
  nfc_context *context_2;

  nfc_device *device_3;
  nfc_target target_3;
  nfc_context *context_3;

  // Initialize libnfc and set the nfc_context
  nfc_init(&context_1);
  nfc_init(&context_2);
  nfc_init(&context_3);

  if (context_1 == NULL || context_2 == NULL) || context_3 == NULL)) {
    printf("Unable to init libnfc.\n");
    exit(EXIT_FAILURE);
  }

  device_1 = nfc_open(context_1, NULL);
  device_2 = nfc_open(context_1, NULL);
  device_3 = nfc_open(context_2, NULL);

  if (device_1 == NULL || device_2 == NULL || device_3 == NULL) {
    printf("ERROR: %s\n", "Unable to open NFC device.");
    exit(EXIT_FAILURE);
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  const char *deviceId = nfc_device_get_connstring(pnd);
  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
  printf("NFC reader connstring: %s \n", deviceId);

  // Poll for a ISO14443A (MIFARE) tag
  const nfc_modulation nmMifare = {
    .nmt = NMT_ISO14443A,
    .nbr = NBR_106,
  };

  // get the index of the leds to flickr
  int index;
  index = atoi(argv[4]);

  const char* url;
  url = argv[3];
  char body[50];

  while(1){


    // always make sure leds are just on properly on init of loop
    // by giving an out of range index all leds will init
    flash_leds(12);

    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
      printf("The following (NFC) ISO14443A tag was found:\n");
      printf("    ATQA (SENS_RES): ");
      print_hex(nt.nti.nai.abtAtqa, 2);
      printf("       UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
      print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
      printf("      SAK (SEL_RES): ");
      print_hex(&nt.nti.nai.btSak, 1);
      if (nt.nti.nai.szAtsLen) {
        printf("          ATS (ATR): ");
        print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
      }

      // convert the tag into human readable format to work with
      char usertagid[20]="";
      size_t szPos;
      for(szPos=0; szPos<nt.nti.nai.szUidLen;szPos++){
       sprintf(usertagid + strlen(usertagid), "%02x", nt.nti.nai.abtUid[szPos]);
     } 

      // logging
     printf("tag found w/ id \"%s\"\n", usertagid); 
     printf("writing to file \"%s\"", argv[2]);

     flash_leds(index);
     usleep(60*1000);
     flash_leds(12);
     usleep(60*1000);
     flash_leds(index);
     usleep(60*1000);
     flash_leds(12);


      // get time
     //struct timeval tv;
     //gettimeofday(&tv,NULL);
      //tv.tv_sec // seconds
      //tv.tv_usec // microseconds
     int ctime;
    ctime = ((unsigned)time(NULL))*1000; // convert to ms

      // write that tag to the file arg
      // TODO write all params so we can use this as a backup in case of no network
    FILE *file; 
      file = fopen(argv[2],"a+"); /* apend file (add text to 
      a file or create a file if it does not exist.*/ 
      fprintf(file,"%d;%s\n",ctime, usertagid); /*writes*/ 
      fclose(file); /*done!*/ 

        CURL *curl;
        CURLcode res; 
  /* get a curl handle */ 
        curl = curl_easy_init();
        if(curl) {
    /* First set the URL that is about to receive our POST. This URL can
       just as well be a https:// URL if that is what should receive the
       data. */ 
       curl_easy_setopt(curl, CURLOPT_URL, url);
       http://stackoverflow.com/questions/11444583/command-line-curl-timeout-parameter
       curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2);
    /* Now specify the POST data */ 

    // prepare the body
    // timestamp and other fields to be added here instead of this sample data
       sprintf( body, "timestamp=%d&tagId=%s&%s", ctime, usertagid, argv[5]);
       curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);

    // logging posting to 
       printf("posting to url [%s] with body [%s]", url, body);

    /* Perform the request, res will get the return code */ 
       res = curl_easy_perform(curl);
    /* Check for errors */ 
       if(res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
          curl_easy_strerror(res));

    /* always cleanup */ 
      curl_easy_cleanup(curl);
    }
    
    } // end of found target if

    // add some wait time here, sleep expects seconds
    // check usleep, should work with microseconds instead
    usleep(100);

  }// end of loop

  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
int
main(int argc, const char *argv[])
{
  nfc_device *pnd;
  nfc_target nt;
  nfc_context *context;
  nfc_init(&context);
  
  printf("\nRunning checks...\n");

  if (context == NULL) {
    printf("Unable to init libnfc (malloc)\n");
    exit(EXIT_FAILURE);
  } 

  const char *acLibnfcVersion = nfc_version();
  (void)argc;
  printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);

  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    printf("ERROR: %s", "Unable to open NFC device.");
    exit(EXIT_FAILURE);
  }
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));

  const nfc_modulation nmMifare = {
    .nmt = NMT_ISO14443A,
    .nbr = NBR_106,
  };
  // nfc_set_property_bool(pnd, NP_AUTO_ISO14443_4, true);
  printf("Polling for target...\n");
  while (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0);
  printf("Target detected! Running command set...\n\n");
  uint8_t capdu[264];
  size_t capdulen;
  uint8_t rapdu[264];
  size_t rapdulen;
  // Select application
  memcpy(capdu, "\x00\xA4\x04\x00\x07\xF0\x39\x41\x48\x14\x81\x00\x00", 13);
  capdulen=13;
  rapdulen=sizeof(rapdu);

  printf("Sending ADPU SELECT...\n");
  if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0) {
    exit(EXIT_FAILURE);
  }
  if (rapdulen < 2 || rapdu[rapdulen-2] != 0x90 || rapdu[rapdulen-1] != 0x00) {
    exit(EXIT_FAILURE);
  }
  printf("Application selected!\n\n");

  // Select Capability Container
  memcpy(capdu, "\x00\xa4\x00\x0c\x02\xe1\x03", 7);  
  capdulen=7;
  rapdulen=sizeof(rapdu);
  
  printf("Sending CC SELECT...\n");
  if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0)
    exit(EXIT_FAILURE);
  if (rapdulen < 2 || rapdu[rapdulen-2] != 0x90 || rapdu[rapdulen-1] != 0x00) {
    capdu[3]='\x00'; // Maybe an older Tag4 ?
    if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0)
      exit(EXIT_FAILURE);
  }
  printf("Capability Container selected!\n\n");

  // Read Capability Container
  memcpy(capdu, "\x00\xb0\x00\x00\x0f", 5);  
  capdulen=5;
  rapdulen=sizeof(rapdu);
  
  printf("Sending ReadBinary from CC...\n");
  if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0)
    exit(EXIT_FAILURE);
  if (rapdulen < 2 || rapdu[rapdulen-2] != 0x90 || rapdu[rapdulen-1] != 0x00)
    exit(EXIT_FAILURE);
  printf("\nCapability Container header:\n");
  size_t  szPos;
  for (szPos = 0; szPos < rapdulen-2; szPos++) {
    printf("%02x ", rapdu[szPos]);
  }
  printf("\n\n");

  // NDEF Select
  memcpy(capdu, "\x00\xa4\x00\x0C\x02\xE1\x04", 7);
  capdulen=7;
  rapdulen=sizeof(rapdu);
  printf("Sending NDEF Select...\n");
  if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0)
    exit(EXIT_FAILURE);
  if (rapdulen < 2 || rapdu[rapdulen-2] != 0x90 || rapdu[rapdulen-1] != 0x00)
    exit(EXIT_FAILURE);
  printf("\n");

  // ReadBinary
  memcpy(capdu, "\x00\xb0\x00\x00\x02", 5);
  capdulen=5;
  rapdulen=sizeof(rapdu);
  printf("Sending ReadBinary NLEN...\n");
  if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0)
    exit(EXIT_FAILURE);
  if (rapdulen < 2 || rapdu[rapdulen-2] != 0x90 || rapdu[rapdulen-1] != 0x00)
    exit(EXIT_FAILURE);
  printf("\n");

  // ReadBinary - Get NDEF data
  memcpy(capdu, "\x00\xb0\x00\x00\x0f", 5);
  capdulen=5;
  rapdulen=sizeof(rapdu);
  printf("Sending ReadBinary, get NDEF data...\n");
  if (CardTransmit(pnd, capdu, capdulen, rapdu, &rapdulen) < 0)
    exit(EXIT_FAILURE);
  if (rapdulen < 2 || rapdu[rapdulen-2] != 0x90 || rapdu[rapdulen-1] != 0x00)
    exit(EXIT_FAILURE);
  printf("\n");

  printf("Wrapping up, closing session.\n\n");

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
예제 #27
0
int
main(int argc, char *argv[])
{
  int      arg, i;
  bool     format = false;
  unsigned int c;
  char     tmp[3] = { 0x00, 0x00, 0x00 };


  // Get commandline options
  for (arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "-h")) {
      print_usage(argv);
      exit(EXIT_SUCCESS);
    } else if (0 == strcmp(argv[arg], "-f")) {
      format = true;
    } else if (0 == strcmp(argv[arg], "-q")) {
      quiet_output = true;
    } else if (strlen(argv[arg]) == 8) {
      for (i = 0 ; i < 4 ; ++i) {
        memcpy(tmp, argv[arg] + i * 2, 2);
        sscanf(tmp, "%02x", &c);
        abtData[i] = (char) c;
      }
      abtData[4] = abtData[0] ^ abtData[1] ^ abtData[2] ^ abtData[3];
      iso14443a_crc_append(abtData, 16);
    } else {
      ERR("%s is not supported option.", argv[arg]);
      print_usage(argv);
      exit(EXIT_FAILURE);
    }
  }

  nfc_context *context;
  nfc_init(&context);

  // Try to open the NFC reader
  pnd = nfc_open(context, NULL);

  if (!pnd) {
    printf("Error opening NFC reader\n");
    exit(EXIT_FAILURE);
  }

  // Initialise NFC device as "initiator"
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  // Configure the CRC
  if (nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    exit(EXIT_FAILURE);
  }
  // Use raw send/receive methods
  if (nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    exit(EXIT_FAILURE);
  }
  // Disable 14443-4 autoswitching
  if (nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    exit(EXIT_FAILURE);
  }

  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));

  // Send the 7 bits request command specified in ISO 14443A (0x26)
  if (!transmit_bits(abtReqa, 7)) {
    printf("Error: No tag available\n");
    nfc_close(pnd);
    nfc_exit(context);
    return 1;
  }
  memcpy(abtAtqa, abtRx, 2);

  // Anti-collision
  transmit_bytes(abtSelectAll, 2);

  // Check answer
  if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
    printf("WARNING: BCC check failed!\n");
  }

  // Save the UID CL1
  memcpy(abtRawUid, abtRx, 4);

  //Prepare and send CL1 Select-Command
  memcpy(abtSelectTag + 2, abtRx, 5);
  iso14443a_crc_append(abtSelectTag, 7);
  transmit_bytes(abtSelectTag, 9);
  abtSak = abtRx[0];

  // Test if we are dealing with a CL2
  if (abtSak & CASCADE_BIT) {
    szCL = 2;//or more
    // Check answer
    if (abtRawUid[0] != 0x88) {
      printf("WARNING: Cascade bit set but CT != 0x88!\n");
    }
  }

  if (szCL == 2) {
    // We have to do the anti-collision for cascade level 2

    // Prepare CL2 commands
    abtSelectAll[0] = 0x95;

    // Anti-collision
    transmit_bytes(abtSelectAll, 2);

    // Check answer
    if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
      printf("WARNING: BCC check failed!\n");
    }

    // Save UID CL2
    memcpy(abtRawUid + 4, abtRx, 4);

    // Selection
    abtSelectTag[0] = 0x95;
    memcpy(abtSelectTag + 2, abtRx, 5);
    iso14443a_crc_append(abtSelectTag, 7);
    transmit_bytes(abtSelectTag, 9);
    abtSak = abtRx[0];

    // Test if we are dealing with a CL3
    if (abtSak & CASCADE_BIT) {
      szCL = 3;
      // Check answer
      if (abtRawUid[0] != 0x88) {
        printf("WARNING: Cascade bit set but CT != 0x88!\n");
      }
    }

    if (szCL == 3) {
      // We have to do the anti-collision for cascade level 3

      // Prepare and send CL3 AC-Command
      abtSelectAll[0] = 0x97;
      transmit_bytes(abtSelectAll, 2);

      // Check answer
      if ((abtRx[0] ^ abtRx[1] ^ abtRx[2] ^ abtRx[3] ^ abtRx[4]) != 0) {
        printf("WARNING: BCC check failed!\n");
      }

      // Save UID CL3
      memcpy(abtRawUid + 8, abtRx, 4);

      // Prepare and send final Select-Command
      abtSelectTag[0] = 0x97;
      memcpy(abtSelectTag + 2, abtRx, 5);
      iso14443a_crc_append(abtSelectTag, 7);
      transmit_bytes(abtSelectTag, 9);
      abtSak = abtRx[0];
    }
  }

  // Request ATS, this only applies to tags that support ISO 14443A-4
  if (abtRx[0] & SAK_FLAG_ATS_SUPPORTED) {
    iso_ats_supported = true;
  }

  printf("\nFound tag with\n UID: ");
  switch (szCL) {
    case 1:
      printf("%02x%02x%02x%02x", abtRawUid[0], abtRawUid[1], abtRawUid[2], abtRawUid[3]);
      break;
    case 2:
      printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
      printf("%02x%02x%02x%02x", abtRawUid[4], abtRawUid[5], abtRawUid[6], abtRawUid[7]);
      break;
    case 3:
      printf("%02x%02x%02x", abtRawUid[1], abtRawUid[2], abtRawUid[3]);
      printf("%02x%02x%02x", abtRawUid[5], abtRawUid[6], abtRawUid[7]);
      printf("%02x%02x%02x%02x", abtRawUid[8], abtRawUid[9], abtRawUid[10], abtRawUid[11]);
      break;
  }
  printf("\n");
  printf("ATQA: %02x%02x\n SAK: %02x\n", abtAtqa[1], abtAtqa[0], abtSak);
  if (szAts > 1) { // if = 1, it's not actual ATS but error code
    printf(" ATS: ");
    print_hex(abtAts, szAts);
  }
  printf("\n");

  // now reset UID
  iso14443a_crc_append(abtHalt, 2);
  transmit_bytes(abtHalt, 4);
  transmit_bits(abtUnlock1, 7);
  if (format) {
    transmit_bytes(abtWipe, 1);
    transmit_bytes(abtHalt, 4);
    transmit_bits(abtUnlock1, 7);
  }
  transmit_bytes(abtUnlock2, 1);
  transmit_bytes(abtWrite, 4);
  transmit_bytes(abtData, 18);
  if (format) {
    for (i = 3 ; i < 64 ; i += 4) {
      abtWrite[1] = (char) i;
      iso14443a_crc_append(abtWrite, 2);
      transmit_bytes(abtWrite, 4);
      transmit_bytes(abtBlank, 18);
    }
  }


  nfc_close(pnd);
  nfc_exit(context);
  return EXIT_SUCCESS;
}
예제 #28
0
파일: nfosc.c 프로젝트: guozanhua/nfosc
void nfosc_start() {
    if (running) return;
    
    max_symbol_id = 0;
    session_id = -1;
    buffer_size = 0;
    
    // try to open the NFC device
    printf("nfOSC v0.5 using libnfc v%s\n", nfc_version());
    printf("looking for NFC devices ...\n");
    fflush(stdout);
    
    nfc_init(&context);
    if (context == NULL) {
        fprintf(stderr, "unable to init libnfc (malloc)\n");
        exit(1);
    }
    
    nfc_connstring connstrings[MAX_DEVICE_COUNT];
    size_t szFound = nfc_list_devices (context, connstrings, MAX_DEVICE_COUNT);
    
    no_devices = (int)szFound;
    for (int dev=0;dev<no_devices;dev++) {
        pnd[device_count] = nfc_open(context, connstrings[dev]);
        if (pnd[device_count] == NULL) continue;
        nfc_initiator_init(pnd[device_count]);
        
        // drop the field for a while
        nfc_device_set_property_bool(pnd[device_count],NP_ACTIVATE_FIELD,false);
        
        // let the reader only try once to find a tag
        nfc_device_set_property_bool(pnd[device_count],NP_INFINITE_SELECT,false);
        
        // configure the CRC and Parity settings
        nfc_device_set_property_bool(pnd[device_count],NP_HANDLE_CRC,true);
        nfc_device_set_property_bool(pnd[device_count],NP_HANDLE_PARITY,true);
        
        // enable field so more power consuming cards can power themselves up
        nfc_device_set_property_bool(pnd[device_count],NP_ACTIVATE_FIELD,true);
        
        printf("connected to NFC reader #%d: %s\n",device_count,nfc_device_get_name(pnd[device_count]));
        device_count++;
    }
    
    no_devices = device_count;
    
    
    if (device_count==0) {
        printf("no device found!\n");
        return;
    } else if (device_count==1) {
        printf("1 device found\n");
        sprintf(source_string, "NFOSC");
    } else printf("%d devices found\n", device_count);
    
    read_database();
    
    printf("sending OSC packets to %s %s\n",host,port);
    target = lo_address_new(host, port);
    
    running = true;
    
    pthread_create(&main_thread , NULL, (void *)&main_loop, NULL);
    
}
예제 #29
0
int main(int argc, const char *argv[])
{
  nfc_device *pnd;
  nfc_target nt;
  const nfc_target ntbis;

  // Allocate only a pointer to nfc_context
  nfc_context *context;

  // Initialize libnfc and set the nfc_context
  nfc_init(&context);
  if (context == NULL) {
    printf("Unable to init libnfc (malloc)\n");
    exit(EXIT_FAILURE);
  }

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version();
  (void)argc;
  printf("%s utilise libnfc v%s\n", argv[0], acLibnfcVersion);

  // Open, using the first available NFC device which can be in order of selection:
  //   - default device specified using environment variable or
  //   - first specified device in libnfc.conf (/etc/nfc) or
  //   - first specified device in device-configuration directory (/etc/nfc/devices.d) or
  //   - first auto-detected (if feature is not disabled in libnfc.conf) device
  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    printf("ERROR: %s\n", "Unable to open NFC device.");
    exit(EXIT_FAILURE);
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  printf("Lecteur NFC: %s \n", nfc_device_get_name(pnd));

  // Poll for a ISO14443A (MIFARE) tag
  const nfc_modulation nmMifare = {
    .nmt = NMT_ISO14443A,
    .nbr = NBR_106,
  };

  int uinp_fd;
  if ((uinp_fd = setup_uinput_device()) < 0) {
  printf("Unable to find uinput device\n");
  return -1;
  }
  sleep(1);
  



  long int uid = 0;
  int i = 0;
  int check = 1;
  while (1) {
    if (nfc_initiator_list_passive_targets(pnd, nmMifare, &nt, 1) > 0) {
      if (uid != parse_dex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen)) {
        //printf("%s\n", strtol(*nt.nti.nai.abtUid, 16));
        i++;
        printf("\nmotherfucker %d\n", i);
        printf("Uid : ");
        print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
        printf("Parse dex : ");
        printf("%ld\n",parse_dex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen));
        uid = parse_dex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
        //printf("Before x : ");
        //printf("%s\n", before_x(uid));
        printf("Do x : ");
        do_x(uinp_fd, uid);
      } else {
        //printf("i: %d uid:%ld nt:%ld\n",i, uid, parse_dex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen));
        //i++;
      }
    } else {
      check = 0;
      uid = 0;
    }
  }
    /* Destroy the input device */
  ioctl(uinp_fd, UI_DEV_DESTROY);
  /* Close the UINPUT device */
  close(uinp_fd);
  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
int
main (int argc, const char *argv[])
{
  nfc_device_t *pnd;

  (void) argc;
  (void) argv;

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version ();
  printf ("%s use libnfc %s\n", argv[0], acLibnfcVersion);

  // Connect using the first available NFC device
  pnd = nfc_connect (NULL);

  if (pnd == NULL) {
    ERR ("%s", "Unable to connect to NFC device.");
    return EXIT_FAILURE;
  }

  printf ("Connected to NFC device: %s\n", pnd->acName);

  // Print the example's menu
  printf ("\nSelect the communication mode:\n");
  printf ("[1] Virtual card mode.\n");
  printf ("[2] Wired card mode.\n");
  printf ("[3] Dual card mode.\n");
  printf (">> ");

  // Take user's choice
  char    input = getchar ();
  int     mode = input - '0' + 1;
  printf ("\n");
  if (mode < VIRTUAL_CARD_MODE || mode > DUAL_CARD_MODE) {
    ERR ("%s", "Invalid selection.");
    return EXIT_FAILURE;
  }
  // Connect with the SAM
  sam_connection (pnd, mode);

  switch (mode) {
  case VIRTUAL_CARD_MODE:
    {
      // FIXME after the loop the device doesn't respond to host commands...
      printf ("Now the SAM is readable for 1 minute from an external reader.\n");
      wait_one_minute ();
    }
    break;

  case WIRED_CARD_MODE:
    {
      nfc_target_t nt;

      // Set connected NFC device to initiator mode
      nfc_initiator_init (pnd);

      // Drop the field for a while
      if (!nfc_configure (pnd, NDO_ACTIVATE_FIELD, false)) {
        nfc_perror (pnd, "nfc_configure");
        exit (EXIT_FAILURE);
      }
      // Let the reader only try once to find a tag
      if (!nfc_configure (pnd, NDO_INFINITE_SELECT, false)) {
        nfc_perror (pnd, "nfc_configure");
        exit (EXIT_FAILURE);
      }
      // Enable field so more power consuming cards can power themselves up
      if (!nfc_configure (pnd, NDO_ACTIVATE_FIELD, true)) {
        nfc_perror (pnd, "nfc_configure");
        exit (EXIT_FAILURE);
      }
      // Read the SAM's info
      const nfc_modulation_t nmSAM = {
        .nmt = NMT_ISO14443A,
        .nbr = NBR_106,
      };
      if (!nfc_initiator_select_passive_target (pnd, nmSAM, NULL, 0, &nt)) {
        nfc_perror (pnd, "nfc_initiator_select_passive_target");
        ERR ("%s", "Reading of SAM info failed.");
        return EXIT_FAILURE;
      }

      printf ("The following ISO14443A tag (SAM) was found:\n\n");
      print_nfc_iso14443a_info (nt.nti.nai, true);
    }
    break;

  case DUAL_CARD_MODE:
    {
      byte_t  abtRx[MAX_FRAME_LEN];
      size_t  szRx;

      nfc_target_t nt = {
        .nm.nmt = NMT_ISO14443A,
        .nm.nbr = NBR_UNDEFINED,
        .nti.nai.abtAtqa = { 0x04, 0x00 },
        .nti.nai.abtUid = { 0x08, 0xad, 0xbe, 0xef },
        .nti.nai.btSak = 0x20,
        .nti.nai.szUidLen = 4,
        .nti.nai.szAtsLen = 0,
      };
      printf ("Now both, NFC device (configured as target) and SAM are readables from an external NFC initiator.\n");
      printf ("Please note that NFC device (configured as target) stay in target mode until it receive RATS, ATR_REQ or proprietary command.\n");
      if (!nfc_target_init (pnd, &nt, abtRx, &szRx)) {
        nfc_perror(pnd, "nfc_target_init");
        return EXIT_FAILURE;
      }
      // wait_one_minute ();
    }
    break;
  }

  // Disconnect from the SAM
  sam_connection (pnd, NORMAL_MODE);

  // Disconnect from NFC device
  nfc_disconnect (pnd);

  return EXIT_SUCCESS;
}