int create_files (MifareTag tag)
{
    int res = 0;
    MifareDESFireAID aid = mifare_desfire_aid_new (0x1);
    res = mifare_desfire_select_application(tag, aid);
    if (res < 0)
        errx (EXIT_FAILURE, "Application selection failed");
    free (aid);

    MifareDESFireKey key = mifare_desfire_des_key_new_with_version (initial_key);
    res = mifare_desfire_authenticate (tag, 0, key);
    if (res < 0)
        errx (EXIT_FAILURE, "Authentication to application 1 failed");
    mifare_desfire_key_free (key);

    /* FIXME: Check the accessrights ... */
    printf ("Creating std_data_file 0x01...\n");
    res = mifare_desfire_create_std_data_file(tag, 0x01,0x03,0xe1ff,0x80);
    if (res < 0)
        errx (EXIT_FAILURE, "CreateStdDataFile failed");

    /* FIXME: Check the accessrights (See section 3.3 of the datasheet)... */
    printf ("Creating std_data_file 0x02...\n");
    res = mifare_desfire_create_std_data_file(tag, 0x02,0x03,0xe111,0x80);
    if (res < 0)
        errx (EXIT_FAILURE, "CreateStdDataFile failed");

    aid = mifare_desfire_aid_new (0x2);
    res = mifare_desfire_select_application(tag, aid);
    if (res < 0)
        errx (EXIT_FAILURE, "Application selection failed");
    free (aid);

    key = mifare_desfire_des_key_new_with_version (initial_key);
    res = mifare_desfire_authenticate (tag, 0, key);
    if (res < 0)
        errx (EXIT_FAILURE, "Authentication to application 2 failed");
    mifare_desfire_key_free (key);

    /* FIXME: Check the accessrights ... */
    printf ("Creating std_data_file 0x01...\n");
    res = mifare_desfire_create_std_data_file(tag, 0x01,0x03, 0xe110, 0x20);
    if (res < 0)
        errx (EXIT_FAILURE, "CreateValueFile failed");

    /* FIXME: Check the accessrights ... */
    printf ("Creating std_data_file 0x02...\n");
    res = mifare_desfire_create_std_data_file(tag, 0x02,0x03, 0xf110, 0x7e0);
    if (res < 0)
        errx (EXIT_FAILURE, "CreateLinearRecordFile failed");

    return EXIT_SUCCESS;
}
Пример #2
0
void
test_mifare_desfire_des_macing (void)
{
    int res;

    mifare_desfire_auto_authenticate (tag, 0);

    MifareDESFireKey key = mifare_desfire_des_key_new_with_version (key_data_null);
    res = mifare_desfire_change_key (tag, 0, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");

    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");

    MifareDESFireAID aid = mifare_desfire_aid_new (0x00123456);
    res = mifare_desfire_create_application (tag, aid, 0xFF, 1);
    cut_assert_success ("mifare_desfire_create_application()");

    res = mifare_desfire_select_application (tag, aid);
    cut_assert_success ("mifare_desfire_select_application");
    free (aid);

    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");

    res = mifare_desfire_create_std_data_file (tag, 1, MDCM_MACED, 0x0000, 20);
    cut_assert_success ("mifare_desfire_create_std_data_file()");

    char *s= "Hello World";
    res = mifare_desfire_write_data (tag, 1, 0, strlen (s), s);
    cut_assert_success ("mifare_desfire_write_data()");

    char buffer[50];
    res = mifare_desfire_read_data (tag, 1, 0, 0, buffer);
    cut_assert_success ("mifare_desfire_read_data()");
    cut_assert_equal_int (20, res, cut_message ("retval"));
    cut_assert_equal_string (s, buffer, cut_message ("value"));

    res = mifare_desfire_select_application (tag, NULL);
    cut_assert_success ("mifare_desfire_select_application");
    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");

    /* Wipeout the card */
    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");

    mifare_desfire_key_free (key);
}
int create_applications (MifareTag tag)
{
    int res = 0;
    MifareDESFireKey key = mifare_desfire_des_key_new_with_version (initial_key);
    res = mifare_desfire_authenticate (tag, 0, key);
    if (res < 0)
        errx (EXIT_FAILURE, "Authentication to master application failed");
    mifare_desfire_key_free (key);

    printf ("Creating Application #1...\n");
    MifareDESFireAID aid = mifare_desfire_aid_new (0x1);
    res = mifare_desfire_create_application (tag, aid, 0x0f, 0x2);
    if (res < 0)
        errx (EXIT_FAILURE, "Application #1 creation failed, try erasing the card before retrying.");
    free(aid);

    printf ("Creating Application #2...\n");
    aid = mifare_desfire_aid_new (0x2);
    res = mifare_desfire_create_application (tag, aid, 0x0f, 0x2);
    if (res < 0)
        errx (EXIT_FAILURE, "Application #2 creation failed, try erasing the card before retrying.");
    free(aid);

    return res;
}
bool authenticate(FreefareTag tag, MifareDESFireKey key, uint8_t key_no)
{
  //MifareDESFireKey key1 = mifare_desfire_aes_key_new (new_key_data);
  mifare_desfire_select_application(tag, main_aid);
  int auth = mifare_desfire_authenticate(tag, key_no, key);
  return (auth>=0);
}
Пример #5
0
static bool rfid_authenticate(MifareTag tag, struct rfid_key *key) {
	int ret;
	bool result = false;

	ret = mifare_desfire_connect(tag);
	if(ret < 0) {
		log("failed to connect to tag");
		return false;
	}

	ret = mifare_desfire_select_application(tag, door_aid);
	if(ret < 0) {
		log("failed to select application");
		goto out_tag;
	}

	MifareDESFireKey dfkey = mifare_desfire_3des_key_new(key->key);

	ret = mifare_desfire_authenticate(tag, 0xD, dfkey);
	if(ret < 0) {
		log("authentication failed");
		goto out_key;
	}

	if(ret == 0)
		result = true;

out_key:
	mifare_desfire_key_free(dfkey);
out_tag:
	mifare_desfire_disconnect(tag);

	return result;
}
int write_encrypted_tag_key (MifareTag tag, keyvault_t *kv, RSA *global_public, RSA *shop_public, RSA *shop_private, size_t len)
{
    int res = 0;

    uint8_t *crypted = malloc (RSA_size(global_public));
    res = RSA_public_encrypt (len, (unsigned char*) kv->k, (unsigned char*) crypted, global_public, RSA_PKCS1_PADDING);
    if (res < 0)
        fprintf (stderr, "Something went wrong while ciphering\n");
    printf ("Encrypted key has length %d\n", RSA_size(global_public));

    unsigned int siglen = RSA_size (shop_private);
    unsigned int digestlen = RSA_size(global_public);
    unsigned char *digest = digest_message (crypted, &digestlen);
    uint8_t *signature = malloc (siglen);
    res = RSA_sign (NID_sha1, digest, digestlen,  (unsigned char *) signature, &siglen , shop_private);
    if (res <= 0)
        fprintf (stderr, "Something went wrong while signing\n");

    res = RSA_verify (NID_sha1, (unsigned char*) digest, digestlen, (unsigned char *) signature, siglen, shop_public);
    if (res <= 0)
        fprintf (stderr, "Something went wrong while signing, can't verify the thing with our pubkey\n");



    MifareDESFireAID aid = mifare_desfire_aid_new (0x1);
    res = mifare_desfire_select_application(tag, aid);
    if (res < 0)
        errx (EXIT_FAILURE, "Application selection failed");
    free (aid);

    MifareDESFireKey key = mifare_desfire_3des_key_new_with_version (kv->k_w_1);
    mifare_desfire_key_set_version (key, 0x01);
    res = mifare_desfire_authenticate (tag, 1, key);
    if (res < 0)
        freefare_perror(tag, "Authentication to application #1 failed");
    mifare_desfire_key_free (key);

    ssize_t written = mifare_desfire_write_data (tag, 0x01, 0x0, 0x80, crypted);
    if (written < 0)
        freefare_perror(tag, "Writing data to tag");
    else
        printf ("Wrote %ld bytes E(K) to card ...\n", written);

    written = mifare_desfire_write_data (tag, 0x02, 0x0, 0x80, signature);
    if (written < 0)
        freefare_perror(tag, "Writing data to tag");
    else
        printf ("Wrote %ld bytes Sign(E(K)) to card ...\n", written);

    free (crypted);
    free (signature);
    free (digest);
    return res;
}
Пример #7
0
static int
application_setup (MifareTag tag, const MifareDESFireAID aid, MifareDESFireKey access_key)
{
    int res;

    MifareDESFireKey master_key = mifare_desfire_3des_key_new_with_version (master_key_data);
    MifareDESFireKey public_key = mifare_desfire_des_key_new_with_version (public_key_data);

    res = mifare_desfire_create_application (tag, aid, 0x0f, 2);
    if (0 == res) res = mifare_desfire_select_application (tag, aid);
    if (0 == res) res = mifare_desfire_authenticate (tag, 0, public_key);
    if (0 == res) res = mifare_desfire_change_key (tag, COUNTER_RW_KEYNO, master_key, NULL);
    if (0 == res) res = mifare_desfire_authenticate (tag, COUNTER_RW_KEYNO, master_key);
    if (0 == res) res = mifare_desfire_create_value_file (tag, COUNTER_FILENO, MDCM_PLAIN, 0x1000, 0, 12, 0, 0);
    if (0 == res) res = mifare_desfire_change_key (tag, 1, access_key, NULL);

    mifare_desfire_key_free (master_key);
    mifare_desfire_key_free (public_key);

    return res;
}
int erase_card (MifareTag tag)
{
    int res = 0;
    MifareDESFireKey key = mifare_desfire_des_key_new_with_version (initial_key);
    res = mifare_desfire_authenticate (tag, 0, key);
    if (res < 0)
        errx (EXIT_FAILURE, "Authentication on master application failed");
    mifare_desfire_key_free (key);

    printf ("Erasing card ...\n");
    res = mifare_desfire_format_picc (tag);
    if (res < 0)
        errx (EXIT_FAILURE, "PICC format failed");

    return res;
}
Пример #9
0
int
explain_application (MifareTag tag, MifareDESFireAID aid, MifareDESFireKey key)
{
    char buffer[1024];
    if (mifare_desfire_select_application (tag, aid) < 0) {
        fprintf (stderr, "mifare_desfire_select_application() failed\n");
        return -1;
    }

    if (mifare_desfire_authenticate (tag, USER_ACCESS_KEYNO, key) < 0) {
        freefare_perror (tag, "mifare_desfire_authenticate_des");
        return -1;
    }

    ssize_t len = mifare_desfire_read_data_ex (tag, UCARD_METDATA_FILENO, 0, 0, buffer, USER_ACCESS_COMMUNICATION_MODE);
    if (len < 0) {
        fprintf (stderr, "mifare_desfire_read_data_ex() failed\n");
        return -1;
    }

    char *p = buffer;

    fprintf (stdout, "  Application \"%s\" with AID 0x%06x has the following files:\n",
             p,
             mifare_desfire_aid_get_aid (aid));

    p = strchr (p, '\0');
    p++;

    int file_no = 0;

    while (*p) {
        fprintf (stdout, "    File %2d - %s\n", file_no++, p);
        p = strchr (p, '\0');
        p++;

        if (UCARD_METDATA_FILENO == file_no)
            file_no++;
    }

    return 0;
}
Пример #10
0
int mifare_desfire_auto_authenticate (FreefareTag tag, uint8_t key_no, MifareDESFireKey key)
{
    /* Determine which key is currently the master one */
    uint8_t key_version;
    int res = mifare_desfire_get_key_version (tag, key_no, &key_version);

    printf("key_version: %x\n", key_version);
    switch (key_version) {
        case 0x00:
          key = mifare_desfire_des_key_new_with_version (key_data_null);
        break;
        case 0x42:
          key = mifare_desfire_aes_key_new_with_version (key_data_aes, key_data_aes_version);
        break;
        case 0xAA:
          key = mifare_desfire_des_key_new_with_version (key_data_des);
        break;
        case 0xC7:
          key = mifare_desfire_3des_key_new_with_version (key_data_3des);
        break;
        case 0x55:
          key = mifare_desfire_3k3des_key_new_with_version (key_data_3k3des);
        break;
    }

    /* Authenticate with this key */
    switch (key_version) {
        case 0x00:
        case 0xAA:
        case 0xC7:
            res = mifare_desfire_authenticate (tag, key_no, key);
        break;
        case 0x55:
            res = mifare_desfire_authenticate_iso (tag, key_no, key);
        break;
        case 0x42:
            res = mifare_desfire_authenticate_aes (tag, key_no, key);
        break;
    }

    return res;
}
Пример #11
0
void
test_mifare_desfire_get_many_application_ids (void)
{
    int res;

    MifareDESFireKey key = mifare_desfire_des_key_new_with_version (key_data_null);
    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");
    mifare_desfire_key_free (key);

    /* Wipeout the card */
    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");

    for (int i = 0; i < NAID; i++) {
	MadAid mad_aid = { i, i };
	MifareDESFireAID aid = mifare_desfire_aid_new_with_mad_aid ( mad_aid, i % 0x10);

	res = mifare_desfire_create_application (tag, aid, 0xff, 0);
	cut_assert_success ("mifare_desfire_create_application()");

	free (aid);
    }


    MifareDESFireAID *aids;
    size_t aid_count;

    res = mifare_desfire_get_application_ids (tag, &aids, &aid_count);
    cut_assert_success ("mifare_desfire_get_application_ids()");

    cut_assert_equal_int (NAID, aid_count, cut_message ("count"));

    mifare_desfire_free_application_ids (aids);

    /* Wipeout the card */
    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");
}
void modify_makerspace_key(FreefareTag tag, uint8_t key_no, MifareDESFireKey new_key, MifareDESFireKey old_key, MifareDESFireKey master)
{
  int res;
  res = mifare_desfire_select_application(tag, main_aid);
  if(res < 0)
  {
    printf("Error: modify_makerspace_main_key: failed to select application\n");
  }
  
  res = mifare_desfire_authenticate(tag, 0, master);
  if(res < 0)
  {
    printf("Error: modify_makerspace_main_key: failed to authenticate\n");
  }
  
  res = mifare_desfire_change_key(tag, key_no, new_key, old_key);
  if(res < 0)
  {
    printf("Error: modify_makerspace_main_key: failed to change key\n");
  }
  //mifare_desfire_key_free (key1);
}
Пример #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);
    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() */
Пример #14
0
static int
on_card_presented ( struct ucard *ucard, struct ucard_application *ucard_application )
{
    int res;
    MifareDESFireAID *aids = NULL;
    uint8_t *files = NULL;
    size_t aid_count;
    size_t file_count;

    (void) ucard_application;

    MifareDESFireKey user_key = mifare_desfire_3des_key_new_with_version ( user_key_data );
    MifareTag tag = ucard_get_tag(ucard);

    res = mifare_desfire_get_application_ids(tag, &aids, &aid_count);
    printf("********************************************************\n");
    printf ("Vous avez %d comptes sur votre carte\n", (int) aid_count);
    printf("********************************************************\n");
    for (size_t i=0; i<aid_count;i++)
    {
        res = mifare_desfire_select_application ( tag, aids[i] );
        res = mifare_desfire_authenticate ( tag, 0, user_key );
        res =  mifare_desfire_get_file_ids(tag,&files,&file_count);
        char buffer[1024];
        ssize_t len = mifare_desfire_read_data (tag, UCARD_METDATA_FILENO, 0, 0, buffer);
        if (len < 0) {
            fprintf (stderr, "mifare_desfire_read_data() failed\n");
        }
        char *p = buffer;
        fprintf (stdout, "  Application \"%s\" :\n", p);
        p = strchr (p, '\0');
        p++;
        int file_no = 0;
        printf("********************************************************\n");
        while (*p) {

                if (UCARD_METDATA_FILENO == file_no)
                    file_no++;

                struct mifare_desfire_file_settings settings;
                res = mifare_desfire_get_file_settings(tag,files[file_no],&settings);
                int file_type=settings.file_type;
                if ((file_type == 0) || (file_type == 1)){
                    char data[settings.settings.standard_file.file_size];
                    res = mifare_desfire_read_data(tag,files[file_no],0,sizeof(data),data);
                    fprintf (stdout, "    %s : %s\n", p, data);
                }
                if (file_type == 2){
                    int value;
                    res = mifare_desfire_get_value(tag,files[file_no],&value);
                    fprintf (stdout, "    %s : %d\n", p, value);
                }
                if ((file_type == 3) || (file_type == 4)){
                    char record[settings.settings.linear_record_file.record_size];
                    res = mifare_desfire_read_records(tag,files[file_no],0,sizeof(record),record);
                    fprintf (stdout, "    %s : %s\n", p, record);
                }
                p = strchr (p, '\0');
                p++;
                file_no++;
        }
            printf("********************************************************\n");
    }
    if (aid_count > 0) {
        mifare_desfire_free_application_ids(aids);
    }
    mifare_desfire_key_free (user_key);
    return 1;
}
Пример #15
0
void
test_mifare_desfire_free_read (void)
{
    int res;

    mifare_desfire_auto_authenticate (tag, 0);

    /* Wipeout the card */
    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");

    mifare_desfire_auto_authenticate (tag, 0);

    MifareDESFireKey key = mifare_desfire_des_key_new_with_version (key_data_null);
    res = mifare_desfire_change_key (tag, 0, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");

    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");

    MifareDESFireAID aid = mifare_desfire_aid_new (0x00123456);
    res = mifare_desfire_create_application (tag, aid, 0xFF, 2);
    cut_assert_success ("mifare_desfire_create_application()");

    res = mifare_desfire_select_application (tag, aid);
    cut_assert_success ("mifare_desfire_select_application");
    free (aid);

    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");

    res = mifare_desfire_create_std_data_file (tag, 1, MDCM_MACED, 0x0000, 20);
    cut_assert_success ("mifare_desfire_create_std_data_file()");

    char *s= "Hello World";
    res = mifare_desfire_write_data (tag, 1, 0, strlen (s), s);
    cut_assert_success ("mifare_desfire_write_data()");

    res = mifare_desfire_change_file_settings (tag, 1, MDCM_ENCIPHERED, 0xEFFF);
    cut_assert_success ("mifare_desfire_change_file_settings");

    char buffer[20];
    res = mifare_desfire_read_data (tag, 1, 0, 0, buffer);
    cut_assert_equal_int (sizeof (buffer), res, cut_message ("Data with free access should be read in PLAIN mode only."));
    cut_assert_equal_int (OPERATION_OK, mifare_desfire_last_pcd_error (tag), cut_message ("Wrong PCD error"));

    res = mifare_desfire_read_data_ex (tag, 1, 0, 0, buffer, MDCM_MACED);
    cut_assert_equal_int (-1, res, cut_message ("Data with free access should be read in PLAIN mode only."));
    cut_assert_equal_int (CRYPTO_ERROR, mifare_desfire_last_pcd_error (tag), cut_message ("Wrong PCD error"));

    res = mifare_desfire_read_data_ex (tag, 1, 0, 0, buffer, MDCM_ENCIPHERED);
    cut_assert_equal_int (-1, res, cut_message ("Data with free access should be read in PLAIN mode only."));
    cut_assert_equal_int (CRYPTO_ERROR, mifare_desfire_last_pcd_error (tag), cut_message ("Wrong PCD error"));

    /* Wipeout the card */
    mifare_desfire_select_application (tag, NULL);
    cut_assert_equal_int (OPERATION_OK, mifare_desfire_last_pcd_error (tag), cut_message ("Wrong PCD error"));
    res = mifare_desfire_authenticate (tag, 0, key);

    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");

    mifare_desfire_key_free (key);
}
void
test_mifare_desfire_ev1_3des (void)
{
    int res;

    /* Select the master application */
    res = mifare_desfire_select_application (tag, NULL);
    cut_assert_success ("mifare_desfire_select_application()");

    /* Get version information */
    struct mifare_desfire_version_info version_info;
    res = mifare_desfire_get_version (tag, &version_info);
    cut_assert_success ("mifare_desfire_get_version()");

     mifare_desfire_auto_authenticate (tag, 0);

    /*
     * This unit test change key settings to more restrictive ones, so reset
     * them to factory defaults in case the previous run failed unexpectedly.
     */
    res = mifare_desfire_change_key_settings (tag, 0xF);
    cut_assert_success ("mifare_desfire_change_key_settings()");
    res = mifare_desfire_change_key_settings (tag, 0xF);
    cut_assert_success ("mifare_desfire_change_key_settings()");

    /* Change master key to AES */
    MifareDESFireKey key = mifare_desfire_3des_key_new_with_version (key_data_3des);
    mifare_desfire_change_key (tag, 0, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");

    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    /* Wipeout the card */
    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");


    /* Create 3 applications */
    res = mifare_desfire_select_application (tag, NULL);
    cut_assert_success ("mifare_desfire_select_application()");

    key = mifare_desfire_3des_key_new_with_version (key_data_3des);
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    uint8_t key_version;
    res = mifare_desfire_get_key_version (tag, 0, &key_version);
    cut_assert_success ("mifare_desfire_get_key_version()");
    cut_assert_equal_int (0x55, 0x55, cut_message ("Wrong key_version value."));

    uint32_t size;
    res = mifare_desfire_free_mem (tag, &size);
    cut_assert_success ("mifare_desfire_free_mem()");

    MifareDESFireAID aid_a = mifare_desfire_aid_new (0x00AAAAAA);
    //cut_assert_not_null (aid_a, cut_message ("Cannot allocate AID"));
    res = mifare_desfire_create_application (tag, aid_a, 0xFF, 0);
    cut_assert_success ("mifare_desfire_create_application()");

    MifareDESFireAID aid_b = mifare_desfire_aid_new (0x00BBBBBB);
    cut_assert_not_null (aid_b, cut_message ("Cannot allocate AID"));
    res = mifare_desfire_create_application (tag, aid_b, 0xEF, 6);
    cut_assert_success ("mifare_desfire_create_application()");

    MifareDESFireAID aid_c = mifare_desfire_aid_new (0x00CCCCCC);
    cut_assert_not_null (aid_c, cut_message ("Cannot allocate AID"));
    res = mifare_desfire_create_application (tag, aid_c, 0xC2, 14);
    cut_assert_success ("mifare_desfire_create_application()");

    // Ensure we can find the created applications
    MifareDESFireAID *aids = NULL;
    size_t aid_count;
    res = mifare_desfire_get_application_ids (tag, &aids, &aid_count);
    cut_assert_success ("mifare_desfire_get_application_ids()");
    cut_assert_equal_int (3, aid_count, cut_message ("Wrong application count"));
    mifare_desfire_free_application_ids (aids);

    // Create files in the application A
    res = mifare_desfire_select_application (tag, aid_a);
    cut_assert_success ("mifare_desfire_select_application()");

    uint8_t std_data_file_id = 15;

    res = mifare_desfire_create_std_data_file (tag, std_data_file_id, MDCM_PLAIN, 0xEEEE, 100);
    cut_assert_success ("mifare_desfire_create_std_data_file()");

    res = mifare_desfire_create_backup_data_file (tag, 5, MDCM_PLAIN, 0xEEEE, 64);
    cut_assert_success ("mifare_desfire_create_backup_data_file()");

    res = mifare_desfire_create_value_file (tag, 4, MDCM_PLAIN, 0xEEEE, 0, 1000, 0, 0);
    cut_assert_success ("mifare_desfire_create_value_file()");

    res = mifare_desfire_create_cyclic_record_file (tag, 0, MDCM_PLAIN, 0xEEEE, 4, 10);
    cut_assert_success ("mifare_desfire_create_cyclic_record_file()");

    // Write some data in the standard data file
    res = mifare_desfire_write_data (tag, std_data_file_id, 0, 30, (uint8_t *)"Some data to write to the card");
    cut_assert_success ("mifare_desfire_write_data()");
    cut_assert_equal_int (30, res, cut_message ("Wrong number of bytes writen"));

    res = mifare_desfire_write_data (tag, std_data_file_id, 34, 22, (uint8_t *)"Another block of data.");
    cut_assert_success ("mifare_desfire_write_data()");
    cut_assert_equal_int (22, res, cut_message ("Wrong number of bytes writen"));

    // Make the file read-only
    res = mifare_desfire_change_file_settings (tag, std_data_file_id, MDCM_PLAIN, 0xEFFF);
    cut_assert_success ("mifare_desfire_change_file_settings()");

    // Read a part of the file
    uint8_t buffer[120];
    res = mifare_desfire_read_data (tag, std_data_file_id, 10, 50, &buffer);
    cut_assert_success ("mifare_desfire_read_data()");
    cut_assert_equal_int (50, res, cut_message ("Wrong number of bytes read"));
    cut_assert_equal_memory ("to write to the card\0\0\0\0Another block of data.\0\0\0\0", 50, buffer, 50, cut_message ("Wrong data"));

    // Read all the file at once
    res = mifare_desfire_read_data (tag, std_data_file_id, 0, 0, &buffer);
    cut_assert_success ("mifare_desfire_read_data()");
    cut_assert_equal_int (100, res, cut_message ("Wrong number of bytes read"));
    cut_assert_equal_memory ("Some data to write to the"
			     " card\0\0\0\0Another block of"
			     " data.\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
			     "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 100, buffer, 100, cut_message ("Wrong data"));

    // Try to overwrute the file
    res = mifare_desfire_write_data (tag, std_data_file_id, 20, 5, (char *)"Test!");
    cut_assert_equal_int (-1, res, cut_message ("Wrong return value"));
    cut_assert_equal_int (PERMISSION_ERROR, mifare_desfire_last_picc_error (tag), cut_message ("Wrong PICC error"));

    int32_t expected_value = 0;
    for (int transaction = 0; transaction < 15; transaction++) {

	char data_buffer[3];

	sprintf (data_buffer, "%02d", transaction);

	// Write to the backup file
	res = mifare_desfire_write_data (tag, 5, 3*transaction, 3, data_buffer);
	cut_assert_success ("mifare_desfire_write_data()");

	// Manipulate the value file
	res = mifare_desfire_credit (tag, 4, 100);
	cut_assert_success ("mifare_desfire_credit()");

	res = mifare_desfire_debit (tag, 4, 97);
	cut_assert_success ("mifare_desfire_debit()");

	// Write to the cyclic record file
	res = mifare_desfire_write_record (tag, 0, 2, 2, data_buffer);
	cut_assert_success ("mifare_desfire_write_record()");

	// Overwrite the cyclic record file
	res = mifare_desfire_write_record (tag, 0, 0, 2, (char *)"r.");
	cut_assert_success("mifare_desfire_write_record()");

	// Ensure that no content was changed yet
	char ref_buffer[64];
	memset (ref_buffer, 0, sizeof (ref_buffer));
	for (int n = 0; n < transaction; n++) {
	    sprintf (ref_buffer + 3 * n, "%02d", n);
	}

	res = mifare_desfire_read_data (tag, 5, 0, 0, buffer);
	cut_assert_success ("mifare_desfire_read_data()");
	cut_assert_equal_int (64, res, cut_message ("Wrong number of bytes read"));
	cut_assert_equal_memory (buffer, 64, ref_buffer, 64, cut_message ("Wrong data"));

	int32_t value;
	res = mifare_desfire_get_value (tag, 4, &value);
	cut_assert_success ("mifare_desfire_get_value()");
	cut_assert_equal_int (expected_value, value, cut_message ("Wrong value"));

	// Reading records from an empty file would abort the transaction
	if (0 != transaction) {
	    // Get the latest record
	    res = mifare_desfire_read_records (tag, 0, 0, 1, buffer);
	    cut_assert_success ("mifare_desfire_read_records()");
	    sprintf (ref_buffer, "r.%02d", transaction);
	    cut_assert_not_equal_memory (ref_buffer, 4, buffer, res, cut_message ("Wrong data"));
	}

	// Commit !
	res = mifare_desfire_commit_transaction (tag);
	cut_assert_success ("mifare_desfire_commit_transaction()");


	res = mifare_desfire_read_data (tag, 5, 3*transaction, 3, buffer);
	cut_assert_success ("mifare_desfire_read_data()");
	cut_assert_equal_memory (data_buffer, 3, buffer, res, cut_message ("Wrong data"));

	expected_value += 3;

	res = mifare_desfire_get_value (tag, 4, &value);
	cut_assert_success ("mifare_desfire_get_value()");
	cut_assert_equal_int (expected_value, value, cut_message ("Wrong value"));

	res = mifare_desfire_read_records (tag, 0, 0, 1, buffer);
	cut_assert_success ("mifare_desfire_read_records()");
	sprintf (ref_buffer, "r.%02d", transaction);
	cut_assert_equal_memory (ref_buffer, 4, buffer, res, cut_message ("Wrong data"));
    }

    // Ensure limited credit is disabled
    res = mifare_desfire_limited_credit (tag, 4, 20);
    cut_assert_equal_int (-1, res, cut_message ("mifare_desfire_limited_credit() should fail"));

    // Get all files
    uint8_t *files;
    size_t file_count;
    res = mifare_desfire_get_file_ids (tag, &files, &file_count);
    cut_assert_success ("mifare_desfire_get_file_ids()");
    cut_assert_equal_int (4, file_count, cut_message ("Wrong number of files"));

    for (size_t i=0; i<file_count;i++) {
	if ((files[i] != 0) && (files[i] != 4) &&
	    (files[i] != 5) && (files[i] != 15)) {
	    cut_fail ("File %d should not exist.", files[i]);
	}

	struct mifare_desfire_file_settings settings;
	res = mifare_desfire_get_file_settings (tag, files[i], &settings);
	cut_assert_success ("mifare_desfire_get_file_settings()");

	switch (files[i]) {
	case 0:
	    cut_assert_equal_int (MDFT_CYCLIC_RECORD_FILE_WITH_BACKUP, settings.file_type, cut_message ("Wrong file type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("Wrong communication settings"));
	    cut_assert_equal_int (4, settings.settings.linear_record_file.record_size, cut_message ("Wrong record size"));
	    cut_assert_equal_int (10, settings.settings.linear_record_file.max_number_of_records, cut_message ("Wrong max number of records"));
	    cut_assert_equal_int (9, settings.settings.linear_record_file.current_number_of_records, cut_message ("Wrong current number of records"));
	    break;
	case 4:
	    cut_assert_equal_int (MDFT_VALUE_FILE_WITH_BACKUP, settings.file_type, cut_message ("Wrong file type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("Wrong communication settings"));

	    cut_assert_equal_int (0, settings.settings.value_file.lower_limit, cut_message ("Wrong lower limit"));
	    cut_assert_equal_int (1000, settings.settings.value_file.upper_limit, cut_message ("Wrong upper limit"));
	    cut_assert_equal_int (97, settings.settings.value_file.limited_credit_value, cut_message ("Wrong limited_credit value"));
	    cut_assert_equal_int (0, settings.settings.value_file.limited_credit_enabled, cut_message ("Wrong limited_credit enable state"));
	    break;
	case 5:
	    cut_assert_equal_int (MDFT_BACKUP_DATA_FILE, settings.file_type, cut_message ("Wrong file type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("Wrong communication settings"));
	    cut_assert_equal_int (64, settings.settings.standard_file.file_size, cut_message ("Wrong file size"));
	    break;
	case 15:
	    cut_assert_equal_int (MDFT_STANDARD_DATA_FILE, settings.file_type, cut_message ("Wrong file type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("Wrong communication settings"));
	    cut_assert_equal_int (100, settings.settings.standard_file.file_size, cut_message ("Wrong file size"));
	    break;
	default:
	    cut_fail ("Wow!  Cosmic ray!");
	}

	res = mifare_desfire_delete_file (tag, files[i]);
	cut_assert_success ("mifare_desfire_delete_file()");
    }

    free (files);

    // All files should have been removed
    res = mifare_desfire_get_file_ids (tag, &files, &file_count);
    cut_assert_success ("mifare_desfire_get_file_ids()");
    cut_assert_equal_int (0, file_count, cut_message ("Wrong number of files"));

    // Delete application A
    res = mifare_desfire_select_application (tag, 0);
    cut_assert_success ("mifare_desfire_select_application()");

    key = mifare_desfire_3des_key_new (key_data_3des);
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    res = mifare_desfire_delete_application (tag, aid_a);
    cut_assert_success ("mifare_desfire_delete_application()");

    // Ensure application A was deleted
    res = mifare_desfire_get_application_ids (tag, &aids, &aid_count);
    cut_assert_success ("mifare_desfire_get_application_ids()");
    cut_assert_equal_int (2, aid_count, cut_message ("Wrong application count"));
    mifare_desfire_free_application_ids (aids);

    // Change application B keys
    res = mifare_desfire_select_application (tag, aid_b);
    cut_assert_success ("mifare_desfire_select_application()");

    key = mifare_desfire_des_key_new (key_data_null);
    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");
    mifare_desfire_key_free (key);

    // Use an AES application master key
    key = mifare_desfire_3des_key_new_with_version ((uint8_t *) "App.B Master Key12345678");
    res = mifare_desfire_change_key (tag, 0, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);

    /* Authenticate with the new master key */
    key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Master Key12345678");
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    res = mifare_desfire_get_key_version (tag, 0, &key_version);
    cut_assert_success ("mifare_desfire_get_key_version()");
    cut_assert_equal_int (0x83, key_version, cut_message ("Wrong key version"));

    /* Change key #1 */
    key = mifare_desfire_des_key_new (key_data_null);
    res = mifare_desfire_authenticate (tag, 1, key);
    cut_assert_success ("mifare_desfire_authenticate()");
    mifare_desfire_key_free (key);

    key = mifare_desfire_3des_key_new ((uint8_t *) "Another AES key!12345678");
    res = mifare_desfire_change_key (tag, 1, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);

    /* Change key #5 */
    key = mifare_desfire_des_key_new (key_data_null);
    res = mifare_desfire_authenticate (tag, 5, key);
    cut_assert_success ("mifare_desfire_authenticate()");
    mifare_desfire_key_free (key);

    key = mifare_desfire_3des_key_new ((uint8_t *) "B's Chg Keys Key12345678");
    res = mifare_desfire_change_key (tag, 5, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);

    /* Set key #5 as the change key */
    key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Master Key12345678");
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    res = mifare_desfire_change_key_settings (tag, 0x5F);
    cut_assert_success ("mifare_desfire_change_key_settings()");

    uint8_t key_settings;
    uint8_t max_keys;
    res = mifare_desfire_get_key_settings (tag, &key_settings, &max_keys);
    cut_assert_success ("mifare_desfire_get_key_settings()");

    cut_assert_equal_int (0x5F, key_settings, cut_message ("Wrong key settings"));
    cut_assert_equal_int (6, max_keys, cut_message ("Wrong maximum number of keys"));

    /* Change key #1 to #4 using the three key procedure. */
    key = mifare_desfire_3des_key_new ((uint8_t *) "B's Chg Keys Key12345678");
    res = mifare_desfire_authenticate_iso (tag, 5, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    key = mifare_desfire_3des_key_new ((uint8_t *)"App.B Key #1.   12345678");
    MifareDESFireKey key1 = mifare_desfire_3des_key_new ((uint8_t *) "Another AES key!12345678");
    res = mifare_desfire_change_key (tag, 1, key, key1);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);
    mifare_desfire_key_free (key1);
    key = mifare_desfire_3des_key_new ((uint8_t *)"App.B Key #2..  12345678");
    res = mifare_desfire_change_key (tag, 2, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);
    key = mifare_desfire_3des_key_new ((uint8_t *)"App.B Key #3... 12345678");
    res = mifare_desfire_change_key (tag, 3, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);
    key = mifare_desfire_3des_key_new ((uint8_t *)"App.B Key #4....12345678");
    res = mifare_desfire_change_key (tag, 4, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (key);

    std_data_file_id--;

    res = mifare_desfire_create_std_data_file (tag, std_data_file_id, MDCM_PLAIN, 0x1234, 100);
    cut_assert_success ("mifare_desfire_create_std_data_file()");
    expected_value = -1000000;
    res = mifare_desfire_create_value_file (tag, 4, 0, 0x1324, -987654321, -1000, expected_value, 1);
    cut_assert_success ("mifare_desfire_create_value_file()");
    res = mifare_desfire_create_linear_record_file (tag, 1, 0, 0x1324, 25, 4);

    int nr = 0;
    for (int transaction = 0; transaction < 7; transaction++) {
	uint8_t cs = transaction % 3;
	if (cs == 2) cs++;

	key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Key #4....12345678");
	res = mifare_desfire_authenticate_iso (tag, 4, key);
	cut_assert_success ("mifare_desfire_authenticate_iso()");
	mifare_desfire_key_free (key);

	res = mifare_desfire_change_file_settings (tag, std_data_file_id, cs, 0x1234);
	cut_assert_success ("mifare_desfire_change_file_settings()");
	res = mifare_desfire_change_file_settings (tag, 4, cs, 0x1324);
	cut_assert_success ("mifare_desfire_change_file_settings()");
	res = mifare_desfire_change_file_settings (tag, 1, cs, 0x1324);
	cut_assert_success ("mifare_desfire_change_file_settings()");

	// Authenticate witht he write key
	key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Key #2..  12345678");
	res = mifare_desfire_authenticate_iso (tag, 2, key);
	cut_assert_success ("mifare_desfire_authenticate_iso()");
	mifare_desfire_key_free (key);

	char data_buffer[100];
	char data_buffer2[100];
	char data_buffer3[100];
	for (int i = 0; i < 100; i++)
	    data_buffer[i] = transaction + i;

	res = mifare_desfire_write_data (tag, std_data_file_id, 0, 100, data_buffer);
	cut_assert_success ("mifare_desfire_write_data()");

	sprintf (data_buffer2, "Transaction #%d", transaction);

	res = mifare_desfire_write_data (tag, std_data_file_id, 5, strlen (data_buffer2), data_buffer2);
	cut_assert_success ("mifare_desfire_write_data()");

	memcpy (data_buffer + 5, data_buffer2, strlen (data_buffer2));

	// Write to the linear record.  When it's full, erase it and restart.
	for (int i = 0; i < 2; i++) {
	    if ((transaction % 2 == 1) && (i == 1)) {
		res = mifare_desfire_clear_record_file (tag, 1);
		cut_assert_success ("mifare_desfire_clear_record_file()");

		sprintf (data_buffer3, "Test invalid write");
		res = mifare_desfire_write_record (tag, 1, 0, strlen (data_buffer3), data_buffer3);
		cut_assert_equal_int (-1, res, cut_message ("error code"));
		cut_assert_equal_int (PERMISSION_ERROR, mifare_desfire_last_picc_error (tag), cut_message ("PICC error"));

		// The previous failure has aborted the transaction, so
		// re-authenticate, then clear record again.
		key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Key #2..  12345678");
		res = mifare_desfire_authenticate_iso (tag, 2, key);
		cut_assert_success ("mifare_desfire_authenticate_iso");
		mifare_desfire_key_free (key);

		res = mifare_desfire_clear_record_file (tag, 1);
		cut_assert_success ("mifare_desfire_clear_record_file()");

		res = mifare_desfire_commit_transaction (tag);
		cut_assert_success ("mifare_desfire_commit_transaction()");
		nr = 0;
	    }

	    res = mifare_desfire_write_record (tag, 1, 0, 25, "0123456789012345678901234");
	    cut_assert_success ("mifare_desfire_write_record()");

	    res = mifare_desfire_write_record (tag, 1, 5, strlen (data_buffer2), data_buffer2);
	    cut_assert_success ("mifare_desfire_write_record()");
	}
	nr++;

	// Modify the value file
	res = mifare_desfire_debit (tag, 4, 1300);
	cut_assert_success ("mifare_desfire_debit()");
	expected_value -= 1300;
	res = mifare_desfire_credit (tag, 4, 20);
	cut_assert_success ("mifare_desfire_credit()");
	expected_value += 20;
	res = mifare_desfire_debit (tag, 4, 1700);
	cut_assert_success ("mifare_desfire_debit()");
	expected_value -= 1700;

	// Commit
	res = mifare_desfire_commit_transaction (tag);
	cut_assert_success ("mifare_desfire_commit_transaction()");

	// Refund the whole debited amount
	res = mifare_desfire_limited_credit (tag, 4, 3000);
	cut_assert_success ("mifare_desfire_limited_credit()");
	expected_value += 3000;

	// Commit
	res = mifare_desfire_commit_transaction (tag);
	cut_assert_success ("mifare_desfire_commit_transaction()");

	// Authenticate with the key that allows reading
	key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Key #1.   12345678");
	res = mifare_desfire_authenticate_iso (tag, 1, key);
	cut_assert_success ("mifare_desfire_authenticate_iso()");
	mifare_desfire_key_free (key);

	// Read first half of the file
	res = mifare_desfire_read_data (tag, std_data_file_id, 0, 50, data_buffer3);
	cut_assert_success ("mifare_desfire_read_data()");
	cut_assert_equal_int (50, res, cut_message ("length"));
	cut_assert_equal_memory (data_buffer, 50, data_buffer3, res, cut_message ("data"));

	// Read second half of the file
	res = mifare_desfire_read_data (tag, std_data_file_id, 50, 0, data_buffer3);
	cut_assert_success ("mifare_desfire_read_data()");
	cut_assert_equal_int (50, res, cut_message ("length"));
	cut_assert_equal_memory (data_buffer + 50, 50, data_buffer3, res, cut_message ("data"));

	// Get the value file current balance
	int32_t value;
	res = mifare_desfire_get_value (tag, 4, &value);
	cut_assert_success ("mifare_desfire_get_value()");
	cut_assert_equal_int (expected_value, value, cut_message ("value"));

	// Get the number of records in the linear record file
	struct mifare_desfire_file_settings settings;
	res = mifare_desfire_get_file_settings (tag, 1, &settings);
	cut_assert_success ("mifare_desfire_get_file_settings()");
	cut_assert_equal_int (MDFT_LINEAR_RECORD_FILE_WITH_BACKUP, settings.file_type, cut_message ("settings"));
	cut_assert_equal_int (nr, settings.settings.linear_record_file.current_number_of_records, cut_message ("settings"));

	// Read the oldest record
	res = mifare_desfire_read_records (tag, 1, nr - 1, 1, data_buffer3);
	cut_assert_success ("mifare_desfire_read_records()");
	cut_assert_equal_int (25, res, cut_message ("length"));

	sprintf (data_buffer, "0123456789012345678901234");
	sprintf (data_buffer2, "Transaction #%d", transaction - nr + 1);
	memcpy ((uint8_t *)data_buffer + 5, data_buffer2, strlen (data_buffer2));
	cut_assert_equal_memory (data_buffer, strlen (data_buffer), data_buffer3, res, cut_message ("data"));

	// Read all records
	res = mifare_desfire_read_records (tag, 1, 0, 0, data_buffer3);
	cut_assert_success ("mifare_desfire_read_records()");
	cut_assert_equal_int (25 * nr, res, cut_message ("length"));
    }

    res = mifare_desfire_get_file_ids (tag, &files, &file_count);
    cut_assert_success ("mifare_desfire_get_file_ids");
    cut_assert_equal_int (3, file_count, cut_message ("count"));

    for (size_t i = 0; i < file_count; i++) {
	struct mifare_desfire_file_settings settings;
	res = mifare_desfire_get_file_settings (tag, files[i], &settings);
	cut_assert_success ("mifare_desfire_get_file_settings()");

	switch (files[i]) {
	case 1:
	    cut_assert_equal_int (MDFT_LINEAR_RECORD_FILE_WITH_BACKUP, settings.file_type, cut_message ("type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("cs"));
	    cut_assert_equal_int (0x1324, settings.access_rights, cut_message ("access_rights"));
	    cut_assert_equal_int (25, settings.settings.linear_record_file.record_size, cut_message ("record_size"));
	    cut_assert_equal_int (4, settings.settings.linear_record_file.max_number_of_records, cut_message ("max_number_of_records"));
	    cut_assert_equal_int (2, settings.settings.linear_record_file.current_number_of_records, cut_message ("current_number_of_records"));
	    break;
	case 4:
	    cut_assert_equal_int (MDFT_VALUE_FILE_WITH_BACKUP , settings.file_type, cut_message ("type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("cs"));
	    cut_assert_equal_int (0x1324, settings.access_rights, cut_message ("access_rights"));
	    cut_assert_equal_int (-987654321, settings.settings.value_file.lower_limit, cut_message ("lower_limit"));
	    cut_assert_equal_int (-1000, settings.settings.value_file.upper_limit, cut_message ("upper_limit"));
	    cut_assert_equal_int (0, settings.settings.value_file.limited_credit_value, cut_message ("limited_credit_value"));
	    cut_assert_equal_int (1, settings.settings.value_file.limited_credit_enabled, cut_message ("limited_credit_enabled"));
	    break;
	case 14: /* std_data_file_id */
	    cut_assert_equal_int (MDFT_STANDARD_DATA_FILE, settings.file_type, cut_message ("type"));
	    cut_assert_equal_int (MDCM_PLAIN, settings.communication_settings, cut_message ("cs"));
	    cut_assert_equal_int (0x1234, settings.access_rights, cut_message ("access_rights"));
	    cut_assert_equal_int (100, settings.settings.standard_file.file_size, cut_message ("size"));
	    break;
	default:
	    cut_fail ("file_no");

	}

	res = mifare_desfire_delete_file (tag, files[i]);
	cut_assert_success ("mifare_desfire_delete_file()");
    }
    free (files);

    // Check there are no files anymore
    res = mifare_desfire_get_file_ids (tag, &files, &file_count);
    cut_assert_success ("mifare_desfire_get_file_ids");
    cut_assert_equal_int (0, file_count, cut_message ("count"));

    /* Delete application B */
    key = mifare_desfire_3des_key_new ((uint8_t *) "App.B Master Key12345678");
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    res = mifare_desfire_delete_application (tag, aid_b);
    cut_assert_success ("mifare_desfire_delete_application()");

    res = mifare_desfire_get_application_ids (tag, &aids, &aid_count);
    cut_assert_success ("mifare_desfire_get_application_ids()");
    cut_assert_equal_int (1, aid_count, cut_message ("Wrong AID count"));
    mifare_desfire_free_application_ids (aids);

    /* Tests using application C */

    res = mifare_desfire_select_application (tag, aid_c);
    cut_assert_success ("mifare_desfire_select_application()");

    key = mifare_desfire_des_key_new (key_data_null);
    res = mifare_desfire_authenticate (tag, 12, key);
    cut_assert_success ("mifare_desfire_authenticate()");

    MifareDESFireKey new_key = mifare_desfire_3des_key_new ((uint8_t *)"App.C Key #1.   12345678");
    res = mifare_desfire_change_key (tag, 1, new_key, key);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (new_key);

    new_key = mifare_desfire_3des_key_new ((uint8_t *)"App.C Key #2..  12345678");
    res = mifare_desfire_change_key (tag, 2, new_key, key);
    cut_assert_success ("mifare_desfire_change_key()");
    mifare_desfire_key_free (new_key);

    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);


    res = mifare_desfire_create_cyclic_record_file (tag, 6, MDCM_PLAIN, 0x12E0, 100, 22);
    cut_assert_success ("mifare_desfire_create_cyclic_record_file()");

    for (int transaction = 0; transaction < 50; transaction++) {
	char data_buffer[100];
	char read_buffer[100];

	uint8_t cs = transaction % 3;
	if (cs == 2) cs++;

	key = mifare_desfire_des_key_new (key_data_null);
	res = mifare_desfire_authenticate (tag, 0, key);
	cut_assert_success ("mifare_desfire_authenticate()");
	mifare_desfire_key_free (key);

	res = mifare_desfire_change_file_settings (tag, 6, cs, 0x12E0);
	cut_assert_success ("mifare_desfire_change_file_settings()");

	if (transaction & 4) {
	    key = mifare_desfire_3des_key_new ((uint8_t *) "App.C Key #2..  12345678");
	    res = mifare_desfire_authenticate_iso (tag, 2, key);
	    cut_assert_success ("mifare_desfire_authenticate_iso()");
	    mifare_desfire_key_free (key);
	} else {
	    cs = 0;
	}

	memset (data_buffer, '_', 100);
	data_buffer[0]  = transaction;
	data_buffer[99] = transaction;
	sprintf (data_buffer + 5, " Transaction #%d ", transaction);
	res = mifare_desfire_write_record (tag, 6, 0, 100, data_buffer);
	cut_assert_success ("mifare_desfire_write_record()");

	if (transaction & 4) {
	    key = mifare_desfire_3des_key_new ((uint8_t *) "App.C Key #1.   12345678");
	    res = mifare_desfire_authenticate_iso (tag, 1, key);
	    cut_assert_success ("mifare_desfire_authenticate_iso()");
	    mifare_desfire_key_free (key);
	}

	if (transaction % 7 == 0) {
	    res = mifare_desfire_abort_transaction (tag);
	    cut_assert_success ("mifare_desfire_abort_transaction()");

	    ssize_t n = mifare_desfire_read_records (tag, 6, 0, 1, read_buffer);
	    if (transaction == 0) {
		cut_assert_equal_int (-1, n, cut_message ("Wrong return value"));
	    } else {
		cut_assert_equal_int (100, n, cut_message ("Wrong return value"));
		cut_assert_not_equal_memory (data_buffer, sizeof (data_buffer), read_buffer, sizeof (read_buffer), cut_message ("Wrong data"));
	    }
	} else {
	    res = mifare_desfire_commit_transaction (tag);
	    cut_assert_success ("mifare_desfire_commit_transaction()");

	    ssize_t n = mifare_desfire_read_records (tag, 6, 0, 1, read_buffer);
	    cut_assert_equal_int (100, n, cut_message ("Wrong return value"));
	    cut_assert_equal_memory (data_buffer, sizeof (data_buffer), read_buffer, sizeof (read_buffer), cut_message ("Wrong data"));
	}
    }

    // Read each record
    key = mifare_desfire_3des_key_new ((uint8_t *) "App.C Key #1.   12345678");
    res = mifare_desfire_authenticate_iso (tag, 1, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    int t = 49;
    for (int i = 0; i < 22; i++) {
	char data_buffer[100];
	char ref_data_buffer[100];

	if (0 == (t % 7))
	    t--;

	memset (ref_data_buffer, '_', 100);
	ref_data_buffer[0]  = t;
	ref_data_buffer[99] = t;
	sprintf (ref_data_buffer + 5, " Transaction #%d ", t);
	res = mifare_desfire_read_records (tag, 6, i, 1, data_buffer);
	if (i == 21) {
	    cut_assert_equal_int (-1, res, cut_message ("return value"));
	} else {
	    cut_assert_success ("mifare_desfire_read_records()");
	    cut_assert_equal_memory (ref_data_buffer, 100, data_buffer, res, cut_message ("data"));
	}

	t--;
    }

    /*
     * Change master key settings to require master key authentication for all
     * card operations.  Only allow to revert this.
     */

    res = mifare_desfire_select_application (tag, 0);
    cut_assert_success ("mifare_desfire_select_application()");

    key = mifare_desfire_3des_key_new (key_data_3des);
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    res = mifare_desfire_change_key_settings (tag, 0x08);
    cut_assert_success ("mifare_desfire_change_key_settings()");

    /* Clear authentication */
    res = mifare_desfire_select_application (tag, 0);
    cut_assert_success ("mifare_desfire_select_application()");

    /* We should not be able to list applications now */
    res = mifare_desfire_get_application_ids (tag, &aids, &aid_count);
    cut_assert_equal_int (-1, res, cut_message ("Wrong return value"));
    cut_assert_equal_int (AUTHENTICATION_ERROR, mifare_desfire_last_picc_error (tag), cut_message ("Wrong PICC error"));

    /* Deleting an application should not be possible */
    res = mifare_desfire_delete_application (tag, aid_c);
    cut_assert_equal_int (-1, res, cut_message ("Wrong return value"));
    cut_assert_equal_int (AUTHENTICATION_ERROR, mifare_desfire_last_picc_error (tag), cut_message ("Wrong PICC error"));

    /* Creating an application should also be forbidden */
    MifareDESFireAID aid_d = mifare_desfire_aid_new (0x00DDDDDD);
    res = mifare_desfire_create_application (tag, aid_d, 0xEF, 0);
    cut_assert_equal_int (-1, res, cut_message ("Wrong return value"));
    cut_assert_equal_int (AUTHENTICATION_ERROR, mifare_desfire_last_picc_error (tag), cut_message ("Wrong PICC error"));

    /*
     * Now we retry authenticated with the master key.
     */
    key = mifare_desfire_3des_key_new (key_data_3des);
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    /* We should be able to list applications again */
    res = mifare_desfire_get_application_ids (tag, &aids, &aid_count);
    cut_assert_success ("mifare_desfire_get_application_ids()");
    cut_assert_equal_int (1, aid_count, cut_message ("Wrong AID count"));
    mifare_desfire_free_application_ids (aids);

    /* Deleting an application should be possible again */
    res = mifare_desfire_delete_application (tag, aid_c);
    cut_assert_success ("mifare_desfire_delete_application()");

    /* Creating an application should also be possible */
    res = mifare_desfire_create_application (tag, aid_d, 0xEF, 0);
    cut_assert_success ("mifare_desfire_create_application()");

    /* Revert master key settings to default */
    res = mifare_desfire_change_key_settings (tag, 0xF);
    cut_assert_success ("mifare_desfire_change_key_settings()");

    /* Change the master key back to the default one */
    key = mifare_desfire_3des_key_new (key_data_3des);
    res = mifare_desfire_authenticate_iso (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate_iso()");
    mifare_desfire_key_free (key);

    key = mifare_desfire_des_key_new_with_version (key_data_null);
    res = mifare_desfire_change_key (tag, 0, key, NULL);
    cut_assert_success ("mifare_desfire_change_key()");

    /*
     * Delete everything from the card
     */

    res = mifare_desfire_authenticate (tag, 0, key);
    cut_assert_success ("mifare_desfire_authenticate()");
    mifare_desfire_key_free (key);

    res = mifare_desfire_format_picc (tag);
    cut_assert_success ("mifare_desfire_format_picc()");

    free (aid_a);
    free (aid_b);
    free (aid_c);
    free (aid_d);
}
int setup_keys (MifareTag tag, keyvault_t *kv)
{
    int res = 0;
    MifareDESFireAID aid = mifare_desfire_aid_new (0x1);
    res = mifare_desfire_select_application(tag, aid);
    if (res < 0)
        errx (EXIT_FAILURE, "Application selection failed");
    free (aid);

    MifareDESFireKey old_key = mifare_desfire_des_key_new_with_version (initial_key);
    res = mifare_desfire_authenticate (tag, 0, old_key);
    if (res < 0)
        errx (EXIT_FAILURE, "Authentication to application 1 failed");

    MifareDESFireKey new_key;
    if (get_keytype_3DES (kv, CRYPTO_KEY_KM1))
    {
        printf ("Setting 3DES key K_M1 ...\n");
        new_key = mifare_desfire_3des_key_new_with_version (kv->k_m_1);
    }
    else
    {
        printf ("Setting DES key K_M1 ...\n");
        new_key = mifare_desfire_des_key_new_with_version (kv->k_m_1);
    }

    res = mifare_desfire_change_key (tag, 0x00, new_key, old_key);
    if (res < 0)
        freefare_perror (tag, "Change key 0x00");

    res = mifare_desfire_authenticate (tag, 0, new_key);
    if (res < 0)
        freefare_perror (tag, "Reauthing after changing key 0x00");

    mifare_desfire_key_free (new_key);

    if (get_keytype_3DES (kv, CRYPTO_KEY_KW1))
    {
        printf ("Setting 3DES key K_W1 ...\n");
        new_key = mifare_desfire_3des_key_new_with_version (kv->k_w_1);
    }
    else
    {
        printf ("Setting DES key K_W1 ...\n");
        new_key = mifare_desfire_des_key_new_with_version (kv->k_w_1);
    }
    res = mifare_desfire_change_key (tag, 0x01, new_key, old_key);
    if (res < 0)
        freefare_perror (tag, "Change key 0x01");
    mifare_desfire_key_free (new_key);

    /* AID 2 ... */

    aid = mifare_desfire_aid_new (0x2);
    res = mifare_desfire_select_application(tag, aid);
    if (res < 0)
        errx (EXIT_FAILURE, "Application selection failed");
    free (aid);

    res = mifare_desfire_authenticate (tag, 0, old_key);
    if (res < 0)
        errx (EXIT_FAILURE, "Authentication to application 2 failed");

    if (get_keytype_3DES (kv, CRYPTO_KEY_KM2))
    {
        printf ("Setting 3DES key K_M2 ...\n");
        new_key = mifare_desfire_3des_key_new_with_version (kv->k_m_2);
    }
    else
    {
        printf ("Setting DES key K_M2 ...\n");
        new_key = mifare_desfire_des_key_new_with_version (kv->k_m_2);
    }
    res = mifare_desfire_change_key (tag, 0x00, new_key, old_key);
    if (res < 0)
        freefare_perror (tag, "Change key 0x00");

    res = mifare_desfire_authenticate (tag, 0, new_key);
    if (res < 0)
        freefare_perror (tag, "Reauthing after changing key 0x00");

    mifare_desfire_key_free (new_key);

    if (get_keytype_3DES (kv, CRYPTO_KEY_K))
    {
        printf ("Setting 3DES key K ...\n");
        new_key = mifare_desfire_3des_key_new_with_version (kv->k);
    }
    else
    {
        printf ("Setting DES key K ...\n");
        new_key = mifare_desfire_des_key_new_with_version (kv->k);
    }
    res = mifare_desfire_change_key (tag, 0x01, new_key, old_key);
    if (res < 0)
        freefare_perror (tag, "Change key 0x01");
    mifare_desfire_key_free (new_key);
    mifare_desfire_key_free (old_key);

    return EXIT_SUCCESS;
}
Пример #18
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() */
Пример #19
0
inline int authApplication(MifareTag tag,int keyNumber)
{
  MifareDESFireKey key = mifare_desfire_3des_key_new(createDesKey(makePinpad(), "des-ede"));
  return mifare_desfire_authenticate(tag,keyNumber, key);
}
Пример #20
0
int resetKey()
{
  nfc_device *device = NULL;
  MifareTag *tag = NULL;
  MifareDESFireAID aid;
  uint8_t key_data_null[8] = { 0,0,0,0,0,0,0,0};
  MifareDESFireKey defaultKey = mifare_desfire_des_key_new_with_version (key_data_null);

  device = getRfidDevice();

  if (!device)
    return NULL;

  tag = freefare_get_tags(device);

  mifare_desfire_connect (tag[0]);

  aid = mifare_desfire_aid_new(AID_NUMBER);

  if (mifare_desfire_select_application (tag[0], aid) < 0)
  {
    nfc_close(device);
    return -1;
  }

  MifareDESFireKey key = mifare_desfire_3des_key_new(createDesKey(makePinpad(),"des-ede"));

  if (mifare_desfire_authenticate(tag[0], defaultKeyNumber, key) < 0)
  {
    fprintf(stderr,"Authentication with key failed\n");
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_change_key(tag[0], 0, defaultKey, key) < 0)
  {
    fprintf(stderr,"Key change to defaultKey failed\n");
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_authenticate(tag[0], defaultKeyNumber, defaultKey) < 0 )
  {
    fprintf(stderr,"Authentication with defaultKey failed\n");
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_select_application (tag[0], NULL) < 0)
  {
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_authenticate(tag[0], defaultKeyNumber, defaultKey) < 0)
  {
    fprintf(stderr,"Authentication with key failed\n");
    if (mifare_desfire_change_key(tag[0], 0, defaultKey, key) < 0)
    {
      fprintf(stderr,"Key change to defaultKey in Master application failed\n");
      nfc_close(device);
      return -1;
    }
  }

  printf("Schlüssel Erfolgreich geändert\n");

  nfc_close(device);

  return 0;
}
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':
            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() */
Пример #23
0
int deleteApplication()
{
  nfc_device *device = NULL;
  MifareTag *tag = NULL;
  MifareDESFireAID aid = mifare_desfire_aid_new(AID_NUMBER);
  uint8_t *files = NULL;
  size_t file_count = 0;
  uint8_t key_data_null[8] = { 0,0,0,0,0,0,0,0};
  MifareDESFireKey defaultKey = mifare_desfire_des_key_new_with_version (key_data_null);

  device = getRfidDevice();

  if (!device)
    return NULL;

  tag = freefare_get_tags(device);

  mifare_desfire_connect (tag[0]);

  if (mifare_desfire_select_application (tag[0], aid) < 0)
  {
    fprintf(stderr,"select AID failed\n");
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_authenticate(tag[0], defaultKeyNumber, defaultKey) < 0 )
  {
    fprintf(stderr,"auth default key on AID failed\n");
    nfc_close(device);
    return -1;
  }

  mifare_desfire_get_file_ids(tag[0], &files, &file_count);

  size_t i;
  for (i = 0; i < file_count; i++)
  {
    mifare_desfire_delete_file(tag[0],files[i]);
  }


  if (mifare_desfire_select_application (tag[0], NULL) < 0)
  {
    fprintf(stderr,"select Master Application failed\n");
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_authenticate(tag[0], defaultKeyNumber, defaultKey) < 0 )
  {
    fprintf(stderr,"auth Master Application failed\n");
    nfc_close(device);
    return -1;
  }

  if (mifare_desfire_delete_application(tag[0],aid) < 0)
  {
    fprintf(stderr,"delete application failed\n");
    nfc_close(device);
    return -1;
  }

  printf("Application deleted\n");

  nfc_close(device);

  return 0;
}
Пример #24
0
int writeRSA(RSA *rsa)
{
  nfc_device *device = NULL;
  MifareTag *tag = NULL;
  MifareDESFireAID aid;
  uint8_t key_data_null[8] = { 0,0,0,0,0,0,0,0};
  MifareDESFireKey defaultKey = mifare_desfire_des_key_new_with_version (key_data_null);

  device = getRfidDevice();

  if (!device)
    return -1;

  tag = freefare_get_tags(device);

  mifare_desfire_connect (tag[0]);

  aid = mifare_desfire_aid_new(AID_NUMBER);

  mifare_desfire_create_application(tag[0],aid,0xED,1);

  if (mifare_desfire_select_application (tag[0], aid) < 0)
  {
    nfc_close(device);
    return -1;
  }

  MifareDESFireKey key = mifare_desfire_3des_key_new(createDesKey(makePinpad(),"des-ede"));

  if (mifare_desfire_authenticate(tag[0],0 , defaultKey) == 0 )
  {
    if (mifare_desfire_change_key(tag[0], 0, key, defaultKey) < 0)
    {
      fprintf(stderr,"Change defaultKey to key failed\n");
      nfc_close(device);
      return -1;
    }
  }

  if (mifare_desfire_authenticate(tag[0],0 , key) < 0 )
  {
    fprintf(stderr,"Falscher Key\n");
    nfc_close(device);
    return -1;
  }

  if (writeBignum(tag[0],aid,rsa->n,0) < 0)
  {
    fprintf(stderr,"writeBignum %d failed\n",0);
    nfc_close(device);
    return -1;
  }

  if (writeBignum(tag[0],aid,rsa->d,5) < 0)
  {
    fprintf(stderr,"writeBignum %d failed\n",5);
    nfc_close(device);
    return -1;
  }

  if (writeBignum(tag[0],aid,rsa->e,10) < 0)
  {
    fprintf(stderr,"writeBignum %d failed\n",10);
    nfc_close(device);
    return -1;
  }

  printf("Key Geschrieben\n");
  fflush(stdout);

  nfc_close(device);

  return 0;
}
Пример #25
0
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);
}