Reorder client src directories

This commit is contained in:
Bjoern Kerler
2020-04-16 10:25:29 +02:00
parent 94192d0976
commit 81bc0bc2b9
387 changed files with 73 additions and 106 deletions

View File

@@ -0,0 +1,852 @@
/*-
* Copyright (C) 2010, Romain Tartiere.
*
* 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:
*
* NIST Special Publication 800-38B
* Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication
* May 2005
*/
#include "desfire_crypto.h"
#include <stdlib.h>
#include <string.h>
#include "commonutil.h"
#include "mbedtls/aes.h"
#include "mbedtls/des.h"
#include "ui.h"
#include "crc.h"
#include "crc16.h" // crc16 ccitt
#include "crc32.h"
mbedtls_des_context ctx;
mbedtls_des3_context ctx3;
mbedtls_aes_context actx;
#ifndef AddCrc14A
# define AddCrc14A(data, len) compute_crc(CRC_14443_A, (data), (len), (data)+(len), (data)+(len)+1)
#endif
static inline void update_key_schedules(desfirekey_t key);
static inline void update_key_schedules(desfirekey_t key) {
// DES_set_key ((DES_cblock *)key->data, &(key->ks1));
// DES_set_key ((DES_cblock *)(key->data + 8), &(key->ks2));
// if (T_3K3DES == key->type) {
// DES_set_key ((DES_cblock *)(key->data + 16), &(key->ks3));
// }
}
/******************************************************************************/
void des_encrypt(void *out, const void *in, const void *key) {
mbedtls_des_setkey_enc(&ctx, key);
mbedtls_des_crypt_ecb(&ctx, in, out);
}
void des_decrypt(void *out, const void *in, const void *key) {
mbedtls_des_setkey_dec(&ctx, key);
mbedtls_des_crypt_ecb(&ctx, in, out);
}
void tdes_nxp_receive(const void *in, void *out, size_t length, const void *key, unsigned char iv[8], int keymode) {
if (length % 8) return;
if (keymode == 2) mbedtls_des3_set2key_dec(&ctx3, key);
else mbedtls_des3_set3key_dec(&ctx3, key);
uint8_t i;
unsigned char temp[8];
uint8_t *tin = (uint8_t *) in;
uint8_t *tout = (uint8_t *) out;
while (length > 0) {
memcpy(temp, tin, 8);
mbedtls_des3_crypt_ecb(&ctx3, tin, tout);
for (i = 0; i < 8; i++)
tout[i] = (unsigned char)(tout[i] ^ iv[i]);
memcpy(iv, temp, 8);
tin += 8;
tout += 8;
length -= 8;
}
}
void tdes_nxp_send(const void *in, void *out, size_t length, const void *key, unsigned char iv[8], int keymode) {
if (length % 8) return;
if (keymode == 2) mbedtls_des3_set2key_enc(&ctx3, key);
else mbedtls_des3_set3key_enc(&ctx3, key);
uint8_t i;
uint8_t *tin = (uint8_t *) in;
uint8_t *tout = (uint8_t *) out;
while (length > 0) {
for (i = 0; i < 8; i++)
tin[i] = (unsigned char)(tin[i] ^ iv[i]);
mbedtls_des3_crypt_ecb(&ctx3, tin, tout);
memcpy(iv, tout, 8);
tin += 8;
tout += 8;
length -= 8;
}
}
void Desfire_des_key_new(const uint8_t value[8], desfirekey_t key) {
uint8_t data[8];
memcpy(data, value, 8);
for (int n = 0; n < 8; n++)
data[n] &= 0xfe;
Desfire_des_key_new_with_version(data, key);
}
void Desfire_des_key_new_with_version(const uint8_t value[8], desfirekey_t key) {
if (key != NULL) {
key->type = T_DES;
memcpy(key->data, value, 8);
memcpy(key->data + 8, value, 8);
update_key_schedules(key);
}
}
void Desfire_3des_key_new(const uint8_t value[16], desfirekey_t key) {
uint8_t data[16];
memcpy(data, value, 16);
for (int n = 0; n < 8; n++)
data[n] &= 0xfe;
for (int n = 8; n < 16; n++)
data[n] |= 0x01;
Desfire_3des_key_new_with_version(data, key);
}
void Desfire_3des_key_new_with_version(const uint8_t value[16], desfirekey_t key) {
if (key != NULL) {
key->type = T_3DES;
memcpy(key->data, value, 16);
update_key_schedules(key);
}
}
void Desfire_3k3des_key_new(const uint8_t value[24], desfirekey_t key) {
uint8_t data[24];
memcpy(data, value, 24);
for (int n = 0; n < 8; n++)
data[n] &= 0xfe;
Desfire_3k3des_key_new_with_version(data, key);
}
void Desfire_3k3des_key_new_with_version(const uint8_t value[24], desfirekey_t key) {
if (key != NULL) {
key->type = T_3K3DES;
memcpy(key->data, value, 24);
update_key_schedules(key);
}
}
void Desfire_aes_key_new(const uint8_t value[16], desfirekey_t key) {
Desfire_aes_key_new_with_version(value, 0, key);
}
void Desfire_aes_key_new_with_version(const uint8_t value[16], uint8_t version, desfirekey_t key) {
if (key != NULL) {
memcpy(key->data, value, 16);
key->type = T_AES;
key->aes_version = version;
}
}
uint8_t Desfire_key_get_version(desfirekey_t key) {
uint8_t version = 0;
for (int n = 0; n < 8; n++) {
version |= ((key->data[n] & 1) << (7 - n));
}
return version;
}
void Desfire_key_set_version(desfirekey_t key, uint8_t version) {
for (int n = 0; n < 8; n++) {
uint8_t version_bit = ((version & (1 << (7 - n))) >> (7 - n));
key->data[n] &= 0xfe;
key->data[n] |= version_bit;
if (key->type == T_DES) {
key->data[n + 8] = key->data[n];
} else {
// Write ~version to avoid turning a 3DES key into a DES key
key->data[n + 8] &= 0xfe;
key->data[n + 8] |= ~version_bit;
}
}
}
void Desfire_session_key_new(const uint8_t rnda[], const uint8_t rndb[], desfirekey_t authkey, desfirekey_t key) {
uint8_t buffer[24];
switch (authkey->type) {
case T_DES:
memcpy(buffer, rnda, 4);
memcpy(buffer + 4, rndb, 4);
Desfire_des_key_new_with_version(buffer, key);
break;
case T_3DES:
memcpy(buffer, rnda, 4);
memcpy(buffer + 4, rndb, 4);
memcpy(buffer + 8, rnda + 4, 4);
memcpy(buffer + 12, rndb + 4, 4);
Desfire_3des_key_new_with_version(buffer, key);
break;
case T_3K3DES:
memcpy(buffer, rnda, 4);
memcpy(buffer + 4, rndb, 4);
memcpy(buffer + 8, rnda + 6, 4);
memcpy(buffer + 12, rndb + 6, 4);
memcpy(buffer + 16, rnda + 12, 4);
memcpy(buffer + 20, rndb + 12, 4);
Desfire_3k3des_key_new(buffer, key);
break;
case T_AES:
memcpy(buffer, rnda, 4);
memcpy(buffer + 4, rndb, 4);
memcpy(buffer + 8, rnda + 12, 4);
memcpy(buffer + 12, rndb + 12, 4);
Desfire_aes_key_new(buffer, key);
break;
}
}
static void xor(const uint8_t *ivect, uint8_t *data, const size_t len);
static size_t key_macing_length(desfirekey_t key);
// iceman, see memxor inside string.c, dest/src swapped..
static void xor(const uint8_t *ivect, uint8_t *data, const size_t len) {
for (size_t i = 0; i < len; i++) {
data[i] ^= ivect[i];
}
}
void cmac_generate_subkeys(desfirekey_t key) {
int kbs = key_block_size(key);
const uint8_t R = (kbs == 8) ? 0x1B : 0x87;
uint8_t l[kbs];
memset(l, 0, kbs);
uint8_t ivect[kbs];
memset(ivect, 0, kbs);
mifare_cypher_blocks_chained(NULL, key, ivect, l, kbs, MCD_RECEIVE, MCO_ENCYPHER);
bool xor = false;
// Used to compute CMAC on complete blocks
memcpy(key->cmac_sk1, l, kbs);
xor = l[0] & 0x80;
lsl(key->cmac_sk1, kbs);
if (xor)
key->cmac_sk1[kbs - 1] ^= R;
// Used to compute CMAC on the last block if non-complete
memcpy(key->cmac_sk2, key->cmac_sk1, kbs);
xor = key->cmac_sk1[0] & 0x80;
lsl(key->cmac_sk2, kbs);
if (xor)
key->cmac_sk2[kbs - 1] ^= R;
}
void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac) {
int kbs = key_block_size(key);
uint8_t *buffer = malloc(padded_data_length(len, kbs));
memcpy(buffer, data, len);
if ((!len) || (len % kbs)) {
buffer[len++] = 0x80;
while (len % kbs) {
buffer[len++] = 0x00;
}
xor(key->cmac_sk2, buffer + len - kbs, kbs);
} else {
xor(key->cmac_sk1, buffer + len - kbs, kbs);
}
mifare_cypher_blocks_chained(NULL, key, ivect, buffer, len, MCD_SEND, MCO_ENCYPHER);
memcpy(cmac, ivect, kbs);
free(buffer);
}
size_t key_block_size(const desfirekey_t key) {
if (key == NULL)
return 0;
size_t block_size = 8;
switch (key->type) {
case T_DES:
case T_3DES:
case T_3K3DES:
block_size = 8;
break;
case T_AES:
block_size = 16;
break;
}
return block_size;
}
/*
* Size of MACing produced with the key.
*/
static size_t key_macing_length(const desfirekey_t key) {
size_t mac_length = MAC_LENGTH;
switch (key->type) {
case T_DES:
case T_3DES:
mac_length = MAC_LENGTH;
break;
case T_3K3DES:
case T_AES:
mac_length = CMAC_LENGTH;
break;
}
return mac_length;
}
/*
* Size required to store nbytes of data in a buffer of size n*block_size.
*/
size_t padded_data_length(const size_t nbytes, const size_t block_size) {
if ((!nbytes) || (nbytes % block_size))
return ((nbytes / block_size) + 1) * block_size;
else
return nbytes;
}
/*
* Buffer size required to MAC nbytes of data
*/
size_t maced_data_length(const desfirekey_t key, const size_t nbytes) {
return nbytes + key_macing_length(key);
}
/*
* Buffer size required to encipher nbytes of data and a two bytes CRC.
*/
size_t enciphered_data_length(const desfiretag_t tag, const size_t nbytes, int communication_settings) {
size_t crc_length = 0;
if (!(communication_settings & NO_CRC)) {
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
crc_length = 2;
break;
case AS_NEW:
crc_length = 4;
break;
}
}
size_t block_size = DESFIRE(tag)->session_key ? key_block_size(DESFIRE(tag)->session_key) : 1;
return padded_data_length(nbytes + crc_length, block_size);
}
void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, size_t offset, int communication_settings) {
uint8_t *res = data;
uint8_t mac[4];
size_t edl;
bool append_mac = true;
desfirekey_t key = DESFIRE(tag)->session_key;
if (!key)
return data;
switch (communication_settings & MDCM_MASK) {
case MDCM_PLAIN:
if (AS_LEGACY == DESFIRE(tag)->authentication_scheme)
break;
/*
* When using new authentication methods, PLAIN data transmission from
* the PICC to the PCD are CMACed, so we have to maintain the
* cryptographic initialisation vector up-to-date to check data
* integrity later.
*
* The only difference with CMACed data transmission is that the CMAC
* is not apended to the data send by the PCD to the PICC.
*/
append_mac = false;
/* pass through */
case MDCM_MACED:
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
if (!(communication_settings & MAC_COMMAND))
break;
/* pass through */
edl = padded_data_length(*nbytes - offset, key_block_size(DESFIRE(tag)->session_key)) + offset;
// Fill in the crypto buffer with data ...
memcpy(res, data, *nbytes);
// ... and 0 padding
memset(res + *nbytes, 0, edl - *nbytes);
mifare_cypher_blocks_chained(tag, NULL, NULL, res + offset, edl - offset, MCD_SEND, MCO_ENCYPHER);
memcpy(mac, res + edl - 8, 4);
// Copy again provided data (was overwritten by mifare_cypher_blocks_chained)
memcpy(res, data, *nbytes);
if (!(communication_settings & MAC_COMMAND))
break;
// Append MAC
size_t bla = maced_data_length(DESFIRE(tag)->session_key, *nbytes - offset) + offset;
bla++;
memcpy(res + *nbytes, mac, 4);
*nbytes += 4;
break;
case AS_NEW:
if (!(communication_settings & CMAC_COMMAND))
break;
cmac(key, DESFIRE(tag)->ivect, res, *nbytes, DESFIRE(tag)->cmac);
if (append_mac) {
size_t len = maced_data_length(key, *nbytes);
++len;
memcpy(res, data, *nbytes);
memcpy(res + *nbytes, DESFIRE(tag)->cmac, CMAC_LENGTH);
*nbytes += CMAC_LENGTH;
}
break;
}
break;
case MDCM_ENCIPHERED:
/* |<-------------- data -------------->|
* |<--- offset -->| |
* +---------------+--------------------+-----+---------+
* | CMD + HEADERS | DATA TO BE SECURED | CRC | PADDING |
* +---------------+--------------------+-----+---------+ ----------------
* | |<~~~~v~~~~~~~~~~~~~>| ^ | | (DES / 3DES)
* | | `---- crc16() ----' | |
* | | | ^ | | ----- *or* -----
* |<~~~~~~~~~~~~~~~~~~~~v~~~~~~~~~~~~~>| ^ | | (3K3DES / AES)
* | `---- crc32() ----' | |
* | | ---- *then* ----
* |<---------------------------------->|
* encypher()/decypher()
*/
if (!(communication_settings & ENC_COMMAND))
break;
edl = enciphered_data_length(tag, *nbytes - offset, communication_settings) + offset;
// Fill in the crypto buffer with data ...
memcpy(res, data, *nbytes);
if (!(communication_settings & NO_CRC)) {
// ... CRC ...
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
AddCrc14A(res + offset, *nbytes - offset);
*nbytes += 2;
break;
case AS_NEW:
crc32_append(res, *nbytes);
*nbytes += 4;
break;
}
}
// ... and padding
memset(res + *nbytes, 0, edl - *nbytes);
*nbytes = edl;
mifare_cypher_blocks_chained(tag, NULL, NULL, res + offset, *nbytes - offset, MCD_SEND, (AS_NEW == DESFIRE(tag)->authentication_scheme) ? MCO_ENCYPHER : MCO_DECYPHER);
break;
default:
*nbytes = -1;
res = NULL;
break;
}
return res;
}
void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes, int communication_settings) {
void *res = data;
void *edata = NULL;
uint8_t first_cmac_byte = 0x00;
desfirekey_t key = DESFIRE(tag)->session_key;
if (!key)
return data;
// Return directly if we just have a status code.
if (1 == *nbytes)
return res;
switch (communication_settings & MDCM_MASK) {
case MDCM_PLAIN:
if (AS_LEGACY == DESFIRE(tag)->authentication_scheme)
break;
/* pass through */
case MDCM_MACED:
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
if (communication_settings & MAC_VERIFY) {
*nbytes -= key_macing_length(key);
if (*nbytes == 0) {
*nbytes = -1;
res = NULL;
#ifdef WITH_DEBUG
Dbprintf("No room for MAC!");
#endif
break;
}
size_t edl = enciphered_data_length(tag, *nbytes - 1, communication_settings);
edata = malloc(edl);
memcpy(edata, data, *nbytes - 1);
memset((uint8_t *)edata + *nbytes - 1, 0, edl - *nbytes + 1);
mifare_cypher_blocks_chained(tag, NULL, NULL, edata, edl, MCD_SEND, MCO_ENCYPHER);
if (0 != memcmp((uint8_t *)data + *nbytes - 1, (uint8_t *)edata + edl - 8, 4)) {
#ifdef WITH_DEBUG
Dbprintf("MACing not verified");
hexdump((uint8_t *)data + *nbytes - 1, key_macing_length(key), "Expect ", 0);
hexdump((uint8_t *)edata + edl - 8, key_macing_length(key), "Actual ", 0);
#endif
DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR;
*nbytes = -1;
res = NULL;
}
}
break;
case AS_NEW:
if (!(communication_settings & CMAC_COMMAND))
break;
if (communication_settings & CMAC_VERIFY) {
if (*nbytes < 9) {
*nbytes = -1;
res = NULL;
break;
}
first_cmac_byte = ((uint8_t *)data)[*nbytes - 9];
((uint8_t *)data)[*nbytes - 9] = ((uint8_t *)data)[*nbytes - 1];
}
int n = (communication_settings & CMAC_VERIFY) ? 8 : 0;
cmac(key, DESFIRE(tag)->ivect, ((uint8_t *)data), *nbytes - n, DESFIRE(tag)->cmac);
if (communication_settings & CMAC_VERIFY) {
((uint8_t *)data)[*nbytes - 9] = first_cmac_byte;
if (0 != memcmp(DESFIRE(tag)->cmac, (uint8_t *)data + *nbytes - 9, 8)) {
#ifdef WITH_DEBUG
Dbprintf("CMAC NOT verified :-(");
hexdump((uint8_t *)data + *nbytes - 9, 8, "Expect ", 0);
hexdump(DESFIRE(tag)->cmac, 8, "Actual ", 0);
#endif
DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR;
*nbytes = -1;
res = NULL;
} else {
*nbytes -= 8;
}
}
break;
}
free(edata);
break;
case MDCM_ENCIPHERED:
(*nbytes)--;
bool verified = false;
int crc_pos = 0x00;
int end_crc_pos = 0x00;
uint8_t x;
/*
* AS_LEGACY:
* ,-----------------+-------------------------------+--------+
* \ BLOCK n-1 | BLOCK n | STATUS |
* / PAYLOAD | CRC0 | CRC1 | 0x80? | 0x000000000000 | 0x9100 |
* `-----------------+-------------------------------+--------+
*
* <------------ DATA ------------>
* FRAME = PAYLOAD + CRC(PAYLOAD) + PADDING
*
* AS_NEW:
* ,-------------------------------+-----------------------------------------------+--------+
* \ BLOCK n-1 | BLOCK n | STATUS |
* / PAYLOAD | CRC0 | CRC1 | CRC2 | CRC3 | 0x80? | 0x0000000000000000000000000000 | 0x9100 |
* `-------------------------------+-----------------------------------------------+--------+
* <----------------------------------- DATA ------------------------------------->|
*
* <----------------- DATA ---------------->
* FRAME = PAYLOAD + CRC(PAYLOAD + STATUS) + PADDING + STATUS
* `------------------'
*/
mifare_cypher_blocks_chained(tag, NULL, NULL, res, *nbytes, MCD_RECEIVE, MCO_DECYPHER);
/*
* Look for the CRC and ensure it is followed by NULL padding. We
* can't start by the end because the CRC is supposed to be 0 when
* verified, and accumulating 0's in it should not change it.
*/
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
crc_pos = *nbytes - 8 - 1; // The CRC can be over two blocks
if (crc_pos < 0) {
/* Single block */
crc_pos = 0;
}
break;
case AS_NEW:
/* Move status between payload and CRC */
res = DESFIRE(tag)->crypto_buffer;
memcpy(res, data, *nbytes);
crc_pos = (*nbytes) - 16 - 3;
if (crc_pos < 0) {
/* Single block */
crc_pos = 0;
}
memcpy((uint8_t *)res + crc_pos + 1, (uint8_t *)res + crc_pos, *nbytes - crc_pos);
((uint8_t *)res)[crc_pos] = 0x00;
crc_pos++;
*nbytes += 1;
break;
}
do {
uint16_t crc_16 = 0x00;
uint32_t crc = 0x00;
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
AddCrc14A((uint8_t *)res, end_crc_pos);
end_crc_pos = crc_pos + 2;
//
crc = crc_16;
break;
case AS_NEW:
end_crc_pos = crc_pos + 4;
crc32_ex(res, end_crc_pos, (uint8_t *)&crc);
break;
}
if (!crc) {
verified = true;
for (int n = end_crc_pos; n < *nbytes - 1; n++) {
uint8_t byte = ((uint8_t *)res)[n];
if (!((0x00 == byte) || ((0x80 == byte) && (n == end_crc_pos))))
verified = false;
}
}
if (verified) {
*nbytes = crc_pos;
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
((uint8_t *)data)[(*nbytes)++] = 0x00;
break;
case AS_NEW:
/* The status byte was already before the CRC */
break;
}
} else {
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
break;
case AS_NEW:
x = ((uint8_t *)res)[crc_pos - 1];
((uint8_t *)res)[crc_pos - 1] = ((uint8_t *)res)[crc_pos];
((uint8_t *)res)[crc_pos] = x;
break;
}
crc_pos++;
}
} while (!verified && (end_crc_pos < *nbytes));
if (!verified) {
#ifdef WITH_DEBUG
/* FIXME In some configurations, the file is transmitted PLAIN */
Dbprintf("CRC not verified in decyphered stream");
#endif
DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR;
*nbytes = -1;
res = NULL;
}
break;
default:
PrintAndLogEx(ERR, "Unknown communication settings");
*nbytes = -1;
res = NULL;
break;
}
return res;
}
void mifare_cypher_single_block(desfirekey_t key, uint8_t *data, uint8_t *ivect, MifareCryptoDirection direction, MifareCryptoOperation operation, size_t block_size) {
uint8_t ovect[MAX_CRYPTO_BLOCK_SIZE];
if (direction == MCD_SEND) {
xor(ivect, data, block_size);
} else {
memcpy(ovect, data, block_size);
}
uint8_t edata[MAX_CRYPTO_BLOCK_SIZE];
switch (key->type) {
case T_DES:
switch (operation) {
case MCO_ENCYPHER:
//DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
des_encrypt(edata, data, key->data);
break;
case MCO_DECYPHER:
//DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
des_decrypt(edata, data, key->data);
break;
}
break;
case T_3DES:
switch (operation) {
case MCO_ENCYPHER:
mbedtls_des3_set2key_enc(&ctx3, key->data);
mbedtls_des3_crypt_ecb(&ctx3, data, edata);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
// DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_DECRYPT);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
break;
case MCO_DECYPHER:
mbedtls_des3_set2key_dec(&ctx3, key->data);
mbedtls_des3_crypt_ecb(&ctx3, data, edata);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
// DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_ENCRYPT);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
break;
}
break;
case T_3K3DES:
switch (operation) {
case MCO_ENCYPHER:
mbedtls_des3_set3key_enc(&ctx3, key->data);
mbedtls_des3_crypt_ecb(&ctx3, data, edata);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
// DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_DECRYPT);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks3), DES_ENCRYPT);
break;
case MCO_DECYPHER:
mbedtls_des3_set3key_dec(&ctx3, key->data);
mbedtls_des3_crypt_ecb(&ctx3, data, edata);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks3), DES_DECRYPT);
// DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_ENCRYPT);
// DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
break;
}
break;
case T_AES:
switch (operation) {
case MCO_ENCYPHER: {
mbedtls_aes_init(&actx);
mbedtls_aes_setkey_enc(&actx, key->data, 128);
mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_ENCRYPT, sizeof(edata), ivect, data, edata);
mbedtls_aes_free(&actx);
break;
}
case MCO_DECYPHER: {
mbedtls_aes_init(&actx);
mbedtls_aes_setkey_dec(&actx, key->data, 128);
mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_DECRYPT, sizeof(edata), ivect, edata, data);
mbedtls_aes_free(&actx);
break;
}
}
break;
}
memcpy(data, edata, block_size);
if (direction == MCD_SEND) {
memcpy(ivect, data, block_size);
} else {
xor(ivect, data, block_size);
memcpy(ivect, ovect, block_size);
}
}
/*
* This function performs all CBC cyphering / deciphering.
*
* The tag argument may be NULL, in which case both key and ivect shall be set.
* When using the tag session_key and ivect for processing data, these
* arguments should be set to NULL.
*
* Because the tag may contain additional data, one may need to call this
* function with tag, key and ivect defined.
*/
void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *ivect, uint8_t *data, size_t data_size, MifareCryptoDirection direction, MifareCryptoOperation operation) {
size_t block_size;
if (tag) {
if (!key)
key = DESFIRE(tag)->session_key;
if (!ivect)
ivect = DESFIRE(tag)->ivect;
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
memset(ivect, 0, MAX_CRYPTO_BLOCK_SIZE);
break;
case AS_NEW:
break;
}
}
block_size = key_block_size(key);
size_t offset = 0;
while (offset < data_size) {
mifare_cypher_single_block(key, data + offset, ivect, direction, operation, block_size);
offset += block_size;
}
}

View File

@@ -0,0 +1,135 @@
#ifndef __DESFIRE_CRYPTO_H
#define __DESFIRE_CRYPTO_H
#include "common.h"
#include "mifare.h" // structs
#include "crc32.h"
//#include "../../armsrc/printf.h"
//#include "../../armsrc/desfire.h"
//#include "../../armsrc/iso14443a.h"
#define MAX_CRYPTO_BLOCK_SIZE 16
/* Mifare DESFire EV1 Application crypto operations */
#define APPLICATION_CRYPTO_DES 0x00
#define APPLICATION_CRYPTO_3K3DES 0x40
#define APPLICATION_CRYPTO_AES 0x80
#define MAC_LENGTH 4
#define CMAC_LENGTH 8
typedef enum {
MCD_SEND,
MCD_RECEIVE
} MifareCryptoDirection;
typedef enum {
MCO_ENCYPHER,
MCO_DECYPHER
} MifareCryptoOperation;
#define MDCM_MASK 0x000F
#define CMAC_NONE 0
// Data send to the PICC is used to update the CMAC
#define CMAC_COMMAND 0x010
// Data received from the PICC is used to update the CMAC
#define CMAC_VERIFY 0x020
// MAC the command (when MDCM_MACED)
#define MAC_COMMAND 0x100
// The command returns a MAC to verify (when MDCM_MACED)
#define MAC_VERIFY 0x200
#define ENC_COMMAND 0x1000
#define NO_CRC 0x2000
#define MAC_MASK 0x0F0
#define CMAC_MACK 0xF00
/* Communication mode */
#define MDCM_PLAIN 0x00
#define MDCM_MACED 0x01
#define MDCM_ENCIPHERED 0x03
/* Error code managed by the library */
#define CRYPTO_ERROR 0x01
enum DESFIRE_CRYPTOALGO {
T_DES = 0x00,
T_3DES = 0x01, //aka 2K3DES
T_3K3DES = 0x02,
T_AES = 0x03
};
enum DESFIRE_AUTH_SCHEME {
AS_LEGACY,
AS_NEW
};
#define DESFIRE_KEY(key) ((struct desfire_key *) key)
struct desfire_key {
enum DESFIRE_CRYPTOALGO type;
uint8_t data[24];
uint8_t cmac_sk1[24];
uint8_t cmac_sk2[24];
uint8_t aes_version;
};
typedef struct desfire_key *desfirekey_t;
#define DESFIRE(tag) ((struct desfire_tag *) tag)
struct desfire_tag {
iso14a_card_select_t info;
int active;
uint8_t last_picc_error;
uint8_t last_internal_error;
uint8_t last_pcd_error;
desfirekey_t session_key;
enum DESFIRE_AUTH_SCHEME authentication_scheme;
uint8_t authenticated_key_no;
uint8_t ivect[MAX_CRYPTO_BLOCK_SIZE];
uint8_t cmac[16];
uint8_t *crypto_buffer;
size_t crypto_buffer_size;
uint32_t selected_application;
};
typedef struct desfire_tag *desfiretag_t;
typedef unsigned long DES_KS[16][2]; /* Single-key DES key schedule */
typedef unsigned long DES3_KS[48][2]; /* Triple-DES key schedule */
extern int Asmversion; /* 1 if we're linked with an asm version, 0 if C */
void des_encrypt(void *out, const void *in, const void *key);
void des_decrypt(void *out, const void *in, const void *key);
void tdes_nxp_receive(const void *in, void *out, size_t length, const void *key, unsigned char iv[8], int keymode);
void tdes_nxp_send(const void *in, void *out, size_t length, const void *key, unsigned char iv[8], int keymode);
void Desfire_des_key_new(const uint8_t value[8], desfirekey_t key);
void Desfire_3des_key_new(const uint8_t value[16], desfirekey_t key);
void Desfire_des_key_new_with_version(const uint8_t value[8], desfirekey_t key);
void Desfire_3des_key_new_with_version(const uint8_t value[16], desfirekey_t key);
void Desfire_3k3des_key_new(const uint8_t value[24], desfirekey_t key);
void Desfire_3k3des_key_new_with_version(const uint8_t value[24], desfirekey_t key);
void Desfire_2k3des_key_new_with_version(const uint8_t value[16], desfirekey_t key);
void Desfire_aes_key_new(const uint8_t value[16], desfirekey_t key);
void Desfire_aes_key_new_with_version(const uint8_t value[16], uint8_t version, desfirekey_t key);
uint8_t Desfire_key_get_version(desfirekey_t key);
void Desfire_key_set_version(desfirekey_t key, uint8_t version);
void Desfire_session_key_new(const uint8_t rnda[], const uint8_t rndb[], desfirekey_t authkey, desfirekey_t key);
void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, size_t offset, int communication_settings);
void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes, int communication_settings);
void mifare_cypher_single_block(desfirekey_t key, uint8_t *data, uint8_t *ivect, MifareCryptoDirection direction, MifareCryptoOperation operation, size_t block_size);
void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *ivect, uint8_t *data, size_t data_size, MifareCryptoDirection direction, MifareCryptoOperation operation);
size_t key_block_size(const desfirekey_t key);
size_t padded_data_length(const size_t nbytes, const size_t block_size);
size_t maced_data_length(const desfirekey_t key, const size_t nbytes);
size_t enciphered_data_length(const desfiretag_t tag, const size_t nbytes, int communication_settings);
void cmac_generate_subkeys(desfirekey_t key);
void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac);
#endif

258
client/src/mifare/mad.c Normal file
View File

@@ -0,0 +1,258 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2019 Merlok
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// MIFARE Application Directory (MAD) functions
//-----------------------------------------------------------------------------
#include "mad.h"
#include "ui.h"
#include "commonutil.h" // ARRAYLEN
#include "crc.h"
#include "util.h"
// https://www.nxp.com/docs/en/application-note/AN10787.pdf
static madAIDDescr madKnownAIDs[] = {
{0x0000, "free"},
{0x0001, "defect, e.g. access keys are destroyed or unknown"},
{0x0002, "reserved"},
{0x0003, "contains additional directory info"},
{0x0004, "contains card holder information in ASCII format."},
{0x0005, "not applicable (above memory size)"},
{0x03e1, "NDEF"},
};
static madAIDDescr madKnownClusterCodes[] = {
{0x00, "cluster: card administration"},
{0x01, "cluster: miscellaneous applications"},
{0x02, "cluster: miscellaneous applications"},
{0x03, "cluster: miscellaneous applications"},
{0x04, "cluster: miscellaneous applications"},
{0x05, "cluster: miscellaneous applications"},
{0x06, "cluster: miscellaneous applications"},
{0x07, "cluster: miscellaneous applications"},
{0x08, "cluster: airlines"},
{0x09, "cluster: ferry traffic"},
{0x10, "cluster: railway services"},
{0x11, "cluster: miscellaneous applications"},
{0x12, "cluster: transport"},
{0x14, "cluster: security solutions"},
{0x18, "cluster: city traffic"},
{0x19, "cluster: Czech Railways"},
{0x20, "cluster: bus services"},
{0x21, "cluster: multi modal transit"},
{0x28, "cluster: taxi"},
{0x30, "cluster: road toll"},
{0x31, "cluster: generic transport"},
{0x38, "cluster: company services"},
{0x40, "cluster: city card services"},
{0x47, "cluster: access control & security"},
{0x48, "cluster: access control & security"},
{0x49, "cluster: VIGIK"},
{0x4A, "cluster: Ministry of Defence, Netherlands"},
{0x4B, "cluster: Bosch Telecom, Germany"},
{0x4C, "cluster: European Union Institutions"},
{0x50, "cluster: ski ticketing"},
{0x51, "cluster: access control & security"},
{0x52, "cluster: access control & security"},
{0x53, "cluster: access control & security"},
{0x54, "cluster: access control & security"},
{0x55, "cluster: SOAA standard for offline access standard"},
{0x56, "cluster: access control & security"},
{0x58, "cluster: academic services"},
{0x60, "cluster: food"},
{0x68, "cluster: non-food trade"},
{0x70, "cluster: hotel"},
{0x71, "cluster: loyalty"},
{0x75, "cluster: airport services"},
{0x78, "cluster: car rental"},
{0x79, "cluster: Dutch government"},
{0x80, "cluster: administration services"},
{0x88, "cluster: electronic purse"},
{0x90, "cluster: television"},
{0x91, "cluster: cruise ship"},
{0x95, "cluster: IOPTA"},
{0x97, "cluster: metering"},
{0x98, "cluster: telephone"},
{0xA0, "cluster: health services"},
{0xA8, "cluster: warehouse"},
{0xB0, "cluster: electronic trade"},
{0xB8, "cluster: banking"},
{0xC0, "cluster: entertainment & sports"},
{0xC8, "cluster: car parking"},
{0xC9, "cluster: fleet management"},
{0xD0, "cluster: fuel, gasoline"},
{0xD8, "cluster: info services"},
{0xE0, "cluster: press"},
{0xE1, "cluster: NFC Forum"},
{0xE8, "cluster: computer"},
{0xF0, "cluster: mail"},
{0xF8, "cluster: miscellaneous applications"},
};
static const char unknownAID[] = "";
static const char *GetAIDDescription(uint16_t AID) {
for (int i = 0; i < ARRAYLEN(madKnownAIDs); i++)
if (madKnownAIDs[i].AID == AID)
return madKnownAIDs[i].Description;
for (int i = 0; i < ARRAYLEN(madKnownClusterCodes); i++)
if (madKnownClusterCodes[i].AID == (AID >> 8)) // high byte - cluster code
return madKnownClusterCodes[i].Description;
return unknownAID;
}
static int madCRCCheck(uint8_t *sector, bool verbose, int MADver) {
if (MADver == 1) {
uint8_t crc = CRC8Mad(&sector[16 + 1], 15 + 16);
if (crc != sector[16]) {
PrintAndLogEx(WARNING, "Wrong MAD%d CRC. Calculated: 0x%02x, from card: 0x%02x", MADver, crc, sector[16]);
return 3;
};
} else {
uint8_t crc = CRC8Mad(&sector[1], 15 + 16 + 16);
if (crc != sector[0]) {
PrintAndLogEx(WARNING, "Wrong MAD%d CRC. Calculated: 0x%02x, from card: 0x%02x", MADver, crc, sector[16]);
return 3;
};
}
return 0;
}
static uint16_t madGetAID(uint8_t *sector, int MADver, int sectorNo) {
if (MADver == 1)
return (sector[16 + 2 + (sectorNo - 1) * 2] << 8) + (sector[16 + 2 + (sectorNo - 1) * 2 + 1]);
else
return (sector[2 + (sectorNo - 1) * 2] << 8) + (sector[2 + (sectorNo - 1) * 2 + 1]);
}
int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2) {
int res = 0;
if (!sector0)
return 1;
uint8_t GPB = sector0[3 * 16 + 9];
if (verbose)
PrintAndLogEx(NORMAL, "GPB: 0x%02x", GPB);
// DA (MAD available)
if (!(GPB & 0x80)) {
PrintAndLogEx(ERR, "DA=0! MAD not available.");
return 1;
}
// MA (multi-application card)
if (verbose) {
if (GPB & 0x40)
PrintAndLogEx(NORMAL, "Multi application card.");
else
PrintAndLogEx(NORMAL, "Single application card.");
}
uint8_t MADVer = GPB & 0x03;
if (verbose)
PrintAndLogEx(NORMAL, "MAD version: %d", MADVer);
// MAD version
if ((MADVer != 0x01) && (MADVer != 0x02)) {
PrintAndLogEx(ERR, "Wrong MAD version: 0x%02x", MADVer);
return 2;
};
if (haveMAD2)
*haveMAD2 = (MADVer == 2);
res = madCRCCheck(sector0, true, 1);
if (verbose && !res)
PrintAndLogEx(NORMAL, "CRC8-MAD1 OK.");
if (MADVer == 2 && sector10) {
int res2 = madCRCCheck(sector10, true, 2);
if (!res)
res = res2;
if (verbose && !res2)
PrintAndLogEx(NORMAL, "CRC8-MAD2 OK.");
}
return res;
}
int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen) {
*madlen = 0;
bool haveMAD2 = false;
MADCheck(sector0, sector10, false, &haveMAD2);
for (int i = 1; i < 16; i++) {
mad[*madlen] = madGetAID(sector0, 1, i);
(*madlen)++;
}
if (haveMAD2) {
// mad2 sector (0x10 == 16dec) here
mad[*madlen] = 0x0005;
(*madlen)++;
for (int i = 1; i < 24; i++) {
mad[*madlen] = madGetAID(sector10, 2, i);
(*madlen)++;
}
}
return 0;
}
int MAD1DecodeAndPrint(uint8_t *sector, bool verbose, bool *haveMAD2) {
// check MAD1 only
MADCheck(sector, NULL, verbose, haveMAD2);
// info byte
uint8_t InfoByte = sector[16 + 1] & 0x3f;
if (InfoByte) {
PrintAndLogEx(NORMAL, "Card publisher sector: 0x%02x", InfoByte);
} else {
if (verbose)
PrintAndLogEx(NORMAL, "Card publisher sector not present.");
}
if (InfoByte == 0x10 || InfoByte >= 0x28)
PrintAndLogEx(WARNING, "Info byte error");
PrintAndLogEx(NORMAL, "00 MAD1");
for (int i = 1; i < 16; i++) {
uint16_t AID = madGetAID(sector, 1, i);
PrintAndLogEx(NORMAL, "%02d [%04X] %s", i, AID, GetAIDDescription(AID));
};
return 0;
};
int MAD2DecodeAndPrint(uint8_t *sector, bool verbose) {
PrintAndLogEx(NORMAL, "16 MAD2");
int res = madCRCCheck(sector, true, 2);
if (verbose && !res)
PrintAndLogEx(NORMAL, "CRC8-MAD2 OK.");
uint8_t InfoByte = sector[1] & 0x3f;
PrintAndLogEx(NORMAL, "MAD2 Card publisher sector: 0x%02x", InfoByte);
for (int i = 1; i < 8 + 8 + 7 + 1; i++) {
uint16_t AID = madGetAID(sector, 2, i);
PrintAndLogEx(NORMAL, "%02d [%04X] %s", i + 16, AID, GetAIDDescription(AID));
};
return 0;
};

27
client/src/mifare/mad.h Normal file
View File

@@ -0,0 +1,27 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2019 Merlok
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// MIFARE Application Directory (MAD) functions
//-----------------------------------------------------------------------------
#ifndef _MAD_H_
#define _MAD_H_
#include "common.h"
typedef struct {
uint16_t AID;
const char *Description;
} madAIDDescr;
int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2);
int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen);
int MAD1DecodeAndPrint(uint8_t *sector, bool verbose, bool *haveMAD2);
int MAD2DecodeAndPrint(uint8_t *sector, bool verbose);
#endif // _MAD_H_

174
client/src/mifare/mfkey.c Normal file
View File

@@ -0,0 +1,174 @@
//-----------------------------------------------------------------------------
// Merlok - June 2011
// Roel - Dec 2009
// Unknown author
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// MIFARE Darkside hack
//-----------------------------------------------------------------------------
#include "mfkey.h"
#include "crapto1/crapto1.h"
// MIFARE
int inline compare_uint64(const void *a, const void *b) {
if (*(uint64_t *)b == *(uint64_t *)a) return 0;
if (*(uint64_t *)b < * (uint64_t *)a) return 1;
return -1;
}
// create the intersection (common members) of two sorted lists. Lists are terminated by -1. Result will be in list1. Number of elements is returned.
uint32_t intersection(uint64_t *listA, uint64_t *listB) {
if (listA == NULL || listB == NULL)
return 0;
uint64_t *p1, *p2, *p3;
p1 = p3 = listA;
p2 = listB;
while (*p1 != UINT64_C(-1) && *p2 != UINT64_C(-1)) {
if (compare_uint64(p1, p2) == 0) {
*p3++ = *p1++;
p2++;
} else {
while (compare_uint64(p1, p2) < 0) ++p1;
while (compare_uint64(p1, p2) > 0) ++p2;
}
}
*p3 = UINT64_C(-1);
return p3 - listA;
}
// Darkside attack (hf mf mifare)
// if successful it will return a list of keys, not just one.
uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t par_info, uint64_t ks_info, uint64_t **keys) {
struct Crypto1State *states;
uint32_t i, pos;
uint8_t ks3x[8], par[8][8];
uint64_t key_recovered;
uint64_t *keylist;
// Reset the last three significant bits of the reader nonce
nr &= 0xFFFFFF1F;
for (pos = 0; pos < 8; pos++) {
ks3x[7 - pos] = (ks_info >> (pos * 8)) & 0x0F;
uint8_t bt = (par_info >> (pos * 8)) & 0xFF;
par[7 - pos][0] = (bt >> 0) & 1;
par[7 - pos][1] = (bt >> 1) & 1;
par[7 - pos][2] = (bt >> 2) & 1;
par[7 - pos][3] = (bt >> 3) & 1;
par[7 - pos][4] = (bt >> 4) & 1;
par[7 - pos][5] = (bt >> 5) & 1;
par[7 - pos][6] = (bt >> 6) & 1;
par[7 - pos][7] = (bt >> 7) & 1;
}
states = lfsr_common_prefix(nr, ar, ks3x, par, (par_info == 0));
if (!states) {
*keys = NULL;
return 0;
}
keylist = (uint64_t *)states;
for (i = 0; keylist[i]; i++) {
lfsr_rollback_word(states + i, uid ^ nt, 0);
crypto1_get_lfsr(states + i, &key_recovered);
keylist[i] = key_recovered;
}
keylist[i] = -1;
*keys = keylist;
return i;
}
// recover key from 2 different reader responses on same tag challenge
bool mfkey32(nonces_t *data, uint64_t *outputkey) {
struct Crypto1State *s, *t;
uint64_t outkey = 0;
uint64_t key = 0; // recovered key
bool isSuccess = false;
uint8_t counter = 0;
uint32_t p640 = prng_successor(data->nonce, 64);
s = lfsr_recovery32(data->ar ^ p640, 0);
for (t = s; t->odd | t->even; ++t) {
lfsr_rollback_word(t, 0, 0);
lfsr_rollback_word(t, data->nr, 1);
lfsr_rollback_word(t, data->cuid ^ data->nonce, 0);
crypto1_get_lfsr(t, &key);
crypto1_word(t, data->cuid ^ data->nonce, 0);
crypto1_word(t, data->nr2, 1);
if (data->ar2 == (crypto1_word(t, 0, 0) ^ p640)) {
outkey = key;
counter++;
if (counter == 20) break;
}
}
isSuccess = (counter == 1);
*outputkey = (isSuccess) ? outkey : 0;
crypto1_destroy(s);
return isSuccess;
}
// recover key from 2 reader responses on 2 different tag challenges
// skip "several found keys". Only return true if ONE key is found
bool mfkey32_moebius(nonces_t *data, uint64_t *outputkey) {
struct Crypto1State *s, *t;
uint64_t outkey = 0;
uint64_t key = 0; // recovered key
bool isSuccess = false;
int counter = 0;
uint32_t p640 = prng_successor(data->nonce, 64);
uint32_t p641 = prng_successor(data->nonce2, 64);
s = lfsr_recovery32(data->ar ^ p640, 0);
for (t = s; t->odd | t->even; ++t) {
lfsr_rollback_word(t, 0, 0);
lfsr_rollback_word(t, data->nr, 1);
lfsr_rollback_word(t, data->cuid ^ data->nonce, 0);
crypto1_get_lfsr(t, &key);
crypto1_word(t, data->cuid ^ data->nonce2, 0);
crypto1_word(t, data->nr2, 1);
if (data->ar2 == (crypto1_word(t, 0, 0) ^ p641)) {
outkey = key;
++counter;
if (counter == 20) break;
}
}
isSuccess = (counter == 1);
*outputkey = (isSuccess) ? outkey : 0;
crypto1_destroy(s);
return isSuccess;
}
// recover key from reader response and tag response of one authentication sequence
int mfkey64(nonces_t *data, uint64_t *outputkey) {
uint64_t key = 0; // recovered key
uint32_t ks2; // keystream used to encrypt reader response
uint32_t ks3; // keystream used to encrypt tag response
struct Crypto1State *revstate;
// Extract the keystream from the messages
ks2 = data->ar ^ prng_successor(data->nonce, 64);
ks3 = data->at ^ prng_successor(data->nonce, 96);
revstate = lfsr_recovery64(ks2, ks3);
lfsr_rollback_word(revstate, 0, 0);
lfsr_rollback_word(revstate, 0, 0);
lfsr_rollback_word(revstate, data->nr, 1);
lfsr_rollback_word(revstate, data->cuid ^ data->nonce, 0);
crypto1_get_lfsr(revstate, &key);
crypto1_destroy(revstate);
*outputkey = key;
return 0;
}

27
client/src/mifare/mfkey.h Normal file
View File

@@ -0,0 +1,27 @@
//-----------------------------------------------------------------------------
// Merlok - June 2011
// Roel - Dec 2009
// Unknown author
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// MIFARE Darkside hack
//-----------------------------------------------------------------------------
#ifndef MFKEY_H
#define MFKEY_H
#include "common.h"
#include "mifare.h"
uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t par_info, uint64_t ks_info, uint64_t **keys);
bool mfkey32(nonces_t *data, uint64_t *outputkey);
bool mfkey32_moebius(nonces_t *data, uint64_t *outputkey);
int mfkey64(nonces_t *data, uint64_t *outputkey);
int compare_uint64(const void *a, const void *b);
uint32_t intersection(uint64_t *listA, uint64_t *listB);
#endif

506
client/src/mifare/mifare4.c Normal file
View File

@@ -0,0 +1,506 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2018 Merlok
// Copyright (C) 2018 drHatson
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// iso14443-4 mifare commands
//-----------------------------------------------------------------------------
#include "mifare4.h"
#include <string.h>
#include "commonutil.h" // ARRAYLEN
#include "comms.h" // DropField
#include "cmdhf14a.h"
#include "ui.h"
#include "crypto/libpcrypto.h"
static bool VerboseMode = false;
void mfpSetVerboseMode(bool verbose) {
VerboseMode = verbose;
}
static const PlusErrorsElm_t PlusErrors[] = {
{0xFF, ""},
{0x00, "Transfer cannot be granted within the current authentication."},
{0x06, "Access Conditions not fulfilled. Block does not exist, block is not a value block."},
{0x07, "Too many read or write commands in the session or in the transaction."},
{0x08, "Invalid MAC in command or response"},
{0x09, "Block Number is not valid"},
{0x0a, "Invalid block number, not existing block number"},
{0x0b, "The current command code not available at the current card state."},
{0x0c, "Length error"},
{0x0f, "General Manipulation Error. Failure in the operation of the PICC (cannot write to the data block), etc."},
{0x90, "OK"},
};
const char *mfpGetErrorDescription(uint8_t errorCode) {
for (int i = 0; i < ARRAYLEN(PlusErrors); i++)
if (errorCode == PlusErrors[i].Code)
return PlusErrors[i].Description;
return PlusErrors[0].Description;
}
AccessConditions_t MFAccessConditions[] = {
{0x00, "rdAB wrAB incAB dectrAB"},
{0x01, "rdAB dectrAB"},
{0x02, "rdAB"},
{0x03, "rdB wrB"},
{0x04, "rdAB wrB"},
{0x05, "rdB"},
{0x06, "rdAB wrB incB dectrAB"},
{0x07, "none"}
};
AccessConditions_t MFAccessConditionsTrailer[] = {
{0x00, "rdAbyA rdCbyA rdBbyA wrBbyA"},
{0x01, "wrAbyA rdCbyA wrCbyA rdBbyA wrBbyA"},
{0x02, "rdCbyA rdBbyA"},
{0x03, "wrAbyB rdCbyAB wrCbyB wrBbyB"},
{0x04, "wrAbyB rdCbyAB wrBbyB"},
{0x05, "rdCbyAB wrCbyB"},
{0x06, "rdCbyAB"},
{0x07, "rdCbyAB"}
};
const char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data) {
static char StaticNone[] = "none";
uint8_t data1 = ((data[1] >> 4) & 0x0f) >> blockn;
uint8_t data2 = ((data[2]) & 0x0f) >> blockn;
uint8_t data3 = ((data[2] >> 4) & 0x0f) >> blockn;
uint8_t cond = (data1 & 0x01) << 2 | (data2 & 0x01) << 1 | (data3 & 0x01);
if (blockn == 3) {
for (int i = 0; i < ARRAYLEN(MFAccessConditionsTrailer); i++)
if (MFAccessConditionsTrailer[i].cond == cond) {
return MFAccessConditionsTrailer[i].description;
}
} else {
for (int i = 0; i < ARRAYLEN(MFAccessConditions); i++)
if (MFAccessConditions[i].cond == cond) {
return MFAccessConditions[i].description;
}
};
return StaticNone;
};
/*
static int CalculateEncIVCommand(mf4Session_t *session, uint8_t *iv, bool verbose) {
memcpy(&iv[0], &session->TI, 4);
memcpy(&iv[4], &session->R_Ctr, 2);
memcpy(&iv[6], &session->W_Ctr, 2);
memcpy(&iv[8], &session->R_Ctr, 2);
memcpy(&iv[10], &session->W_Ctr, 2);
memcpy(&iv[12], &session->R_Ctr, 2);
memcpy(&iv[14], &session->W_Ctr, 2);
return 0;
}
static int CalculateEncIVResponse(mf4Session *session, uint8_t *iv, bool verbose) {
memcpy(&iv[0], &session->R_Ctr, 2);
memcpy(&iv[2], &session->W_Ctr, 2);
memcpy(&iv[4], &session->R_Ctr, 2);
memcpy(&iv[6], &session->W_Ctr, 2);
memcpy(&iv[8], &session->R_Ctr, 2);
memcpy(&iv[10], &session->W_Ctr, 2);
memcpy(&iv[12], &session->TI, 4);
return 0;
}
*/
int CalculateMAC(mf4Session_t *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose) {
if (!session || !session->Authenticated || !mac || !data || !datalen)
return 1;
memset(mac, 0x00, 8);
uint16_t ctr = session->R_Ctr;
switch (mtype) {
case mtypWriteCmd:
case mtypWriteResp:
ctr = session->W_Ctr;
break;
case mtypReadCmd:
case mtypReadResp:
break;
}
uint8_t macdata[2049] = {data[0], (ctr & 0xFF), (ctr >> 8), 0};
int macdatalen = datalen;
memcpy(&macdata[3], session->TI, 4);
switch (mtype) {
case mtypReadCmd:
memcpy(&macdata[7], &data[1], datalen - 1);
macdatalen = datalen + 6;
break;
case mtypReadResp:
macdata[7] = blockNum;
macdata[8] = 0;
macdata[9] = blockCount;
memcpy(&macdata[10], &data[1], datalen - 1);
macdatalen = datalen + 9;
break;
case mtypWriteCmd:
memcpy(&macdata[7], &data[1], datalen - 1);
macdatalen = datalen + 6;
break;
case mtypWriteResp:
macdatalen = 1 + 6;
break;
}
if (verbose)
PrintAndLogEx(NORMAL, "MAC data[%d]: %s", macdatalen, sprint_hex(macdata, macdatalen));
return aes_cmac8(NULL, session->Kmac, macdata, mac, macdatalen);
}
int MifareAuth4(mf4Session_t *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool dropFieldIfError, bool verbose, bool silentMode) {
uint8_t data[257] = {0};
int datalen = 0;
uint8_t RndA[17] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00};
uint8_t RndB[17] = {0};
if (silentMode)
verbose = false;
if (session)
session->Authenticated = false;
uint8_t cmd1[] = {0x70, keyn[1], keyn[0], 0x00};
int res = ExchangeRAW14a(cmd1, sizeof(cmd1), activateField, true, data, sizeof(data), &datalen, silentMode);
if (res) {
if (!silentMode) PrintAndLogEx(ERR, "Exchande raw error: %d", res);
if (dropFieldIfError) DropField();
return 2;
}
if (verbose)
PrintAndLogEx(INFO, "<phase1: %s", sprint_hex(data, datalen));
if (datalen < 1) {
if (!silentMode) PrintAndLogEx(ERR, "Card response wrong length: %d", datalen);
if (dropFieldIfError) DropField();
return 3;
}
if (data[0] != 0x90) {
if (!silentMode) PrintAndLogEx(ERR, "Card response error: %02x", data[2]);
if (dropFieldIfError) DropField();
return 3;
}
if (datalen != 19) { // code 1b + 16b + crc 2b
if (!silentMode) PrintAndLogEx(ERR, "Card response must be 19 bytes long instead of: %d", datalen);
if (dropFieldIfError) DropField();
return 3;
}
aes_decode(NULL, key, &data[1], RndB, 16);
RndB[16] = RndB[0];
if (verbose)
PrintAndLogEx(INFO, "RndB: %s", sprint_hex(RndB, 16));
uint8_t cmd2[33] = {0};
cmd2[0] = 0x72;
uint8_t raw[32] = {0};
memmove(raw, RndA, 16);
memmove(&raw[16], &RndB[1], 16);
aes_encode(NULL, key, raw, &cmd2[1], 32);
if (verbose)
PrintAndLogEx(INFO, ">phase2: %s", sprint_hex(cmd2, 33));
res = ExchangeRAW14a(cmd2, sizeof(cmd2), false, true, data, sizeof(data), &datalen, silentMode);
if (res) {
if (!silentMode) PrintAndLogEx(ERR, "Exchande raw error: %d", res);
if (dropFieldIfError) DropField();
return 4;
}
if (verbose)
PrintAndLogEx(INFO, "<phase2: %s", sprint_hex(data, datalen));
aes_decode(NULL, key, &data[1], raw, 32);
if (verbose) {
PrintAndLogEx(INFO, "res: %s", sprint_hex(raw, 32));
PrintAndLogEx(INFO, "RndA`: %s", sprint_hex(&raw[4], 16));
}
if (memcmp(&raw[4], &RndA[1], 16)) {
if (!silentMode) PrintAndLogEx(ERR, "\nAuthentication FAILED. rnd is not equal");
if (verbose) {
PrintAndLogEx(ERR, "RndA reader: %s", sprint_hex(&RndA[1], 16));
PrintAndLogEx(ERR, "RndA card: %s", sprint_hex(&raw[4], 16));
}
if (dropFieldIfError) DropField();
return 5;
}
if (verbose) {
PrintAndLogEx(INFO, " TI: %s", sprint_hex(raw, 4));
PrintAndLogEx(INFO, "pic: %s", sprint_hex(&raw[20], 6));
PrintAndLogEx(INFO, "pcd: %s", sprint_hex(&raw[26], 6));
}
uint8_t kenc[16] = {0};
memcpy(&kenc[0], &RndA[11], 5);
memcpy(&kenc[5], &RndB[11], 5);
for (int i = 0; i < 5; i++)
kenc[10 + i] = RndA[4 + i] ^ RndB[4 + i];
kenc[15] = 0x11;
aes_encode(NULL, key, kenc, kenc, 16);
if (verbose) {
PrintAndLogEx(INFO, "kenc: %s", sprint_hex(kenc, 16));
}
uint8_t kmac[16] = {0};
memcpy(&kmac[0], &RndA[7], 5);
memcpy(&kmac[5], &RndB[7], 5);
for (int i = 0; i < 5; i++)
kmac[10 + i] = RndA[0 + i] ^ RndB[0 + i];
kmac[15] = 0x22;
aes_encode(NULL, key, kmac, kmac, 16);
if (verbose) {
PrintAndLogEx(INFO, "kmac: %s", sprint_hex(kmac, 16));
}
if (!leaveSignalON)
DropField();
if (verbose)
PrintAndLogEx(NORMAL, "");
if (session) {
session->Authenticated = true;
session->R_Ctr = 0;
session->W_Ctr = 0;
session->KeyNum = keyn[1] + (keyn[0] << 8);
memmove(session->RndA, RndA, 16);
memmove(session->RndB, RndB, 16);
memmove(session->Key, key, 16);
memmove(session->TI, raw, 4);
memmove(session->PICCap2, &raw[20], 6);
memmove(session->PCDCap2, &raw[26], 6);
memmove(session->Kenc, kenc, 16);
memmove(session->Kmac, kmac, 16);
}
if (verbose)
PrintAndLogEx(INFO, "Authentication OK");
return 0;
}
static int intExchangeRAW14aPlus(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) {
if (VerboseMode)
PrintAndLogEx(INFO, ">>> %s", sprint_hex(datain, datainlen));
int res = ExchangeRAW14a(datain, datainlen, activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen, false);
if (VerboseMode)
PrintAndLogEx(INFO, "<<< %s", sprint_hex(dataout, *dataoutlen));
return res;
}
int MFPWritePerso(uint8_t *keyNum, uint8_t *key, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) {
uint8_t rcmd[3 + 16] = {0xa8, keyNum[1], keyNum[0], 0x00};
memmove(&rcmd[3], key, 16);
return intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
}
int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) {
uint8_t rcmd[1] = {0xaa};
return intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
}
int MFPReadBlock(mf4Session_t *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) {
uint8_t rcmd[4 + 8] = {(plain ? (0x37) : (0x33)), blockNum, 0x00, blockCount};
if (!plain && session)
CalculateMAC(session, mtypReadCmd, blockNum, blockCount, rcmd, 4, &rcmd[4], VerboseMode);
int res = intExchangeRAW14aPlus(rcmd, plain ? 4 : sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
if (res)
return res;
if (session)
session->R_Ctr++;
if (session && mac && *dataoutlen > 11)
CalculateMAC(session, mtypReadResp, blockNum, blockCount, dataout, *dataoutlen - 8 - 2, mac, VerboseMode);
return 0;
}
int MFPWriteBlock(mf4Session_t *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) {
uint8_t rcmd[1 + 2 + 16 + 8] = {0xA3, blockNum, 0x00};
memmove(&rcmd[3], data, 16);
if (session)
CalculateMAC(session, mtypWriteCmd, blockNum, 1, rcmd, 19, &rcmd[19], VerboseMode);
int res = intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
if (res)
return res;
if (session)
session->W_Ctr++;
if (session && mac && *dataoutlen > 3)
CalculateMAC(session, mtypWriteResp, blockNum, 1, dataout, *dataoutlen, mac, VerboseMode);
return 0;
}
int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose) {
uint8_t keyn[2] = {0};
bool plain = false;
uint16_t uKeyNum = 0x4000 + sectorNo * 2 + (keyType ? 1 : 0);
keyn[0] = uKeyNum >> 8;
keyn[1] = uKeyNum & 0xff;
if (verbose)
PrintAndLogEx(INFO, "--sector[%d]:%02x key:%04x", mfNumBlocksPerSector(sectorNo), sectorNo, uKeyNum);
mf4Session_t _session;
int res = MifareAuth4(&_session, keyn, key, true, true, true, verbose, false);
if (res) {
PrintAndLogEx(ERR, "Sector %d authentication error: %d", sectorNo, res);
return res;
}
uint8_t data[250] = {0};
int datalen = 0;
uint8_t mac[8] = {0};
uint8_t firstBlockNo = mfFirstBlockOfSector(sectorNo);
for (int n = firstBlockNo; n < firstBlockNo + mfNumBlocksPerSector(sectorNo); n++) {
res = MFPReadBlock(&_session, plain, n & 0xff, 1, false, true, data, sizeof(data), &datalen, mac);
if (res) {
PrintAndLogEx(ERR, "Sector %d read error: %d", sectorNo, res);
DropField();
return res;
}
if (datalen && data[0] != 0x90) {
PrintAndLogEx(ERR, "Sector %d card read error: %02x %s", sectorNo, data[0], mfpGetErrorDescription(data[0]));
DropField();
return 5;
}
if (datalen != 1 + 16 + 8 + 2) {
PrintAndLogEx(ERR, "Sector %d error returned data length:%d", sectorNo, datalen);
DropField();
return 6;
}
memcpy(&dataout[(n - firstBlockNo) * 16], &data[1], 16);
if (verbose)
PrintAndLogEx(INFO, "data[%03d]: %s", n, sprint_hex(&data[1], 16));
if (memcmp(&data[1 + 16], mac, 8)) {
PrintAndLogEx(WARNING, "WARNING: mac on block %d not equal...", n);
PrintAndLogEx(WARNING, "MAC card: %s", sprint_hex(&data[1 + 16], 8));
PrintAndLogEx(WARNING, "MAC reader: %s", sprint_hex(mac, 8));
if (!verbose)
return 7;
} else {
if (verbose)
PrintAndLogEx(INFO, "MAC: %s", sprint_hex(&data[1 + 16], 8));
}
}
DropField();
return 0;
}
int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) {
uint8_t c[] = {0x3c, 0x00};
return intExchangeRAW14aPlus(c, sizeof(c), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
}
int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) {
uint8_t tmp[20] = {0};
uint8_t c[] = {0x60};
int res = intExchangeRAW14aPlus(c, sizeof(c), activateField, true, tmp, maxdataoutlen, dataoutlen);
if (res != 0) {
DropField();
*dataoutlen = 0;
return res;
}
memcpy(dataout, tmp + 1, (*dataoutlen - 3));
*dataoutlen = 0;
// MFDES_ADDITIONAL_FRAME
if (tmp[0] == 0xAF) {
c[0] = 0xAF;
res = intExchangeRAW14aPlus(c, sizeof(c), false, true, tmp, maxdataoutlen, dataoutlen);
if (res == 0) {
memcpy(dataout + 7, tmp + 1, (*dataoutlen - 3));
// MFDES_ADDITIONAL_FRAME
res = intExchangeRAW14aPlus(c, sizeof(c), false, false, tmp, maxdataoutlen, dataoutlen);
if (res == 0) {
if (tmp[0] == 0x90) {
memcpy(dataout + 7 + 7, tmp + 1, (*dataoutlen - 3));
*dataoutlen = 28;
}
}
}
}
DropField();
return res;
}
// Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards),
// plus evtl. 8 sectors with 16 blocks each (4k cards)
uint8_t mfNumBlocksPerSector(uint8_t sectorNo) {
if (sectorNo < 32)
return 4;
else
return 16;
}
uint8_t mfFirstBlockOfSector(uint8_t sectorNo) {
if (sectorNo < 32)
return sectorNo * 4;
else
return 32 * 4 + (sectorNo - 32) * 16;
}
uint8_t mfSectorTrailer(uint8_t blockNo) {
if (blockNo < 32 * 4) {
return (blockNo | 0x03);
} else {
return (blockNo | 0x0f);
}
}
bool mfIsSectorTrailer(uint8_t blockNo) {
return (blockNo == mfSectorTrailer(blockNo));
}
uint8_t mfSectorNum(uint8_t blockNo) {
if (blockNo < 32 * 4)
return blockNo / 4;
else
return 32 + (blockNo - 32 * 4) / 16;
}

View File

@@ -0,0 +1,74 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2018 Merlok
// Copyright (C) 2018 drHatson
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// iso14443-4 mifare commands
//-----------------------------------------------------------------------------
#ifndef MIFARE4_H
#define MIFARE4_H
#include "common.h"
typedef struct {
bool Authenticated;
uint8_t Key[16];
uint16_t KeyNum;
uint8_t RndA[16];
uint8_t RndB[16];
uint8_t TI[4];
uint8_t PICCap2[6];
uint8_t PCDCap2[6];
uint8_t Kenc[16];
uint8_t Kmac[16];
uint16_t R_Ctr;
uint16_t W_Ctr;
} mf4Session_t;
typedef enum {
mtypReadCmd,
mtypReadResp,
mtypWriteCmd,
mtypWriteResp,
} MACType_t;
typedef struct {
uint8_t cond;
const char *description;
} AccessConditions_t;
typedef struct {
uint8_t Code;
const char *Description;
} PlusErrorsElm_t;
void mfpSetVerboseMode(bool verbose);
const char *mfpGetErrorDescription(uint8_t errorCode);
int CalculateMAC(mf4Session_t *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose);
int MifareAuth4(mf4Session_t *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool dropFieldIfError, bool verbose, bool silentMode);
int MFPWritePerso(uint8_t *keyNum, uint8_t *key, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
int MFPReadBlock(mf4Session_t *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac);
int MFPWriteBlock(mf4Session_t *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac);
int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose);
int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen);
const char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data);
uint8_t mfNumBlocksPerSector(uint8_t sectorNo);
uint8_t mfFirstBlockOfSector(uint8_t sectorNo);
uint8_t mfSectorTrailer(uint8_t blockNo);
bool mfIsSectorTrailer(uint8_t blockNo);
uint8_t mfSectorNum(uint8_t blockNo);
#endif // mifare4.h

View File

@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2017 Merlok
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Mifare default constants
//-----------------------------------------------------------------------------
#include "mifaredefault.h"
#include "commonutil.h" // ARRAYLEN
const char *g_mifare_plus_default_keys[] = {
"ffffffffffffffffffffffffffffffff", // default key
"00000000000000000000000000000000",
"a0a1a2a3a4a5a6a7a0a1a2a3a4a5a6a7", // MAD key
"b0b1b2b3b4b5b6b7b0b1b2b3b4b5b6b7",
"d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7", // NDEF key
"11111111111111111111111111111111",
"22222222222222222222222222222222",
"33333333333333333333333333333333",
"44444444444444444444444444444444",
"55555555555555555555555555555555",
"66666666666666666666666666666666",
"77777777777777777777777777777777",
"88888888888888888888888888888888",
"99999999999999999999999999999999",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"cccccccccccccccccccccccccccccccc",
"dddddddddddddddddddddddddddddddd",
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"000102030405060708090a0b0c0d0e0f",
"0102030405060708090a0b0c0d0e0f10",
"00010203040506070809101112131415",
"01020304050607080910111213141516",
"404142434445464748494a4b4c4d4e4f",
"303132333435363738393a3b3c3d3e3f",
};
size_t g_mifare_plus_default_keys_len = ARRAYLEN(g_mifare_plus_default_keys);

View File

@@ -0,0 +1,50 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2017 Merlok
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Mifare default constants
//-----------------------------------------------------------------------------
#ifndef MIFAREDEFAULT_H__
#define MIFAREDEFAULT_H__
#include "common.h"
static const uint64_t g_mifare_default_keys[] = {
0xffffffffffff, // Default key (first key used by program if no user defined key)
0x000000000000, // Blank key
0xa0a1a2a3a4a5, // NFCForum MAD key
0xb0b1b2b3b4b5,
0xc0c1c2c3c4c5,
0xd0d1d2d3d4d5,
0xaabbccddeeff,
0x1a2b3c4d5e6f,
0x123456789abc,
0x010203040506,
0x123456abcdef,
0xabcdef123456,
0x4d3a99c351dd,
0x1a982c7e459a,
0xd3f7d3f7d3f7, // NDEF public key
0x714c5c886e97,
0x587ee5f9350f,
0xa0478cc39091,
0x533cb6c723f6,
0x8fd0a4f256e9,
0x0000014b5c31,
0xb578f38a5c61,
0x96a301bce267
};
static const uint8_t g_mifare_mad_key[] = {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5};
static const uint8_t g_mifare_ndef_key[] = {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7};
static const uint8_t g_mifarep_mad_key[] = {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7};
static const uint8_t g_mifarep_ndef_key[] = {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7};
extern const char *g_mifare_plus_default_keys[];
extern size_t g_mifare_plus_default_keys_len;
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
// Merlok, 2011, 2019
// people from mifare@nethemba.com, 2010
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// High frequency ISO14443A commands
//-----------------------------------------------------------------------------
#ifndef __MIFARE_HOST_H
#define __MIFARE_HOST_H
#include "common.h"
#include "util.h" // FILE_PATH_SIZE
#define MIFARE_SECTOR_RETRY 10
// mifare tracer flags
#define TRACE_IDLE 0x00
#define TRACE_AUTH1 0x01
#define TRACE_AUTH2 0x02
#define TRACE_AUTH_OK 0x03
#define TRACE_READ_DATA 0x04
#define TRACE_WRITE_OK 0x05
#define TRACE_WRITE_DATA 0x06
#define TRACE_ERROR 0xFF
typedef struct {
union {
struct Crypto1State *slhead;
uint64_t *keyhead;
} head;
union {
struct Crypto1State *sltail;
uint64_t *keytail;
} tail;
uint32_t len;
uint32_t uid;
uint32_t blockNo;
uint32_t keyType;
uint32_t nt_enc;
uint32_t ks1;
} StateList_t;
typedef struct {
uint64_t Key[2];
uint8_t foundKey[2];
} sector_t;
typedef struct {
uint8_t keyA[6];
uint8_t keyB[6];
//uint8_t foundKey[2];
} icesector_t;
extern char logHexFileName[FILE_PATH_SIZE];
#define KEYS_IN_BLOCK ((PM3_CMD_DATA_SIZE - 4) / 6)
#define KEYBLOCK_SIZE (KEYS_IN_BLOCK * 6)
#define CANDIDATE_SIZE (0xFFFF * 6)
int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key);
int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate);
int mfStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey);
int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key);
int mfCheckKeys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk,
uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory);
int mfCheckKeys_file(uint8_t *destfn, uint64_t *key);
int mfKeyBrute(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint64_t *resultkey);
int mfReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data);
int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount);
int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount);
int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth);
int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_t wipecard);
int mfCWipe(uint8_t *uid, uint8_t *atqa, uint8_t *sak);
int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params);
int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params);
int mfTraceInit(uint8_t *tuid, uint8_t uidlen, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile);
int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile);
int isTraceCardEmpty(void);
int isBlockEmpty(int blockN);
int isBlockTrailer(int blockN);
int loadTraceCard(uint8_t *tuid, uint8_t uidlen);
int saveTraceCard(void);
int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len);
int detect_classic_prng(void);
int detect_classic_nackbug(bool verbose);
void detect_classic_magic(void);
int detect_classic_static_nonce(void);
void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted);
#endif

523
client/src/mifare/ndef.c Normal file
View File

@@ -0,0 +1,523 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2019 Merlok
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// NFC Data Exchange Format (NDEF) functions
//-----------------------------------------------------------------------------
#include "ndef.h"
#include <string.h>
#include "ui.h"
#include "util.h" // sprint_hex...
#include "emv/dump.h"
#include "crypto/asn1utils.h"
#include "pm3_cmd.h"
#define STRBOOL(p) ((p) ? "+" : "-")
static const char *TypeNameFormat_s[] = {
"Empty Record",
"Well Known Record",
"MIME Media Record",
"Absolute URI Record",
"External Record",
"Unknown Record",
"Unchanged Record",
"n/a"
};
static const char *ndefSigType_s[] = {
"Not present", // No signature present
"RSASSA_PSS_SHA_1 (1024)", // PKCS_1
"RSASSA_PKCS1_v1_5_WITH_SHA_1 (1024)", // PKCS_1
"DSA-1024",
"ECDSA-P192",
"RSASSA-PSS-2048",
"RSASSA-PKCS1-v1_5-2048",
"DSA-2048",
"ECDSA-P224",
"ECDSA-K233",
"ECDSA-B233",
"ECDSA-P256",
"n/a"
};
static const char *ndefCertificateFormat_s[] = {
"X_509",
"X9_68 (M2M)",
"n/a"
};
static const char *URI_s[] = {
"", // 0x00
"http://www.", // 0x01
"https://www.", // 0x02
"http://", // 0x03
"https://", // 0x04
"tel:", // 0x05
"mailto:", // 0x06
"ftp://anonymous:anonymous@", // 0x07
"ftp://ftp.", // 0x08
"ftps://", // 0x09
"sftp://", // 0x0A
"smb://", // 0x0B
"nfs://", // 0x0C
"ftp://", // 0x0D
"dav://", // 0x0E
"news:", // 0x0F
"telnet://", // 0x10
"imap:", // 0x11
"rtsp://", // 0x12
"urn:", // 0x13
"pop:", // 0x14
"sip:", // 0x15
"sips:", // 0x16
"tftp:", // 0x17
"btspp://", // 0x18
"btl2cap://", // 0x19
"btgoep://", // 0x1A
"tcpobex://", // 0x1B
"irdaobex://", // 0x1C
"file://", // 0x1D
"urn:epc:id:", // 0x1E
"urn:epc:tag:", // 0x1F
"urn:epc:pat:", // 0x20
"urn:epc:raw:", // 0x21
"urn:epc:", // 0x22
"urn:nfc:" // 0x23
};
static uint16_t ndefTLVGetLength(uint8_t *data, size_t *indx) {
uint16_t len = 0;
if (data[0] == 0xff) {
len = (data[1] << 8) + data[2];
*indx += 3;
} else {
len = data[0];
*indx += 1;
}
return len;
}
static int ndefDecodeHeader(uint8_t *data, size_t datalen, NDEFHeader_t *header) {
header->Type = NULL;
header->Payload = NULL;
header->ID = NULL;
header->MessageBegin = data[0] & 0x80;
header->MessageEnd = data[0] & 0x40;
header->ChunkFlag = data[0] & 0x20;
header->ShortRecordBit = data[0] & 0x10;
header->IDLenPresent = data[0] & 0x08;
header->TypeNameFormat = data[0] & 0x07;
header->len = 1 + 1 + (header->ShortRecordBit ? 1 : 4) + (header->IDLenPresent ? 1 : 0); // header + typelen + payloadlen + idlen
if (header->len > datalen)
return PM3_ESOFT;
header->TypeLen = data[1];
header->Type = data + header->len;
header->PayloadLen = (header->ShortRecordBit ? (data[2]) : ((data[2] << 24) + (data[3] << 16) + (data[4] << 8) + data[5]));
if (header->IDLenPresent) {
header->IDLen = (header->ShortRecordBit ? (data[3]) : (data[6]));
} else {
header->IDLen = 0;
}
header->Payload = header->Type + header->TypeLen + header->IDLen;
header->RecLen = header->len + header->TypeLen + header->PayloadLen + header->IDLen;
if (header->RecLen > datalen)
return 3;
return PM3_SUCCESS;
}
static int ndefPrintHeader(NDEFHeader_t *header) {
PrintAndLogEx(INFO, "Header:");
PrintAndLogEx(SUCCESS, "\tMessage Begin: %s", STRBOOL(header->MessageBegin));
PrintAndLogEx(SUCCESS, "\tMessage End: %s", STRBOOL(header->MessageEnd));
PrintAndLogEx(SUCCESS, "\tChunk Flag: %s", STRBOOL(header->ChunkFlag));
PrintAndLogEx(SUCCESS, "\tShort Record Bit: %s", STRBOOL(header->ShortRecordBit));
PrintAndLogEx(SUCCESS, "\tID Len Present: %s", STRBOOL(header->IDLenPresent));
PrintAndLogEx(SUCCESS, "\tType Name Format: [0x%02x] %s", header->TypeNameFormat, TypeNameFormat_s[header->TypeNameFormat]);
PrintAndLogEx(SUCCESS, "\tHeader length : %zu", header->len);
PrintAndLogEx(SUCCESS, "\tType length : %zu", header->TypeLen);
PrintAndLogEx(SUCCESS, "\tPayload length : %zu", header->PayloadLen);
PrintAndLogEx(SUCCESS, "\tID length : %zu", header->IDLen);
PrintAndLogEx(SUCCESS, "\tRecord length : %zu", header->RecLen);
return PM3_SUCCESS;
}
static int ndefDecodeSig1(uint8_t *sig, size_t siglen) {
size_t indx = 1;
uint8_t sigType = sig[indx] & 0x7f;
bool sigURI = sig[indx] & 0x80;
PrintAndLogEx(SUCCESS, "\tsignature type: %s", ((sigType < stNA) ? ndefSigType_s[sigType] : ndefSigType_s[stNA]));
PrintAndLogEx(SUCCESS, "\tsignature uri: %s", (sigURI ? "present" : "not present"));
size_t intsiglen = (sig[indx + 1] << 8) + sig[indx + 2];
// ecdsa 0x04
if (sigType == stECDSA_P192 || sigType == stECDSA_P256) {
indx += 3;
int slen = 24;
if (sigType == stECDSA_P256)
slen = 32;
PrintAndLogEx(SUCCESS, "\tsignature [%zu]: %s", intsiglen, sprint_hex_inrow(&sig[indx], intsiglen));
uint8_t rval[300] = {0};
uint8_t sval[300] = {0};
int res = ecdsa_asn1_get_signature(&sig[indx], intsiglen, rval, sval);
if (!res) {
PrintAndLogEx(SUCCESS, "\t\tr: %s", sprint_hex(rval + 32 - slen, slen));
PrintAndLogEx(SUCCESS, "\t\ts: %s", sprint_hex(sval + 32 - slen, slen));
}
}
indx += intsiglen;
if (sigURI) {
size_t intsigurilen = (sig[indx] << 8) + sig[indx + 1];
indx += 2;
PrintAndLogEx(SUCCESS, "\tsignature uri [%zu]: %.*s", intsigurilen, (int)intsigurilen, &sig[indx]);
indx += intsigurilen;
}
uint8_t certFormat = (sig[indx] >> 4) & 0x07;
uint8_t certCount = sig[indx] & 0x0f;
bool certURI = sig[indx] & 0x80;
PrintAndLogEx(SUCCESS, "\tcertificate format: %s", ((certFormat < sfNA) ? ndefCertificateFormat_s[certFormat] : ndefCertificateFormat_s[sfNA]));
PrintAndLogEx(SUCCESS, "\tcertificates count: %d", certCount);
// print certificates
indx++;
for (int i = 0; i < certCount; i++) {
size_t intcertlen = (sig[indx + 1] << 8) + sig[indx + 2];
indx += 2;
PrintAndLogEx(SUCCESS, "\tcertificate %d [%zu]: %s", i + 1, intcertlen, sprint_hex_inrow(&sig[indx], intcertlen));
indx += intcertlen;
}
// have certificate uri
if ((indx <= siglen) && certURI) {
size_t inturilen = (sig[indx] << 8) + sig[indx + 1];
indx += 2;
PrintAndLogEx(SUCCESS, "\tcertificate uri [%zu]: %.*s", inturilen, (int)inturilen, &sig[indx]);
}
return PM3_SUCCESS;
};
// https://github.com/nfcpy/ndeflib/blob/master/src/ndef/signature.py#L292
static int ndefDecodeSig2(uint8_t *sig, size_t siglen) {
size_t indx = 1;
uint8_t sigType = sig[indx] & 0x7f;
bool sigURI = sig[indx] & 0x80;
indx++;
uint8_t hashType = sig[indx];
indx++;
PrintAndLogEx(SUCCESS, "\tsignature type :\t" _GREEN_("%s"), ((sigType < stNA) ? ndefSigType_s[sigType] : ndefSigType_s[stNA]));
PrintAndLogEx(SUCCESS, "\tsignature uri :\t\t%s", (sigURI ? "present" : "not present"));
PrintAndLogEx(SUCCESS, "\thash type :\t\t%s", ((hashType == 0x02) ? _GREEN_("SHA-256") : _RED_("unknown")));
size_t intsiglen = (sig[indx] << 8) + sig[indx + 1];
indx += 2;
if (sigURI) {
indx += 2;
PrintAndLogEx(SUCCESS, "\tsignature uri [%zu]: %.*s", intsiglen, (int)intsiglen, &sig[indx]);
indx += intsiglen;
} else {
PrintAndLogEx(SUCCESS, "\tsignature [%zu]: %s", intsiglen, sprint_hex_inrow(&sig[indx], intsiglen));
if (sigType == stECDSA_P192 || sigType == stECDSA_P256) {
int slen = intsiglen / 2;
if (slen == 24 || slen == 32) {
PrintAndLogEx(SUCCESS, "\tsignature : " _GREEN_("ECDSA-%d"), slen * 8);
PrintAndLogEx(SUCCESS, "\t\tr: %s", sprint_hex(&sig[indx], slen));
PrintAndLogEx(SUCCESS, "\t\ts: %s", sprint_hex(&sig[indx + slen], slen));
}
} else {
PrintAndLogEx(INFO, "\tsignature: unknown type");
}
indx += intsiglen;
}
uint8_t certFormat = (sig[indx] >> 4) & 0x07;
uint8_t certCount = sig[indx] & 0x0f;
bool certURI = sig[indx] & 0x80;
PrintAndLogEx(SUCCESS, "\tcertificate format : " _GREEN_("%s"), ((certFormat < sfNA) ? ndefCertificateFormat_s[certFormat] : ndefCertificateFormat_s[sfNA]));
PrintAndLogEx(SUCCESS, "\tcertificates count : %d", certCount);
// print certificates
indx++;
for (int i = 0; i < certCount; i++) {
size_t intcertlen = (sig[indx + 1] << 8) + sig[indx + 2];
indx += 2;
PrintAndLogEx(SUCCESS, "\tcertificate %d [%zu]: %s", i + 1, intcertlen, sprint_hex_inrow(&sig[indx], intcertlen));
indx += intcertlen;
}
// have certificate uri
if ((indx <= siglen) && certURI) {
size_t inturilen = (sig[indx] << 8) + sig[indx + 1];
indx += 2;
PrintAndLogEx(SUCCESS, "\tcertificate uri [%zu]: %.*s", inturilen, (int)inturilen, &sig[indx]);
}
return PM3_SUCCESS;
};
static int ndefDecodeSig(uint8_t *sig, size_t siglen) {
PrintAndLogEx(SUCCESS, "\tsignature version : \t" _GREEN_("0x%02x"), sig[0]);
if (sig[0] != 0x01 && sig[0] != 0x20) {
PrintAndLogEx(ERR, "signature version unknown.");
return PM3_ESOFT;
}
if (sig[0] == 0x01)
return ndefDecodeSig1(sig, siglen);
if (sig[0] == 0x20)
return ndefDecodeSig2(sig, siglen);
return PM3_ESOFT;
}
static int ndefDecodePayload(NDEFHeader_t *ndef) {
switch (ndef->TypeNameFormat) {
case tnfWellKnownRecord:
PrintAndLogEx(INFO, "Well Known Record");
PrintAndLogEx(INFO, "\ttype\t: %.*s", (int)ndef->TypeLen, ndef->Type);
if (!strncmp((char *)ndef->Type, "T", ndef->TypeLen)) {
uint8_t utf8 = (ndef->Payload[0] >> 7);
uint8_t lc_len = ndef->Payload[0] & 0x3F;
PrintAndLogEx(INFO,
"\tUTF %d\t: " _GREEN_("%.*s") ", " _GREEN_("%.*s"),
(utf8 == 0) ? 8 : 16,
lc_len,
ndef->Payload + 1,
(int)ndef->PayloadLen - 1 - lc_len,
ndef->Payload + 1 + lc_len
);
}
if (!strncmp((char *)ndef->Type, "U", ndef->TypeLen)) {
PrintAndLogEx(INFO
, "\turi\t: " _GREEN_("%s%.*s")
, (ndef->Payload[0] <= 0x23 ? URI_s[ndef->Payload[0]] : "[err]")
, (int)(ndef->PayloadLen - 1)
, &ndef->Payload[1]
);
}
if (!strncmp((char *)ndef->Type, "Sig", ndef->TypeLen)) {
ndefDecodeSig(ndef->Payload, ndef->PayloadLen);
}
break;
case tnfAbsoluteURIRecord:
PrintAndLogEx(INFO, "Absolute URI Record");
PrintAndLogEx(INFO, "\ttype : %.*s", (int)ndef->TypeLen, ndef->Type);
PrintAndLogEx(INFO, "\tpayload : %.*s", (int)ndef->PayloadLen, ndef->Payload);
break;
case tnfEmptyRecord:
PrintAndLogEx(INFO, "Empty Record");
PrintAndLogEx(INFO, "\t -to be impl-");
break;
case tnfMIMEMediaRecord:
PrintAndLogEx(INFO, "MIME Media Record");
PrintAndLogEx(INFO, "\t -to be impl-");
break;
case tnfExternalRecord:
PrintAndLogEx(INFO, "External Record");
PrintAndLogEx(INFO, "\t -to be impl-");
break;
case tnfUnchangedRecord:
PrintAndLogEx(INFO, "Unchanged Record");
PrintAndLogEx(INFO, "\t -to be impl-");
break;
case tnfUnknownRecord:
PrintAndLogEx(INFO, "Unknown Record");
PrintAndLogEx(INFO, "\t -to be impl-");
break;
}
return PM3_SUCCESS;
}
static int ndefRecordDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen) {
NDEFHeader_t NDEFHeader = {0};
int res = ndefDecodeHeader(ndefRecord, ndefRecordLen, &NDEFHeader);
if (res != PM3_SUCCESS)
return res;
ndefPrintHeader(&NDEFHeader);
if (NDEFHeader.TypeLen) {
PrintAndLogEx(INFO, "Type data:");
dump_buffer(NDEFHeader.Type, NDEFHeader.TypeLen, stdout, 1);
}
if (NDEFHeader.IDLen) {
PrintAndLogEx(INFO, "ID data:");
dump_buffer(NDEFHeader.ID, NDEFHeader.IDLen, stdout, 1);
}
if (NDEFHeader.PayloadLen) {
PrintAndLogEx(INFO, "Payload data:");
dump_buffer(NDEFHeader.Payload, NDEFHeader.PayloadLen, stdout, 1);
if (NDEFHeader.TypeLen)
ndefDecodePayload(&NDEFHeader);
}
return PM3_SUCCESS;
}
int NDEFRecordsDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen) {
bool firstRec = true;
size_t len = 0;
size_t counter = 0;
while (len < ndefRecordLen) {
counter++;
NDEFHeader_t NDEFHeader = {0};
int res = ndefDecodeHeader(&ndefRecord[len], ndefRecordLen - len, &NDEFHeader);
if (res != PM3_SUCCESS)
return res;
if (firstRec) {
if (!NDEFHeader.MessageBegin) {
PrintAndLogEx(ERR, "NDEF first record have MessageBegin = false!");
return PM3_ESOFT;
}
firstRec = false;
}
if (NDEFHeader.MessageEnd && len + NDEFHeader.RecLen != ndefRecordLen) {
PrintAndLogEx(ERR, "NDEF records have wrong length. Must be %zu, calculated %zu", ndefRecordLen, len + NDEFHeader.RecLen);
return PM3_ESOFT;
}
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(SUCCESS, "Record " _YELLOW_("%zu"), counter);
PrintAndLogEx(INFO, "-----------------------------------------------------");
ndefRecordDecodeAndPrint(&ndefRecord[len], NDEFHeader.RecLen);
len += NDEFHeader.RecLen;
if (NDEFHeader.MessageEnd)
break;
}
return PM3_SUCCESS;
}
// http://apps4android.org/nfc-specifications/NFCForum-TS-Type-2-Tag_1.1.pdf
int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose) {
size_t indx = 0;
PrintAndLogEx(INFO, "");
PrintAndLogEx(INFO, "NDEF parsing");
while (indx < ndefLen) {
PrintAndLogEx(INFO, "-----------------------------------------------------");
switch (ndef[indx]) {
case 0x00: {
indx++;
uint16_t len = ndefTLVGetLength(&ndef[indx], &indx);
PrintAndLogEx(SUCCESS, "-- NDEF NULL block.");
if (len)
PrintAndLogEx(WARNING, "NDEF NULL block size must be 0, got %d bytes", len);
indx += len;
break;
}
case 0x01: {
indx++;
uint16_t len = ndefTLVGetLength(&ndef[indx], &indx);
PrintAndLogEx(INFO, "-- NDEF Lock Control.");
if (len != 3) {
PrintAndLogEx(WARNING, "NDEF Lock Control block size must be 3 instead of %d.", len);
} else {
uint8_t PagesAddr = (ndef[indx] >> 4) & 0x0f;
uint8_t ByteOffset = ndef[indx] & 0x0f;
uint8_t Size = ndef[indx + 1];
uint8_t BytesLockedPerLockBit = (ndef[indx + 2] >> 4) & 0x0f;
uint8_t BytesPerPage = ndef[indx + 2] & 0x0f;
PrintAndLogEx(SUCCESS, "PagesAddr. number of pages: %d", PagesAddr);
PrintAndLogEx(SUCCESS, "ByteOffset. number of bytes: %d", ByteOffset);
PrintAndLogEx(SUCCESS, "Size. size in bits of the lock area: %d. bytes approx: %d", Size, Size / 8);
PrintAndLogEx(SUCCESS, "BytesPerPage. number of bytes per page: %d", BytesPerPage);
PrintAndLogEx(SUCCESS, "BytesLockedPerLockBit. number of bytes that each dynamic lock bit is able to lock: %d", BytesLockedPerLockBit);
}
indx += len;
break;
}
case 0x02: {
indx++;
uint16_t len = ndefTLVGetLength(&ndef[indx], &indx);
PrintAndLogEx(INFO, "-- NDEF Memory Control.");
if (len != 3) {
PrintAndLogEx(WARNING, "NDEF Memory Control block size must be 3 instead of %d.", len);
} else {
uint8_t PagesAddr = (ndef[indx] >> 4) & 0x0f;
uint8_t ByteOffset = ndef[indx] & 0x0f;
uint8_t Size = ndef[indx + 1];
uint8_t BytesPerPage = ndef[indx + 2] & 0x0f;
PrintAndLogEx(SUCCESS, "PagesAddr. number of pages: %d", PagesAddr);
PrintAndLogEx(SUCCESS, "ByteOffset. number of bytes: %d", ByteOffset);
PrintAndLogEx(SUCCESS, "Size. size in bits of the reserved area: %d. bytes approx: %d", Size, Size / 8);
PrintAndLogEx(SUCCESS, "BytesPerPage. number of bytes per page: %d", BytesPerPage);
}
indx += len;
break;
}
case 0x03: {
indx++;
uint16_t len = ndefTLVGetLength(&ndef[indx], &indx);
PrintAndLogEx(SUCCESS, "Found NDEF message (%d bytes)", len);
int res = NDEFRecordsDecodeAndPrint(&ndef[indx], len);
if (res != PM3_SUCCESS)
return res;
indx += len;
break;
}
case 0xfd: {
indx++;
uint16_t len = ndefTLVGetLength(&ndef[indx], &indx);
PrintAndLogEx(SUCCESS, "-- NDEF proprietary info. Skipped %d bytes.", len);
indx += len;
break;
}
case 0xfe: {
PrintAndLogEx(SUCCESS, "-- NDEF Terminator. Done.");
return PM3_SUCCESS;
}
default: {
PrintAndLogEx(ERR, "unknown tag 0x%02x", ndef[indx]);
return PM3_ESOFT;
}
}
}
return PM3_SUCCESS;
}

68
client/src/mifare/ndef.h Normal file
View File

@@ -0,0 +1,68 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2019 Merlok
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// NFC Data Exchange Format (NDEF) functions
//-----------------------------------------------------------------------------
#ifndef _NDEF_H_
#define _NDEF_H_
#include "common.h"
typedef enum {
tnfEmptyRecord = 0x00,
tnfWellKnownRecord = 0x01,
tnfMIMEMediaRecord = 0x02,
tnfAbsoluteURIRecord = 0x03,
tnfExternalRecord = 0x04,
tnfUnknownRecord = 0x05,
tnfUnchangedRecord = 0x06
} TypeNameFormat_t;
typedef enum {
stNotPresent = 0x00,
stRSASSA_PSS_SHA_1 = 0x01,
stRSASSA_PKCS1_v1_5_WITH_SHA_1 = 0x02,
stDSA_1024 = 0x03,
stECDSA_P192 = 0x04,
stRSASSA_PSS_2048 = 0x05,
stRSASSA_PKCS1_v1_5_2048 = 0x06,
stDSA_2048 = 0x07,
stECDSA_P224 = 0x08,
stECDSA_K233 = 0x09,
stECDSA_B233 = 0x0a,
stECDSA_P256 = 0x0b,
stNA = 0x0c
} ndefSigType_t;
typedef enum {
sfX_509 = 0x00,
sfX9_68 = 0x01,
sfNA = 0x02
} ndefCertificateFormat_t;
typedef struct {
bool MessageBegin;
bool MessageEnd;
bool ChunkFlag;
bool ShortRecordBit;
bool IDLenPresent;
TypeNameFormat_t TypeNameFormat;
size_t TypeLen;
size_t PayloadLen;
size_t IDLen;
size_t len;
size_t RecLen;
uint8_t *Type;
uint8_t *Payload;
uint8_t *ID;
} NDEFHeader_t;
int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose);
int NDEFRecordsDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen);
#endif // _NDEF_H_