Split out autojunk and actual code files.

This commit is contained in:
Romain Tartiere 2010-01-08 11:46:23 +00:00
parent 8a9d90210a
commit 32e740ea6d
9 changed files with 7 additions and 8 deletions

13
libfreefare/Makefile.am Normal file
View file

@ -0,0 +1,13 @@
ACLOCAL_AMFLAGS = -I m4
AM_CFLAGS = -I. @LIBNFC_CFLAGS@
AM_LDFLAGS = @LIBNFC_LIBS@
lib_LTLIBRARIES = libfreefare.la
libfreefare_la_SOURCES = mifare_classic.c mad.c mifare_application.c
libfreefare_la_HEADERS = freefare.h
libfreefare_ladir = $(includedir)
EXTRA_DIST = freefare_internal.h

111
libfreefare/freefare.h Normal file
View file

@ -0,0 +1,111 @@
/*-
* Copyright (C) 2009, Romain Tartiere, Romuald Conty.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* $Id$
*/
#ifndef __FREEFARE_H__
#define __FREEFARE_H__
#include <sys/types.h>
#include <stdint.h>
#include <nfc/nfc.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
struct mifare_classic_tag;
typedef struct mifare_classic_tag *MifareClassicTag;
typedef unsigned char MifareClassicBlock[16];
typedef uint8_t MifareSectorNumber;
typedef unsigned char MifareClassicBlockNumber;
typedef enum { MFC_KEY_A, MFC_KEY_B } MifareClassicKeyType;
typedef unsigned char MifareClassicKey[6];
MifareClassicTag *mifare_classic_get_tags (nfc_device_t *device);
void mifare_classic_free_tags (MifareClassicTag *tags);
int mifare_classic_connect (MifareClassicTag tag);
int mifare_classic_disconnect (MifareClassicTag tag);
int mifare_classic_authenticate (MifareClassicTag tag, const MifareClassicBlockNumber block, const MifareClassicKey key, const MifareClassicKeyType key_type);
int mifare_classic_read (MifareClassicTag tag, const MifareClassicBlockNumber block, MifareClassicBlock *data);
int mifare_classic_init_value (MifareClassicTag tag, const MifareClassicBlockNumber block, const int32_t value, const MifareClassicBlockNumber adr);
int mifare_classic_read_value (MifareClassicTag tag, const MifareClassicBlockNumber block, int32_t *value, MifareClassicBlockNumber *adr);
int mifare_classic_write (MifareClassicTag tag, const MifareClassicBlockNumber block, const MifareClassicBlock data);
int mifare_classic_increment (MifareClassicTag tag, const MifareClassicBlockNumber block, const uint32_t amount);
int mifare_classic_decrement (MifareClassicTag tag, const MifareClassicBlockNumber block, const uint32_t amount);
int mifare_classic_restore (MifareClassicTag tag, const MifareClassicBlockNumber block);
int mifare_classic_transfer (MifareClassicTag tag, const MifareClassicBlockNumber block);
int mifare_classic_get_trailer_block_permission (MifareClassicTag tag, const MifareClassicBlockNumber block, const uint16_t permission, const MifareClassicKeyType key_type);
int mifare_classic_get_data_block_permission (MifareClassicTag tag, const MifareClassicBlockNumber block, const unsigned char permission, const MifareClassicKeyType key_type);
int mifare_classic_format_sector (MifareClassicTag tag, const MifareSectorNumber sector);
char* mifare_classic_get_uid(MifareClassicTag tag);
void mifare_classic_trailer_block (MifareClassicBlock *block, const MifareClassicKey key_a, const uint8_t ab_0, const uint8_t ab_1, const uint8_t ab_2, const uint8_t ab_tb, const uint8_t gpb, const MifareClassicKey key_b);
/* MIFARE Classic Access Bits */
#define MCAB_R 0x8
#define MCAB_W 0x4
#define MCAB_D 0x2
#define MCAB_I 0x1
#define MCAB_READ_KEYA 0x400
#define MCAB_WRITE_KEYA 0x100
#define MCAB_READ_ACCESS_BITS 0x040
#define MCAB_WRITE_ACCESS_BITS 0x010
#define MCAB_READ_KEYB 0x004
#define MCAB_WRITE_KEYB 0x001
struct mad_aid {
uint8_t function_cluster_code;
uint8_t application_code;
};
typedef struct mad_aid MadAid;
struct mad;
typedef struct mad *Mad;
Mad mad_new (uint8_t version);
Mad mad_read (MifareClassicTag tag);
int mad_write (MifareClassicTag tag, Mad mad, MifareClassicKey key_b_sector_00, MifareClassicKey key_b_sector_10);
int mad_get_version (Mad mad);
void mad_set_version (Mad mad, uint8_t version);
MifareSectorNumber mad_get_card_publisher_sector(Mad mad);
int mad_set_card_publisher_sector(Mad mad, MifareSectorNumber cps);
int mad_get_aid(Mad mad, MifareSectorNumber sector, MadAid *aid);
int mad_set_aid(Mad mad, MifareSectorNumber sector, MadAid aid);
void mad_free (Mad mad);
MifareSectorNumber *mifare_application_alloc (Mad mad, MadAid aid, size_t size);
void mifare_application_free (Mad mad, MadAid aid);
MifareSectorNumber *mifare_application_find (Mad mad, MadAid aid);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* !__FREEFARE_H__ */

View file

@ -0,0 +1,30 @@
/*
* Copyright (C) 2010, Romain Tartiere, Romuald Conty.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* $Id$
*/
#ifndef __FREEFARE_INTERNAL_H__
#define __FREEFARE_INTERNAL_H__
struct mad_sector_0x00;
struct mad_sector_0x10;
void crc8 (uint8_t *crc, const uint8_t value);
uint8_t sector_0x00_crc8 (Mad mad);
uint8_t sector_0x10_crc8 (Mad mad);
#endif /* !__FREEFARE_INTERNAL_H__ */

418
libfreefare/mad.c Normal file
View file

@ -0,0 +1,418 @@
/*-
* Copyright (C) 2009, 2010, Romain Tartiere, Romuald Conty.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* $Id$
*/
/*
* This implementation was written based on information provided by the
* following document:
*
* AN10787
* MIFARE Application Directory (MAD)
* Rev. 04 - 5 March 2009
*/
#include "config.h"
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <freefare.h>
#include "mad.h"
/*
* XXX The documentation says the preset is 0xE3, but the various card dumps
* and the documentation example MAD CRC can be verified only with a CRC
* preset of 0x67.
*
* This is still under investigation:
* http://www.libnfc.org/community/post/667/
* http://discussion.forum.nokia.com/forum/showthread.php?t=181702#14
*/
#define CRC_PRESET 0x67
#define SECTOR_0X00_AIDS 15
#define SECTOR_0X10_AIDS 23
struct mad_sector_0x00 {
uint8_t crc;
uint8_t info;
MadAid aids[SECTOR_0X00_AIDS];
};
struct mad_sector_0x10 {
uint8_t crc;
uint8_t info;
MadAid aids[SECTOR_0X10_AIDS];
};
struct mad {
struct mad_sector_0x00 sector_0x00;
struct mad_sector_0x10 sector_0x10;
uint8_t version;
};
/* Read key A */
const MifareClassicKey mad_key_a = {
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5
};
/*
* Allocate an empty new MAD.
*/
Mad
mad_new (uint8_t version)
{
Mad mad = malloc (sizeof (*mad));
if (!mad)
return NULL;
mad->version = version;
memset (&(mad->sector_0x00), '\0', sizeof (mad->sector_0x00));
memset (&(mad->sector_0x10), '\0', sizeof (mad->sector_0x10));
return mad;
}
/*
* Compute CRC.
*/
void
crc8 (uint8_t *crc, const uint8_t value)
{
/* x^8 + x^4 + x^3 + x^2 + 1 => 0x11d */
const uint8_t poly = 0x1d;
for (int current_bit = 7; current_bit >= 0; current_bit--) {
int bit_out = (*crc) & 0x80;
*crc = ((*crc) << 1) | (( value >> (current_bit)) & 0x01);
if (bit_out)
*crc ^= poly;
}
}
uint8_t
sector_0x00_crc8 (Mad mad)
{
uint8_t crc = CRC_PRESET;
crc8 (&crc, mad->sector_0x00.info);
for (int n = 0; n < SECTOR_0X00_AIDS; n++) {
crc8 (&crc, mad->sector_0x00.aids[n].application_code);
crc8 (&crc, mad->sector_0x00.aids[n].function_cluster_code);
}
crc8 (&crc, 0x00);
return crc;
}
uint8_t
sector_0x10_crc8 (Mad mad)
{
uint8_t crc = CRC_PRESET;
crc8 (&crc, mad->sector_0x10.info);
for (int n = 0; n < SECTOR_0X10_AIDS; n++) {
crc8 (&crc, mad->sector_0x10.aids[n].application_code);
crc8 (&crc, mad->sector_0x10.aids[n].function_cluster_code);
}
crc8 (&crc, 0x00);
return crc;
}
/*
* Read a MAD from the provided MIFARE tag.
*/
Mad
mad_read (MifareClassicTag tag)
{
Mad mad = malloc (sizeof (*mad));
if (!mad)
goto error;
/* Authenticate using MAD key A */
if (mifare_classic_authenticate (tag, 0x03, mad_key_a, MFC_KEY_A) < 0) {
goto error;
}
/* Read first sector trailer block */
MifareClassicBlock data;
if (mifare_classic_read (tag, 0x03, &data) < 0) {
goto error;
}
uint8_t gpb = data[9];
/* Check MAD availability (DA bit) */
if (!(gpb & 0x80)) {
goto error;
}
/* Get MAD version (ADV bits) */
switch (gpb & 0x03) {
case 0x01:
mad->version = 1;
break;
case 0x02:
mad->version = 2;
break;
default:
/* MAD enabled but version not supported */
errno = ENOTSUP;
goto error;
}
/* Read MAD data at 0x00 (MAD1, MAD2) */
if (mifare_classic_read (tag, 0x01, &data) < 0)
goto error;
memcpy (&(mad->sector_0x00), data, sizeof (data));
if (mifare_classic_read (tag, 0x02, &data) < 0)
goto error;
memcpy (&(mad->sector_0x00) + sizeof (data), data, sizeof (data));
uint8_t crc = mad->sector_0x00.crc;
uint8_t computed_crc = sector_0x00_crc8 (mad);
if (crc != computed_crc)
goto error;
/* Read MAD data at 0x10 (MAD2) */
if (mad->version == 2) {
/* Authenticate using MAD key A */
if (mifare_classic_authenticate (tag, 0x43, mad_key_a, MFC_KEY_A) < 0) {
goto error;
}
if (mifare_classic_read (tag, 0x40, &data) < 0)
goto error;
memcpy (&(mad->sector_0x10), data, sizeof (data));
if (mifare_classic_read (tag, 0x41, &data) < 0)
goto error;
memcpy (&(mad->sector_0x10) + sizeof (data), data, sizeof (data));
if (mifare_classic_read (tag, 0x42, &data) < 0)
goto error;
memcpy (&(mad->sector_0x10) + sizeof (data) * 2, data, sizeof (data));
crc = mad->sector_0x10.crc;
computed_crc = sector_0x10_crc8 (mad);
if (crc != computed_crc)
goto error;
}
return mad;
error:
free (mad);
return NULL;
}
/*
* Write the mad to the provided MIFARE tad using the provided Key-B keys.
*/
int
mad_write (MifareClassicTag tag, Mad mad, MifareClassicKey key_b_sector_00, MifareClassicKey key_b_sector_10)
{
MifareClassicBlock data;
if (mifare_classic_authenticate (tag, 0x00, key_b_sector_00, MFC_KEY_B) < 0)
return -1;
if ((1 != mifare_classic_get_data_block_permission (tag, 0x01, MCAB_W, MFC_KEY_B)) ||
(1 != mifare_classic_get_data_block_permission (tag, 0x02, MCAB_W, MFC_KEY_B)) ||
(1 != mifare_classic_get_trailer_block_permission (tag, 0x03, MCAB_WRITE_KEYA, MFC_KEY_B)) ||
(1 != mifare_classic_get_trailer_block_permission (tag, 0x03, MCAB_WRITE_ACCESS_BITS, MFC_KEY_B))) {
errno = EPERM;
return -1;
}
uint8_t gpb = 0x80;
/*
* FIXME Handle mono-application cards
*/
gpb |= 0x40;
/* Write MAD version */
switch (mad->version) {
case 1:
gpb |= 0x01;
break;
case 2:
gpb |= 0x02;
break;
}
if (2 == mad->version) {
if (mifare_classic_authenticate (tag, 0x40, key_b_sector_10, MFC_KEY_B) < 0)
return -1;
if ((1 != mifare_classic_get_data_block_permission (tag, 0x40, MCAB_W, MFC_KEY_B)) ||
(1 != mifare_classic_get_data_block_permission (tag, 0x41, MCAB_W, MFC_KEY_B)) ||
(1 != mifare_classic_get_data_block_permission (tag, 0x42, MCAB_W, MFC_KEY_B)) ||
(1 != mifare_classic_get_trailer_block_permission (tag, 0x43, MCAB_WRITE_KEYA, MFC_KEY_B)) ||
(1 != mifare_classic_get_trailer_block_permission (tag, 0x43, MCAB_WRITE_ACCESS_BITS, MFC_KEY_B))) {
errno = EPERM;
return -1;
}
mad->sector_0x10.crc = sector_0x10_crc8 (mad);
memcpy (data, &(mad->sector_0x10), sizeof (data));
if (mifare_classic_write (tag, 0x40, data) < 0) return -1;
memcpy (data, &(mad->sector_0x10) + sizeof (data), sizeof (data));
if (mifare_classic_write (tag, 0x41, data) < 0) return -1;
memcpy (data, &(mad->sector_0x10) + sizeof (data) * 2, sizeof (data));
if (mifare_classic_write (tag, 0x42, data) < 0) return -1;
mifare_classic_trailer_block (&data, mad_key_a, 0x0, 0x1, 0x1, 0x6, 0x00, key_b_sector_10);
if (mifare_classic_write (tag, 0x42, data) < 0) return -1;
}
mad->sector_0x00.crc = sector_0x00_crc8 (mad);
if (mifare_classic_authenticate (tag, 0x00, key_b_sector_00, MFC_KEY_B) < 0) return -1;
memcpy (data, &(mad->sector_0x00), sizeof (data));
if (mifare_classic_write (tag, 0x01, data) < 0) return -1;
memcpy (data, &(mad->sector_0x00) + sizeof (data), sizeof (data));
if (mifare_classic_write (tag, 0x02, data) < 0) return -1;
mifare_classic_trailer_block (&data, mad_key_a, 0x0, 0x1, 0x1, 0x6, gpb, key_b_sector_00);
if (mifare_classic_write (tag, 0x03, data) < 0) return -1;
return 0;
}
/*
* Return a MAD version.
*/
int
mad_get_version (Mad mad)
{
return mad->version;
}
/*
* Set a MAD version.
*/
void
mad_set_version (Mad mad, uint8_t version)
{
if ((version == 2) && (mad->version == 1)) {
/* We use a larger MAD so initialise the new blocks */
memset (&(mad->sector_0x10), '\0', sizeof (mad->sector_0x10));
}
mad->version = version;
}
/*
* Return the MAD card publisher sector.
*/
MifareSectorNumber
mad_get_card_publisher_sector(Mad mad)
{
return (mad->sector_0x00.info & 0x3f);
}
/*
* Set the MAD card publisher sector.
*/
int
mad_set_card_publisher_sector(Mad mad, MifareSectorNumber cps)
{
if (((mad->version == 2) && (cps > 0x27)) | (mad->version == 1) && (cps > 0x0f)) {
errno = EINVAL;
return -1;
}
mad->sector_0x00.info = (cps & 0x3f);
return 0;
}
/*
* Get the provided sector's application identifier.
*/
int
mad_get_aid(Mad mad, MifareSectorNumber sector, MadAid *aid)
{
if ((sector < 1) || (sector == 0x10) || (sector > 0x27)) {
errno = EINVAL;
return -1;
}
if (sector > 0x0f) {
if (mad->version != 2) {
errno = EINVAL;
return -1;
}
aid->function_cluster_code = mad->sector_0x10.aids[sector - 0x0f - 2].function_cluster_code;
aid->application_code = mad->sector_0x10.aids[sector - 0x0f - 2].application_code;
} else {
aid->function_cluster_code = mad->sector_0x00.aids[sector - 1].function_cluster_code;
aid->application_code = mad->sector_0x00.aids[sector - 1].application_code;
}
return 0;
}
/*
* Set the provided sector's application identifier.
*/
int
mad_set_aid(Mad mad, MifareSectorNumber sector, MadAid aid)
{
if (sector > 0x27) {
errno = EINVAL;
return -1;
}
if (sector > 0x0f) {
if (mad->version != 2) {
errno = EINVAL;
return -1;
}
mad->sector_0x00.aids[sector - 0x0f - 1].function_cluster_code = aid.function_cluster_code;
mad->sector_0x00.aids[sector - 0x0f - 1].application_code = aid.application_code;
} else {
mad->sector_0x00.aids[sector - 1].function_cluster_code = aid.function_cluster_code;
mad->sector_0x00.aids[sector - 1].application_code = aid.application_code;
}
return 0;
}
/*
* Free memory allocated by mad_new() and mad_read().
*/
void
mad_free (Mad mad)
{
free (mad);
}

View file

@ -0,0 +1,172 @@
/*-
* Copyright (C) 2009, Romain Tartiere, Romuald Conty.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* $Id$
*/
/*
* This implementation was written based on information provided by the
* following document:
*
* /dev/brain
*/
#include "config.h"
#include <stdlib.h>
#include <freefare.h>
#define FIRST_SECTOR 1
int aidcmp (const MadAid left, const MadAid right);
size_t count_aids (const Mad mad, const MadAid aid);
/*
* Get the number of sectors allocated in the MAD for the provided application.
*/
size_t
count_aids (const Mad mad, const MadAid aid)
{
size_t result = 0;
MifareSectorNumber s_max = (mad_get_version (mad) == 1) ? 0x0f : 0x27;
/* Count application sectors */
MadAid c_aid;
for (MifareSectorNumber s = FIRST_SECTOR; s <= s_max; s++) {
mad_get_aid (mad, s, &c_aid);
if (0 == aidcmp (aid, c_aid)) {
result++;
}
}
return result;
}
/*
* Compare two application identifiers.
*/
inline int
aidcmp (const MadAid left, const MadAid right)
{
return ((left.function_cluster_code - right.function_cluster_code) << 8) | (left.application_code - right.application_code);
}
/*
* Card publisher functions (MAD owner).
*/
/*
* Allocates a new application into a MAD.
*/
MifareSectorNumber *
mifare_application_alloc (Mad mad, MadAid aid, size_t size)
{
/*
* Ensure the card does not already have the application registered.
*/
MifareSectorNumber *found;
if ((found = mifare_application_find (mad, aid))) {
free (found);
return NULL;
}
MifareSectorNumber *res = malloc (sizeof (*res) * (size+1));
res[size] = 0;
/*
* Ensure the remaining free space is suficient before destroying the MAD.
*/
MadAid free_aid = { 0x00, 0x00 };
MifareSectorNumber *free_aids = mifare_application_find (mad, free_aid);
if (!free_aids)
return NULL;
for (int c = 0; c < size; c++) {
if (free_aids[c]) {
res[c] = free_aids[c];
} else {
free (res);
res = NULL;
break;
}
}
free (free_aids);
if (res) {
/* Update the MAD */
for (int c = 0; c < size; c++)
mad_set_aid (mad, res[c], aid);
}
/* Return the list of allocated sectors */
return res;
}
/*
* Remove an application from a MAD.
*/
void
mifare_application_free (Mad mad, MadAid aid)
{
MifareSectorNumber *sectors = mifare_application_find (mad, aid);
MifareSectorNumber *p = sectors;
MadAid free_aid = { 0x00, 0x00 };
while (*p) {
mad_set_aid (mad, *p, free_aid);
p++;
}
free (sectors);
}
/*
* Application owner functions.
*/
/*
* Get all sector numbers of an application from the provided MAD.
*/
MifareSectorNumber *
mifare_application_find (Mad mad, MadAid aid)
{
MifareSectorNumber *res = NULL;
size_t res_count = count_aids (mad, aid);
if (res_count)
res = malloc (sizeof (*res) * res_count + 1);
size_t r = FIRST_SECTOR, w = 0;
if (res) {
/* Fill in the result */
MadAid c_aid;
while (w < res_count) {
mad_get_aid (mad, r, &c_aid);
if (0 == aidcmp (c_aid, aid)) {
res[w++] = r;
}
r++;
}
res[w] = 0;
}
return res;
}

View file

@ -0,0 +1,742 @@
/*-
* Copyright (C) 2009, 2010, Romain Tartiere, Romuald Conty.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* $Id$
*/
/*
* This implementation was written based on information provided by the
* following documents:
*
* MF1ICS50 Functional specification
* Rev. 5.3 29 January 2008
*
* Making the Best of Mifare Classic
* Wouter Teepe (Radboud University Nijmegen)
* October 6, 2008
*/
#include "config.h"
#if defined(HAVE_SYS_ENDIAN_H)
# include <sys/endian.h>
#endif
#if defined(HAVE_ENDIAN_H)
# define _BSD_SOURCE
# include <endian.h>
#endif
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <nfc/nfc.h>
#include <freefare.h>
struct mifare_classic_tag {
nfc_device_t *device;
nfc_iso14443a_info_t info;
int active;
MifareClassicKeyType last_authentication_key_type;
/*
* The following block numbers are on 2 bytes in order to use invalid
* address and avoid false cache hit with inconsistent data.
*/
struct {
int16_t sector_trailer_block_number;
uint16_t sector_access_bits;
int16_t block_number;
uint8_t block_access_bits;
} cached_access_bits;
};
union mifare_classic_block {
unsigned char data[16];
struct {
uint32_t value;
uint32_t value_;
uint32_t value__;
MifareClassicBlockNumber address;
MifareClassicBlockNumber address_;
MifareClassicBlockNumber address__;
MifareClassicBlockNumber address___;
} value;
struct {
MifareClassicKey key_a;
uint8_t access_bits[3];
uint8_t gpb;
MifareClassicKey key_b;
} trailer;
};
typedef unsigned char MifareClassicAccessBits;
unsigned char mifare_data_access_permissions[] = {
/*
* [ Key A ] [ Key B ]
* | |
* ,----------- r(ead) |
* |,---------- w(rite) |
* ||,--------- d(ecrement) |
* |||,-------- i(ncrement) |
* |||| |
* |||| ,------------------------ r
* ,----- C3 |||| |,----------------------- w
* |,---- C2 |||| ||,---------------------- d
* ||,--- C1 |||| |||,--------------------- i
* ||| |||| ||||
* 0b000 0b 1111 1111 */ 0xff, /* Default (blank card) */
/* 0b001 0b 1000 1100 */ 0x8c,
/* 0b010 0b 1000 1000 */ 0x88,
/* 0b011 0b 1010 1111 */ 0xaf,
/* 0b100 0b 1010 1010 */ 0xaa,
/* 0b101 0b 0000 1000 */ 0x08,
/* 0b110 0b 0000 1100 */ 0x0c,
/* 0b111 0b 0000 0000 */ 0x00
};
uint16_t mifare_trailer_access_permissions[] = {
/*
* [ Key A ] [ Access bits ] [ Key B ]
* | | |
* ,----------- read A | |
* |,---------- read B | |
* ||,--------- write A | |
* |||,-------- write B | |
* |||| | |
* |||| ,----------------------- read A |
* |||| |,---------------------- read B |
* |||| ||,--------------------- write A |
* |||| |||,-------------------- write B |
* |||| |||| |
* |||| |||| ,----------------------------------- read A
* ,----- C3 |||| |||| |,---------------------------------- read B
* |,---- C2 |||| |||| ||,--------------------------------- write A
* ||,--- C1 |||| |||| |||,-------------------------------- write B
* ||| |||| |||| ||||
* 0b000 0b 0010 1000 1010*/ 0x28a,
/* 0b001 0b 0001 1100 0000*/ 0x1c0,
/* 0b010 0b 0000 1000 1000*/ 0x088,
/* 0b011 0b 0000 1100 0000*/ 0x0c0,
/* 0b100 0b 0010 1010 1010*/ 0x2aa, /* Default (blank card) */
/* 0b101 0b 0000 1101 0000*/ 0x0d0,
/* 0b110 0b 0001 1101 0001*/ 0x1d1,
/* 0b111 0b 0000 1100 0000*/ 0x0c0
};
/*
* Private functions
*/
int get_block_access_bits (MifareClassicTag tag, const MifareClassicBlockNumber block, MifareClassicAccessBits *block_access_bits);
/*
* MIFARE card communication preparation functions
*
* The following functions send NFC commands to the initiator to prepare
* communication with a MIFARE card, and perform required cleannups after using
* the target.
*/
/*
* Get a list of the MIFARE card near to the provided NFC initiator.
*
* The list can be freed using the mifare_classic_free_tags() function.
*/
MifareClassicTag *
mifare_classic_get_tags (nfc_device_t *device)
{
MifareClassicTag *tags = NULL;
int tag_count = 0;
nfc_initiator_init(device);
// Drop the field for a while
nfc_configure(device,NDO_ACTIVATE_FIELD,false);
// Let the reader only try once to find a tag
nfc_configure(device,NDO_INFINITE_SELECT,false);
// Configure the CRC and Parity settings
nfc_configure(device,NDO_HANDLE_CRC,true);
nfc_configure(device,NDO_HANDLE_PARITY,true);
// Enable field so more power consuming cards can power themselves up
nfc_configure(device,NDO_ACTIVATE_FIELD,true);
// Poll for a ISO14443A (MIFARE) tag
nfc_target_info_t target_info;
while (nfc_initiator_select_tag(device,NM_ISO14443A_106,NULL,0,&target_info)) {
// Ensure the target is a MIFARE classic tag.
if (!((target_info.nai.abtAtqa[0] == 0x00) &&
(target_info.nai.abtAtqa[1] == 0x04) &&
(target_info.nai.btSak == 0x08)) && /* NXP MIFARE Classic 1K */
!((target_info.nai.abtAtqa[0] == 0x00) &&
(target_info.nai.abtAtqa[1] == 0x02) &&
(target_info.nai.btSak == 0x18)) && /* NXP MIFARE Classic 4K */
!((target_info.nai.abtAtqa[0] == 0x00) &&
(target_info.nai.abtAtqa[1] == 0x02) &&
(target_info.nai.btSak == 0x38))) /* Nokia MIFARE Classic 4K - emulated */
continue;
tag_count++;
/* (Re)Allocate memory for the found MIFARE classic array */
if (!tags) {
if (!(tags = malloc ((tag_count) * sizeof (MifareClassicTag) + sizeof (void *)))) {
return NULL;
}
} else {
MifareClassicTag *p = realloc (tags, (tag_count) * sizeof (MifareClassicTag) + sizeof (void *));
if (p)
tags = p;
else
return p; // FAIL! Return what has been found so far.
}
/* Allocate memory for the found MIFARE classic tag */
if (!(tags[tag_count-1] = malloc (sizeof (struct mifare_classic_tag)))) {
return tags; // FAIL! Return what has been found before.
}
(tags[tag_count-1])->device = device;
(tags[tag_count-1])->info = target_info.nai;
(tags[tag_count-1])->active = 0;
tags[tag_count] = NULL;
nfc_initiator_deselect_tag (device);
}
return tags;
}
/*
* Free the provided tag list.
*/
void
mifare_classic_free_tags (MifareClassicTag *tags)
{
if (tags) {
for (int i=0; tags[i]; i++) {
free (tags[i]);
}
free (tags);
}
}
/*
* Establish connection to the provided tag.
*/
int
mifare_classic_connect (MifareClassicTag tag)
{
if (tag->active) {
errno = EINVAL;
return -1;
}
nfc_target_info_t pnti;
if (nfc_initiator_select_tag (tag->device, NM_ISO14443A_106, tag->info.abtUid, 4, &pnti)) {
tag->active = 1;
} else {
errno = EIO;
return -1;
}
return 0;
}
/*
* Terminate connection with the provided tag.
*/
int
mifare_classic_disconnect (MifareClassicTag tag)
{
if (!(tag->active)) {
errno = EINVAL;
return -1;
}
if (nfc_initiator_deselect_tag (tag->device)) {
tag->active = 0;
} else {
errno = EIO;
return -1;
}
return 0;
}
/*
* Card manipulation functions
*
* The following functions perform direct communication with the connected
* MIFARE card.
*/
/*
* Send an authentification command to the provided MIFARE target.
*/
int
mifare_classic_authenticate (MifareClassicTag tag, const MifareClassicBlockNumber block, const MifareClassicKey key, const MifareClassicKeyType key_type)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[12];
command[0] = (key_type == MFC_KEY_A) ? MC_AUTH_A : MC_AUTH_B;
command[1] = block;
memcpy (&(command[2]), key, 6);
memcpy (&(command[8]), tag->info.abtUid, 4);
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), NULL, &n))) {
tag->active = false; /* Tag is no more active if authentication failed. */
errno = EIO;
return -1;
}
tag->cached_access_bits.sector_trailer_block_number = -1;
tag->cached_access_bits.sector_access_bits = 0x00;
tag->last_authentication_key_type = key_type;
// No result. The MIFARE tag just ACKed.
return 0;
}
/*
* Read data from the provided MIFARE target.
*/
int
mifare_classic_read (MifareClassicTag tag, const MifareClassicBlockNumber block, MifareClassicBlock *data)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[2];
command[0] = MC_READ;
command[1] = block;
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), *data, &n))) {
errno = EIO;
return -1;
}
return 0;
}
int
mifare_classic_init_value (MifareClassicTag tag, const MifareClassicBlockNumber block, const int32_t value, const MifareClassicBlockNumber adr)
{
union mifare_classic_block b;
b.value.value = value;
b.value.value_ = ~value;
b.value.value__ = value;
b.value.address = adr;
b.value.address_ = ~adr;
b.value.address__ = adr;
b.value.address___ = ~adr;
if (mifare_classic_write (tag, block, b.data) < 0)
return -1;
return 0;
}
int
mifare_classic_read_value (MifareClassicTag tag, const MifareClassicBlockNumber block, int32_t *value, MifareClassicBlockNumber *adr)
{
MifareClassicBlock data;
if (mifare_classic_read (tag, block, &data) < 0)
return -1;
union mifare_classic_block b = *((union mifare_classic_block *)(&data));
if ((b.value.value != (~b.value.value_)) || (b.value.value != b.value.value__)) {
errno = EIO;
return -1;
}
if ((b.value.address != (unsigned char)(~b.value.address_)) || (b.value.address != b.value.address__) || (b.value.address_ != b.value.address___)) {
errno = EIO;
return -1;
}
if (value)
*value = le32toh (b.value.value);
if (adr)
*adr = b.value.address;
return 0;
}
/*
* Write data to the provided MIFARE target.
*/
int
mifare_classic_write (MifareClassicTag tag, const MifareClassicBlockNumber block, const MifareClassicBlock data)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[2 + sizeof (MifareClassicBlock)];
command[0] = MC_WRITE;
command[1] = block;
memcpy (&(command[2]), data, sizeof (MifareClassicBlock));
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), NULL, &n))) {
errno = EIO;
return -1;
}
// No result. The MIFARE tag just ACKed.
return 0;
}
/*
* Increment the given value block by the provided amount into the internal
* data register.
*/
int
mifare_classic_increment (MifareClassicTag tag, const MifareClassicBlockNumber block, const uint32_t amount)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[6];
command[0] = MC_INCREMENT;
command[1] = block;
int32_t le_amount = htole32 (amount);
memcpy(&(command[2]), &le_amount, sizeof (le_amount));
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), NULL, &n))) {
errno = EIO;
return -1;
}
// No result. The MIFARE tag just ACKed.
return 0;
}
/*
* Decrement the given value block by the provided amount into the internal
* data register.
*/
int
mifare_classic_decrement (MifareClassicTag tag, const MifareClassicBlockNumber block, const uint32_t amount)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[6];
command[0] = MC_DECREMENT;
command[1] = block;
int32_t le_amount = htole32 (amount);
memcpy(&(command[2]), &le_amount, sizeof (le_amount));
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), NULL, &n))) {
errno = EIO;
return -1;
}
// No result. The MIFARE tag just ACKed.
return 0;
}
/*
* Store the provided block to the internal data register.
*/
int
mifare_classic_restore (MifareClassicTag tag, const MifareClassicBlockNumber block)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[2];
/* XXX Should be MC_RESTORE according to the MIFARE documentation. */
command[0] = MC_STORE;
command[1] = block;
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), NULL, &n))) {
errno = EIO;
return -1;
}
// No result. The MIFARE tag just ACKed.
return 0;
}
/*
* Store the internal data register to the provided block.
*/
int
mifare_classic_transfer (MifareClassicTag tag, const MifareClassicBlockNumber block)
{
if (!tag->active) {
errno = EINVAL;
return -1;
}
unsigned char command[2];
command[0] = MC_TRANSFER;
command[1] = block;
// Send command
size_t n;
if (!(nfc_initiator_transceive_dep_bytes (tag->device, command, sizeof (command), NULL, &n))) {
errno = EIO;
return -1;
}
// No result. The MIFARE tag just ACKed.
return 0;
}
/*
* Access bit manipulation functions
*
* The following functions provide a convenient API for reading MIFARE card
* access bits. A cache system makes these functions query a single time the
* MIFARE card regardless of the number of information requested between two
* authentifications (i.e. for the current sector).
*/
/*
* Fetch access bits for a given block from the block's sector's trailing
* block.
*/
int
get_block_access_bits (MifareClassicTag tag, const MifareClassicBlockNumber block, MifareClassicAccessBits *block_access_bits)
{
/*
* The first block which holds the manufacturer block seems to have
* inconsistent access bits.
*/
if (block == 0) {
errno = EINVAL;
return -1;
}
uint16_t sector_access_bits, sector_access_bits_;
MifareClassicBlockNumber trailer = ((block) / 4) * 4 + 3;
if (tag->cached_access_bits.sector_trailer_block_number == trailer) {
/* cache hit! */
sector_access_bits = tag->cached_access_bits.sector_access_bits;
} else {
MifareClassicBlock trailer_data;
if (mifare_classic_read (tag, trailer, &trailer_data) < 0) {
return -1;
}
sector_access_bits_ = trailer_data[6] | ((trailer_data[7] & 0x0f) << 8) | 0xf000;
sector_access_bits = ((trailer_data[7] & 0xf0) >> 4) | (trailer_data[8] << 4);
if (sector_access_bits != (uint16_t) ~sector_access_bits_) {
/* Sector locked */
errno = EIO;
return -1;
}
tag->cached_access_bits.sector_trailer_block_number = trailer;
tag->cached_access_bits.block_number = -1;
tag->cached_access_bits.sector_access_bits = sector_access_bits;
}
if (tag->cached_access_bits.block_number == block) {
/* cache hit! */
*block_access_bits = tag->cached_access_bits.block_access_bits;
} else {
*block_access_bits = 0;
/* ,-------C3
* |,------C2
* ||,---- C1
* ||| */
uint16_t block_access_bits_mask = 0x0111 << (block % 4);
/* |||
* ||`---------------.
* |`---------------.|
* `---------------.||
* ||| */
if (sector_access_bits & block_access_bits_mask & 0x000f) *block_access_bits |= 0x01; /* C1 */
if (sector_access_bits & block_access_bits_mask & 0x00f0) *block_access_bits |= 0x02; /* C2 */
if (sector_access_bits & block_access_bits_mask & 0x0f00) *block_access_bits |= 0x04; /* C3 */
tag->cached_access_bits.block_access_bits = *block_access_bits;
}
return 0;
}
/*
* Get information about the trailer block.
*/
int
mifare_classic_get_trailer_block_permission (MifareClassicTag tag, const MifareClassicBlockNumber block, const uint16_t permission, const MifareClassicKeyType key_type)
{
MifareClassicAccessBits access_bits;
if (get_block_access_bits (tag, block, &access_bits) < 0) {
return -1;
}
if (tag->cached_access_bits.sector_trailer_block_number == block) {
return (mifare_trailer_access_permissions[access_bits] & (permission) << ((key_type == MFC_KEY_A) ? 1 : 0)) ? 1 : 0;
} else {
errno = EINVAL;
return -1;
}
}
/*
* Get information about data blocks.
*/
int
mifare_classic_get_data_block_permission (MifareClassicTag tag, const MifareClassicBlockNumber block, const unsigned char permission, const MifareClassicKeyType key_type)
{
MifareClassicAccessBits access_bits;
if (get_block_access_bits (tag, block, &access_bits) < 0) {
return -1;
}
if (tag->cached_access_bits.sector_trailer_block_number != block) {
return ((mifare_data_access_permissions[access_bits] & (permission << ( (key_type == MFC_KEY_A) ? 4 : 0 ))) ? 1 : 0);
} else {
errno = EINVAL;
return -1;
}
}
/*
* Miscellaneous functions
*/
/*
* Reset a MIFARE target sector to factory default.
*/
int
mifare_classic_format_sector (MifareClassicTag tag, const MifareSectorNumber sector)
{
MifareClassicBlockNumber first_sector_block = sector * 4;
/*
* Check that the current key allow us to rewrite data and trailer blocks.
*/
if ((mifare_classic_get_data_block_permission(tag, first_sector_block, MCAB_W, tag->last_authentication_key_type) != 1) ||
(mifare_classic_get_data_block_permission(tag, first_sector_block + 1, MCAB_W, tag->last_authentication_key_type) != 1) ||
(mifare_classic_get_data_block_permission(tag, first_sector_block + 2, MCAB_W, tag->last_authentication_key_type) != 1) ||
(mifare_classic_get_trailer_block_permission(tag, first_sector_block + 3, MCAB_WRITE_KEYA, tag->last_authentication_key_type) != 1) ||
(mifare_classic_get_trailer_block_permission(tag, first_sector_block + 3, MCAB_WRITE_ACCESS_BITS, tag->last_authentication_key_type) != 1) ||
(mifare_classic_get_trailer_block_permission(tag, first_sector_block + 3, MCAB_WRITE_KEYB, tag->last_authentication_key_type) != 1)) {
errno = EPERM;
return -1;
}
MifareClassicBlock empty_data_block;
memset (empty_data_block, '\x00', sizeof (empty_data_block));
MifareClassicBlock default_trailer_block = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* Key A */
0xff, 0x07, 0x80, /* Access bits */
0x69, /* GPB */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff /* Key B */
};
if ((mifare_classic_write (tag, first_sector_block, empty_data_block) < 0) ||
(mifare_classic_write (tag, first_sector_block + 1, empty_data_block) < 0) ||
(mifare_classic_write (tag, first_sector_block + 2, empty_data_block) < 0) ||
(mifare_classic_write (tag, first_sector_block + 3, default_trailer_block) < 0)) {
errno = EIO;
return -1;
}
return 0;
}
/*
* UID accessor
*/
char*
mifare_classic_get_uid(MifareClassicTag tag)
{
char* uid = malloc((4 * 2) + 1);
for( uint8_t i = 0; i < 4; i++) {
unsigned char msb = (tag->info.abtUid[i] | 0xf0) >> 4;
unsigned char lsb = (tag->info.abtUid[i] | 0x0f);
uid[i] = msb < 9 ? msb + '0' : msb + 'a';
uid[i+1] = lsb < 9 ? lsb + '0' : lsb + 'a';
}
uid[8] = '\0';
return uid;
}
/*
* Generates a MIFARE trailer block.
*/
void
mifare_classic_trailer_block (MifareClassicBlock *block, const MifareClassicKey key_a, const uint8_t ab_0, const uint8_t ab_1, const uint8_t ab_2, const uint8_t ab_tb, const uint8_t gpb, const MifareClassicKey key_b)
{
union mifare_classic_block *b = (union mifare_classic_block *)block; // *((union mifare_classic_block *)(&block));
memcpy (b->trailer.key_a, key_a, sizeof (MifareClassicKey));
uint32_t access_bits = ((((( ab_0 & 0x4) >> 2) << 8) | (((ab_0 & 0x2) >> 1) << 4) | (ab_0 & 0x1)) |
(((((ab_1 & 0x4) >> 2) << 8) | (((ab_1 & 0x2) >> 1) << 4) | (ab_1 & 0x1)) << 1) |
(((((ab_2 & 0x4) >> 2) << 8) | (((ab_2 & 0x2) >> 1) << 4) | (ab_2 & 0x1)) << 2) |
(((((ab_tb & 0x4) >> 2) << 8) | (((ab_tb & 0x2) >> 1) << 4) | (ab_tb & 0x1)) << 3));
uint32_t access_bits_ = ((~access_bits) & 0x00000fff);
uint32_t ab = htole32(((access_bits << 12) | access_bits_));
memcpy (&(b->trailer.access_bits), &ab, 3);
b->trailer.gpb = gpb;
memcpy (b->trailer.key_b, key_b, sizeof (MifareClassicKey));
}