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");
}
void
cut_teardown (void)
{
    if (tag)
        mifare_classic_disconnect (tag);

    if (tags) {
        freefare_free_tags (tags);
        tags = NULL;
    }

    if (device)
        nfc_close (device);
  
    nfc_exit(NULL);
}
void
cut_teardown (void)
{
    if (tag)
        mifare_desfire_disconnect (tag);

    if (tags) {
        freefare_free_tags (tags);
        tags = NULL;
    }

    if (device)
        nfc_close (device);

    nfc_exit (context);
}
Пример #4
0
bool rfid_authenticate_any(nfc_device *dev, key_callback_t cb) {
	MifareTag *tags = freefare_get_tags(dev);
	if(!tags) {
		// FIXME: reset reader?
		log("error listing tags");
		return false;
	}

	for(int i = 0; tags[i]; i++) {
		MifareTag tag = tags[i];

		if(freefare_get_tag_type(tag) != DESFIRE) {
			log("tag is not a desfire tag");
			continue;
		}

		char *uid = freefare_get_tag_uid(tag);
		debug("got uid %s", uid);

		struct rfid_key key;
		enum rfid_key_cb_result result = cb(uid, &key);
		switch(result) {
			case TAG_UNKNOWN:
				log("no key found in git");
				break;
			case TAG_FORBIDDEN:
				log("tag forbidden by policy");
				break;
			case TAG_ALLOWED:
				debug("tag allowed by policy");
				return rfid_authenticate(tag, &key);
			case KEY_CB_ERROR:
				log("key callback error");
				break;
			default:
				die("unknown key callback result received: %d", result);
		}

		free(uid);
	}

	debug("exhausted all available tags");

	freefare_free_tags(tags);
	return false;
}
void RFIDHandler::scan_cards()
{
	FreefareTag *tags = NULL;

	tags = freefare_get_tags(m_nfc_device);

	if(tags == NULL)
	{
		cout << "Error getting tags..." << endl;
		return;
	}

	for(int i = 0;tags[i];i++)
	{
		if (MIFARE_DESFIRE != freefare_get_tag_type (tags[i]))
		{
			continue;
		}

		//int result;

		char *tag_uid_temp = freefare_get_tag_uid (tags[i]);
		std::string tag_uid(tag_uid_temp);
		delete[] tag_uid_temp;

		RFIDClient rfid_client("https://access-control.rollamakerspace.com/get_key.php");

		bool has_access = false;
		std::vector<uint8_t>* key_data = rfid_client.get_key_and_access(tag_uid, m_area, has_access);

		if(has_access)
		{
			if(authenticate_card(m_aid, key_data))
			{
				this->set_door(true);
				sleep(3);
				this->set_door(false);
			}
		}

		delete key_data;
	}

	freefare_free_tags(tags);
}
Пример #6
0
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);
}
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");
}
Пример #8
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);
}
Пример #9
0
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);
}
Пример #10
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':
		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 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() */
Пример #12
0
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);
}
Пример #13
0
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);
}
Пример #14
0
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 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);
}
Пример #16
0
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() */
Пример #17
0
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;
}
Пример #18
0
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);
}