Ejemplo n.º 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 !
}
Ejemplo n.º 2
0
/*
 * call-seq:
 *  name
 *
 * Get the name of the tag reader
 */
static VALUE name(VALUE self)
{
  nfc_device * dev;
  Data_Get_Struct(self, nfc_device, dev);

  return rb_str_new2(nfc_device_get_name(dev));
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
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");
}
Ejemplo n.º 5
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);
}
Ejemplo n.º 6
0
void nfosc_stop() {
    int i;
    if (!running) return;
    running = false;
    if( main_thread ) pthread_detach(main_thread);
    main_thread = NULL;
    
    lo_bundle osc_bundle = lo_bundle_new(LO_TT_IMMEDIATE);
    for (i=0;i<buffer_size;i++) {
        
        lo_message del_message = lo_message_new();
        lo_message_add_int32(del_message, tag_buffer[i].device_id);
        lo_message_add_int32(del_message, tag_buffer[i].symbol_id);
        lo_message_add_int32(del_message, tag_buffer[i].type_id);
        lo_message_add_string(del_message, tag_buffer[i].uid_str);
        lo_bundle_add_message(osc_bundle, "/nfosc/del", del_message);
        
        if (verbose) printf("del %d %d %d %s\n",tag_buffer[i].session_id,tag_buffer[i].symbol_id,tag_buffer[i].type_id,tag_buffer[i].uid_str);
    }
    
    lo_timetag frame_time;
    lo_timetag_now (&frame_time);
    
    for (int dev=0;dev<no_devices;dev++) {
        if (pnd[dev]==NULL) continue;
        lo_message frm_message = lo_message_new();
        lo_message_add_int32(frm_message, -1);
        lo_message_add_timetag(frm_message, frame_time);
        lo_message_add_int32(frm_message, 0);                       // sensor dim
        if (device_count>1) sprintf(source_string, "NFOSC:%d",dev);
        lo_message_add_string(frm_message, source_string);          // source name
        lo_bundle_add_message(osc_bundle, "/tuio2/frm", frm_message);
        
        lo_message sid_message = lo_message_new();
        lo_bundle_add_message(osc_bundle, "/tuio2/alv", sid_message);
    }
    
    int ret = lo_send_bundle(target, osc_bundle);
    if(ret == -1) {
        fprintf(stderr, "an OSC error occured: %s\n", lo_address_errstr(target));
        exit(1);
    }
    
    for (int dev=0;dev<no_devices;dev++) {
        if (pnd[dev]!=NULL) {
            printf("closing NFC reader #%d: %s\n",dev,nfc_device_get_name(pnd[dev]));
            nfc_close(pnd[dev]);
        }
    }
    nfc_exit(context);
    write_database();
}
Ejemplo n.º 7
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));
}
Ejemplo n.º 8
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;
}
    std::string NFCReaderUnit::fetchRealName()
    {
        if (d_device)
        {
            std::string name(nfc_device_get_name(d_device));
			if (name.length() == 0)
				d_connectedName = "NAME_WAS_EMPTY";
			else
				d_connectedName = name;
            return d_connectedName;
        }
        else
            return d_connectedName = "CANNOT_FETCH_NAME";
    }
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);   
}
Ejemplo n.º 11
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);
}
Ejemplo n.º 12
0
int
main(int argc, char *argv[])
{
  LONG rv;
  SCARDCONTEXT hContext;
  SCARDHANDLE hCard;
  char *reader;
  BYTE pbSendBuffer[1 + 1 + sizeof(nfc_connstring)];
  DWORD dwSendLength;
  BYTE pbRecvBuffer[1];
  DWORD dwActiveProtocol, dwRecvLength, dwReaders;
  char* mszReaders = NULL;

  if (argc == 1 ||
      (argc == 2 && (strncmp(argv[1], "yes", strlen("yes")) == 0)))
    pbSendBuffer[0] = IFDNFC_SET_ACTIVE;
  else if (argc == 2 && (strncmp(argv[1], "no", strlen("no")) == 0))
    pbSendBuffer[0] = IFDNFC_SET_INACTIVE;
  else if (argc == 2 && (strncmp(argv[1], "se", strlen("se")) == 0))
    pbSendBuffer[0] = IFDNFC_SET_ACTIVE_SE;
  else if (argc == 2 && (strncmp(argv[1], "status", strlen("status")) == 0))
    pbSendBuffer[0] = IFDNFC_GET_STATUS;
  else {
    printf("Usage: %s [yes|no|status]\n", argv[0]);
    exit(EXIT_FAILURE);
  }


  rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext);
  if (rv < 0)
    goto pcsc_error;

  dwReaders = 0;
  // Ask how many bytes readers list take
  rv = SCardListReaders(hContext, NULL, NULL, &dwReaders);
  if (rv < 0)
    goto pcsc_error;
  // Then allocate and fill mszReaders
  mszReaders = malloc(dwReaders);
  rv = SCardListReaders(hContext, NULL, mszReaders, &dwReaders);
  if (rv < 0)
    goto pcsc_error;

  int l;
  for (reader = mszReaders;
       dwReaders > 0;
       l = strlen(reader) + 1, dwReaders -= l, reader += l) {
    if (strcmp(IFDNFC_READER_NAME, reader) <= 0)
      break;
  }
  if (dwReaders <= 0) {
    printf("Could not find a reader named: %s\n", IFDNFC_READER_NAME);
    rv = SCARD_E_NO_READERS_AVAILABLE;
    goto pcsc_error;
  }

  // TODO Handle multiple ifdnfc instance for multiple NFC device ?
  rv = SCardConnect(hContext, reader, SCARD_SHARE_DIRECT, 0, &hCard,
                    &dwActiveProtocol);
  if (rv < 0)
    goto pcsc_error;

  if ((pbSendBuffer[0] == IFDNFC_SET_ACTIVE) || (pbSendBuffer[0] == IFDNFC_SET_ACTIVE_SE))  {
    const BYTE command = pbSendBuffer[0];
    // To correctly probe NFC devices, ifdnfc must be disactivated first
    pbSendBuffer[0] = IFDNFC_SET_INACTIVE;
    dwSendLength = 1;
    rv = SCardControl(hCard, IFDNFC_CTRL_ACTIVE, pbSendBuffer,
                      dwSendLength, pbRecvBuffer, sizeof(pbRecvBuffer),
                      &dwRecvLength);
    if (rv < 0) {
      goto pcsc_error;
    }

    pbSendBuffer[0] = command;
    // Initialize libnfc
    nfc_context *context;
    nfc_init(&context);
    if (context == NULL) {
      fprintf(stderr, "Unable to init libnfc (malloc)\n");
      goto error;
    }
    // Allocate nfc_connstring array
    nfc_connstring connstrings[MAX_DEVICE_COUNT];
    // List devices
    size_t szDeviceFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT);

    int connstring_index = -1;
    switch (szDeviceFound) {
      case 0:
        fprintf(stderr, "Unable to activate ifdnfc: no NFC device found.\n");
        nfc_exit(context);
        goto error;
        break;
      case 1:
        // Only one NFC device available, so auto-select it!
        connstring_index = 0;
        break;
      default:
        // More than one available NFC devices, propose a shell menu:
        printf("%d NFC devices found, please select one:\n", (int)szDeviceFound);
        for (size_t i = 0; i < szDeviceFound; i++) {
          nfc_device *pnd = nfc_open(context, connstrings[i]);
          if (pnd != NULL) {
            printf("[%d] %s\t  (%s)\n", (int)i, nfc_device_get_name(pnd), nfc_device_get_connstring(pnd));
            nfc_close(pnd);
          } else {
            fprintf(stderr, "nfc_open failed for %s\n", connstrings[i]);
          }
        }
        // libnfc isn't needed anymore
        nfc_exit(context);
        printf(">> ");
        // Take user's choice
        if (1 != scanf("%2d", &connstring_index)) {
          fprintf(stderr, "Value must an integer.\n");
          goto error;
        }
        if ((connstring_index < 0) || (connstring_index >= (int)szDeviceFound)) {
          fprintf(stderr, "Invalid index selection.\n");
          goto error;
        }
        break;
    }
    printf("Activating ifdnfc with \"%s\"...\n", connstrings[connstring_index]);
    // pbSendBuffer = { IFDNFC_SET_ACTIVE (1 byte), length (2 bytes), nfc_connstring (lenght bytes)}
    const uint16_t u16ConnstringLength = strlen(connstrings[connstring_index]) + 1;
    memcpy(pbSendBuffer + 1, &u16ConnstringLength, sizeof(u16ConnstringLength));
    memcpy(pbSendBuffer + 1 + sizeof(u16ConnstringLength), connstrings[connstring_index], u16ConnstringLength);
    dwSendLength = 1 + sizeof(u16ConnstringLength) + u16ConnstringLength;
  } else {
    // pbSendBuffer[0] != IFDNFC_SET_ACTIVE
    dwSendLength = 1;
  }

  rv = SCardControl(hCard, IFDNFC_CTRL_ACTIVE, pbSendBuffer,
                    dwSendLength, pbRecvBuffer, sizeof(pbRecvBuffer),
                    &dwRecvLength);
  if (rv < 0) {
    goto pcsc_error;
  }
  if (dwRecvLength < 1) {
    rv = SCARD_F_INTERNAL_ERROR;
    goto pcsc_error;
  }

  switch (pbRecvBuffer[0]) {
    case IFDNFC_IS_ACTIVE: {
      uint16_t u16ConnstringLength;
      if (dwRecvLength < (1 + sizeof(u16ConnstringLength))) {
        rv = SCARD_F_INTERNAL_ERROR;
        goto pcsc_error;
      }
      memcpy(&u16ConnstringLength, pbRecvBuffer + 1, sizeof(u16ConnstringLength));
      if ((dwRecvLength - (1 + sizeof(u16ConnstringLength))) != u16ConnstringLength) {
        rv = SCARD_F_INTERNAL_ERROR;
        goto pcsc_error;
      }
      nfc_connstring connstring;
      memcpy(connstring, pbRecvBuffer + 1 + sizeof(u16ConnstringLength), u16ConnstringLength);
      printf("%s is active using %s.\n", IFDNFC_READER_NAME, connstring);
    }
    break;
    case IFDNFC_IS_INACTIVE:
      printf("%s is inactive.\n", IFDNFC_READER_NAME);
      break;
    default:
      rv = SCARD_F_INTERNAL_ERROR;
      goto pcsc_error;
  }


  rv = SCardDisconnect(hCard, SCARD_LEAVE_CARD);
  if (rv < 0)
    goto pcsc_error;

  free(mszReaders);

  exit(EXIT_SUCCESS);

pcsc_error:
  puts(pcsc_stringify_error(rv));
error:
  if (mszReaders)
    free(mszReaders);

  exit(EXIT_FAILURE);
}
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);
}
Ejemplo n.º 14
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;
}
Ejemplo n.º 15
0
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);
    
}
Ejemplo n.º 16
0
int
main(int argc, const char *argv[])
{
  bool    bReadAction;
  FILE   *pfDump;

  if (argc < 3) {
    printf("\n");
    printf("%s r|w <dump.mfd>\n", argv[0]);
    printf("\n");
    printf("r|w         - Perform read from or write to card\n");
    printf("<dump.mfd>  - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
    printf("\n");
    exit(EXIT_FAILURE);
  }

  DBG("\nChecking arguments and settings\n");

  bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');

  if (bReadAction) {
    memset(&mtDump, 0x00, sizeof(mtDump));
  } else {
    pfDump = fopen(argv[2], "rb");

    if (pfDump == NULL) {
      ERR("Could not open dump file: %s\n", argv[2]);
      exit(EXIT_FAILURE);
    }

    if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
      ERR("Could not read from dump file: %s\n", argv[2]);
      fclose(pfDump);
      exit(EXIT_FAILURE);
    }
    fclose(pfDump);
  }
  DBG("Successfully opened the dump file\n");

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

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

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

  // Let the device 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_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

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

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

  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
    nfc_exit(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 < nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  if (bReadAction) {
    if (read_card()) {
      printf("Writing data to file: %s ... ", argv[2]);
      fflush(stdout);
      pfDump = fopen(argv[2], "wb");
      if (pfDump == NULL) {
        printf("Could not open file: %s\n", argv[2]);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
        printf("Could not write to file: %s\n", argv[2]);
        fclose(pfDump);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      fclose(pfDump);
      printf("Done.\n");
    }
  } else {
    write_card();
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 17
0
int main(int argc, const char *argv[])
{
  nfc_device *pnd;
  //nfc_target nt;
  MifareTag *tags = NULL;
  int i,j,k;
  int nbrsect=0;

  MifareClassicBlock data;

  // 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\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);
  }

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

  tags = freefare_get_tags(pnd);

  if (!tags) {
    printf("no Mifare classic\n");
  } else {
    for (i = 0; tags[i]; i++) {
      switch(freefare_get_tag_type(tags[i])) {
	case CLASSIC_1K:
	  printf("%u : Mifare 1k (S50) : %s\n", i, freefare_get_tag_uid(tags[i]));
	  nbrsect=16;
	  break;
	case CLASSIC_4K:
	  printf("%u : Mifare 4k (S70) : %s\n", i, freefare_get_tag_uid(tags[i]));
	  nbrsect=40;
	  break;
	default:
	  printf("%u : other ISO14443A tag : %s\n", i, freefare_get_tag_uid(tags[i]));
      }
    }
  }

  if (!tags[0]) {
    printf("no tag found !\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  printf ("Found %s\n", freefare_get_tag_friendly_name (tags[0]));

  /*
     MifareClassicBlockNumber dablock = 1;
     if(mifare_classic_connect(tags[0]) == OPERATION_OK) {
     printf("Connected !\n");
     if(mifare_classic_authenticate(tags[0], dablock, keys[0], MFC_KEY_A) == OPERATION_OK) {
     printf("Authenticated !\n");
     if(mifare_classic_get_data_block_permission (tags[0], dablock, MCAB_R|MCAB_W, MFC_KEY_A))
     printf("i can READ block %d with key A\n", dablock);
     if(mifare_classic_get_trailer_block_permission (tags[0], ((dablock)/4)*4+3, MCAB_READ_KEYB, MFC_KEY_B))
     printf("i can READ KEY A in trailer\n");
     }
     }
   */

  for(i=0; i<nbrsect; i++) {
    for(j=0; j < sizeof(keys)/sizeof(keys[0]); j++) {
      if((mifare_classic_connect(tags[0]) == OPERATION_OK) && 
	  (mifare_classic_authenticate(
				       tags[0], 
				       mifare_classic_sector_last_block(i), 
				       keys[j], 
				       MFC_KEY_A) == OPERATION_OK)) {
	printf("sector %02d auth with A[%d]\n", i, j);
	for(k=mifare_classic_sector_first_block(i); 
	    k<=mifare_classic_sector_last_block(i); k++) {
	  if(mifare_classic_read(tags[0], k, &data) == OPERATION_OK) {
	    print_hex(data,16);
	  } else {
	    printf("read error\n");
	  }
	}
	mifare_classic_disconnect(tags[0]);
	break;
      }
      mifare_classic_disconnect(tags[0]);
    }
    printf("\n");
  }
  printf("\n");

  freefare_free_tags(tags);

  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 18
0
int NFC_afficher_UID (char *ATQA, char *UID, char *SAQ, char * ATS) //! Attention à la taille des tableaux de caractères !
{
    nfc_device *pnd;
    nfc_target nt;
    nfc_context *context;
    nfc_init(&context);
    if (context == NULL)
    {
        sprintf(message_erreur,"ERREUR : Impossible d'utiliser LIBNFC !");
        return EXIT_FAILURE; //! ERREUR : Impossible d'utiliser LIBNFC !
    }
    pnd = nfc_open(context, NULL);
    if (pnd == NULL)
    {
        sprintf(message_erreur,"Error opening NFC reader !");
        return EXIT_FAILURE; //! ERREUR : Aucun périphérique détecté !
    }
    if (nfc_initiator_init(pnd) < 0)
    {
        nfc_perror(pnd, "nfc_initiator_init");
        nfc_strerror_r(pnd, message_erreur, TAILLE_MESSAGE_ERREUR);
        return EXIT_FAILURE; //! ERREUR - Sortie de la fonction
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"Lecteur NFC : %s\n", nfc_device_get_name(pnd)); //! Identifiant du lecteur NFC
    #endif
    
    const nfc_modulation nmMifare =
    {
        .nmt = NMT_ISO14443A,
        .nbr = NBR_106,
    };
    
    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0)
    {
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"L'étiquette (NFC) ISO14443A suivante a été trouvée :\n\n");
        fprintf(stderr,"    ATQA (SENS_RES): ");
        fprintf(stderr,"\033[%sm","31");
        #endif
        sprint_hex(nt.nti.nai.abtAtqa,2,ATQA); //! Récupération du ATQA
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"\033[%sm","0");
        fprintf(stderr,"\n       UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
        fprintf(stderr,"\033[%sm","31");
        #endif
        sprint_hex(nt.nti.nai.abtUid,nt.nti.nai.szUidLen,UID); //! Récupération du UID
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"\033[%sm","0");
        fprintf(stderr,"\n      SAK (SEL_RES): ");
        fprintf(stderr,"\033[%sm","31");
        #endif
        sprint_hex(&nt.nti.nai.btSak,1,SAQ); //! Récupération du SAQ
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"\033[%sm","0");
        #endif
        if (nt.nti.nai.szAtsLen)
        {
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"\n          ATS (ATR): ");
            fprintf(stderr,"\033[%sm","31");
            #endif
            sprint_hex(nt.nti.nai.abtAts,nt.nti.nai.szAtsLen,ATS); //! Récupération du ATS
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"\033[%sm","0");
            #endif
        }
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"\n");
        #endif
    }
    nfc_close(pnd); //! On libère le périphérique NFC
    nfc_exit(context);
    return EXIT_SUCCESS; //! Succès !
}
Ejemplo n.º 19
0
int
main(int argc, const char *argv[])
{
  int     iAction = 0;
  uint8_t iUID[MAX_UID_LEN] = { 0x0 };
  size_t  szUID = 0;
  bool    bOTP = false;
  bool    bLock = false;
  bool    bUID = false;
  FILE   *pfDump;

  if (argc < 2) {
      print_usage(argv);
      exit(EXIT_FAILURE);
  }

  DBG("\nChecking arguments and settings\n");

  // Get commandline options
  for (int arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "r")) {
      iAction = 1;
    } else if (0 == strcmp(argv[arg], "w")) {
      iAction = 2;
    } else if (0 == strcmp(argv[arg], "--with-uid")) {
      if (argc < 5) {
        ERR("Please supply a UID of 4, 7 or 10 bytes long. Ex: a1:b2:c3:d4");
        exit(EXIT_FAILURE);
      }
      szUID = str_to_uid(argv[4], iUID);
    } else if (0 == strcmp(argv[arg], "--full")) {
      bOTP = true;
      bLock = true;
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--otp")) {
      bOTP = true;
    } else if (0 == strcmp(argv[arg], "--lock")) {
      bLock = true;
    } else if (0 == strcmp(argv[arg], "--uid")) {
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--check-magic")) {
      iAction = 3;
    } else {
      //Skip validation of the filename
      if ((arg != 2) && (arg != 4)) {
        ERR("%s is not supported option.", argv[arg]);
        print_usage(argv);
        exit(EXIT_FAILURE);
      }
    }
  }

  if (iAction == 1) {
    memset(&mtDump, 0x00, sizeof(mtDump));
  } else if (iAction == 2) {
    pfDump = fopen(argv[2], "rb");

    if (pfDump == NULL) {
      ERR("Could not open dump file: %s\n", argv[2]);
      exit(EXIT_FAILURE);
    }

    if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
      ERR("Could not read from dump file: %s\n", argv[2]);
      fclose(pfDump);
      exit(EXIT_FAILURE);
    }
    fclose(pfDump);
    DBG("Successfully opened the dump file\n");
  } else if (iAction == 3) {
    DBG("Switching to Check Magic Mode\n");
  } else {
    ERR("Unable to determine operating mode");
    exit(EXIT_FAILURE);
  }

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

  // Try to open the NFC device
  pnd = nfc_open(context, NULL);
  if (pnd == NULL) {
    ERR("Error opening NFC device");
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));

  if (list_passive_targets(pnd)) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

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

  // Let the device 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_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

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

  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Get the info from the current tag
  printf("Using MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  if (iAction == 1) {
    if (read_card()) {
      printf("Writing data to file: %s ... ", argv[2]);
      fflush(stdout);
      pfDump = fopen(argv[2], "wb");
      if (pfDump == NULL) {
        printf("Could not open file: %s\n", argv[2]);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
        printf("Could not write to file: %s\n", argv[2]);
        fclose(pfDump);
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      fclose(pfDump);
      printf("Done.\n");
    }
  } else if (iAction == 2) {
    write_card(bOTP, bLock, bUID);
  } else if (iAction == 3) {
    if (!check_magic()) {
        printf("Card is not magic\n");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
    } else {
        printf("Card is magic\n");
    }
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 20
0
int main(int argc, const char *argv[])
{
  nfc_device *pnd;
//  nfc_target nt;
//  static mifare_param mp;
  int i, j;

  MifareTag *tags = NULL;
  int error = 0;
  MifareClassicBlock dablock;
//  MifareClassicBlock mydata = {0x00,0x00,0x00,0x42,   0xff,0xff,0xff,0xbd,   0x00,0x00,0x00,0x42,   0,0xff,0x00,0xff};

  MifareClassicBlock my_trailer_block;
  MifareClassicKey my_key_A = { 0xff,0xff,0xff,0xff,0xff,0xff };
  MifareClassicKey my_key_B = { 0xff,0xff,0xff,0xff,0xff,0xff };


  // 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 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) {
    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));

  // 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);
    }
  }
  */

  tags = freefare_get_tags(pnd);
  if (!tags) {
	  printf("no Mifare classic\n");
  } else {
	  for (i = 0; (!error) && tags[i]; i++) {
		  if (freefare_get_tag_type(tags[i]) == CLASSIC_1K)
			  printf("%u : Mifare 1k (S50)\n",i);
		  if (freefare_get_tag_type(tags[i]) == CLASSIC_4K)
			  printf("%u : Mifare 4k (S70)\n",i);
	  }
	  if(mifare_classic_connect(tags[0])==0) {
		  printf("connected\n");
		  if(mifare_classic_authenticate(tags[0], 1,keys[0],MFC_KEY_B) == OPERATION_OK) {
			  printf("Authenticated !\n");

			  if(mifare_classic_read (tags[0], 1, &dablock) == OPERATION_OK) {
			  	printf("Block readed\n");
				for(j=0; j<16; j++) {
					printf("%02X ", dablock[j]);
				}
				printf("\n");
			  } else {
				  printf("Auth error : %s\n", freefare_strerror(tags[0]));
			  }

			  if(mifare_classic_get_data_block_permission (tags[0], 1, MCAB_R, MFC_KEY_A))
				  printf("i can READ this block with B\n");
			  if(mifare_classic_get_data_block_permission (tags[0], 1, MCAB_W, MFC_KEY_A))
				  printf("i can WRITE this block with B\n");
			  if(mifare_classic_get_data_block_permission (tags[0], 1, MCAB_I, MFC_KEY_A))
				  printf("i can INC this block with B\n");
			  if(mifare_classic_get_data_block_permission (tags[0], 1, MCAB_D, MFC_KEY_A))
				  printf("i can DEC this block with B\n");

			  printf("---\n");

			  /* trailer = ((block) / 4) * 4 + 3; */
			  if(mifare_classic_get_trailer_block_permission (tags[0], 3, MCAB_READ_KEYA, MFC_KEY_A))
				  printf("i can READ KEY A in trailer\n");
			  if(mifare_classic_get_trailer_block_permission (tags[0], 3, MCAB_WRITE_KEYA, MFC_KEY_A))
				  printf("i can WRITE KEY A in trailer\n");
			  if(mifare_classic_get_trailer_block_permission (tags[0], 3, MCAB_READ_ACCESS_BITS, MFC_KEY_A))
				  printf("i can READ ACCESS BITS in trailer\n");
			  if(mifare_classic_get_trailer_block_permission (tags[0], 3, MCAB_WRITE_ACCESS_BITS, MFC_KEY_A))
				  printf("i can WRITE ACCESS BITS in trailer\n");
			  if(mifare_classic_get_trailer_block_permission (tags[0], 3, MCAB_READ_KEYB, MFC_KEY_A))
				  printf("i can READ KEYB in trailer\n");
			  if(mifare_classic_get_trailer_block_permission (tags[0], 3, MCAB_WRITE_KEYB, MFC_KEY_A))
				  printf("i can WRITE KEYB in trailer\n");

			  /*
			  if(mifare_classic_write (tags[0], 1, mydata) == 0) {
				  printf("write ok\n");
			  }
			  */
			  if(mifare_classic_init_value (tags[0], 1, 0x42, 00) == 0) {
				  printf("init value bloc ok\n");
			  }

			  /* compose trailer block */
			  /*                                                          ab0    ab1     ab2   abt    gpb    */
			  /* abt = C_100 = 4 = 100 = c3c2c1  != datasheet c1c2c3*/
			  //mifare_classic_trailer_block (&my_trailer_block, my_key_A, C_000, C_011, C_000, C_100,  0x69, my_key_B);
			  mifare_classic_trailer_block (&my_trailer_block, my_key_A, C_000, C_000, C_000, C_100,  0x69, my_key_B);
			  for(j=0; j<16; j++) {
				  printf("%02X ", my_trailer_block[j]);
			  }
			  printf("\n");
			  if(mifare_classic_write (tags[0], 3, my_trailer_block) == 0) {
				  printf("trailer write ok\n");
			  }
			  /*
			  if(mifare_classic_decrement(tags[0], 1, 1) == OPERATION_OK) {
				  printf("decrement ok\n");
			  } else {
				  printf("Decrement error : %s\n", freefare_strerror(tags[0]));
			  }

			  if(mifare_classic_transfer (tags[0], 1) == OPERATION_OK) {
				  printf("transfer ok\n");
			  } else {
				  printf("Transfert error : %s\n", freefare_strerror(tags[0]));
			  }

			  if(mifare_classic_read(tags[0], 1, &dablock) == OPERATION_OK) {
			  	printf("Block readed\n");
				for(j=0; j<16; j++) {
					printf("%02X ", dablock[j]);
				}
				printf("\n");
			  } else {
				  printf("Read error : %s\n", freefare_strerror(tags[0]));
			  }
			  */

		  } else {
			  printf("Erreur : %s\n", freefare_strerror(tags[0]));
		  }
		  mifare_classic_disconnect(tags[0]);
	  }
  }



/*
  for(i=0; i<1; i++) {
    for(j=0; j<8; j++) {
      memcpy(mp.mpa.abtKey, &keys[j*6], 6);
      res = nfc_initiator_mifare_cmd(pnd, MC_AUTH_B, 0, &mp);
      if(res) {
        printf("sector %u / key %u : yes\n", i, j);
        continue;
      } else {
        printf("sector %u / key %u : no\n", i, j);
      }
    }
  }
*/

  /*
  // mifare parameters
  memcpy(mp.mpa.abtAuthUid,nt.nti.nai.abtUid,4);
  memcpy(mp.mpa.abtKey, &keys[0*6], 6);

  //                                           block
  res = nfc_initiator_mifare_cmd(pnd, MC_AUTH_A, 0, &mp);
  if(res) {
    printf("Auth success\n");
  } else {
    printf("Auth failed\n");
  }

  for(i=0; i<4; i++) {
    res = nfc_initiator_mifare_cmd(pnd, MC_READ, i, &mp);
    if(res) {
      print_hex(mp.mpd.abtData,16);
    } else {
      printf("Read failed\n");
    }
  }
  */



  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
int
main(int argc, char *argv[])
{
  int     arg;
  bool    quiet_output = false;
  const char *acLibnfcVersion = nfc_version();

  // Get commandline options
  for (arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "-h")) {
      print_usage(argv);
      return EXIT_SUCCESS;
    } else if (0 == strcmp(argv[arg], "-q")) {
      quiet_output = true;
    } else {
      ERR("%s is not supported option.", argv[arg]);
      print_usage(argv);
      return 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_connstring connstrings[MAX_DEVICE_COUNT];
  // List available devices
  size_t szFound = nfc_list_devices(NULL, connstrings, MAX_DEVICE_COUNT);

  if (szFound < 2) {
    ERR("%zd device found but two opened devices are needed to relay NFC.", szFound);
    return EXIT_FAILURE;
  }

  nfc_init(NULL);

  // Try to open the NFC emulator device
  pndTag = nfc_open(NULL, connstrings[0]);
  if (pndTag == NULL) {
    printf("Error opening NFC emulator device\n");
    return EXIT_FAILURE;
  }

  printf("Hint: tag <---> initiator (relay) <---> target (relay) <---> original reader\n\n");

  printf("NFC emulator device: %s opened\n", nfc_device_get_name(pndTag));
  printf("[+] Try to break out the auto-emulation, this requires a second reader!\n");
  printf("[+] To do this, please send any command after the anti-collision\n");
  printf("[+] For example, send a RATS command or use the \"nfc-anticol\" tool\n");

  nfc_target nt = {
    .nm = {
      .nmt = NMT_ISO14443A,
      .nbr = NBR_UNDEFINED,
    },
    .nti = {
      .nai = {
        .abtAtqa = { 0x04, 0x00 },
        .abtUid = { 0x08, 0xad, 0xbe, 0xef },
        .btSak = 0x20,
        .szUidLen = 4,
        .szAtsLen = 0,
      },
Ejemplo n.º 22
0
int
main(int argc, const char *argv[])
{
  if (argc < 2) {
    usage(); 
    exit(EXIT_FAILURE);   
  } 

  parseopts(argv[1]);  

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

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

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

// 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_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
// Disable ISO14443-4 switching in order to read devices that emulate Mifare Classic with ISO14443-4 compliance.
  if (nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    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");
    nfc_close(pnd);
    nfc_exit(context);
    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");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

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

// Try to find a MIFARE Classic tag
  if (select_target(pnd, &nt) <= 0) {
    printf("Error: no tag was found\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
// Test if we are dealing with a MIFARE compatible tag
  if ((nt.nti.nai.btSak & 0x08) == 0) {
    printf("Warning: tag is probably not a MFC!\n");
  }

  printf("Found MIFARE Classic card:\n");
  nt.nm = nmMifare;
  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;

    printf("Guessing size: seems to be a %i-byte card\n", (uiBlocks + 1) * 16);

  if (parse_card()) {
	printf("Done, %d blocks read.\n", uiBlocks + 1);
	fflush(stdout);
  }

  if(is_addv) if(!easy_add_value(0xff) || !parse_card()) printf("Failed Add Value!!\n");    

  printTag(&e); 

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 23
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!");
  }
Ejemplo n.º 24
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);
}
Ejemplo n.º 25
0
int
main(int argc, const char *argv[])
{
  (void) argc;
  (void) argv;

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

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

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

  if (pnd == NULL) {
    ERR("%s", "Unable to open NFC device.");
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

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

  // 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
  int input = getchar();
  printf("\n");
  if ((input < '1') || (input > '3')) {
    ERR("%s", "Invalid selection.");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  /*
   * '1' -> "Virtual mode" (0x02)
   * '2' -> "Wired card" (0x03)
   * '3' -> "Dual card" (0x04)
   */
  int iMode = input - '0' + 0x01;
  pn532_sam_mode mode = iMode;

  // Connect with the SAM

  switch (mode) {
    case PSM_VIRTUAL_CARD: {
      // FIXME Its a private pn53x function
      if (pn532_SAMConfiguration(pnd, mode, 0) < 0) {
        nfc_perror(pnd, "pn53x_SAMConfiguration");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      printf("Now the SAM is readable for 1 minute from an external reader.\n");
      wait_one_minute();
    }
    break;

    case PSM_WIRED_CARD: {
      // Set opened NFC device to initiator mode
      if (nfc_initiator_init_secure_element(pnd) < 0) {
        nfc_perror(pnd, "nfc_initiator_init_secure_element");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }

      // 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_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      // Read the SAM's info
      const nfc_modulation nmSAM = {
        .nmt = NMT_ISO14443A,
        .nbr = NBR_106,
      };
      nfc_target nt;

      int res;
      if ((res = nfc_initiator_select_passive_target(pnd, nmSAM, NULL, 0, &nt)) < 0) {
        nfc_perror(pnd, "nfc_initiator_select_passive_target");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      } else if (res == 0) {
        ERR("No SAM found.");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      } else if (res == 1) {
        printf("The following ISO14443A tag (SAM) was found:\n");
        print_nfc_target(&nt, true);
      } else {
        ERR("%s", "More than one ISO14442 tag found as SAM.");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
    }
    break;

    case PSM_DUAL_CARD: {
      // FIXME Its a private pn53x function
      if (pn532_SAMConfiguration(pnd, mode, 0) < 0) {
        nfc_perror(pnd, "pn53x_SAMConfiguration");
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
      }
      uint8_t  abtRx[MAX_FRAME_LEN];

      nfc_target nt = {
        .nm = {
          .nmt = NMT_ISO14443A,
          .nbr = NBR_UNDEFINED,
        },
        .nti = {
          .nai = {
            .abtAtqa = { 0x04, 0x00 },
            .abtUid = { 0x08, 0xad, 0xbe, 0xef },
            .btSak = 0x20,
            .szUidLen = 4,
            .szAtsLen = 0,
          },
        },
      };
Ejemplo n.º 26
0
int
main(int argc, const char *argv[])
{
  int     iAction = 0;
  uint8_t iDumpSize = sizeof(mifareul_tag);
  uint8_t iUID[MAX_UID_LEN] = { 0x0 };
  size_t  szUID = 0;
  bool    bOTP = false;
  bool    bLock = false;
  bool    bUID = false;
  bool    bPWD = false;
  bool    bPart = false;
  bool    bFilename = false;
  FILE   *pfDump;

  if (argc < 3) {
    print_usage(argv);
    exit(EXIT_FAILURE);
  }

  DBG("\nChecking arguments and settings\n");

  // Get commandline options
  for (int arg = 1; arg < argc; arg++) {
    if (0 == strcmp(argv[arg], "r")) {
      iAction = 1;
    } else if (0 == strcmp(argv[arg], "w")) {
      iAction = 2;
    } else if (0 == strcmp(argv[arg], "--with-uid")) {
      if (arg + 1 == argc) {
        ERR("Please supply a UID of 4, 7 or 10 bytes long. Ex: a1:b2:c3:d4");
        exit(EXIT_FAILURE);
      }
      szUID = str_to_uid(argv[++arg], iUID);
    } else if (0 == strcmp(argv[arg], "--full")) {
      bOTP = true;
      bLock = true;
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--otp")) {
      bOTP = true;
    } else if (0 == strcmp(argv[arg], "--lock")) {
      bLock = true;
    } else if (0 == strcmp(argv[arg], "--uid")) {
      bUID = true;
    } else if (0 == strcmp(argv[arg], "--check-magic")) {
      iAction = 3;
    } else if (0 == strcmp(argv[arg], "--partial")) {
      bPart = true;
    } else if (0 == strcmp(argv[arg], "--pw")) {
      bPWD = true;
      if (arg + 1 == argc || strlen(argv[++arg]) != 8 || ! ev1_load_pwd(iPWD, argv[arg])) {
        ERR("Please supply a PASSWORD of 8 HEX digits");
        exit(EXIT_FAILURE);
      }
    } else {
      //Skip validation of the filename
      if (arg != 2) {
        ERR("%s is not a supported option.", argv[arg]);
        print_usage(argv);
        exit(EXIT_FAILURE);
      } else {
        bFilename = true;
      }
    }
  }
  if (! bFilename) {
    ERR("Please supply a Mifare Dump filename");
    exit(EXIT_FAILURE);
  }

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

  // Try to open the NFC device
  pnd = nfc_open(context, NULL);
  if (pnd == NULL) {
    ERR("Error opening NFC device");
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));

  if (list_passive_targets(pnd)) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

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

  // Let the device 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_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Try to find a MIFARE Ultralight tag
  if (nfc_initiator_select_passive_target(pnd, nmMifare, (szUID) ? iUID : NULL, szUID, &nt) <= 0) {
    ERR("no tag was found\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }

  // Test if we are dealing with a MIFARE compatible tag
  if (nt.nti.nai.abtAtqa[1] != 0x44) {
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
    nfc_exit(context);
    exit(EXIT_FAILURE);
  }
  // Get the info from the current tag
  printf("Using MIFARE Ultralight card with UID: ");
  size_t  szPos;
  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
    printf("%02x", nt.nti.nai.abtUid[szPos]);
  }
  printf("\n");

  // test if tag is EV1
  if (get_ev1_version()) {
    if (!bPWD)
      printf("Tag is EV1 - PASSWORD may be required\n");
    printf("EV1 storage size: ");
    if (abtRx[6] == 0x0b) {
      printf("48 bytes\n");
      uiBlocks = 0x14;
      iEV1Type = EV1_UL11;
      iDumpSize = sizeof(mifareul_ev1_mf0ul11_tag);
    } else if (abtRx[6] == 0x0e) {
      printf("128 bytes\n");
      uiBlocks = 0x29;
      iEV1Type = EV1_UL21;
      iDumpSize = sizeof(mifareul_ev1_mf0ul21_tag);
    } else
      printf("unknown!\n");
  } else {
    // re-init non EV1 tag
    if (nfc_initiator_select_passive_target(pnd, nmMifare, (szUID) ? iUID : NULL, szUID, &nt) <= 0) {
      ERR("no tag was found\n");
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
  }

  // EV1 login required
  if (bPWD) {
    printf("Authing with PWD: %02x%02x%02x%02x ", iPWD[0], iPWD[1], iPWD[2], iPWD[3]);
    if (!ev1_pwd_auth(iPWD)) {
      printf("\n");
      ERR("AUTH failed!\n");
      exit(EXIT_FAILURE);
    } else {
      printf("Success - PACK: %02x%02x\n", abtRx[0], abtRx[1]);
      memcpy(iPACK, abtRx, 2);
    }
  }

  if (iAction == 1) {
    memset(&mtDump, 0x00, sizeof(mtDump));
  } else if (iAction == 2) {
    pfDump = fopen(argv[2], "rb");

    if (pfDump == NULL) {
      ERR("Could not open dump file: %s\n", argv[2]);
      exit(EXIT_FAILURE);
    }

    size_t  szDump;
    if (((szDump = fread(&mtDump, 1, sizeof(mtDump), pfDump)) != iDumpSize && !bPart) || szDump <= 0) {
      ERR("Could not read from dump file or size mismatch: %s\n", argv[2]);
      fclose(pfDump);
      exit(EXIT_FAILURE);
    }
    if (szDump != iDumpSize)
      printf("Performing partial write\n");
    fclose(pfDump);
    DBG("Successfully opened the dump file\n");
  } else if (iAction == 3) {
    DBG("Switching to Check Magic Mode\n");
  } else {
    ERR("Unable to determine operating mode");
    exit(EXIT_FAILURE);
  }

  if (iAction == 1) {
    bool bRF = read_card();
    printf("Writing data to file: %s ... ", argv[2]);
    fflush(stdout);
    pfDump = fopen(argv[2], "wb");
    if (pfDump == NULL) {
      printf("Could not open file: %s\n", argv[2]);
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    if (fwrite(&mtDump, 1, uiReadPages * 4, pfDump) != uiReadPages * 4) {
      printf("Could not write to file: %s\n", argv[2]);
      fclose(pfDump);
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    }
    fclose(pfDump);
    printf("Done.\n");
    if (!bRF)
      printf("Warning! Read failed - partial data written to file!\n");
  } else if (iAction == 2) {
    write_card(bOTP, bLock, bUID);
  } else if (iAction == 3) {
    if (!check_magic()) {
      printf("Card is not magic\n");
      nfc_close(pnd);
      nfc_exit(context);
      exit(EXIT_FAILURE);
    } else {
      printf("Card is magic\n");
    }
  }

  nfc_close(pnd);
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 27
0
int NFC_Mifare_Ultralight(int argc, const char *argv[]) //! Lecture - Écriture d'une carte MIFARE Ultralight
{
    bool    bReadAction;
    FILE   *pfDump;
    if (argc < 3)
    {
        sprintf(message_erreur,"Syntaxe incorrecte !");
        return EXIT_FAILURE; //! Échec !
    }
    DBG("\nChecking arguments and settings\n");
    bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');
    if (bReadAction) //! LECTURE
    {
        memset(&mtDump, 0x00, sizeof(mtDump));
    }
    else //! ÉCRITURE
    {
        if (argc !=3 && argc !=6)
        {
            sprintf(message_erreur,"Syntaxe incorrecte !");
            return EXIT_FAILURE; //! Échec !
        }
        pfDump = fopen(argv[2], "rb");
        if (pfDump == NULL)
        {
            sprintf(message_erreur,"Could not open dump file: %s !", argv[2]);
            return EXIT_FAILURE; //! Échec !
        }
        if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump))
        {
            sprintf(message_erreur,"Could not read from dump file: %s !", argv[2]);
            fclose(pfDump);
            return EXIT_FAILURE; //! Échec !
        }
        fclose(pfDump);
    }
    DBG("Successfully opened the dump file\n");
    nfc_context *context;
    nfc_init(&context);
    if (context == NULL)
    {
        sprintf(message_erreur,"Unable to init libnfc (malloc) !");
        return EXIT_FAILURE; //! Échec !
    }
    //! Try to open the NFC device
    pnd = nfc_open(context, NULL);
    if (pnd == NULL)
    {
        sprintf(message_erreur,"Error opening NFC device !");
        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 device 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 !
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"NFC device: %s opened\n", nfc_device_get_name(pnd));
    #endif
    //! Try to find a MIFARE Ultralight tag
    if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0)
    {
        sprintf(message_erreur,"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.abtAtqa[1] != 0x44) {
        sprintf(message_erreur,"Tag is not a MIFARE Ultralight card !");
        nfc_close(pnd);
        nfc_exit(context);
        return EXIT_FAILURE; //! Échec !
    }
    //! Get the info from the current tag
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"Found MIFARE Ultralight card with UID: ");
    #endif
    size_t  szPos;
    for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++)
    {
        #ifdef DEBUG_PRINTF
        fprintf(stderr,"%02x", nt.nti.nai.abtUid[szPos]);
        #endif
    }
    #ifdef DEBUG_PRINTF
    fprintf(stderr,"\n");
    #endif
    if (bReadAction)
    {
        if (read_card_ultralight())
        {
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Writing data to file: %s ... ", argv[2]);
            #endif
            fflush(stdout);
            pfDump = fopen(argv[2], "wb");
            if (pfDump == NULL)
            {
                sprintf(message_erreur,"Could not open file: %s !", argv[2]);
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
            if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump))
            {
                sprintf(message_erreur,"Could not write to file: %s !", argv[2]);
                fclose(pfDump);
                nfc_close(pnd);
                nfc_exit(context);
                return EXIT_FAILURE; //! Échec !
            }
            fclose(pfDump);
            #ifdef DEBUG_PRINTF
            fprintf(stderr,"Done.\n");
            #endif
        }
        else //! Échec !
        {
            nfc_close(pnd);
            nfc_exit(context);
            return EXIT_FAILURE;
        }
    }
    else
    {
        write_card_ultralight(argc,argv);
    }
    nfc_close(pnd);
    nfc_exit(context);
    return EXIT_SUCCESS; //! Succès !
}
Ejemplo n.º 28
0
int
main(int argc, char *argv[])
{
  uint8_t *pbtTx = NULL;
  size_t  szTxBits;
  bool    quiet_output = false;

  int     arg,
          i;

  // 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")) {
      printf("Quiet mode.\n");
      quiet_output = true;
    } else if ((arg == argc - 1) && (strlen(argv[arg]) == 8)) {         // See if UID was specified as HEX string
      uint8_t  abtTmp[3] = { 0x00, 0x00, 0x00 };
      printf("[+] Using UID: %s\n", argv[arg]);
      abtUidBcc[4] = 0x00;
      for (i = 0; i < 4; ++i) {
        memcpy(abtTmp, argv[arg] + i * 2, 2);
        abtUidBcc[i] = (uint8_t) strtol((char *) abtTmp, NULL, 16);
        abtUidBcc[4] ^= abtUidBcc[i];
      }
    } else {
      ERR("%s is not supported option.", argv[arg]);
      print_usage(argv);
      exit(EXIT_FAILURE);
    }
  }

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

  nfc_context *context;
  nfc_init(&context);

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

  if (pnd == NULL) {
    printf("Unable to open NFC device\n");
    exit(EXIT_FAILURE);
  }

  printf("\n");
  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
  printf("[+] Try to break out the auto-emulation, this requires a second NFC device!\n");
  printf("[+] To do this, please send any command after the anti-collision\n");
  printf("[+] For example, send a RATS command or use the \"nfc-anticol\" or \"nfc-list\" tool.\n");

  // Note: We have to build a "fake" nfc_target in order to do exactly the same that was done before the new nfc_target_init() was introduced.
  nfc_target nt = {
    .nm = {
      .nmt = NMT_ISO14443A,
      .nbr = NBR_UNDEFINED,
    },
    .nti = {
      .nai = {
        .abtAtqa = { 0x04, 0x00 },
        .abtUid = { 0x08, 0xad, 0xbe, 0xef },
        .btSak = 0x20,
        .szUidLen = 4,
        .szAtsLen = 0,
      },