void cut_setup (void) { int res; nfc_connstring devices[8]; size_t device_count; nfc_init (&context); cut_assert_not_null (context, cut_message ("Unable to init libnfc (malloc)")); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) cut_omit ("No device found"); for (size_t i = 0; i < device_count; i++) { device = nfc_open (context, devices[i]); if (!device) cut_omit ("nfc_open() failed."); tags = freefare_get_tags (device); cut_assert_not_null (tags, cut_message ("freefare_get_tags() failed")); tag = NULL; for (int i=0; tags[i]; i++) { if (freefare_get_tag_type(tags[i]) == MIFARE_DESFIRE) { tag = tags[i]; res = mifare_desfire_connect (tag); cut_assert_equal_int (0, res, cut_message ("mifare_desfire_connect() failed")); struct mifare_desfire_version_info version_info; res = mifare_desfire_get_version (tag, &version_info); cut_assert_equal_int (0, res, cut_message ("mifare_desfire_get_version")); if (version_info.hardware.storage_size < 0x18) { cut_omit ("DESFire EV1 tests require at least a 4K card"); } if ((version_info.hardware.version_major >= 1) && (version_info.software.version_major >= 1)) { return; } mifare_desfire_disconnect (tag); } } nfc_close (device); device = NULL; freefare_free_tags (tags); tags = NULL; } cut_omit ("No MIFARE DESFire EV1 tag on NFC device"); }
bool nfosc_check() { nfc_context *test_context; nfc_connstring test_strings[MAX_DEVICE_COUNT]; nfc_init(&test_context); if (test_context == NULL) return false; size_t szFound = nfc_list_devices (test_context, test_strings, MAX_DEVICE_COUNT); nfc_exit(context); if (szFound) return true; else return false; }
nfc_device *rfid_init(void) { nfc_init(&nfc_ctx); if(!nfc_ctx) { log("initializing libnfc failed"); return NULL; } door_aid = mifare_desfire_aid_new(0x2305CA); nfc_connstring devices[NFC_MAX_DEVICES]; int device_count = nfc_list_devices(nfc_ctx, devices, NFC_MAX_DEVICES); if(device_count <= 0) { log("no NFC devices found"); return NULL; } log("found %u NFC devices:", device_count); for(int i = 0; i < device_count; i++) log(" - %s", devices[i]); int selected_device = -1; const char *conf_connstring = getenv("RFID_CONNSTRING"); if(conf_connstring) { for(int i = 0; i < device_count; i++) if(strstr(devices[i], conf_connstring)) { selected_device = i; break; } } else { log("no connection string supplied, using first device"); selected_device = 0; } if(selected_device == -1) { log("could not find requested device"); return NULL; } log("using device %s", devices[selected_device]); nfc_device *dev = nfc_open(nfc_ctx, devices[selected_device]); if(!dev) { log("opening NFC device failed"); return NULL; } if(nfc_initiator_init(dev) < 0) { nfc_perror(dev, "configuring NFC device as initiator failed"); return NULL; } return dev; }
void cut_setup(void) { size_t n = nfc_list_devices(NULL, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } nfc_init(NULL); devices[TARGET] = nfc_open(NULL, connstrings[TARGET]); devices[INITIATOR] = nfc_open(NULL, connstrings[INITIATOR]); signal(SIGINT, abort_test_by_keypress); }
void cut_setup(void) { nfc_init(&context); size_t n = nfc_list_devices(context, connstrings, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } second_device = nfc_open(context, connstrings[0]); first_device = nfc_open(context, connstrings[1]); signal(SIGINT, abort_test_by_keypress); }
Result<std::vector<std::shared_ptr<NfcDevice>>> LibNfc::getDevices() const { nfc_connstring devices[16]; memset((char*)devices, 0, sizeof(devices)); size_t count = nfc_list_devices(_context, devices, 16); if (count < 0) { return Result<std::vector<std::shared_ptr<NfcDevice>>>::error("Failed to list NFC devices: " + count); } std::vector<std::shared_ptr<NfcDevice>> devicesList; for (size_t i = 0; i < count; ++i) { devicesList.push_back(std::make_shared<NfcDevice>(this, devices[i])); } return Result<std::vector<std::shared_ptr<NfcDevice>>>::ok(devicesList); }
int main(int argc, const char *argv[]) { uint8_t abtRx[MAX_FRAME_LEN]; int szRx; uint8_t abtTx[] = "Hello Mars!"; nfc_context *context; nfc_init(&context); #define MAX_DEVICE_COUNT 2 nfc_connstring connstrings[MAX_DEVICE_COUNT]; size_t szDeviceFound = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); // Little hack to allow using nfc-dep-initiator & nfc-dep-target from // the same machine: if there is more than one readers opened // nfc-dep-target will open the second reader // (we hope they're always detected in the same order) if (szDeviceFound == 1) { pnd = nfc_open(context, connstrings[0]); } else if (szDeviceFound > 1) { pnd = nfc_open(context, connstrings[1]); } else { printf("No device found.\n"); return EXIT_FAILURE; } if (argc > 1) { printf("Usage: %s\n", argv[0]); return EXIT_FAILURE; } nfc_target nt = { .nm = { .nmt = NMT_DEP, .nbr = NBR_UNDEFINED }, .nti = { .ndi = { .abtNFCID3 = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xff, 0x00, 0x00 }, .szGB = 4, .abtGB = { 0x12, 0x34, 0x56, 0x78 }, .ndm = NDM_UNDEFINED, /* These bytes are not used by nfc_target_init: the chip will provide them automatically to the initiator */ .btDID = 0x00, .btBS = 0x00, .btBR = 0x00, .btTO = 0x00, .btPP = 0x01, }, },
nfc_device* getRfidDevice() { size_t device_count = 0; nfc_connstring devices[8]; nfc_context *context; nfc_init(&context); device_count = nfc_list_devices(context,devices,8); if (device_count > 0) return nfc_open (context,devices[0]); else { fprintf(stderr,"Connecting to nfc device failed\n"); return NULL; } }
void cut_setup(void) { size_t n; nfc_init(NULL); llcp_init(); //cut_pend ("MAC link over DEP does not work"); n = nfc_list_devices(NULL, device_descriptions, 2); if (n < 2) { cut_omit("At least two NFC devices must be plugged-in to run this test"); } devices[TARGET] = nfc_open(NULL, device_descriptions[TARGET]); devices[INITIATOR] = nfc_open(NULL, device_descriptions[INITIATOR]); }
static VALUE devices(VALUE self, VALUE len) { nfc_context *ctx; nfc_connstring * strs; size_t found, i; VALUE devs; Data_Get_Struct(self, nfc_context, ctx); strs = malloc(sizeof(nfc_connstring) * len); found = nfc_list_devices(ctx, strs, 10); devs = rb_ary_new2(found); for (i = 0; i < found; i++) { rb_ary_push(devs, rb_str_new2(strs[i])); } free(strs); return devs; }
void RFIDHandler::init() { nfc_connstring devices[1]; nfc_context *context; nfc_init (&context); if(nfc_list_devices (context, devices, 1) == 0) { cout << "Error no NFC devices found..." << endl; } m_nfc_device = nfc_open (context, devices[0]); if(m_nfc_device == NULL) { cout << "Error unable to open NFC device" << endl; } }
void cut_setup (void) { int res; nfc_connstring devices[8]; size_t device_count; nfc_init (&context); cut_assert_not_null (context, cut_message ("Unable to init libnfc (malloc)")); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) cut_omit ("No device found"); for (size_t i = 0; i < device_count; i++) { device = nfc_open (context, devices[i]); if (!device) cut_omit ("nfc_open() failed."); tags = freefare_get_tags (device); cut_assert_not_null (tags, cut_message ("freefare_get_tags() failed")); tag = NULL; for (int i=0; tags[i]; i++) { if ((freefare_get_tag_type(tags[i]) == MIFARE_CLASSIC_1K) || (freefare_get_tag_type(tags[i]) == MIFARE_CLASSIC_4K)) { tag = tags[i]; res = mifare_classic_connect (tag); cut_assert_equal_int (0, res, cut_message ("mifare_classic_connect() failed")); return; } } nfc_close (device); device = NULL; freefare_free_tags (tags); tags = NULL; } cut_omit ("No MIFARE Classic tag on NFC device"); }
int main (void) { nfc_connstring nfc_devices[MAX_NFC_DEVICES]; size_t nfc_device_count; nfc_device_count = nfc_list_devices (NULL, nfc_devices, MAX_NFC_DEVICES); bool aborting = false; for (size_t n = 0; (!aborting) && (n < nfc_device_count); n++) { nfc_device *nfc_device = nfc_open (NULL, nfc_devices[n]); MifareTag *tags = freefare_get_tags (nfc_device); for (int i = 0; (!aborting) && tags[i]; i++) { if (DESFIRE == freefare_get_tag_type (tags[i])) { fprintf (stdout, "Found UCard with UID 0x%s\n", freefare_get_tag_uid (tags[i])); printf ("Admin access key: "); char buffer[BUFSIZ]; system ("stty -echo"); fgets (buffer, BUFSIZ, stdin); system ("stty echo"); char *p; if ((p = strchr (buffer, '\n'))) *p = '\0'; ucard_derivate_password (buffer, strlen (buffer), 16, admin_key_data); memset (buffer, '\0', strlen (buffer)); if (explain_tag (tags[i]) < 0) aborting = true; } } freefare_free_tags (tags); } exit((aborting) ? 1 : 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, char **argv) { int res; nfc_connstring devices[8]; size_t device_count; nfc_context *nfcctx; char *uid = NULL; init_crypto_state(); nfc_init(&nfcctx); device_count = nfc_list_devices(nfcctx,devices,8); if (device_count <= 0) { std::cerr << "No device found" << std::endl; } device = nfc_open(nfcctx, devices[0]); tags = freefare_get_tags(device); if (tags[0] == NULL) { std::cerr << "No tag on device" << std::endl; exit(1); } for (int i = 0; tags[i]; i++) { if (freefare_get_tag_type(tags[i]) == CLASSIC_1K) { tag = tags[i]; res = mifare_classic_connect(tag); if (res != 0) { std::cout << "Error connecting to MiFare Classic" << std::endl; exit(1); } std::cout << "Connected to MiFare Classic" << std::endl; uid = freefare_get_tag_uid(tag); break; } } std::cout << "UID: " << uid << std::endl; MifareClassicKey *keyA = (MifareClassicKey *)get_random_bytes(6); std::cout << "Key A: "; print_hex(*keyA,6); char *b64KeyA = getBase64String((char *)keyA,6); std::cout << b64KeyA << std::endl; std::cout << "Key B: "; MifareClassicKey *keyB = (MifareClassicKey *)get_random_bytes(6); print_hex(*keyB,6); char *b64KeyB = getBase64String((char *)keyB,6); bool addedToServer = addCard(uid,b64KeyA,b64KeyB); if (!addedToServer) { printf("Not added to server\n"); } // Authenticate with default key to make changes MifareClassicBlockNumber lastTrailer = mifare_classic_sector_last_block(15); res = mifare_classic_authenticate(tag,lastTrailer,defaultKey,MFC_KEY_A); if (res != 0) { printf("Could not authenticate with default key.. card already formatted?\n"); return -1; } MifareClassicBlockNumber firstBlock = mifare_classic_sector_first_block(15); res = mifare_classic_init_value(tag,firstBlock,SECTOR_15_BLOCK_0_INIT,firstBlock); if (res != 0) { printf("Could not init value block %d\n",firstBlock); } MifareClassicBlock trailerBlock; mifare_classic_trailer_block(&trailerBlock,*keyA,0x03,0x00,0x00,0x04,0x00, *keyB); print_hex(trailerBlock, sizeof(MifareClassicBlock)); res = mifare_classic_write(tag,lastTrailer,trailerBlock); if (res != 0) { printf("Could not write sector 15 trailer. STOP\n"); return -1; } MifareClassicBlock normalTrailerBlock; mifare_classic_trailer_block(&normalTrailerBlock,*keyA,0x00,0x00,0x00,0x04,0x00,*keyB); printf("Writing normal trailer block "); print_hex(&normalTrailerBlock[0], sizeof(MifareClassicBlock)); MifareClassicSectorNumber sector; for(sector=0; sector<15;sector++) { MifareClassicBlockNumber trailerBlockNumber = mifare_classic_sector_last_block(sector); res = mifare_classic_authenticate(tag,trailerBlockNumber,defaultKey,MFC_KEY_A); if (res != 0) { printf("Could not authenticate with default key.. card already formatted?\n"); return -1; } res = mifare_classic_write(tag,trailerBlockNumber,normalTrailerBlock); if (res != 0) { printf("Could not write trailer block for sector %d\n",sector); return -1; } else { printf("Wrote trailer block for sector %d\n",sector); } } free(keyA); free(keyB); free(b64KeyA); free(b64KeyB); free(uid); freefare_free_tags(tags); nfc_close(device); }
int main(int argc, char *argv[]) { int error = EXIT_SUCCESS; nfc_device *device = NULL; MifareTag *tags = NULL; if (argc > 1) errx (EXIT_FAILURE, "usage: %s", argv[0]); nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); if (context == NULL) errx(EXIT_FAILURE, "Unable to init libnfc (malloc)"); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; d < device_count; d++) { device = nfc_open (context, devices[d]); if (!device) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); errx (EXIT_FAILURE, "Error listing tags."); } for (int i = 0; (!error) && tags[i]; i++) { if (DESFIRE != freefare_get_tag_type (tags[i])) continue; int res; // This is hex-encoded see the https://code.google.com/p/libfreefare/source/browse/libfreefare/freefare.c#189 on how to access the raw data char *tag_uid = freefare_get_tag_uid (tags[i]); res = mifare_desfire_connect (tags[i]); if (res < 0) { warnx ("Can't connect to Mifare DESFire target."); error = EXIT_FAILURE; break; } MifareDESFireKey key = mifare_desfire_des_key_new_with_version (key_data_null); res = mifare_desfire_authenticate (tags[i], 0, key); if (res < 0) errx (EXIT_FAILURE, "Authentication on master application failed"); MadAid mad_aid = { 0x12, 0x34 }; MifareDESFireAID aid = mifare_desfire_aid_new_with_mad_aid (mad_aid, 0x5); res = mifare_desfire_create_application (tags[i], aid, 0xFF, 0x1); if (res < 0) errx (EXIT_FAILURE, "Application creation failed"); res = mifare_desfire_select_application (tags[i], aid); if (res < 0) errx (EXIT_FAILURE, "Application selection failed"); res = mifare_desfire_authenticate (tags[i], 0, key); if (res < 0) errx (EXIT_FAILURE, "Authentication on application failed"); res = mifare_desfire_create_std_data_file (tags[i], 1, MDCM_ENCIPHERED, 0x0000, 20); if (res < 0) errx (EXIT_FAILURE, "File creation failed"); const char *s= "Hello World"; res = mifare_desfire_write_data (tags[i], 1, 0, strlen (s), s); if (res < 0) errx (EXIT_FAILURE, "File write failed"); char buffer[20]; res = mifare_desfire_read_data (tags[i], 1, 0, 0, buffer); if (res < 0) errx (EXIT_FAILURE, "File read failed"); res = mifare_desfire_select_application (tags[i], NULL); if (res < 0) errx (EXIT_FAILURE, "Master application selection failed"); res = mifare_desfire_authenticate (tags[i], 0, key); if (res < 0) errx (EXIT_FAILURE, "Authentication on master application failed"); res = mifare_desfire_format_picc (tags[i]); if (res < 0) errx (EXIT_FAILURE, "PICC format failed"); mifare_desfire_key_free (key); free (tag_uid); free (aid); mifare_desfire_disconnect (tags[i]); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); exit (error); } /* main() */
int main (int argc, char *argv[]) { int error = EXIT_SUCCESS; nfc_device *device = NULL; MifareTag *tags = NULL; if (argc > 1) errx (EXIT_FAILURE, "usage: %s", argv[0]); nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); device_count = nfc_list_devices (context, devices, sizeof (devices) / sizeof (*devices)); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found"); for (size_t d = 0; d < device_count; d++) { if (!(device = nfc_open (context, devices[d]))) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } if (!(tags = freefare_get_tags (device))) { nfc_close (device); errx (EXIT_FAILURE, "Error listing tags."); } for (int i = 0; (!error) && tags[i]; i++) { switch (freefare_get_tag_type (tags[i])) { case ULTRALIGHT: case ULTRALIGHT_C: break; default: continue; } char *tag_uid = freefare_get_tag_uid (tags[i]); printf ("Tag with UID %s is a %s\n", tag_uid, freefare_get_tag_friendly_name (tags[i])); if (freefare_get_tag_type (tags[i]) == ULTRALIGHT_C) { MifareTag tag = tags[i]; int res; MifareDESFireKey key; uint8_t key1_3des_data[16] = { 0x49, 0x45, 0x4D, 0x4B, 0x41, 0x45, 0x52, 0x42, 0x21, 0x4E, 0x41, 0x43, 0x55, 0x4F, 0x59, 0x46 }; key = mifare_desfire_3des_key_new (key1_3des_data); if (mifare_ultralight_connect (tag) < 0) errx (EXIT_FAILURE, "Error connecting to tag."); res = mifare_ultralightc_authenticate (tag, key); printf ("Authentication with default key: %s\n", res ? "fail" : "success"); mifare_desfire_key_free (key); mifare_ultralight_disconnect (tag); } free (tag_uid); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); exit(error); }
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, },
int main(int argc, char *argv[]) { int ch; int error = EXIT_SUCCESS; nfc_device *device = NULL; MifareTag *tags = NULL; while ((ch = getopt (argc, argv, "hyK:")) != -1) { switch (ch) { case 'h': usage(argv[0]); exit (EXIT_SUCCESS); break; case 'y': configure_options.interactive = false; break; case 'K': if (strlen(optarg) != 16) { usage(argv[0]); exit (EXIT_FAILURE); } uint64_t n = strtoull(optarg, NULL, 16); int i; for (i=7; i>=0; i--) { key_data_picc[i] = (uint8_t) n; n >>= 8; } break; default: usage(argv[0]); exit (EXIT_FAILURE); } } // Remaining args, if any, are in argv[optind .. (argc-1)] nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); if (context == NULL) errx(EXIT_FAILURE, "Unable to init libnfc (malloc)"); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; (!error) && (d < device_count); d++) { device = nfc_open (context, devices[d]); if (!device) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); errx (EXIT_FAILURE, "Error listing Mifare DESFire tags."); } for (int i = 0; (!error) && tags[i]; i++) { if (DESFIRE != freefare_get_tag_type (tags[i])) continue; char *tag_uid = freefare_get_tag_uid (tags[i]); char buffer[BUFSIZ]; int res; res = mifare_desfire_connect (tags[i]); if (res < 0) { warnx ("Can't connect to Mifare DESFire target."); error = EXIT_FAILURE; break; } // Make sure we've at least an EV1 version struct mifare_desfire_version_info info; res = mifare_desfire_get_version (tags[i], &info); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_get_version"); error = 1; break; } if (info.software.version_major < 1) { warnx ("Found old DESFire, skipping"); continue; } printf ("Found %s with UID %s. ", freefare_get_tag_friendly_name (tags[i]), tag_uid); bool do_it = true; if (configure_options.interactive) { printf ("Change ATS? [yN] "); fgets (buffer, BUFSIZ, stdin); do_it = ((buffer[0] == 'y') || (buffer[0] == 'Y')); } else { printf ("\n"); } if (do_it) { MifareDESFireKey key_picc = mifare_desfire_des_key_new_with_version (key_data_picc); res = mifare_desfire_authenticate (tags[i], 0, key_picc); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_authenticate"); error = EXIT_FAILURE; break; } mifare_desfire_key_free (key_picc); res = mifare_desfire_set_ats (tags[i], new_ats); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_set_ats"); error = EXIT_FAILURE; break; } } mifare_desfire_disconnect (tags[i]); free (tag_uid); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); exit (error); } /* main() */
int main(int argc, char *argv[]) { int error = EXIT_SUCCESS; nfc_device *device = NULL; FreefareTag *tags = NULL; if (argc > 1) errx (EXIT_FAILURE, "usage: %s", argv[0]); nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); if (context == NULL) errx(EXIT_FAILURE, "Unable to init libnfc (malloc)"); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; d < device_count; d++) { device = nfc_open (context, devices[d]); if (!device) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); errx (EXIT_FAILURE, "Error listing tags."); } for (int i = 0; (!error) && tags[i]; i++) { if (MIFARE_DESFIRE != freefare_get_tag_type (tags[i])) continue; int res; char *tag_uid = freefare_get_tag_uid (tags[i]); res = mifare_desfire_connect (tags[i]); if (res < 0) { warnx ("Can't connect to Mifare DESFire target."); error = 1; break; }else{ printf("Connected uid: %s\n", tag_uid); } uint8_t key_version; mifare_desfire_get_key_version (tags[i], 0, &key_version); MifareDESFireKey key = malloc(sizeof(MifareDESFireKey)); res = mifare_desfire_auto_authenticate(tags[i], 0, key); if(res < 0){ printf("Error while geting the master key.....\n"); break; } MifareDESFireAID aid = mifare_desfire_aid_new (0x112233); //res = mifare_desfire_create_application (tags[i], aid, 0xFF, 1); size_t count; MifareDESFireAID **aids = malloc(sizeof(MifareDESFireAID*)); res = mifare_desfire_get_application_ids(tags[i], aids, &count); if(res==0){ printf("found %d applicaton/s\n", (int)count); //struct MifareDESFireAID aidArr[count] = *aids; int j; for(j=0; j<count; j++){ // Fails here aid = (*aids)[j]; printf("aid %d: %x\n", j, mifare_desfire_aid_get_aid(aid)); if(mifare_desfire_aid_get_aid(aid) == 0x112233){ if(mifare_desfire_select_application(tags[i], aid) == 0){ printf("app selected...\n"); size_t fileCount = 0; uint8_t **files = malloc(sizeof(uint8_t)); int rra = mifare_desfire_get_file_ids(tags[i], files, &fileCount); printf("%d found %d file ids\n", rra, (int)fileCount); } } } printf("ok\n"); }else{ printf("error res is %d\n", res); } mifare_desfire_key_free (key); free (tag_uid); mifare_desfire_disconnect (tags[i]); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); exit (error); } /* main() */
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); }
int main (void) { uint8_t issuer_key_data[16]; nfc_connstring nfc_devices[8]; size_t nfc_device_count; nfc_device_count = nfc_list_devices (NULL, nfc_devices, 8); for (size_t n = 0; n < nfc_device_count; n++) { nfc_device *nfc_device = nfc_open (NULL, nfc_devices[n]); MifareTag *tags = freefare_get_tags (nfc_device); for (int i = 0; tags[i]; i++) { MifareTag tag = tags[i]; if (DESFIRE == freefare_get_tag_type (tag)) { printf ("Fond Mifare DESFire with UID: %s\n", freefare_get_tag_uid (tag)); printf ("Issuer private key: "); char buffer[BUFSIZ]; system ("stty -echo"); fgets (buffer, BUFSIZ, stdin); system ("stty echo"); char *p; if ((p = strchr (buffer, '\n'))) *p = '\0'; ucard_derivate_password (buffer, strlen (buffer), 16, issuer_key_data); memset (buffer, '\0', strlen (buffer)); MifareDESFireKey key = mifare_desfire_aes_key_new (issuer_key_data); MifareDESFireAID ucard_info_aid = mifare_desfire_aid_new (UCARD_INFO_AID); int res = mifare_desfire_connect (tag); res = mifare_desfire_select_application (tag, ucard_info_aid); if (res < 0) { freefare_perror (tag, "mifare_desfire_select_application"); goto end; } res = mifare_desfire_authenticate_aes (tag, 1, key); if (res < 0) { freefare_perror (tag, "mifare_desfire_authenticate_aes"); goto end; } char owner_info[BUFSIZ]; res = mifare_desfire_read_data_ex (tag, 10, 0, 0, owner_info, MDCM_ENCIPHERED); if (res < 0) { freefare_perror (tag, "mifare_desfire_read_data"); goto end; } owner_info[res] = '\0'; printf ("Owner: %s\n", owner_info); end: mifare_desfire_disconnect (tag); mifare_desfire_key_free (key); free (ucard_info_aid); } } nfc_close (nfc_device); } exit(EXIT_SUCCESS); }
int NFC_Mifare_Classic_Format(int argc, char *argv[]) //! Formattage d'une carte MIFARE Classic { int ch; int error = EXIT_SUCCESS; nfc_device *device = NULL; MifareTag *tags = NULL; while ((ch = getopt (argc, argv, "fhy")) != -1) { switch (ch) { case 'f': format_options.fast = true; break; case 'y': format_options.interactive = false; break; default: sprintf(message_erreur,"Syntaxe incorrecte !"); return EXIT_FAILURE; } } //! Remaining args, if any, are in argv[optind .. (argc-1)] memcpy(default_keys, default_keys_int, sizeof(default_keys_int)); if ((argc - optind) > 0) { int i, rc; char kbuffer[1024] = {0}; memset ( kbuffer, 0, sizeof kbuffer); FILE *fp = fopen(argv[optind], "rb"); if (fp == NULL) { // errx(EXIT_FAILURE, "Unable to open file"); sprintf(message_erreur,"Unable to open file !"); return EXIT_FAILURE; } for (i = 0; (rc = getc(fp)) != EOF && i < 1024; kbuffer[i++] = rc) { } fclose(fp); i = sizeof(default_keys_int) / 6; int s; for(s = 0; s<16; s++) { int startblock = s * 4; int pos_a = (startblock + 3) * 16; int pos_b = (startblock + 3) * 16 + 10; memcpy((default_keys + i++), kbuffer + pos_a, 6); memcpy((default_keys + i++), kbuffer + pos_b, 6); } } nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); if (context == NULL) { // errx(EXIT_FAILURE, "Unable to init libnfc (malloc) !"); sprintf(message_erreur,"Unable to init libnfc (malloc) !"); return EXIT_FAILURE; } device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) { // errx (EXIT_FAILURE, "Error opening NFC reader !"); sprintf(message_erreur,"Error opening NFC reader !"); return EXIT_FAILURE; } size_t d; for (d = 0; d < device_count; d++) { device = nfc_open (context, devices[d]); if (!device) { sprintf(message_erreur,"Error opening NFC reader !"); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); // errx (EXIT_FAILURE, "Error listing Mifare Classic tag !"); sprintf(message_erreur,"Error listing Mifare Classic tag !"); return EXIT_FAILURE; } int i; for (i = 0; (!error) && tags[i]; i++) { switch (freefare_get_tag_type (tags[i])) { case CLASSIC_1K: case CLASSIC_4K: break; default: continue; } char *tag_uid = freefare_get_tag_uid (tags[i]); char buffer[BUFSIZ]; #ifdef DEBUG_PRINTF fprintf(stderr,"Found %s with UID %s. ", freefare_get_tag_friendly_name (tags[i]), tag_uid); #endif bool format = true; if (format_options.interactive) { #ifdef DEBUG_PRINTF fprintf(stderr,"Format [yN] "); #endif fgets (buffer, BUFSIZ, stdin); format = ((buffer[0] == 'y') || (buffer[0] == 'Y')); } else { #ifdef DEBUG_PRINTF fprintf(stderr,"\n"); #endif } if (format) { enum mifare_tag_type tt = freefare_get_tag_type (tags[i]); at_block = 0; if (format_options.fast) { printf (START_FORMAT_N, (tt == CLASSIC_1K) ? 1 : 2); if (!try_format_sector (tags[i], 0x00)) break; if (tt == CLASSIC_4K) if (!try_format_sector (tags[i], 0x10)) break; printf (DONE_FORMAT); continue; } switch (tt) { case CLASSIC_1K: mod_block = 4; if (!format_mifare_classic_1k (tags[i])) error = 1; break; case CLASSIC_4K: mod_block = 10; if (!format_mifare_classic_4k (tags[i])) error = 1; break; default: /* Keep compiler quiet */ break; } } free (tag_uid); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); return error; }
int main (int argc, char *argv[]) { /* * Collect information */ bool f_flag = false; char *p; char ch; while ((ch = getopt (argc, argv, "f")) != -1) { switch (ch) { case 'f': f_flag = true; break; default: usage (argv[0]); exit (EXIT_FAILURE); break; } } char issuer_address[BUFSIZ]; fprintf (stderr, "Card issuer address: "); fgets (issuer_address, BUFSIZ, stdin); if ((p = strchr (issuer_address, '\n'))) *p = '\0'; char issuer_password[BUFSIZ]; read_password ("Issuer password", issuer_password, BUFSIZ); fprintf (stderr, "\n"); uint8_t issuer_password_data[16]; ucard_derivate_password (issuer_password, strlen (issuer_password), 16, issuer_password_data); memset (issuer_password, '\0', strlen (issuer_password)); MifareDESFireKey card_issuer_key = mifare_desfire_aes_key_new (issuer_password_data); char owner_full_name[BUFSIZ]; fprintf (stderr, "Card owner full user name: "); fgets (owner_full_name, BUFSIZ, stdin); if ((p = strchr (owner_full_name, '\n'))) *p = '\0'; char user_password[BUFSIZ]; read_password ("User password", user_password, BUFSIZ); fprintf (stderr, "\n"); uint8_t user_key_data[16]; ucard_derivate_password (user_password, strlen (user_password), 16, user_key_data); memset (user_password, '\0', strlen (user_password)); MifareDESFireKey user_key = mifare_desfire_aes_key_new_with_version (user_key_data, UCARD_AES_KEY_VERSION); char admin_password[BUFSIZ]; read_password ("Admin password", admin_password, BUFSIZ); fprintf (stderr, "\n"); uint8_t admin_key_data[16]; ucard_derivate_password (admin_password, strlen (admin_password), 16, admin_key_data); memset (admin_password, '\0', strlen (admin_password)); MifareDESFireKey admin_key = mifare_desfire_aes_key_new_with_version (admin_key_data, UCARD_AES_KEY_VERSION); uint8_t null_key_data[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; MifareDESFireKey null_des_key = mifare_desfire_des_key_new (null_key_data); MifareDESFireKey null_aes_key = mifare_desfire_aes_key_new (null_key_data); nfc_connstring nfc_devices[8]; size_t nfc_device_count; nfc_device_count = nfc_list_devices (NULL, nfc_devices, 8); for (size_t n = 0; n < nfc_device_count; n++) { nfc_device *nfc_device = nfc_open(NULL, nfc_devices[n]); MifareTag *tags = freefare_get_tags (nfc_device); for (int i = 0; tags[i]; i++) { MifareTag tag = tags[i]; if (DESFIRE == freefare_get_tag_type (tag)) { /* Actually setup the card */ printf ("Fond Mifare DESFire with UID: %s\n", freefare_get_tag_uid (tag)); /* * Master Application * * Key 0: Card owner 'user' private key */ MifareDESFireAID ucard_info_aid = mifare_desfire_aid_new (UCARD_INFO_AID); int res = mifare_desfire_connect (tag); if (f_flag) { if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, user_key); if (0 == res) res = mifare_desfire_format_picc (tag); } else { if (0 == res) res = mifare_desfire_authenticate (tag, 0, null_des_key); if (0 == res) res = mifare_desfire_change_key (tag, 0, user_key, NULL); if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, user_key); } if (0 == res) res = mifare_desfire_create_application (tag, ucard_info_aid, 0x0F, 0x83); if (!f_flag) { if (0 == res) res = mifare_desfire_change_key_settings (tag, 0x01); } /* * Card information application * * Key 0: Card owner 'admin' private key * Key 1: Card issuer private key * Key 2: Anonymous access public key * * File 9: Card issuer information * File 10: Card owner information * File 11: Keyring */ if (0 == res) res = mifare_desfire_select_application (tag, ucard_info_aid); if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, null_aes_key); if (0 == res) res = mifare_desfire_change_key (tag, 0, admin_key, NULL); if (0 == res) res = mifare_desfire_authenticate_aes (tag, 0, admin_key); if (0 == res) res = mifare_desfire_change_key (tag, 1, card_issuer_key, NULL); if (0 == res) res = mifare_desfire_create_std_data_file (tag, 9, MDCM_ENCIPHERED, 0x0000, strlen (issuer_address)); if (0 == res) res = mifare_desfire_write_data (tag, 9, 0, strlen (issuer_address), issuer_address); if (strlen (issuer_address) == (size_t) res) res = mifare_desfire_change_file_settings (tag, 9, MDCM_ENCIPHERED, 0x2F11); if (0 == res) res = mifare_desfire_create_std_data_file (tag, 10, MDCM_ENCIPHERED, 0x0000, strlen (owner_full_name)); if (0 == res) res = mifare_desfire_write_data (tag, 10, 0, strlen (owner_full_name), owner_full_name); if (strlen (owner_full_name) == (size_t) res) res = mifare_desfire_change_file_settings (tag, 10, MDCM_ENCIPHERED, 0x0F11); if (0 == res) res = mifare_desfire_create_linear_record_file (tag, 11, MDCM_ENCIPHERED, 0xF20F, 3 + 16, 24); if (0 == res) res = mifare_desfire_change_key_settings (tag, 0x01); if (res < 0) { fprintf (stderr, "Oops, something went wrong! (%s)\n", freefare_strerror (tag)); } mifare_desfire_disconnect (tag); free (ucard_info_aid); } } nfc_close (nfc_device); } mifare_desfire_key_free (admin_key); mifare_desfire_key_free (user_key); mifare_desfire_key_free (card_issuer_key); mifare_desfire_key_free (null_aes_key); mifare_desfire_key_free (null_des_key); exit(EXIT_SUCCESS); }
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!"); }
int main(int argc, char *argv[]) { int ch; int error = EXIT_SUCCESS; nfc_device *device = NULL; FreefareTag *tags = NULL; while ((ch = getopt (argc, argv, "hy")) != -1) { switch (ch) { case 'h': usage(argv[0]); exit (EXIT_SUCCESS); break; case 'y': configure_options.interactive = false; break; default: usage(argv[0]); exit (EXIT_FAILURE); } } // Remaining args, if any, are in argv[optind .. (argc-1)] nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); if (context == NULL) errx(EXIT_FAILURE, "Unable to init libnfc (malloc)"); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; (!error) && (d < device_count); d++) { device = nfc_open (context, devices[d]); if (!device) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); errx (EXIT_FAILURE, "Error listing Mifare DESFire tags."); } for (int i = 0; (!error) && tags[i]; i++) { if (MIFARE_DESFIRE != freefare_get_tag_type (tags[i])) continue; char *tag_uid = freefare_get_tag_uid (tags[i]); char buffer[BUFSIZ]; int res; res = mifare_desfire_connect (tags[i]); if (res < 0) { warnx ("Can't connect to Mifare DESFire target."); error = EXIT_FAILURE; break; } // Make sure we've at least an EV1 version struct mifare_desfire_version_info info; res = mifare_desfire_get_version (tags[i], &info); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_get_version"); error = 1; break; } if (info.software.version_major < 1) { warnx ("Found old DESFire, skipping"); continue; } printf ("Found %s with UID %s. ", freefare_get_tag_friendly_name (tags[i]), tag_uid); bool do_it = true; if (configure_options.interactive) { printf ("Change default key? [yN] "); fgets (buffer, BUFSIZ, stdin); do_it = ((buffer[0] == 'y') || (buffer[0] == 'Y')); } else { printf ("\n"); } if (do_it) { MifareDESFireKey default_key = mifare_desfire_des_key_new_with_version (null_key_data); res = mifare_desfire_authenticate (tags[i], 0, default_key); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_authenticate"); error = EXIT_FAILURE; break; } mifare_desfire_key_free (default_key); MifareDESFireKey new_key = mifare_desfire_des_key_new (new_key_data); mifare_desfire_key_set_version (new_key, NEW_KEY_VERSION); res = mifare_desfire_set_default_key (tags[i], new_key); free (new_key); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_set_default_key"); error = EXIT_FAILURE; break; } /* * Perform some tests to ensure the function actually worked * (it's hard to create a unit-test to do so). */ MifareDESFireAID aid = mifare_desfire_aid_new (0x112233); res = mifare_desfire_create_application (tags[i], aid, 0xFF, 1); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_create_application"); error = EXIT_FAILURE; break; } res = mifare_desfire_select_application (tags[i], aid); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_select_application"); error = EXIT_FAILURE; break; } uint8_t version; res = mifare_desfire_get_key_version (tags[i], 0, &version); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_get_key_version"); error = EXIT_FAILURE; break; } if (version != NEW_KEY_VERSION) { fprintf (stderr, "Wrong key version: %02x (expected %02x).\n", version, NEW_KEY_VERSION); error = EXIT_FAILURE; /* continue */ } new_key = mifare_desfire_des_key_new (new_key_data); res = mifare_desfire_authenticate (tags[i], 0, new_key); free (new_key); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_authenticate"); error = EXIT_FAILURE; break; } free (aid); /* Resetdefault settings */ res = mifare_desfire_select_application (tags[i], NULL); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_select_application"); error = EXIT_FAILURE; break; } default_key = mifare_desfire_des_key_new (null_key_data); res = mifare_desfire_authenticate (tags[i], 0, default_key); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_authenticate"); error = EXIT_FAILURE; break; } res = mifare_desfire_set_default_key (tags[i], default_key); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_set_default_key"); error = EXIT_FAILURE; break; } mifare_desfire_key_free (default_key); /* Wipeout the card */ res = mifare_desfire_format_picc (tags[i]); if (res < 0) { freefare_perror (tags[i], "mifare_desfire_format_picc"); error = EXIT_FAILURE; break; } } mifare_desfire_disconnect (tags[i]); free (tag_uid); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); exit (error); }
int main(int argc, char *argv[]) { int ch; int error = EXIT_SUCCESS; nfc_device *device = NULL; MifareTag *tags = NULL; while ((ch = getopt (argc, argv, "hyK:")) != -1) { switch (ch) { case 'h': usage(argv[0]); exit (EXIT_SUCCESS); break; case 'y': format_options.interactive = false; break; case 'K': if (strlen(optarg) != 16) { usage(argv[0]); exit (EXIT_FAILURE); } uint64_t n = strtoull(optarg, NULL, 16); int i; for (i=7; i>=0; i--) { key_data_picc[i] = (uint8_t) n; n >>= 8; } break; default: usage(argv[0]); exit (EXIT_FAILURE); } } // Remaining args, if any, are in argv[optind .. (argc-1)] nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; (!error) && (d < device_count); d++) { device = nfc_open (context, devices[d]); if (!device) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); errx (EXIT_FAILURE, "Error listing Mifare DESFire tags."); } for (int i = 0; (!error) && tags[i]; i++) { if (DESFIRE != freefare_get_tag_type (tags[i])) continue; char *tag_uid = freefare_get_tag_uid (tags[i]); char buffer[BUFSIZ]; printf ("Found %s with UID %s. ", freefare_get_tag_friendly_name (tags[i]), tag_uid); bool format = true; if (format_options.interactive) { printf ("Format [yN] "); fgets (buffer, BUFSIZ, stdin); format = ((buffer[0] == 'y') || (buffer[0] == 'Y')); } else { printf ("\n"); } if (format) { int res; res = mifare_desfire_connect (tags[i]); if (res < 0) { warnx ("Can't connect to Mifare DESFire target."); error = EXIT_FAILURE; break; } MifareDESFireKey key_picc = mifare_desfire_des_key_new_with_version (key_data_picc); res = mifare_desfire_authenticate (tags[i], 0, key_picc); if (res < 0) { warnx ("Can't authenticate on Mifare DESFire target."); error = EXIT_FAILURE; break; } mifare_desfire_key_free (key_picc); // Send Mifare DESFire ChangeKeySetting to change the PICC master key settings into : // bit7-bit4 equal to 0000b // bit3 equal to 1b, the configuration of the PICC master key MAY be changeable or frozen // bit2 equal to 1b, CreateApplication and DeleteApplication commands are allowed without PICC master key authentication // bit1 equal to 1b, GetApplicationIDs, and GetKeySettings are allowed without PICC master key authentication // bit0 equal to 1b, PICC masterkey MAY be frozen or changeable res = mifare_desfire_change_key_settings (tags[i],0x0F); if (res < 0) errx (EXIT_FAILURE, "ChangeKeySettings failed"); res = mifare_desfire_format_picc (tags[i]); if (res < 0) { warn ("Can't format PICC."); error = EXIT_FAILURE; break; } mifare_desfire_disconnect (tags[i]); } free (tag_uid); } freefare_free_tags (tags); nfc_close (device); } nfc_exit (context); exit (error); } /* main() */
int main(int argc, char *argv[]) { int ret = 0; int ch; int testno; const int testcount = sizeof(tests) / sizeof(*tests); char junk; nfc_init(NULL); if (llcp_init() < 0) errx(EXIT_FAILURE, "llcp_init()"); signal(SIGINT, stop_mac_link); while ((ch = getopt_long(argc, argv, "qd:f:l:D:m:Q:ht:T", longopts, NULL)) != -1) { switch (ch) { case 'q': case 'd': case 'f': warnx("ignored option -- %c (hint: edit log4crc)", ch); break; case 'l': if (1 != sscanf(optarg, "%d%c", &options.link_miu, &junk)) { errx(EXIT_FAILURE, "“%s” is not a valid link MIU value", optarg); } break; case 'D': options.device = optarg; break; case 'm': if (0 == strcasecmp("initiator", optarg)) options.mode = M_INITIATOR; else if (0 == strcasecmp("target", optarg)) options.mode = M_TARGET; else errx(EXIT_FAILURE, "“%s” is not a supported mode", optarg); break; case 'Q': if (0 == strcasecmp("android", optarg)) options.quirks = Q_ANDROID; else errx(EXIT_FAILURE, "“%s” is not a support quirks mode", optarg); break; case 't': if (1 != sscanf(optarg, "%d%c", &testno, &junk)) { errx(EXIT_FAILURE, "“%s” is not a valid test number", optarg); } if ((testno < 1) || (testno > testcount)) { errx(EXIT_FAILURE, "Test number %d is not in the [1..%d] range", testno, (int) testcount); } tests[testno - 1].enabled = 1; break; case 'T': fprintf(stderr, "Available tests:\n"); for (size_t i = 0; i < sizeof(tests) / sizeof(*tests); i++) { fprintf(stderr, "%3d - %s\n", (int) i + 1, tests[i].description); } exit(EXIT_SUCCESS); break; case 'h': default: usage(basename(argv[0])); exit(EXIT_FAILURE); break; } } argc -= optind; argv += optind; nfc_connstring device_connstring[1]; int res; res = nfc_list_devices(NULL, device_connstring, 1); if (res < 1) errx(EXIT_FAILURE, "No NFC device found"); nfc_device *device; if (!(device = nfc_open(NULL, device_connstring[0]))) { errx(EXIT_FAILURE, "Cannot open NFC device"); } struct llc_link *llc_link = llc_link_new(); if (!llc_link) { errx(EXIT_FAILURE, "Cannot allocate LLC link data structures"); } mac_link = mac_link_new(device, llc_link); if (!mac_link) errx(EXIT_FAILURE, "Cannot create MAC link"); for (int i = 0; i < testcount; i++) { if (tests[i].enabled) { ret += tests[i].fn(llc_link); } } void *err; mac_link_wait(mac_link, &err); switch (llc_link->role & 0x01) { case LLC_INITIATOR: printf("I was the Initiator\n"); break; case LLC_TARGET: printf("I was the Target\n"); break; } mac_link_free(mac_link); llc_link_free(llc_link); nfc_close(device); llcp_fini(); nfc_exit(NULL); exit(ret); }
int main (int argc, char *argv[]) { int error = EXIT_SUCCESS; nfc_device *device = NULL; FreefareTag *tags = NULL; int ch; char *ndef_file = NULL; while ((ch = getopt (argc, argv, "o:")) != -1) { switch (ch) { case 'o': ndef_file = optarg; break; case '?': usage (argv[0]); exit (EXIT_FAILURE); } } nfc_connstring devices[8]; size_t device_count; nfc_context *context; nfc_init (&context); if (context == NULL) errx (EXIT_FAILURE, "Unable to init libnfc (malloc)"); device_count = nfc_list_devices (context, devices, 8); if (device_count <= 0) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; d < device_count; d++) { device = nfc_open (context, devices[d]); if (!device) { warnx ("nfc_open() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_close (device); errx (EXIT_FAILURE, "Error listing FeliCa tag."); } for (int i = 0; (!error) && tags[i]; i++) { int block = 1; uint8_t ndef_message[NDEF_BUFFER_SIZE]; int ndef_space_left = NDEF_BUFFER_SIZE; uint8_t *p = ndef_message; ssize_t s; // FIXME Instead of reading as much as we can, we should read until end of NDEF record (if any is found). while ((ndef_space_left >= 16) && (s = felica_read (tags[i], FELICA_SC_RO, block++, p, 16)) > 0) { p += s; ndef_space_left -= s; } size_t ndef_message_length = 0; if ((ndef_message[0] & 0x80) == 0x80) { uint8_t *ndef_record; do { ndef_record = ndef_message + ndef_message_length; size_t ndef_record_length = 1 + 1 + ndef_record[1]; size_t payload_length; size_t payload_length_length; if (ndef_record[0] & 0x10) { /* Short record */ payload_length = ndef_record[2]; payload_length_length = 1; } else { payload_length = be32toh ((uint32_t) ndef_record + 2); payload_length_length = 4; } ndef_record_length += payload_length_length; ndef_record_length += payload_length; if (ndef_record[0] & 0x08) { ndef_record_length += 2; } ndef_message_length += ndef_record_length; if (ndef_message_length > NDEF_BUFFER_SIZE) errx (EXIT_FAILURE, "NDEF message truncated"); } while ((ndef_record[0] & 0x40) != 0x40); } if (ndef_message_length == 0) errx (EXIT_FAILURE, "No NDEF message found"); FILE *f; if (ndef_file) f = fopen (ndef_file, "w"); else f = stdout; if (fwrite (ndef_message, ndef_message_length, 1, f) != 1) err (EXIT_FAILURE, "Can't write NDEF message"); fclose (f); } freefare_free_tags (tags); nfc_close (device); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { MYSQL *conn; MYSQL_RES *result; MYSQL_ROW row; int retval; conn = mysql_init(NULL); retval = mysql_real_connect(conn, def_host_name, def_user_name, def_password, def_db_name, def_port_num, def_socket_name, def_client_flag); if(!retval) { printf("Error connecting to database: %s\n", mysql_error(conn)); return -1; } printf("Connection successful\n"); int error = 0; nfc_device_t *device = NULL; MifareTag *tags = NULL; Mad mad; MifareClassicKey transport_key = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; char ndef_input[15] = {'\0'}; char ID[9] = {'\0'}; double balance = 0; printf("\nID: "); scanf("%s", ID); while (getchar() != '\n') continue; printf("\nBalance: "); scanf("%lf", &balance); while (getchar() != '\n') continue; ID[0] = toupper(ID[0]); ID[1] = toupper(ID[1]); char balance_char[6] = {'\0'}; snprintf(balance_char, 6, "%.2f", balance); //ensure balance always with 4 digit, 4.00 => 04.00 char final_balance[6] = {'\0'}; if(strlen(balance_char) != 5) { strcat(final_balance, "0"); strcat(final_balance, balance_char); } else { strcpy(final_balance, balance_char); } strcat(ndef_input, ID); strcat(ndef_input, final_balance); int i = 0; if (ndef_input == NULL) { printf("Write default message.\n"); for(i=0; i < sizeof(ndef_default_msg); i++) { ndef_msg[i] = (uint8_t)ndef_default_msg[i]; } ndef_msg_len = sizeof(ndef_default_msg); } else { for(i=0; i < strlen(ndef_input); i++) { ndef_msg[i] = (uint8_t)ndef_input[i]; } ndef_msg_len = strlen(ndef_input); } printf ("NDEF message is %zu bytes long.\n", ndef_msg_len); struct mifare_classic_key_and_type *card_write_keys; if (!(card_write_keys = malloc (40 * sizeof (*card_write_keys)))) { err (EXIT_FAILURE, "malloc"); } nfc_device_desc_t devices[8]; size_t device_count; nfc_list_devices (devices, 8, &device_count); if (!device_count) errx (EXIT_FAILURE, "No NFC device found."); for (size_t d = 0; d < device_count; d++) { device = nfc_connect (&(devices[d])); if (!device) { warnx ("nfc_connect() failed."); error = EXIT_FAILURE; continue; } tags = freefare_get_tags (device); if (!tags) { nfc_disconnect (device); errx (EXIT_FAILURE, "Error listing MIFARE classic tag."); } for (int i = 0; (!error) && tags[i]; i++) { switch (freefare_get_tag_type (tags[i])) { case CLASSIC_1K: case CLASSIC_4K: break; default: continue; } char *tag_uid = freefare_get_tag_uid (tags[i]); char buffer[BUFSIZ]; printf ("Found %s with UID %s.\n", freefare_get_tag_friendly_name (tags[i]), tag_uid); bool write_ndef = true; for (int n = 0; n < 40; n++) { memcpy(card_write_keys[n].key, transport_key, sizeof (transport_key)); card_write_keys[n].type = MFC_KEY_A; } if (write_ndef) { switch (freefare_get_tag_type (tags[i])) { case CLASSIC_4K: if (!search_sector_key (tags[i], 0x10, &(card_write_keys[0x10].key), &(card_write_keys[0x10].type))) { error = 1; goto error; } /* fallthrough */ case CLASSIC_1K: if (!search_sector_key (tags[i], 0x00, &(card_write_keys[0x00].key), &(card_write_keys[0x00].type))) { error = 1; goto error; } break; default: /* Keep compiler quiet */ break; } if (!error) { /* Ensure the auth key is always a B one. If not, change it! */ switch (freefare_get_tag_type (tags[i])) { case CLASSIC_4K: if (card_write_keys[0x10].type != MFC_KEY_B) { if( 0 != fix_mad_trailer_block (device, tags[i], 0x10, card_write_keys[0x10].key, card_write_keys[0x10].type)) { error = 1; goto error; } memcpy (&(card_write_keys[0x10].key), &default_keyb, sizeof (MifareClassicKey)); card_write_keys[0x10].type = MFC_KEY_B; } /* fallthrough */ case CLASSIC_1K: if (card_write_keys[0x00].type != MFC_KEY_B) { if( 0 != fix_mad_trailer_block (device, tags[i], 0x00, card_write_keys[0x00].key, card_write_keys[0x00].type)) { error = 1; goto error; } memcpy (&(card_write_keys[0x00].key), &default_keyb, sizeof (MifareClassicKey)); card_write_keys[0x00].type = MFC_KEY_B; } break; default: /* Keep compiler quiet */ break; } } size_t encoded_size; uint8_t *tlv_data = tlv_encode (3, ndef_msg, ndef_msg_len, &encoded_size); /* * At his point, we should have collected all information needed to * succeed. */ // If the card already has a MAD, load it. if ((mad = mad_read (tags[i]))) { // If our application already exists, erase it. MifareClassicSectorNumber *sectors, *p; sectors = p = mifare_application_find (mad, mad_nfcforum_aid); if (sectors) { while (*p) { if (mifare_classic_authenticate (tags[i], mifare_classic_sector_last_block(*p), default_keyb, MFC_KEY_B) < 0) { nfc_perror (device, "mifare_classic_authenticate"); error = 1; goto error; } if (mifare_classic_format_sector (tags[i], *p) < 0) { nfc_perror (device, "mifare_classic_format_sector"); error = 1; goto error; } p++; } } free (sectors); mifare_application_free (mad, mad_nfcforum_aid); } else { // Create a MAD and mark unaccessible sectors in the card if (!(mad = mad_new ((freefare_get_tag_type (tags[i]) == CLASSIC_4K) ? 2 : 1))) { perror ("mad_new"); error = 1; goto error; } MifareClassicSectorNumber max_s; switch (freefare_get_tag_type (tags[i])) { case CLASSIC_1K: max_s = 15; break; case CLASSIC_4K: max_s = 39; break; default: /* Keep compiler quiet */ break; } // Mark unusable sectors as so for (size_t s = max_s; s; s--) { if (s == 0x10) continue; if (!search_sector_key (tags[i], s, &(card_write_keys[s].key), &(card_write_keys[s].type))) { mad_set_aid (mad, s, mad_defect_aid); } else if ((memcmp (card_write_keys[s].key, transport_key, sizeof (transport_key)) != 0) && (card_write_keys[s].type != MFC_KEY_A)) { // Revert to transport configuration if (mifare_classic_format_sector (tags[i], s) < 0) { nfc_perror (device, "mifare_classic_format_sector"); error = 1; goto error; } } } } MifareClassicSectorNumber *sectors = mifare_application_alloc (mad, mad_nfcforum_aid, encoded_size); if (!sectors) { nfc_perror (device, "mifare_application_alloc"); error = EXIT_FAILURE; goto error; } if (mad_write (tags[i], mad, card_write_keys[0x00].key, card_write_keys[0x10].key) < 0) { nfc_perror (device, "mad_write"); error = EXIT_FAILURE; goto error; } int s = 0; while (sectors[s]) { MifareClassicBlockNumber block = mifare_classic_sector_last_block (sectors[s]); MifareClassicBlock block_data; mifare_classic_trailer_block (&block_data, mifare_classic_nfcforum_public_key_a, 0x0, 0x0, 0x0, 0x6, 0x40, default_keyb); if (mifare_classic_authenticate (tags[i], block, card_write_keys[sectors[s]].key, card_write_keys[sectors[s]].type) < 0) { nfc_perror (device, "mifare_classic_authenticate"); error = EXIT_FAILURE; goto error; } if (mifare_classic_write (tags[i], block, block_data) < 0) { nfc_perror (device, "mifare_classic_write"); error = EXIT_FAILURE; goto error; } s++; } if ((ssize_t) encoded_size != mifare_application_write (tags[i], mad, mad_nfcforum_aid, tlv_data, encoded_size, default_keyb, MCAB_WRITE_KEYB)) { nfc_perror (device, "mifare_application_write"); error = EXIT_FAILURE; goto error; } //create new student record in database char sql_stmnt[57] = {'\0'}; int n = 0; //filter tag_uid ulong uid_length = strlen(tag_uid); char uid_esc[(2 * uid_length)+1]; mysql_real_escape_string(conn, uid_esc, tag_uid, uid_length); //filter ID ulong id_length = strlen(ID); char id_esc[(2 * id_length)+1]; mysql_real_escape_string(conn, id_esc, ID, id_length); n = snprintf(sql_stmnt, 57, "INSERT INTO student VALUES('%s', '%s', %.1f)", uid_esc, id_esc, balance); retval = mysql_real_query(conn, sql_stmnt, n); if(retval) { printf("Inserting data from DB Failed\n"); return -1; } printf("Insert to DB successful\n"); free (sectors); free (tlv_data); free (mad); } error: free (tag_uid); } //should at the line 412, but the compiler keep on complaining //jump into scope of identifier with variably modified type //no idea why that happens, goto is always call inside any {} to outside error: //even at 412, still not outside enough freefare_free_tags (tags); nfc_disconnect (device); } free (card_write_keys); mysql_free_result(result); mysql_close(conn); exit (error); }