Merge pull request #37 from RfidResearchGroup/master

Update
This commit is contained in:
mwalker33 2020-04-14 07:56:17 +10:00 committed by GitHub
commit a1976fd6fe
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 2663 additions and 1301 deletions

View file

@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file.
This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log...
## [unreleased][unreleased]
- Added CreateStdFile command to Mifare `hf mfdes` (@bkerler)
- Rework des/3des/3k3des/aes auth. Port to mbedtls crypto library on device (@bkerler)
- Port 'hf mfdes' Authentification to CommandNG structure, fix auth session key (@bkerler)
- Updates `hf mfdes` functions, improved logging and added new commands (@bkerler)
- Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u)

View file

@ -26,10 +26,10 @@ APP_CFLAGS = $(PLATFORM_DEFS) \
SRC_LF = lfops.c lfsampling.c pcf7931.c lfdemod.c lfadc.c
SRC_ISO15693 = iso15693.c iso15693tools.c
SRC_ISO14443a = iso14443a.c mifareutil.c mifarecmd.c epa.c mifaresim.c
#UNUSED: mifaresniff.c desfire_crypto.c
#UNUSED: mifaresniff.c
SRC_ISO14443b = iso14443b.c
SRC_FELICA = felica.c
SRC_CRAPTO1 = crypto1.c des.c desfire_key.c mifaredesfire.c aes.c platform_util.c
SRC_CRAPTO1 = crypto1.c des.c desfire_crypto.c mifaredesfire.c aes.c platform_util.c
SRC_CRC = crc.c crc16.c crc32.c
SRC_ICLASS = iclass.c optimized_cipher.c
SRC_LEGIC = legicrf.c legicrfsim.c legic_prng.c

View file

@ -1,497 +0,0 @@
/* des.c */
/*
This file is part of the ARM-Crypto-Lib.
Copyright (C) 2006-2010 Daniel Otte (daniel.otte@rub.de)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file des.c
* \author Daniel Otte
* \email daniel.otte@rub.de
* \date 2007-06-16
* \brief DES and EDE-DES implementation
* \license GPLv3 or later
*
*/
#include "des.h"
#include "string.h"
const uint8_t sbox[256] = {
/* S-box 1 */
0xE4, 0xD1, 0x2F, 0xB8, 0x3A, 0x6C, 0x59, 0x07,
0x0F, 0x74, 0xE2, 0xD1, 0xA6, 0xCB, 0x95, 0x38,
0x41, 0xE8, 0xD6, 0x2B, 0xFC, 0x97, 0x3A, 0x50,
0xFC, 0x82, 0x49, 0x17, 0x5B, 0x3E, 0xA0, 0x6D,
/* S-box 2 */
0xF1, 0x8E, 0x6B, 0x34, 0x97, 0x2D, 0xC0, 0x5A,
0x3D, 0x47, 0xF2, 0x8E, 0xC0, 0x1A, 0x69, 0xB5,
0x0E, 0x7B, 0xA4, 0xD1, 0x58, 0xC6, 0x93, 0x2F,
0xD8, 0xA1, 0x3F, 0x42, 0xB6, 0x7C, 0x05, 0xE9,
/* S-box 3 */
0xA0, 0x9E, 0x63, 0xF5, 0x1D, 0xC7, 0xB4, 0x28,
0xD7, 0x09, 0x34, 0x6A, 0x28, 0x5E, 0xCB, 0xF1,
0xD6, 0x49, 0x8F, 0x30, 0xB1, 0x2C, 0x5A, 0xE7,
0x1A, 0xD0, 0x69, 0x87, 0x4F, 0xE3, 0xB5, 0x2C,
/* S-box 4 */
0x7D, 0xE3, 0x06, 0x9A, 0x12, 0x85, 0xBC, 0x4F,
0xD8, 0xB5, 0x6F, 0x03, 0x47, 0x2C, 0x1A, 0xE9,
0xA6, 0x90, 0xCB, 0x7D, 0xF1, 0x3E, 0x52, 0x84,
0x3F, 0x06, 0xA1, 0xD8, 0x94, 0x5B, 0xC7, 0x2E,
/* S-box 5 */
0x2C, 0x41, 0x7A, 0xB6, 0x85, 0x3F, 0xD0, 0xE9,
0xEB, 0x2C, 0x47, 0xD1, 0x50, 0xFA, 0x39, 0x86,
0x42, 0x1B, 0xAD, 0x78, 0xF9, 0xC5, 0x63, 0x0E,
0xB8, 0xC7, 0x1E, 0x2D, 0x6F, 0x09, 0xA4, 0x53,
/* S-box 6 */
0xC1, 0xAF, 0x92, 0x68, 0x0D, 0x34, 0xE7, 0x5B,
0xAF, 0x42, 0x7C, 0x95, 0x61, 0xDE, 0x0B, 0x38,
0x9E, 0xF5, 0x28, 0xC3, 0x70, 0x4A, 0x1D, 0xB6,
0x43, 0x2C, 0x95, 0xFA, 0xBE, 0x17, 0x60, 0x8D,
/* S-box 7 */
0x4B, 0x2E, 0xF0, 0x8D, 0x3C, 0x97, 0x5A, 0x61,
0xD0, 0xB7, 0x49, 0x1A, 0xE3, 0x5C, 0x2F, 0x86,
0x14, 0xBD, 0xC3, 0x7E, 0xAF, 0x68, 0x05, 0x92,
0x6B, 0xD8, 0x14, 0xA7, 0x95, 0x0F, 0xE2, 0x3C,
/* S-box 8 */
0xD2, 0x84, 0x6F, 0xB1, 0xA9, 0x3E, 0x50, 0xC7,
0x1F, 0xD8, 0xA3, 0x74, 0xC5, 0x6B, 0x0E, 0x92,
0x7B, 0x41, 0x9C, 0xE2, 0x06, 0xAD, 0xF3, 0x58,
0x21, 0xE7, 0x4A, 0x8D, 0xFC, 0x90, 0x35, 0x6B
};
const uint8_t e_permtab[] = {
4, 6, /* 4 bytes in 6 bytes out*/
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1
};
const uint8_t p_permtab[] = {
4, 4, /* 32 bit -> 32 bit */
16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25
};
const uint8_t ip_permtab[] = {
8, 8, /* 64 bit -> 64 bit */
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
};
const uint8_t inv_ip_permtab[] = {
8, 8, /* 64 bit -> 64 bit */
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};
const uint8_t pc1_permtab[] = {
8, 7, /* 64 bit -> 56 bit*/
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
};
const uint8_t pc2_permtab[] = {
7, 6, /* 56 bit -> 48 bit */
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
};
const uint8_t splitin6bitword_permtab[] = {
8, 8, /* 64 bit -> 64 bit */
64, 64, 1, 6, 2, 3, 4, 5,
64, 64, 7, 12, 8, 9, 10, 11,
64, 64, 13, 18, 14, 15, 16, 17,
64, 64, 19, 24, 20, 21, 22, 23,
64, 64, 25, 30, 26, 27, 28, 29,
64, 64, 31, 36, 32, 33, 34, 35,
64, 64, 37, 42, 38, 39, 40, 41,
64, 64, 43, 48, 44, 45, 46, 47
};
const uint8_t shiftkey_permtab[] = {
7, 7, /* 56 bit -> 56 bit */
2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 1,
30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 29
};
const uint8_t shiftkeyinv_permtab[] = {
7, 7,
28, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27,
56, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55
};
/*
1 0
1 0
2 1
2 1
2 1
2 1
2 1
2 1
----
1 0
2 1
2 1
2 1
2 1
2 1
2 1
1 0
*/
#define ROTTABLE 0x7EFC
#define ROTTABLE_INV 0x3F7E
/******************************************************************************/
void permute(const uint8_t *ptable, const uint8_t *in, uint8_t *out) {
uint8_t ob; /* in-bytes and out-bytes */
uint8_t byte, bit; /* counter for bit and byte */
ob = ptable[1];
ptable = &(ptable[2]);
for (byte = 0; byte < ob; ++byte) {
uint8_t t = 0;
for (bit = 0; bit < 8; ++bit) {
uint8_t x = *ptable++ - 1;
t <<= 1;
if ((in[x / 8]) & (0x80 >> (x % 8))) {
t |= 0x01;
}
}
out[byte] = t;
}
}
/******************************************************************************/
void changeendian32(uint32_t *a) {
*a = (*a & 0x000000FF) << 24 |
(*a & 0x0000FF00) << 8 |
(*a & 0x00FF0000) >> 8 |
(*a & 0xFF000000) >> 24;
}
/******************************************************************************/
static inline
void shiftkey(uint8_t *key) {
uint8_t k[7];
memcpy(k, key, 7);
permute((uint8_t *)shiftkey_permtab, k, key);
}
/******************************************************************************/
static inline
void shiftkey_inv(uint8_t *key) {
uint8_t k[7];
memcpy(k, key, 7);
permute((uint8_t *)shiftkeyinv_permtab, k, key);
}
/******************************************************************************/
static inline
uint64_t splitin6bitwords(uint64_t a) {
uint64_t ret = 0;
a &= 0x0000ffffffffffffLL;
permute((uint8_t *)splitin6bitword_permtab, (uint8_t *)&a, (uint8_t *)&ret);
return ret;
}
/******************************************************************************/
static inline
uint8_t substitute(uint8_t a, uint8_t *sbp) {
uint8_t x;
x = sbp[a >> 1];
x = (a & 1) ? x & 0x0F : x >> 4;
return x;
}
/******************************************************************************/
uint32_t des_f(uint32_t r, uint8_t *kr) {
uint8_t i;
uint32_t t = 0, ret;
uint64_t data = 0;
uint8_t *sbp; /* sboxpointer */
permute((uint8_t *)e_permtab, (uint8_t *)&r, (uint8_t *)&data);
for (i = 0; i < 6; ++i)
((uint8_t *)&data)[i] ^= kr[i];
/* Sbox substitution */
data = splitin6bitwords(data);
sbp = (uint8_t *)sbox;
for (i = 0; i < 8; ++i) {
uint8_t x;
x = substitute(((uint8_t *)&data)[i], sbp);
t <<= 4;
t |= x;
sbp += 32;
}
changeendian32(&t);
permute((uint8_t *)p_permtab, (uint8_t *)&t, (uint8_t *)&ret);
return ret;
}
/******************************************************************************/
typedef struct {
union {
uint8_t v8[8];
uint32_t v32[2];
} d;
} data_t;
#define R (data.d.v32[1])
#define L (data.d.v32[0])
void des_enc(void *out, const void *in, const void *key) {
uint8_t kr[6], k[7];
uint8_t i;
data_t data;
permute((uint8_t *)ip_permtab, (uint8_t *)in, data.d.v8);
permute((uint8_t *)pc1_permtab, (const uint8_t *)key, k);
for (i = 0; i < 8; ++i) {
shiftkey(k);
if (ROTTABLE & ((1 << ((i << 1) + 0))))
shiftkey(k);
permute((uint8_t *)pc2_permtab, k, kr);
L ^= des_f(R, kr);
shiftkey(k);
if (ROTTABLE & ((1 << ((i << 1) + 1))))
shiftkey(k);
permute((uint8_t *)pc2_permtab, k, kr);
R ^= des_f(L, kr);
}
/* L <-> R*/
R ^= L;
L ^= R;
R ^= L;
permute((uint8_t *)inv_ip_permtab, data.d.v8, (uint8_t *)out);
}
/******************************************************************************/
void des_dec(void *out, const void *in, const uint8_t *key) {
uint8_t kr[6], k[7];
int8_t i;
data_t data;
permute((uint8_t *)ip_permtab, (uint8_t *)in, data.d.v8);
permute((uint8_t *)pc1_permtab, (const uint8_t *)key, k);
for (i = 7; i >= 0; --i) {
permute((uint8_t *)pc2_permtab, k, kr);
L ^= des_f(R, kr);
shiftkey_inv(k);
if (ROTTABLE & ((1 << ((i << 1) + 1)))) {
shiftkey_inv(k);
}
permute((uint8_t *)pc2_permtab, k, kr);
R ^= des_f(L, kr);
shiftkey_inv(k);
if (ROTTABLE & ((1 << ((i << 1) + 0)))) {
shiftkey_inv(k);
}
}
/* L <-> R*/
R ^= L;
L ^= R;
R ^= L;
permute((uint8_t *)inv_ip_permtab, data.d.v8, (uint8_t *)out);
}
/******************************************************************************/
void tdes_enc(void *out, void *in, const void *key) {
des_enc(out, in, (uint8_t *)key + 0);
des_dec(out, out, (uint8_t *)key + 8);
des_enc(out, out, (uint8_t *)key + 16);
}
/******************************************************************************/
void tdes_dec(void *out, void *in, const uint8_t *key) {
des_dec(out, in, (uint8_t *)key + 16);
des_enc(out, out, (uint8_t *)key + 8);
des_dec(out, out, (uint8_t *)key + 0);
}
void tdes_2key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) {
if (length % 8) return;
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);
des_dec(tout, tin, (uint8_t *)key + 0);
des_enc(tout, tout, (uint8_t *)key + 8);
des_dec(tout, tout, (uint8_t *)key + 0);
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_2key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) {
if (length % 8) return;
uint8_t i;
uint8_t *tin = (uint8_t *) in;
uint8_t *tout = (uint8_t *) out;
while (length > 0) {
for (i = 0; i < 8; i++)
tout[i] = (unsigned char)(tin[i] ^ iv[i]);
des_enc(tout, tin, (uint8_t *)key + 0);
des_dec(tout, tout, (uint8_t *)key + 8);
des_enc(tout, tout, (uint8_t *)key + 0);
memcpy(iv, tout, 8);
tin += 8;
tout += 8;
length -= 8;
}
}
void tdes_3key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) {
if (length % 8) return;
uint8_t i;
uint8_t *tin = (uint8_t *) in;
uint8_t *tout = (uint8_t *) out;
while (length > 0) {
for (i = 0; i < 8; i++)
tout[i] = (unsigned char)(tin[i] ^ iv[i]);
des_enc(tout, tin, (uint8_t *)key + 0);
des_dec(tout, tout, (uint8_t *)key + 8);
des_enc(tout, tout, (uint8_t *)key + 16);
memcpy(iv, tout, 8);
tin += 8;
tout += 8;
length -= 8;
}
}
void tdes_3key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) {
if (length % 8) return;
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);
des_dec(tout, tin, (uint8_t *)key + 0);
des_enc(tout, tout, (uint8_t *)key + 8);
des_dec(tout, tout, (uint8_t *)key + 16);
for (i = 0; i < 8; i++)
tout[i] = (unsigned char)(tout[i] ^ iv[i]);
memcpy(iv, temp, 8);
tin += 8;
tout += 8;
length -= 8;
}
}
/******************************************************************************/

View file

@ -1,116 +0,0 @@
/* des.h */
/*
This file is part of the ARM-Crypto-Lib.
Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file des.h
* \author Daniel Otte
* \date 2007-06-16
* \brief des and tdes declarations
* \license GPLv3 or later
*
*/
#ifndef __DES_H_
#define __DES_H_
#include "common.h"
/* the FIPS 46-3 (1999-10-25) name for triple DES is triple data encryption algorithm so TDEA.
* Also we only implement the three key mode */
/** \def tdea_enc
* \brief defining an alias for void tdes_enc(void* out, const void* in, const void* key)
*/
/** \def tdea_dec
* \brief defining an alias for void tdes_dec(void* out, const void* in, const void* key)
*/
#define tdea_enc tdes_enc
#define tdea_dec tdes_dec
/** \fn void des_enc(void* out, const void* in, const void* key)
* \brief encrypt a block with DES
*
* This function encrypts a block of 64 bits (8 bytes) with the DES algorithm.
* Key expansion is done automatically. The key is 64 bits long, but note that
* only 56 bits are used (the LSB of each byte is dropped). The input and output
* blocks may overlap.
*
* \param out pointer to the block (64 bit = 8 byte) where the ciphertext is written to
* \param in pointer to the block (64 bit = 8 byte) where the plaintext is read from
* \param key pointer to the key (64 bit = 8 byte)
*/
void des_enc(void *out, const void *in, const void *key);
/** \fn void des_dec(void* out, const void* in, const void* key)
* \brief decrypt a block with DES
*
* This function decrypts a block of 64 bits (8 bytes) with the DES algorithm.
* Key expansion is done automatically. The key is 64 bits long, but note that
* only 56 bits are used (the LSB of each byte is dropped). The input and output
* blocks may overlap.
*
* \param out pointer to the block (64 bit = 8 byte) where the plaintext is written to
* \param in pointer to the block (64 bit = 8 byte) where the ciphertext is read from
* \param key pointer to the key (64 bit = 8 byte)
*/
//void des_dec(void* out, const void* in, const void* key);
void des_dec(void *out, const void *in, const uint8_t *key);
/** \fn void tdes_enc(void* out, const void* in, const void* key)
* \brief encrypt a block with Tripple-DES
*
* This function encrypts a block of 64 bits (8 bytes) with the Tripple-DES (EDE)
* algorithm. Key expansion is done automatically. The key is 192 bits long, but
* note that only 178 bits are used (the LSB of each byte is dropped). The input
* and output blocks may overlap.
*
* \param out pointer to the block (64 bit = 8 byte) where the ciphertext is written to
* \param in pointer to the block (64 bit = 8 byte) where the plaintext is read from
* \param key pointer to the key (192 bit = 24 byte)
*/
//void tdes_enc(void* out, const void* in, const void* key);
void tdes_enc(void *out, void *in, const void *key);
/** \fn void tdes_dec(void* out, const void* in, const void* key)
* \brief decrypt a block with Tripple-DES
*
* This function decrypts a block of 64 bits (8 bytes) with the Tripple-DES (EDE)
* algorithm. Key expansion is done automatically. The key is 192 bits long, but
* note that only 178 bits are used (the LSB of each byte is dropped). The input
* and output blocks may overlap.
*
* \param out pointer to the block (64 bit = 8 byte) where the plaintext is written to
* \param in pointer to the block (64 bit = 8 byte) where the ciphertext is read from
* \param key pointer to the key (192 bit = 24 byte)
*/
//void tdes_dec(void* out, const void* in, const void* key);
void tdes_dec(void *out, void *in, const uint8_t *key);
void tdes_2key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]);
void tdes_2key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]);
void tdes_3key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]);
void tdes_3key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]);
// Copied from des.h in desfire imp.
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 */
#endif /*DES_H_*/

View file

@ -25,13 +25,221 @@
* Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication
* May 2005
*/
#include "desfire_crypto.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "desfire_crypto_disabled.h"
#include "commonutil.h"
#include "crc32.h"
#include "crc.h"
#include "crc16.h" // crc16 ccitt
#include "printf.h"
#include "desfire.h"
#include "iso14443a.h"
#include "mbedtls/aes.h"
#include "dbprint.h"
#ifndef AddCrc14A
# define AddCrc14A(data, len) compute_crc(CRC_14443_A, (data), (len), (data)+(len), (data)+(len)+1)
#endif
static mbedtls_des_context ctx;
static mbedtls_des3_context ctx3;
static mbedtls_aes_context actx;
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);
@ -449,7 +657,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes
do {
uint16_t crc_16 = 0x00;
uint32_t crc;
uint32_t crc = 0x00;
switch (DESFIRE(tag)->authentication_scheme) {
case AS_LEGACY:
AddCrc14A((uint8_t *)res, end_crc_pos);
@ -520,7 +728,6 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes
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 {
@ -534,40 +741,44 @@ void mifare_cypher_single_block(desfirekey_t key, uint8_t *data, uint8_t *ivect,
switch (operation) {
case MCO_ENCYPHER:
//DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT);
des_enc(edata, data, key->data);
des_encrypt(edata, data, key->data);
break;
case MCO_DECYPHER:
//DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT);
des_dec(edata, data, key->data);
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);
tdes_enc(edata, data, key->data);
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);
tdes_dec(data, edata, key->data);
break;
}
break;
case T_3K3DES:
switch (operation) {
case MCO_ENCYPHER:
tdes_enc(edata, data, key->data);
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:
tdes_dec(data, edata, key->data);
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);
@ -577,19 +788,15 @@ void mifare_cypher_single_block(desfirekey_t key, uint8_t *data, uint8_t *ivect,
case T_AES:
switch (operation) {
case MCO_ENCYPHER: {
mbedtls_aes_context ctx;
mbedtls_aes_init(&ctx);
mbedtls_aes_setkey_enc(&ctx, key->data, 128);
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, sizeof(edata), ivect, data, edata);
mbedtls_aes_free(&ctx);
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);
break;
}
case MCO_DECYPHER: {
mbedtls_aes_context ctx;
mbedtls_aes_init(&ctx);
mbedtls_aes_setkey_dec(&ctx, key->data, 128);
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, sizeof(edata), ivect, edata, data);
mbedtls_aes_free(&ctx);
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);
break;
}
}

132
armsrc/desfire_crypto.h Normal file
View file

@ -0,0 +1,132 @@
#ifndef __DESFIRE_CRYPTO_H
#define __DESFIRE_CRYPTO_H
#include "common.h"
#include "mifare.h"
#include "mbedtls/aes.h"
#include "mbedtls/des.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;
void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc);
void crc32_append(uint8_t *data, const size_t len);
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

View file

@ -1,18 +0,0 @@
#ifndef __DESFIRE_CRYPTO_H
#define __DESFIRE_CRYPTO_H
#include "common.h"
#include "desfire.h"
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

View file

@ -1,172 +0,0 @@
/*-
* 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$
*/
#include "desfire_key.h"
#include "string.h"
#include "dbprint.h"
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 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);
memcpy(key->data + 16, value, 8);
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_2k3des_key_new_with_version(const uint8_t value[16], desfirekey_t key) {
if (key != NULL) {
key->type = T_2K3DES;
memcpy(key->data, value, 16);
update_key_schedules(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_2K3DES:
memcpy(buffer, rnda, 4);
memcpy(buffer + 4, rndb, 4);
memcpy(buffer + 8, rnda + 4, 4);
memcpy(buffer + 12, rndb + 4, 4);
Desfire_2k3des_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;
}
}

View file

@ -1,19 +0,0 @@
#ifndef __DESFIRE_KEY_INCLUDED
#define __DESFIRE_KEY_INCLUDED
#include "common.h"
#include "desfire.h"
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);
#endif

View file

@ -4,19 +4,18 @@
#include "proxmark3_arm.h"
#include "string.h"
#include "BigBuf.h"
#include "desfire_key.h"
#include "mifareutil.h"
#include "des.h"
#include "desfire_crypto.h"
#include "cmd.h"
#include "dbprint.h"
#include "fpgaloader.h"
#include "iso14443a.h"
#include "crc16.h"
#include "mbedtls/aes.h"
#include "commonutil.h"
#include "util.h"
#include "mifare.h"
#include "ticks.h"
#include "protocols.h"
#define MAX_APPLICATION_COUNT 28
#define MAX_FILE_COUNT 16
@ -34,6 +33,8 @@ static uint8_t deselect_cmd[] = {0xc2, 0xe0, 0xb4};
/* PCB CID CMD PAYLOAD */
//static uint8_t __res[MAX_FRAME_SIZE];
struct desfire_key skey = {0};
static desfirekey_t sessionkey = &skey;
bool InitDesfireCard() {
@ -158,7 +159,7 @@ void MifareDesfireGetInformation() {
memcpy(payload.uid, card.uid, sizeof(payload.uid));
LED_A_ON();
uint8_t cmd[] = {0x90, GET_VERSION, 0x00, 0x00, 0x00};
uint8_t cmd[] = {0x90, MFDES_GET_VERSION, 0x00, 0x00, 0x00};
size_t cmd_len = sizeof(cmd);
len = DesfireAPDU(cmd, cmd_len, resp);
@ -173,7 +174,7 @@ void MifareDesfireGetInformation() {
memcpy(payload.versionHW, resp + 1, sizeof(payload.versionHW));
// ADDITION_FRAME 1
cmd[1] = ADDITIONAL_FRAME;
cmd[1] = MFDES_ADDITIONAL_FRAME;
len = DesfireAPDU(cmd, cmd_len, resp);
if (!len) {
print_result("ERROR <--: ", resp, len);
@ -250,9 +251,13 @@ void MifareDES_Auth1(uint8_t *datain) {
num_to_bytes(value, 4, &RndA[12]);
// Default Keys
uint8_t PICC_MASTER_KEY8[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t PICC_MASTER_KEY16[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint8_t PICC_MASTER_KEY24[24] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint8_t PICC_MASTER_KEY8[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t PICC_MASTER_KEY16[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00
};
uint8_t PICC_MASTER_KEY24[24] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
//uint8_t null_key_data16[16] = {0x00};
//uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77};
//uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
@ -268,7 +273,7 @@ void MifareDES_Auth1(uint8_t *datain) {
if (payload->key == NULL) {
if (payload->algo == MFDES_AUTH_DES) {
memcpy(keybytes, PICC_MASTER_KEY8, 8);
} else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES || payload->algo == MFDES_ALGO_2K3DES) {
} else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES) {
memcpy(keybytes, PICC_MASTER_KEY16, 16);
} else if (payload->algo == MFDES_ALGO_3DES) {
memcpy(keybytes, PICC_MASTER_KEY24, 24);
@ -277,6 +282,7 @@ void MifareDES_Auth1(uint8_t *datain) {
memcpy(keybytes, payload->key, payload->keylen);
}
struct desfire_key defaultkey = {0};
desfirekey_t key = &defaultkey;
@ -287,18 +293,16 @@ void MifareDES_Auth1(uint8_t *datain) {
Desfire_3des_key_new_with_version(keybytes, key);
} else if (payload->algo == MFDES_ALGO_DES) {
Desfire_des_key_new(keybytes, key);
} else if (payload->algo == MFDES_ALGO_2K3DES) {
Desfire_2k3des_key_new_with_version(keybytes, key);
} else if (payload->algo == MFDES_ALGO_3K3DES) {
Desfire_3k3des_key_new_with_version(keybytes, key);
}
uint8_t subcommand = AUTHENTICATE;
uint8_t subcommand = MFDES_AUTHENTICATE;
if (payload->mode == MFDES_AUTH_AES)
subcommand = AUTHENTICATE_AES;
subcommand = MFDES_AUTHENTICATE_AES;
else if (payload->mode == MFDES_AUTH_ISO)
subcommand = AUTHENTICATE_ISO;
subcommand = MFDES_AUTHENTICATE_ISO;
if (payload->mode != MFDES_AUTH_PICC) {
// Let's send our auth command
@ -311,7 +315,7 @@ void MifareDES_Auth1(uint8_t *datain) {
cmd[6] = 0x0;
len = DesfireAPDU(cmd, 7, resp);
} else {
cmd[0] = AUTHENTICATE;
cmd[0] = MFDES_AUTHENTICATE;
cmd[1] = payload->keyno;
len = DesfireAPDU(cmd, 2, resp);
}
@ -324,15 +328,22 @@ void MifareDES_Auth1(uint8_t *datain) {
return;
}
if (resp[2] == (uint8_t)0xaf) {
if (resp[2] == (uint8_t)MFDES_ADDITIONAL_FRAME) {
DbpString("Authentication failed. Invalid key number.");
OnErrorNG(CMD_HF_DESFIRE_AUTH1, 3);
return;
}
int rndlen=8;
int expectedlen = 1 + 8 + 2 + 2;
if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) {
expectedlen = 1 + 16 + 2 + 2;
rndlen=16;
}
if (payload->mode == MFDES_AUTH_PICC) {
expectedlen = 1 + 1 + 8 + 2;
rndlen=8;
}
if (len != expectedlen) {
@ -346,9 +357,9 @@ void MifareDES_Auth1(uint8_t *datain) {
// Part 2
if (payload->mode != MFDES_AUTH_PICC) {
memcpy(encRndB, resp + 1, payload->keylen);
memcpy(encRndB, resp + 1, rndlen);
} else {
memcpy(encRndB, resp + 2, payload->keylen);
memcpy(encRndB, resp + 2, rndlen);
}
// Part 3
@ -361,60 +372,46 @@ void MifareDES_Auth1(uint8_t *datain) {
return;
}
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, RndB);
} else if (payload->algo == MFDES_ALGO_3DES)
tdes_dec(RndB, encRndB, key->data);
else if (payload->algo == MFDES_ALGO_DES)
des_dec(RndB, encRndB, key->data);
else if (payload->algo == MFDES_ALGO_2K3DES)
tdes_2key_dec(RndB, encRndB, 8, key->data, IV);
} else if (payload->algo == MFDES_ALGO_DES)
des_decrypt(RndB, encRndB, key->data);
else if (payload->algo == MFDES_ALGO_3DES)
tdes_nxp_receive(encRndB, RndB, rndlen, key->data, IV, 2);
else if (payload->algo == MFDES_ALGO_3K3DES)
tdes_3key_dec(RndB, encRndB, 16, key->data, IV);
tdes_nxp_receive(encRndB, RndB, rndlen, key->data, IV, 3);
// - Rotate RndB by 8 bits
memcpy(rotRndB, RndB, payload->keylen);
rol(rotRndB, payload->keylen);
memcpy(rotRndB, RndB, rndlen);
rol(rotRndB, rndlen);
uint8_t encRndA[16] = {0x00};
// - Encrypt our response
if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_ISO || payload->mode == MFDES_AUTH_PICC) {
if (payload->algo == MFDES_ALGO_3DES) {
tdes_dec(encRndA, RndA, key->data);
memcpy(both, encRndA, 8);
} else if (payload->algo == MFDES_ALGO_DES) {
des_dec(encRndA, RndA, key->data);
memcpy(both, encRndA, 8);
} else if (payload->algo == MFDES_ALGO_2K3DES) {
tdes_2key_dec(encRndA, RndA, 8, key->data, IV);
memcpy(both, encRndA, 8);
} else if (payload->algo == MFDES_ALGO_3K3DES) {
tdes_3key_dec(encRndA, RndA, 16, key->data, IV);
memcpy(both, encRndA, 16);
}
if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) {
des_decrypt(encRndA, RndA, key->data);
memcpy(both, encRndA, rndlen);
for (int x = 0; x < 8; x++) {
for (int x = 0; x < rndlen; x++) {
rotRndB[x] = rotRndB[x] ^ encRndA[x];
}
des_decrypt(encRndB, rotRndB, key->data);
memcpy(both + 8, encRndB, rndlen);
} else if (payload->mode == MFDES_AUTH_ISO) {
if (payload->algo == MFDES_ALGO_3DES) {
tdes_dec(encRndB, rotRndB, key->data);
memcpy(both + 8, encRndB, 8);
} else if (payload->algo == MFDES_ALGO_DES) {
des_dec(encRndB, rotRndB, key->data);
memcpy(both + 8, encRndB, 8);
} else if (payload->algo == MFDES_ALGO_2K3DES) {
tdes_2key_dec(encRndB, rotRndB, 8, key->data, IV);
memcpy(both + 8, encRndB, 8);
uint8_t tmp[16] = {0x00};
memcpy(tmp, RndA, rndlen);
memcpy(tmp + rndlen, rotRndB, rndlen);
tdes_nxp_send(tmp, both, 16, key->data, IV, 2);
} else if (payload->algo == MFDES_ALGO_3K3DES) {
tdes_3key_dec(encRndB, rotRndB, 16, key->data, IV);
memcpy(both + 16, encRndB, 16);
uint8_t tmp[32] = {0x00};
memcpy(tmp, RndA, rndlen);
memcpy(tmp + rndlen, rotRndB, rndlen);
tdes_nxp_send(tmp, both, 32, key->data, IV, 3);
}
} else if (payload->mode == MFDES_AUTH_AES) {
uint8_t tmp[32] = {0x00};
memcpy(tmp, RndA, 16);
memcpy(tmp + 16, rotRndB, 16);
memcpy(tmp, RndA, rndlen);
memcpy(tmp + 16, rotRndB, rndlen);
if (payload->algo == MFDES_ALGO_AES) {
if (mbedtls_aes_setkey_enc(&ctx, key->data, 128) != 0) {
if (DBGLEVEL >= DBG_EXTENDED) {
@ -433,7 +430,7 @@ void MifareDES_Auth1(uint8_t *datain) {
}
if (payload->mode != MFDES_AUTH_PICC) {
cmd[0] = 0x90;
cmd[1] = ADDITIONAL_FRAME;
cmd[1] = MFDES_ADDITIONAL_FRAME;
cmd[2] = 0x00;
cmd[3] = 0x00;
cmd[4] = bothlen;
@ -441,9 +438,9 @@ void MifareDES_Auth1(uint8_t *datain) {
cmd[bothlen + 5] = 0x0;
len = DesfireAPDU(cmd, 5 + bothlen + 1, resp);
} else {
cmd[0] = ADDITIONAL_FRAME;
memcpy(cmd + 1, both, 16);
len = DesfireAPDU(cmd, 1 + 16, resp);
cmd[0] = MFDES_ADDITIONAL_FRAME;
memcpy(cmd + 1, both, bothlen);
len = DesfireAPDU(cmd, 1 + bothlen, resp);
}
if (!len) {
@ -469,27 +466,25 @@ void MifareDES_Auth1(uint8_t *datain) {
}
// Part 4
struct desfire_key sessionKey = {0};
desfirekey_t skey = &sessionKey;
Desfire_session_key_new(RndA, RndB, key, skey);
Desfire_session_key_new(RndA, RndB, key, sessionkey);
if (DBGLEVEL >= DBG_EXTENDED)
print_result("SESSIONKEY : ", sessionKey.data, payload->keylen);
print_result("SESSIONKEY : ", sessionkey->data, payload->keylen);
if (payload->mode != MFDES_AUTH_PICC) {
memcpy(encRndA, resp + 1, payload->keylen);
memcpy(encRndA, resp + 1, rndlen);
} else {
memcpy(encRndA, resp + 2, payload->keylen);
memcpy(encRndA, resp + 2, rndlen);
}
if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) {
if (payload->algo == MFDES_ALGO_3DES)
tdes_dec(encRndA, encRndA, key->data);
else if (payload->algo == MFDES_ALGO_DES)
des_dec(encRndA, encRndA, key->data);
else if (payload->algo == MFDES_ALGO_2K3DES)
tdes_2key_dec(encRndA, encRndA, 8, key->data, IV);
if (payload->algo == MFDES_ALGO_DES)
des_decrypt(encRndA, encRndA, key->data);
else if (payload->algo == MFDES_ALGO_3DES)
tdes_nxp_receive(encRndA, encRndA, rndlen, key->data, IV, 2);
else if (payload->algo == MFDES_ALGO_3K3DES)
tdes_3key_dec(encRndA, encRndA, 16, key->data, IV);
tdes_nxp_receive(encRndA, encRndA, rndlen, key->data, IV, 3);
} else if (payload->mode == MFDES_AUTH_AES) {
if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) {
if (DBGLEVEL >= DBG_EXTENDED) {
@ -501,13 +496,13 @@ void MifareDES_Auth1(uint8_t *datain) {
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndA, encRndA);
}
rol(RndA, payload->keylen);
rol(RndA, rndlen);
if (DBGLEVEL >= DBG_EXTENDED) {
print_result("RndA : ", RndA, payload->keylen);
print_result("RndB: ", RndB, payload->keylen);
print_result("encRndA : ", encRndA, payload->keylen);
print_result("RndA : ", RndA, rndlen);
print_result("RndB: ", RndB, rndlen);
print_result("encRndA : ", encRndA, rndlen);
}
for (int x = 0; x < payload->keylen; x++) {
for (int x = 0; x < rndlen; x++) {
if (RndA[x] != encRndA[x]) {
DbpString("Authentication failed. Cannot verify Session Key.");
OnErrorNG(CMD_HF_DESFIRE_AUTH1, 4);
@ -613,7 +608,7 @@ void MifareDES_Auth1(uint8_t *datain) {
LED_B_ON();
authres_t rpayload;
rpayload.sessionkeylen = payload->keylen;
memcpy(rpayload.sessionkey, sessionKey.data, rpayload.sessionkeylen);
memcpy(rpayload.sessionkey, sessionkey->data, rpayload.sessionkeylen);
reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(rpayload));
LED_B_OFF();
}

View file

@ -18,7 +18,7 @@
#include "commonutil.h"
#include "crc16.h"
#include "protocols.h"
#include "des.h"
#include "desfire_crypto.h"
int DBGLEVEL = DBG_ERROR;
@ -296,7 +296,7 @@ int mifare_ultra_auth(uint8_t *keybytes) {
memcpy(enc_random_b, resp + 1, 8);
// decrypt nonce.
tdes_2key_dec((void *)random_b, (void *)enc_random_b, sizeof(random_b), (const void *)key, IV);
tdes_nxp_receive((void *)enc_random_b, (void *)random_b, sizeof(random_b), (const void *)key, IV, 2);
rol(random_b, 8);
memcpy(rnd_ab, random_a, 8);
memcpy(rnd_ab + 8, random_b, 8);
@ -316,7 +316,7 @@ int mifare_ultra_auth(uint8_t *keybytes) {
}
// encrypt out, in, length, key, iv
tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b);
tdes_nxp_send(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b, 2);
len = mifare_sendcmd(MIFARE_ULC_AUTH_2, rnd_ab, sizeof(rnd_ab), resp, respPar, NULL);
if (len != 11) {
@ -329,7 +329,7 @@ int mifare_ultra_auth(uint8_t *keybytes) {
memcpy(enc_resp, resp + 1, 8);
// decrypt out, in, length, key, iv
tdes_2key_dec(resp_random_a, enc_resp, 8, key, enc_random_b);
tdes_nxp_receive(enc_resp, resp_random_a, 8, key, enc_random_b, 2);
if (memcmp(resp_random_a, random_a, 8) != 0) {
if (DBGLEVEL >= DBG_ERROR) Dbprintf("failed authentication");
return 0;

View file

@ -185,6 +185,7 @@ CMDSRCS = crapto1/crapto1.c \
mifare/mifare4.c \
mifare/mad.c \
mifare/ndef.c \
mifare/desfire_crypto.c \
cmdanalyse.c \
cmdhf.c \
cmdhflist.c \

View file

@ -38,6 +38,7 @@ int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtable
if (arg_nullcheck(argtable) != 0) {
/* NULL entries were detected, some allocations must have failed */
printf("ERROR: Insufficient memory\n");
fflush(stdout);
return 2;
}
/* Parse the command line as defined by argtable[] */
@ -54,6 +55,7 @@ int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtable
if (programHelp)
printf("%s \n", programHelp);
fflush(stdout);
return 1;
}
@ -62,7 +64,7 @@ int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtable
/* Display the error details contained in the arg_end struct.*/
arg_print_errors(stdout, ((struct arg_end *)argtable[vargtableLen - 1]), programName);
printf("Try '%s --help' for more information.\n", programName);
fflush(stdout);
return 3;
}
@ -155,18 +157,27 @@ int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int
int ibuf = 0;
uint8_t tmp_buf[256] = {0};
int res = CLIParamStrToBuf(argstr, tmp_buf, maxdatalen * 2, &ibuf); // *2 because here HEX
if (res || !ibuf)
if (res) {
printf("Parameter error: buffer overflow.\n");
fflush(stdout);
return res;
}
if (ibuf == 0) {
return res;
}
switch (param_gethex_to_eol((char *)tmp_buf, 0, data, maxdatalen, datalen)) {
case 1:
printf("Parameter error: Invalid HEX value.\n");
fflush(stdout);
return 1;
case 2:
printf("Parameter error: parameter too large.\n");
fflush(stdout);
return 2;
case 3:
printf("Parameter error: Hex string must have even number of digits.\n");
fflush(stdout);
return 3;
}
@ -191,12 +202,13 @@ int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int
if (!ibuf)
return 0;
if (ibuf > maxdatalen)
if (ibuf > maxdatalen) {
fflush(stdout);
return 2;
}
memcpy(data, tmp_buf, ibuf);
*datalen = ibuf;
return 0;
}

View file

@ -2096,9 +2096,9 @@ static void HFiClassCalcNewKey(uint8_t *CSN, uint8_t *OLDKEY, uint8_t *NEWKEY, u
xor_div_key[i] = old_div_key[i] ^ new_div_key[i];
}
if (verbose) {
PrintAndLogEx(SUCCESS, "Old div key : %s\n", sprint_hex(old_div_key, 8));
PrintAndLogEx(SUCCESS, "New div key : %s\n", sprint_hex(new_div_key, 8));
PrintAndLogEx(SUCCESS, "Xor div key : %s\n", sprint_hex(xor_div_key, 8));
PrintAndLogEx(SUCCESS, "Old div key : %s", sprint_hex(old_div_key, 8));
PrintAndLogEx(SUCCESS, "New div key : %s", sprint_hex(new_div_key, 8));
PrintAndLogEx(SUCCESS, "Xor div key : " _YELLOW_("%s") "\n", sprint_hex(xor_div_key, 8));
}
}
@ -2111,7 +2111,7 @@ static int CmdHFiClassCalcNewKey(const char *Cmd) {
uint8_t dataLen = 0;
char tempStr[50] = {0};
bool givenCSN = false;
bool oldElite = false;
bool old_elite = false;
bool elite = false;
bool errors = false;
uint8_t cmdp = 0;
@ -2122,7 +2122,7 @@ static int CmdHFiClassCalcNewKey(const char *Cmd) {
case 'e':
dataLen = param_getstr(Cmd, cmdp, tempStr, sizeof(tempStr));
if (dataLen == 2)
oldElite = true;
old_elite = true;
elite = true;
cmdp++;
break;
@ -2184,7 +2184,7 @@ static int CmdHFiClassCalcNewKey(const char *Cmd) {
}
}
HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, oldElite, true);
HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, old_elite, true);
return PM3_SUCCESS;
}

View file

@ -19,6 +19,7 @@
#include "cmdhw.h"
#include "cmdhf14a.h"
#include "mbedtls/des.h"
#include "mbedtls/aes.h"
#include "crypto/libpcrypto.h"
#include "protocols.h"
#include "mifare.h" // desfire raw command options
@ -28,6 +29,11 @@
#include "emv/emvcore.h" // APDU logging
#include "util_posix.h" // msleep
#include "mifare/mifare4.h" // MIFARE Authenticate / MAC
#include "mifare/desfire_crypto.h"
#include "crapto1/crapto1.h"
struct desfire_key defaultkey = {0};
static desfirekey_t sessionkey = &defaultkey;
uint8_t key_zero_data[16] = { 0x00 };
uint8_t key_ones_data[16] = { 0x01 };
@ -49,6 +55,216 @@ typedef struct mfdes_auth_res {
#define status(x) ( ((uint16_t)(0x91<<8)) + x )
// NXP Appnote AN10787 - Application Directory (MAD)
typedef enum {
CL_ADMIN = 0,
CL_MISC1,
CL_MISC2,
CL_MISC3,
CL_MISC4,
CL_MISC5,
CL_MISC6,
CL_MISC7,
CL_AIRLINES = 8,
CL_FERRY,
CL_RAIL,
CL_MISC,
CL_TRANSPORT,
CL_SECURITY = 0x14,
CL_CITYTRAFFIC = 0x18,
CL_CZECH_RAIL,
CL_BUS,
CL_MMT,
CL_TAXI = 0x28,
CL_TOLL = 0x30,
CL_GENERIC_TRANS,
CL_COMPANY_SERVICES = 0x38,
CL_CITYCARD = 0x40,
CL_ACCESS_CONTROL_1 = 0x47,
CL_ACCESS_CONTROL_2,
CL_VIGIK = 0x49,
CL_NED_DEFENCE = 0x4A,
CL_BOSCH_TELECOM = 0x4B,
CL_EU = 0x4C,
CL_SKI_TICKET = 0x50,
CL_SOAA = 0x55,
CL_ACCESS2 = 0x56,
CL_FOOD = 0x60,
CL_NONFOOD = 0x68,
CL_HOTEL = 0x70,
CL_LOYALTY = 0x71,
CL_AIRPORT = 0x75,
CL_CAR_RENTAL = 0x78,
CL_NED_GOV = 0x79,
CL_ADMIN2 = 0x80,
CL_PURSE = 0x88,
CL_TV = 0x90,
CL_CRUISESHIP = 0x91,
CL_IOPTA = 0x95,
CL_METERING = 0x97,
CL_TELEPHONE = 0x98,
CL_HEALTH = 0xA0,
CL_WAREHOUSE = 0xA8,
CL_BANKING = 0xB8,
CL_ENTERTAIN = 0xC0,
CL_PARKING = 0xC8,
CL_FLEET = 0xC9,
CL_FUEL = 0xD0,
CL_INFO = 0xD8,
CL_PRESS = 0xE0,
CL_NFC = 0xE1,
CL_COMPUTER = 0xE8,
CL_MAIL = 0xF0,
CL_AMISC = 0xF8,
CL_AMISC1 = 0xF9,
CL_AMISC2 = 0xFA,
CL_AMISC3 = 0xFB,
CL_AMISC4 = 0xFC,
CL_AMISC5 = 0xFD,
CL_AMISC6 = 0xFE,
CL_AMISC7 = 0xFF,
} aidcluster_h;
static char *cluster_to_text(uint8_t cluster) {
switch (cluster) {
case CL_ADMIN:
return "card administration";
case CL_MISC1:
return "miscellaneous applications";
case CL_MISC2:
return "miscellaneous applications";
case CL_MISC3:
return "miscellaneous applications";
case CL_MISC4:
return "miscellaneous applications";
case CL_MISC5:
return "miscellaneous applications";
case CL_MISC6:
return "miscellaneous applications";
case CL_MISC7:
return "miscellaneous applications";
case CL_AIRLINES:
return "airlines";
case CL_FERRY:
return "ferry traffic";
case CL_RAIL:
return "railway services";
case CL_MISC:
return "miscellaneous applications";
case CL_TRANSPORT:
return "transport";
case CL_SECURITY:
return "security solutions";
case CL_CITYTRAFFIC:
return "city traffic";
case CL_CZECH_RAIL:
return "Czech Railways";
case CL_BUS:
return "bus services";
case CL_MMT:
return "multi modal transit";
case CL_TAXI:
return "taxi";
case CL_TOLL:
return "road toll";
case CL_GENERIC_TRANS:
return "generic transport";
case CL_COMPANY_SERVICES:
return "company services";
case CL_CITYCARD:
return "city card services";
case CL_ACCESS_CONTROL_1:
return "access control & security";
case CL_ACCESS_CONTROL_2:
return "access control & security";
case CL_VIGIK:
return "VIGIK";
case CL_NED_DEFENCE:
return "Ministry of Defence, Netherlands";
case CL_BOSCH_TELECOM:
return "Bosch Telecom, Germany";
case CL_EU:
return "European Union Institutions";
case CL_SKI_TICKET:
return "ski ticketing";
case CL_SOAA:
return "SOAA standard for offline access standard";
case CL_ACCESS2:
return "access control & security";
case CL_FOOD:
return "food";
case CL_NONFOOD:
return "non-food trade";
case CL_HOTEL:
return "hotel";
case CL_LOYALTY:
return "loyalty";
case CL_AIRPORT:
return "airport services";
case CL_CAR_RENTAL:
return "car rental";
case CL_NED_GOV:
return "Dutch government";
case CL_ADMIN2:
return "administration services";
case CL_PURSE:
return "electronic purse";
case CL_TV:
return "television";
case CL_CRUISESHIP:
return "cruise ship";
case CL_IOPTA:
return "IOPTA";
case CL_METERING:
return "metering";
case CL_TELEPHONE:
return "telephone";
case CL_HEALTH:
return "health services";
case CL_WAREHOUSE:
return "warehouse";
case CL_BANKING:
return "banking";
case CL_ENTERTAIN:
return "entertainment & sports";
case CL_PARKING:
return "car parking";
case CL_FLEET:
return "fleet management";
case CL_FUEL:
return "fuel, gasoline";
case CL_INFO:
return "info services";
case CL_PRESS:
return "press";
case CL_NFC:
return "NFC Forum";
case CL_COMPUTER:
return "computer";
case CL_MAIL:
return "mail";
case CL_AMISC:
return "miscellaneous applications";
case CL_AMISC1:
return "miscellaneous applications";
case CL_AMISC2:
return "miscellaneous applications";
case CL_AMISC3:
return "miscellaneous applications";
case CL_AMISC4:
return "miscellaneous applications";
case CL_AMISC5:
return "miscellaneous applications";
case CL_AMISC6:
return "miscellaneous applications";
case CL_AMISC7:
return "miscellaneous applications";
default:
break;
}
return "reserved";
}
typedef enum {
UNKNOWN = 0,
DESFIRE_MF3ICD40,
@ -331,6 +547,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l
int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw);
if (res != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw));
DropField();
return res;
}
if (dest != NULL) {
@ -340,11 +557,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l
pos += resplen;
if (!readalldata) {
if (*sw == status(MFDES_ADDITIONAL_FRAME)) {
apdu->INS = MFDES_ABORT_TRANSACTION;
apdu->Lc = 0;
apdu->P1 = 0;
apdu->P2 = 0;
res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw);
*recv_len = pos;
return PM3_SUCCESS;
}
return res;
@ -359,6 +572,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l
res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw);
if (res != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw));
DropField();
return res;
}
@ -397,13 +611,302 @@ static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) {
return UNKNOWN;
}
int get_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) {
// 3 different way to authenticate AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32)
// 4 different crypto arg1 DES, 3DES, 3K3DES, AES
// 3 different communication modes, PLAIN,MAC,CRYPTO
mbedtls_aes_context ctx;
uint8_t keybytes[24];
// Crypt constants
uint8_t IV[16] = {0x00};
uint8_t RndA[16] = {0x00};
uint8_t RndB[16] = {0x00};
uint8_t encRndB[16] = {0x00};
uint8_t rotRndB[16] = {0x00}; //RndB'
uint8_t both[32 + 1] = {0x00}; // ek/dk_keyNo(RndA+RndB')
// Generate Random Value
uint32_t ng = msclock();
uint32_t value = prng_successor(ng, 32);
num_to_bytes(value, 4, &RndA[0]);
value = prng_successor(ng, 32);
num_to_bytes(value, 4, &RndA[4]);
value = prng_successor(ng, 32);
num_to_bytes(value, 4, &RndA[8]);
value = prng_successor(ng, 32);
num_to_bytes(value, 4, &RndA[12]);
// Default Keys
uint8_t PICC_MASTER_KEY8[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t PICC_MASTER_KEY16[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint8_t PICC_MASTER_KEY24[24] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
//uint8_t null_key_data16[16] = {0x00};
//uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77};
//uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
// Part 1
// iceman: I guess you want to determine if the key was set. Maybe check keylen instead? 0 = not set.
if (payload->key[0] == '\0') {
if (payload->algo == MFDES_AUTH_DES) {
memcpy(keybytes, PICC_MASTER_KEY8, 8);
} else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES) {
memcpy(keybytes, PICC_MASTER_KEY16, 16);
} else if (payload->algo == MFDES_ALGO_3DES) {
memcpy(keybytes, PICC_MASTER_KEY24, 24);
}
} else {
memcpy(keybytes, payload->key, payload->keylen);
}
struct desfire_key defaultkey = {0};
desfirekey_t key = &defaultkey;
if (payload->algo == MFDES_ALGO_AES) {
mbedtls_aes_init(&ctx);
Desfire_aes_key_new(keybytes, key);
} else if (payload->algo == MFDES_ALGO_3DES) {
Desfire_3des_key_new_with_version(keybytes, key);
} else if (payload->algo == MFDES_ALGO_DES) {
Desfire_des_key_new(keybytes, key);
} else if (payload->algo == MFDES_ALGO_3K3DES) {
Desfire_3k3des_key_new_with_version(keybytes, key);
}
uint8_t subcommand = MFDES_AUTHENTICATE;
if (payload->mode == MFDES_AUTH_AES)
subcommand = MFDES_AUTHENTICATE_AES;
else if (payload->mode == MFDES_AUTH_ISO)
subcommand = MFDES_AUTHENTICATE_ISO;
int recv_len = 0;
uint16_t sw = 0;
uint8_t recv_data[256] = {0};
if (payload->mode != MFDES_AUTH_PICC) {
// Let's send our auth command
uint8_t data[] = {payload->keyno};
sAPDU apdu = {0x90, subcommand, 0x00, 0x00, 0x01, data};
int res = send_desfire_cmd(&apdu, false, recv_data, &recv_len, &sw, 0, false);
if (res != PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Sending auth command %02X " _RED_("failed"), subcommand);
return PM3_ESOFT;
}
} else if (payload->mode == MFDES_AUTH_PICC) {
/*cmd[0] = AUTHENTICATE;
cmd[1] = payload->keyno;
len = DesfireAPDU(cmd, 2, resp);
*/
}
if (!recv_len) {
PrintAndLogEx(ERR, "Authentication failed. Card timeout.");
return PM3_ESOFT;
}
if (sw != status(MFDES_ADDITIONAL_FRAME)) {
PrintAndLogEx(ERR, "Authentication failed. Invalid key number.");
return PM3_ESOFT;
}
int expectedlen = 8;
if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) {
expectedlen = 16;
}
if (recv_len != expectedlen) {
PrintAndLogEx(ERR, "Authentication failed. Length of answer %d doesn't match algo length %d.", recv_len, expectedlen);
return PM3_ESOFT;
}
int rndlen = recv_len;
// Part 2
if (payload->mode != MFDES_AUTH_PICC) {
memcpy(encRndB, recv_data, rndlen);
} else {
memcpy(encRndB, recv_data + 2, rndlen);
}
// Part 3
if (payload->algo == MFDES_ALGO_AES) {
if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) {
PrintAndLogEx(ERR, "mbedtls_aes_setkey_dec failed");
return PM3_ESOFT;
}
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, rndlen, IV, encRndB, RndB);
} else if (payload->algo == MFDES_ALGO_DES)
des_decrypt(RndB, encRndB, key->data);
else if (payload->algo == MFDES_ALGO_3DES)
tdes_nxp_receive(encRndB, RndB, rndlen, key->data, IV, 2);
else if (payload->algo == MFDES_ALGO_3K3DES) {
tdes_nxp_receive(encRndB, RndB, rndlen, key->data, IV, 3);
}
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "encRndB: %s", sprint_hex(encRndB, 8));
PrintAndLogEx(INFO, "RndB: %s", sprint_hex(RndB, 8));
}
// - Rotate RndB by 8 bits
memcpy(rotRndB, RndB, rndlen);
rol(rotRndB, rndlen);
uint8_t encRndA[16] = {0x00};
// - Encrypt our response
if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) {
des_decrypt(encRndA, RndA, key->data);
memcpy(both, encRndA, rndlen);
for (int x = 0; x < rndlen; x++) {
rotRndB[x] = rotRndB[x] ^ encRndA[x];
}
des_decrypt(encRndB, rotRndB, key->data);
memcpy(both + rndlen, encRndB, rndlen);
} else if (payload->mode == MFDES_AUTH_ISO) {
if (payload->algo == MFDES_ALGO_3DES) {
uint8_t tmp[16] = {0x00};
memcpy(tmp, RndA, rndlen);
memcpy(tmp + rndlen, rotRndB, rndlen);
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "rotRndB: %s", sprint_hex(rotRndB, rndlen));
PrintAndLogEx(INFO, "Both: %s", sprint_hex(tmp, 16));
}
tdes_nxp_send(tmp, both, 16, key->data, IV, 2);
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "EncBoth: %s", sprint_hex(both, 16));
}
} else if (payload->algo == MFDES_ALGO_3K3DES) {
uint8_t tmp[32] = {0x00};
memcpy(tmp, RndA, rndlen);
memcpy(tmp + rndlen, rotRndB, rndlen);
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "rotRndB: %s", sprint_hex(rotRndB, rndlen));
PrintAndLogEx(INFO, "Both3k3: %s", sprint_hex(tmp, 32));
}
tdes_nxp_send(tmp, both, 32, key->data, IV, 3);
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "EncBoth: %s", sprint_hex(both, 32));
}
}
} else if (payload->mode == MFDES_AUTH_AES) {
uint8_t tmp[32] = {0x00};
memcpy(tmp, RndA, rndlen);
memcpy(tmp + rndlen, rotRndB, rndlen);
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "rotRndB: %s", sprint_hex(rotRndB, rndlen));
PrintAndLogEx(INFO, "Both3k3: %s", sprint_hex(tmp, 32));
}
if (payload->algo == MFDES_ALGO_AES) {
if (mbedtls_aes_setkey_enc(&ctx, key->data, 128) != 0) {
PrintAndLogEx(ERR, "mbedtls_aes_setkey_enc failed");
return PM3_ESOFT;
}
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, tmp, both);
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "EncBoth: %s", sprint_hex(both, 32));
}
}
}
int bothlen = 16;
if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) {
bothlen = 32;
}
if (payload->mode != MFDES_AUTH_PICC) {
sAPDU apdu = {0x90, MFDES_ADDITIONAL_FRAME, 0x00, 0x00, bothlen, both};
int res = send_desfire_cmd(&apdu, false, recv_data, &recv_len, &sw, 0, false);
if (res != PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Sending auth command %02X " _RED_("failed"), subcommand);
return PM3_ESOFT;
}
} else {
/*cmd[0] = ADDITIONAL_FRAME;
memcpy(cmd + 1, both, 16);
len = DesfireAPDU(cmd, 1 + 16, resp);
if (res != PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Sending auth command %02X " _RED_("failed"),subcommand);
return PM3_ESOFT;
}*/
}
if (!recv_len) {
PrintAndLogEx(ERR, "Authentication failed. Card timeout.");
return PM3_ESOFT;
}
if (payload->mode != MFDES_AUTH_PICC) {
if (sw != status(MFDES_S_OPERATION_OK)) {
PrintAndLogEx(ERR, "Authentication failed.");
return PM3_ESOFT;
}
} else {
/*if (resp[1] != 0x00) {
PrintAndLogEx(ERR,"Authentication failed. Card timeout.");
return PM3_ESOFT;
}*/
}
// Part 4
Desfire_session_key_new(RndA, RndB, key, sessionkey);
if (payload->mode != MFDES_AUTH_PICC) {
memcpy(encRndA, recv_data, rndlen);
} else {
memcpy(encRndA, recv_data + 2, rndlen);
}
if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_ISO || payload->mode == MFDES_AUTH_PICC) {
if (payload->algo == MFDES_ALGO_DES)
des_decrypt(encRndA, encRndA, key->data);
else if (payload->algo == MFDES_ALGO_3DES)
tdes_nxp_receive(encRndA, encRndA, rndlen, key->data, IV, 2);
else if (payload->algo == MFDES_ALGO_3K3DES)
tdes_nxp_receive(encRndA, encRndA, rndlen, key->data, IV, 3);
} else if (payload->mode == MFDES_AUTH_AES) {
if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) {
PrintAndLogEx(ERR, "mbedtls_aes_setkey_dec failed");
return PM3_ESOFT;
}
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, rndlen, IV, encRndA, encRndA);
}
rol(RndA, rndlen);
for (int x = 0; x < rndlen; x++) {
if (RndA[x] != encRndA[x]) {
PrintAndLogEx(ERR, "Authentication failed. Cannot verify Session Key.");
if (g_debugMode > 1) {
PrintAndLogEx(INFO, "Expected_RndA : %s", sprint_hex(RndA, rndlen));
PrintAndLogEx(INFO, "Generated_RndA : %s", sprint_hex(encRndA, rndlen));
}
return PM3_ESOFT;
}
}
rpayload->sessionkeylen = payload->keylen;
memcpy(rpayload->sessionkey, sessionkey->data, rpayload->sessionkeylen);
return PM3_SUCCESS;
}
// -- test if card supports 0x0A
static int test_desfire_authenticate() {
uint8_t data[] = {0x00};
sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0
int recv_len = 0;
uint16_t sw = 0;
return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false);
int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false);
if (res == PM3_SUCCESS)
if (sw == status(MFDES_ADDITIONAL_FRAME)) {
DropField();
return res;
}
return res;
}
// -- test if card supports 0x1A
@ -412,7 +915,13 @@ static int test_desfire_authenticate_iso() {
sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0
int recv_len = 0;
uint16_t sw = 0;
return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false);
int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false);
if (res == PM3_SUCCESS)
if (sw == status(MFDES_ADDITIONAL_FRAME)) {
DropField();
return res;
}
return res;
}
// -- test if card supports 0xAA
@ -421,7 +930,13 @@ static int test_desfire_authenticate_aes() {
sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0
int recv_len = 0;
uint16_t sw = 0;
return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false);
int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false);
if (res == PM3_SUCCESS)
if (sw == status(MFDES_ADDITIONAL_FRAME)) {
DropField();
return res;
}
return res;
}
// --- GET FREE MEM
@ -543,7 +1058,7 @@ static int get_desfire_signature(uint8_t *signature, size_t *signature_len) {
static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) {
PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings);
PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys);
PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys & 0x3F);
PrintAndLogEx(INFO, "-------------------------------------------------------------");
PrintAndLogEx(SUCCESS, " Changekey Access rights");
@ -674,7 +1189,7 @@ static int get_desfire_select_application(uint8_t *aid) {
sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a
int recv_len = 0;
uint16_t sw = 0;
int res = send_desfire_cmd(&apdu, true, NONE, &recv_len, &sw, sizeof(dfname_t), true);
int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t), true);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"), (aid[2] << 16) + (aid[1] << 8) + aid[0], GetErrorString(res, &sw));
DropField();
@ -730,17 +1245,35 @@ typedef struct {
uint8_t name[16];
} aidhdr_t;
static int get_desfire_createapp(aidhdr_t *aidhdr) {
static int get_desfire_createapp(aidhdr_t *aidhdr, bool usename, bool usefid) {
if (aidhdr == NULL) return PM3_EINVARG;
sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t *)aidhdr}; // 0xCA
if (!usename) {
apdu.Lc = apdu.Lc - 16;
}
if (!usefid) {
apdu.Lc = apdu.Lc - 2;
}
uint8_t *data = NULL;
if (!usefid && usename) {
data = (uint8_t *)malloc(apdu.Lc);
apdu.data = data;
memcpy(data, aidhdr, apdu.Lc);
memcpy(&data[3 + 1 + 1], aidhdr->name, 16);
}
uint16_t sw = 0;
int recvlen = 0;
int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true);
if (data != NULL) free(data);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"), GetErrorString(res, &sw));
DropField();
return res;
}
return res;
}
@ -758,6 +1291,30 @@ static int get_desfire_deleteapp(uint8_t *aid) {
return res;
}
typedef struct mfdes_file {
uint8_t fileno; //01
uint8_t fid[2]; //03E1
uint8_t comset; //00
uint8_t access_rights[2]; ///EEEE
uint8_t filesize[3]; //0F0000
} PACKED mfdes_file_t;
static int get_desfire_create_std_file(mfdes_file_t *file) {
if (file == NULL) return PM3_EINVARG;
sAPDU apdu = {0x90, MFDES_CREATE_STD_DATA_FILE, 0x00, 0x00, 1 + 2 + 1 + 2 + 3, (uint8_t *)file}; // 0xCD
uint16_t sw = 0;
int recvlen = 0;
int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_(" Can't create file -> %s"), GetErrorString(res, &sw));
DropField();
return res;
}
return res;
}
int getKeySettings(uint8_t *aid) {
if (aid == NULL) return PM3_EINVARG;
@ -885,16 +1442,16 @@ static void swap16(uint8_t *data) {
static int CmdHF14ADesCreateApp(const char *Cmd) {
CLIParserInit("hf mfdes createaid",
"Create Application ID",
"Usage:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n"
"Usage:\n\thf mfdes createaid -a 123456 -f 1201 -k 0E -l 2E -n Test\n"
);
void *argtable[] = {
arg_param_begin,
arg_strx0("aA", "aid", "<aid>", "App ID to create as hex bytes ("),
arg_strx0("fF", "fid", "<fid>", "File ID to create"),
arg_strx0("fF", "fid", "<fid>", "File ID to create (optional)"),
arg_strx0("kK", "keysetting1", "<keysetting1>", "Key Setting 1 (Application Master Key Settings)"),
arg_strx0("lL", "keysetting2", "<keysetting2>", "Key Setting 2"),
arg_str0("nN", "name", "<name>", "App ISO-4 Name"),
arg_str0("nN", "name", "<name>", "App ISO-4 Name (optional)"),
arg_param_end
};
CLIExecWithReturn(Cmd, argtable, false);
@ -950,10 +1507,12 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
return PM3_EINVARG;
}
if (fidlength < 2) {
if (fidlength > 2) {
PrintAndLogEx(ERR, "FID must have 2 bytes length.");
return PM3_EINVARG;
}
bool usefid = true;
if (fidlength == 0) usefid = false;
if (keylen1 < 1) {
PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length.");
@ -969,6 +1528,8 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
PrintAndLogEx(ERR, "Name has a max. of 16 bytes length.");
return PM3_EINVARG;
}
bool usename = true;
if (namelen == 0) usename = false;
//90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00
/*char name[]="Test";
@ -986,14 +1547,14 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
memcpy(aidhdr.aid, aid, sizeof(aid));
aidhdr.keysetting1 = keysetting1;
aidhdr.keysetting2 = keysetting2;
memcpy(aidhdr.fid, fid, sizeof(fid));
memcpy(aidhdr.name, name, sizeof(name));
if (usefid) memcpy(aidhdr.fid, fid, sizeof(fid));
if (usename) memcpy(aidhdr.name, name, sizeof(name));
uint8_t rootaid[3] = {0x00, 0x00, 0x00};
int res = get_desfire_select_application(rootaid);
if (res != PM3_SUCCESS) return res;
return get_desfire_createapp(&aidhdr);
return get_desfire_createapp(&aidhdr, usename, usefid);
}
static int CmdHF14ADesDeleteApp(const char *Cmd) {
@ -1013,7 +1574,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) {
uint8_t aid[3] = {0};
CLIGetHexWithReturn(1, aid, &aidlength);
CLIParserFree();
swap24(aid);
if (aidlength < 3) {
PrintAndLogEx(ERR, "AID must have 3 bytes length.");
return PM3_EINVARG;
@ -1030,6 +1591,95 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) {
return get_desfire_deleteapp(aid);
}
static int CmdHF14ADesCreateStdFile(const char *Cmd) {
CLIParserInit("hf mfdes createstdfile",
"Create Standard File",
"Usage:"
"\n\thf mfdes createstdfile -a 123456 -f 1122 -n 01 -c 0 -r EEEE -s 000010\n"
);
void *argtable[] = {
arg_param_begin,
arg_strx0("aA", "aid", "<aid>", "AID for file (3 hex bytes, big endian)"),
arg_strx0("nN", "fileno", "<fileno>", "File Number (0x00 - 0x1F)"),
arg_strx0("fF", "fileid", "<fileid>", "ISO FID (2 hex bytes, big endian)"),
arg_int0("cC", "com.set", "<comset>", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"),
arg_strx0("rR", "accessrights", "<accessrights>", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"),
arg_strx0("sS", "filesize", "<filesize>", "File size (3 hex bytes, big endian)"),
arg_param_end
};
CLIExecWithReturn(Cmd, argtable, false);
uint8_t fileno[] = {0};
int aidlength = 0;
uint8_t aid[3] = {0};
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
CLIGetHexWithReturn(2, fileno, &filenolen);
int fidlength = 0;
uint8_t fid[2] = {0};
CLIParamHexToBuf(arg_get_str(3), fid, 2, &fidlength);
uint8_t comset = arg_get_int(4);
int arlength = 0;
uint8_t ar[2] = {0};
CLIGetHexWithReturn(5, ar, &arlength);
int fsizelen = 0;
uint8_t filesize[3] = {0};
CLIGetHexWithReturn(6, filesize, &fsizelen);
CLIParserFree();
swap16(fid);
swap24(filesize);
if (comset != 0 && comset != 1 && comset != 3) {
PrintAndLogEx(ERR, "Communication setting must be either 0=Plain, 1=Plain+MAC or 3=Encrypt.");
return PM3_EINVARG;
}
if (arlength < 2) {
PrintAndLogEx(ERR, "Access rights must have 2 hex bytes length.");
return PM3_EINVARG;
}
if (fsizelen < 3) {
PrintAndLogEx(ERR, "Filesize must have 3 hex bytes length.");
return PM3_EINVARG;
}
if (fidlength < 2) {
PrintAndLogEx(ERR, "ISO File id must have 2 hex bytes length.");
return PM3_EINVARG;
}
// AID
if (aidlength != 3) {
PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3);
return PM3_EINVARG;
}
int res = get_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Couldn't select aid.");
DropField();
return res;
}
mfdes_file_t ft;
memcpy(ft.fid, fid, 2);
memcpy(ft.filesize, filesize, 3);
ft.fileno = fileno[0];
ft.comset = comset;
memcpy(ft.access_rights, ar, 2);
res = get_desfire_create_std_file(&ft);
if (res == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Successfully created standard file.");
} else {
PrintAndLogEx(ERR, "Couldn't create standard file. Error %d", res);
DropField();
}
return res;
}
static int CmdHF14ADesFormatPICC(const char *Cmd) {
CLIParserInit("hf mfdes formatpicc",
@ -1414,6 +2064,8 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) {
}
PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X%02X%02X"), aid[2], aid[1], aid[0]);
PrintAndLogEx(SUCCESS, " AID Function Cluster 0x%02X: " _YELLOW_("%s"), aid[2], cluster_to_text(aid[2]));
for (int m = 0; m < dfname_count; m++) {
if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) {
PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X%02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[1], dfnames[m].fid[0], dfnames[m].name);
@ -1488,17 +2140,19 @@ static int CmdHF14ADesAuth(const char *Cmd) {
CLIParserInit("hf mfdes auth",
"Authenticates Mifare DESFire using Key",
"Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=2K3DES, 4=3K3DES, 5=AES)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n"
"Example:\n\thf mfdes auth -m 3 -t 5 -a 838001 -n 0 -k 00000000000000000000000000000000\n"
"Usage:"
"\n\thf mfdes auth -m 3 -t 4 -a 808301 -n 0 -k 00000000000000000000000000000000 (AES)"
"\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 0 -k 00000000000000000000000000000000 (3DES)"
"\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 0 -k 0000000000000000 (DES)"
);
void *argtable[] = {
arg_param_begin,
arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes, 4=picc)", NULL),
arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=2K3DES, 4=3K3DES, 5=AES)", NULL),
arg_int0("mM", "type", "<type>", "Auth type (1=normal, 2=iso, 3=aes, 4=picc)"),
arg_int0("tT", "algo", "<algo>", "Crypt algo (1=DES, 2=3DES(2K2DES), 4=3K3DES, 5=AES)"),
arg_strx0("aA", "aid", "<aid>", "AID used for authentification (HEX 3 bytes)"),
arg_int0("nN", "keyno", "Key number used for authentification", NULL),
arg_str0("kK", "key", "<Key>", "Key for checking (HEX 16 bytes)"),
arg_int0("nN", "keyno", "<keyno>", "Key number used for authentification"),
arg_str0("kK", "key", "<Key>", "Key for checking (HEX 8-24 bytes)"),
arg_param_end
};
CLIExecWithReturn(Cmd, argtable, false);
@ -1536,7 +2190,7 @@ static int CmdHF14ADesAuth(const char *Cmd) {
}
break;
case MFDES_AUTH_ISO:
if (cmdAuthAlgo != MFDES_ALGO_2K3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) {
if (cmdAuthAlgo != MFDES_ALGO_3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) {
PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode");
return PM3_EINVARG;
}
@ -1559,13 +2213,9 @@ static int CmdHF14ADesAuth(const char *Cmd) {
}
switch (cmdAuthAlgo) {
case MFDES_ALGO_2K3DES:
keylength = 16;
PrintAndLogEx(NORMAL, "2 key 3DES selected");
break;
case MFDES_ALGO_3DES:
keylength = 16;
PrintAndLogEx(NORMAL, "3DES selected");
PrintAndLogEx(NORMAL, "2 key 3DES selected");
break;
case MFDES_ALGO_3K3DES:
keylength = 24;
@ -1605,7 +2255,7 @@ static int CmdHF14ADesAuth(const char *Cmd) {
payload.mode = cmdAuthMode;
payload.algo = cmdAuthAlgo;
payload.keyno = cmdKeyNo;
SendCommandNG(CMD_HF_DESFIRE_AUTH1, (uint8_t *)&payload, sizeof(payload));
/*SendCommandNG(CMD_HF_DESFIRE_AUTH1, (uint8_t *)&payload, sizeof(payload));
PacketResponseNG resp;
@ -1614,15 +2264,14 @@ static int CmdHF14ADesAuth(const char *Cmd) {
DropField();
return PM3_ETIMEOUT;
}
uint8_t isOK = (resp.status == PM3_SUCCESS);
if (isOK) {
struct mfdes_auth_res *rpayload = (struct mfdes_auth_res *)&resp.data.asBytes;
*/
mfdes_auth_res_t rpayload;
if (get_desfire_auth(&payload, &rpayload) == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength));
PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(rpayload->sessionkey, keylength));
PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(rpayload.sessionkey, keylength));
PrintAndLogEx(INFO, "-------------------------------------------------------------");
} else {
PrintAndLogEx(WARNING, _RED_("Auth command failed, reason: %d."), resp.status);
return PM3_ESOFT;
}
PrintAndLogEx(INFO, "-------------------------------------------------------------");
return PM3_SUCCESS;
@ -1633,15 +2282,57 @@ static int CmdHF14ADesList(const char *Cmd) {
return CmdTraceList("des");
}
static int CmdTest(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
uint8_t IV[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t key[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
/*[=] encRndB: 1A BE 10 8D 09 E0 18 13
[=] RndB: 57 9B 94 21 40 2C C6 D7
[=] 3keyenc: 6E 6A EB 86 6E 6A EB 86 9B 94 21 40 2C C6 D7 00
6E 6A EB 86 6E 6A EB 86 9B 94 21 40 2C C6 D7 57
[=] Both: 32 B2 E4 1A 14 CF 8B 34 B4 F9 30 43 5B 68 A3 FD
[=] RndA: 6E 6A EB 86 6E 6A EB 86
*/
uint8_t encRndB[8] = {0x1A, 0xBE, 0x10, 0x8D, 0x09, 0xE0, 0x18, 0x13};
/*
* RndB_enc: DE 50 F9 23 10 CA F5 A5
* RndB: 4C 64 7E 56 72 E2 A6 51
* RndB_rot: 64 7E 56 72 E2 A6 51 4C
* RndA: C9 6C E3 5E 4D 60 87 F2
* RndAB: C9 6C E3 5E 4D 60 87 F2 64 7E 56 72 E2 A6 51 4C
* RndAB_enc: E0 06 16 66 87 04 D5 54 9C 8D 6A 13 A0 F8 FC ED
*/
uint8_t RndB[8] = {0};
uint8_t RndA[8] = {0x6E, 0x6A, 0xEB, 0x86, 0x6E, 0x6A, 0xEB, 0x86};
tdes_nxp_receive(encRndB, RndB, 8, key, IV, 2);
uint8_t rotRndB[8] = {0};
memcpy(rotRndB, RndB, 8);
rol(rotRndB, 8);
uint8_t tmp[16] = {0x00};
uint8_t both[16] = {0x00};
memcpy(tmp, RndA, 8);
memcpy(tmp + 8, rotRndB, 8);
PrintAndLogEx(INFO, "3keyenc: %s", sprint_hex(tmp, 16));
PrintAndLogEx(SUCCESS, " Res : " _GREEN_("%s"), sprint_hex(IV, 8));
tdes_nxp_send(tmp, both, 16, key, IV, 2);
PrintAndLogEx(SUCCESS, " Res : " _GREEN_("%s"), sprint_hex(both, 16));
return PM3_SUCCESS;
}
static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"test", CmdTest, AlwaysAvailable, "Test"},
{"info", CmdHF14ADesInfo, IfPm3Iso14443a, "Tag information"},
{"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"},
{"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"},
{"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"},
{"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"},
{"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"},
{"createstdfile", CmdHF14ADesCreateStdFile, IfPm3Iso14443a, "Create Standard File"},
{"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"},
// {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"},
// {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"},
/*
@ -1655,6 +2346,9 @@ static command_t CommandTable[] = {
'88' Internal Authenticate
'82' External Authenticate
Write Data:
90 3d 00 00 16 01 00 00 00 0f 00 00 00 0f 20 00 3b 00 34 04 06 e1 04 0f fe 00 00 00
90 3d 00 00 09 02 00 00 00 02 00 00 00 00 00
*/
{NULL, NULL, NULL, NULL}
};

View file

@ -2734,7 +2734,6 @@ static int CmdHF14MfuNDEF(const char *Cmd) {
arg_param_end
};
CLIExecWithReturn(Cmd, argtable, true);
CLIGetHexWithReturn(1, key, &keylen);
swapEndian = arg_get_lit(2);
CLIParserFree();
@ -2753,7 +2752,10 @@ static int CmdHF14MfuNDEF(const char *Cmd) {
// Get tag type
TagTypeUL_t tagtype = GetHF14AMfU_Type();
if (tagtype == UL_ERROR) return PM3_ESOFT;
if (tagtype == UL_ERROR) {
PrintAndLogEx(WARNING, "No Ultraligth / NTAG based tag found");
return PM3_ESOFT;
}
// Is tag UL/NTAG?

View file

@ -0,0 +1,884 @@
/*-
* 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 <stdio.h>
#include <string.h>
#include "commonutil.h"
#include "crc32.h"
#include "mbedtls/aes.h"
#include "mbedtls/des.h"
#include "ui.h"
#include "crc.h"
#include "crc16.h" // crc16 ccitt
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
#define htole32(x) (x)
#define CRC32_PRESET 0xFFFFFFFF
static void crc32_byte(uint32_t *crc, const uint8_t value);
static void crc32_byte(uint32_t *crc, const uint8_t value) {
/* x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1 */
const uint32_t poly = 0xEDB88320;
*crc ^= value;
for (int current_bit = 7; current_bit >= 0; current_bit--) {
int bit_out = (*crc) & 0x00000001;
*crc >>= 1;
if (bit_out)
*crc ^= poly;
}
}
void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc) {
uint32_t desfire_crc = CRC32_PRESET;
for (size_t i = 0; i < len; i++) {
crc32_byte(&desfire_crc, data[i]);
}
*((uint32_t *)(crc)) = htole32(desfire_crc);
}
void crc32_append(uint8_t *data, const size_t len) {
crc32_ex(data, len, data + len);
}
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,137 @@
#ifndef __DESFIRE_CRYPTO_H
#define __DESFIRE_CRYPTO_H
#include "common.h"
#include "mifare.h" // structs
//#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 crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc);
void crc32_append(uint8_t *data, const size_t len);
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

View file

@ -1,40 +1,7 @@
/*****************************************************************************
* WARNING
*
* THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY.
*
* USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL
* PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL,
* AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES.
*
* THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS.
*
*****************************************************************************
*
* This file is part of loclass. It is a reconstructon of the cipher engine
* used in iClass, and RFID techology.
*
* The implementation is based on the work performed by
* Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and
* Milosch Meriac in the paper "Dismantling IClass".
*
* Copyright (C) 2014 Martin Holst Swende
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, or, at your option, any later version.
*
* This file 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 General Public License
* along with loclass. If not, see <http://www.gnu.org/licenses/>.
*
*
****************************************************************************/
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
// Preferences Functions
//-----------------------------------------------------------------------------
@ -56,14 +23,36 @@
#include <string.h>
#include "cmdparser.h"
#include <ctype.h>
#include <unistd.h>
//#include "proxgui.h"
//extern void SetWindowsPosition (void);
static int CmdHelp(const char *Cmd);
static int setCmdHelp(const char *Cmd);
// Load all settings into memory (struct)
static char* prefGetFilename (void) {
/*
static char Buffer[FILENAME_MAX+sizeof(preferencesFilename)+2] = {0};
char PATH[FILENAME_MAX] = {0};
getcwd(PATH, sizeof(PATH));
#ifdef _WIN32
snprintf (Buffer,sizeof(Buffer)-1,"%s\\%s",PATH,preferencesFilename);
#else
snprintf (Buffer,sizeof(Buffer)-1,"%s/%s",PATH,preferencesFilename);
#endif
return Buffer;
*/
return preferencesFilename;
}
int preferences_load (void) {
// Set all defaults
session.client_debug_level = OFF;
session.window_changed = false;
session.window_plot_xpos = 10;
session.window_plot_ypos = 30;
session.window_plot_hsize = 400;
@ -76,12 +65,13 @@ int preferences_load (void) {
session.show_hints = false;
session.supports_colors = false;
// loadFileJson wants these, so pass in place holder values, though not used
// in settings load;
uint8_t dummyData = 0x00;
size_t dummyDL = 0x00;
if (loadFileJSON(preferencesFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) {
if (loadFileJSON(prefGetFilename(), &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) {
session.preferences_loaded = true;
}
// Note, if session.settings_loaded == false then the settings_save
@ -93,9 +83,11 @@ int preferences_load (void) {
// Save all settings from memory (struct) to file
int preferences_save (void) {
// Note sure if backup has value ?
char backupFilename[500];
snprintf (backupFilename,sizeof(backupFilename),"%s.bak",preferencesFilename);
char backupFilename[FILENAME_MAX+sizeof(preferencesFilename)+10] = {0};
PrintAndLogEx(INFO,"Saving preferences ...");
snprintf (backupFilename,sizeof(backupFilename)-1,"%s.bak",prefGetFilename());
if (fileExists (backupFilename)) {
if (remove (backupFilename) != 0) {
@ -104,9 +96,9 @@ int preferences_save (void) {
}
}
if (fileExists (preferencesFilename)) {
if (rename (preferencesFilename,backupFilename) != 0) {
PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",preferencesFilename,backupFilename);
if (fileExists (prefGetFilename())) {
if (rename (prefGetFilename(),backupFilename) != 0) {
PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",prefGetFilename(),backupFilename);
return PM3_ESOFT;
}
}
@ -114,8 +106,8 @@ int preferences_save (void) {
uint8_t dummyData = 0x00;
size_t dummyDL = 0x00;
if (saveFileJSON(preferencesFilename, jsfSettings, &dummyData, dummyDL) != PM3_SUCCESS)
PrintAndLogEx (ERR, "Error saving preferences to \"%s\"",preferencesFilename);
if (saveFileJSON(prefGetFilename(), jsfSettings, &dummyData, dummyDL) != PM3_SUCCESS)
PrintAndLogEx (ERR, "Error saving preferences to \"%s\"",prefGetFilename());
return PM3_SUCCESS;
}
@ -215,106 +207,99 @@ void preferences_load_callback (json_t *root) {
}
// Help Functions
static int usage_pref_set() {
PrintAndLogEx(NORMAL, "Usage: pref set [(h)elp] [(e)moji ...] [(c)olor ...] [(hi)nts ...] [debug ...]");
PrintAndLogEx(NORMAL, " [(p)lot ...] [(o)verlay ...]");
static int usage_set_emoji() {
PrintAndLogEx(NORMAL, "Usage: pref set emoji <alias | emoji | alttext | erase>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " help - This help");
PrintAndLogEx(NORMAL, " emoji <(ali)as | (em)oji | (alt)text | (er)ase> - Set the level of emoji support");
PrintAndLogEx(NORMAL, " alias : show alias");
PrintAndLogEx(NORMAL, " emoji : show emoji");
PrintAndLogEx(NORMAL, " alttext : show alternative text");
PrintAndLogEx(NORMAL, " erase : dont show any emoji");
PrintAndLogEx(NORMAL, " color <(o)ff|(a)nsi> - Color support level");
PrintAndLogEx(NORMAL, " off : dont use color");
PrintAndLogEx(NORMAL, " ansi : use ansi color (linux, mac, windows terminal)");
PrintAndLogEx(NORMAL, " hints <(of)f | on> - Show hints on/off");
PrintAndLogEx(NORMAL, " debug <(o)ff | (s)imple | (f)ull> - Client debug level");
PrintAndLogEx(NORMAL, " off : no debug output");
PrintAndLogEx(NORMAL, " simple : information level debug");
PrintAndLogEx(NORMAL, " full : full debug information");
PrintAndLogEx(NORMAL, " plot [x <val>] [y <val>] [h <val>] [w <val>] - Position the plot window");
PrintAndLogEx(NORMAL, " overlay [x <val>] [y <val>] [h <val>] [w <val>] - Position the overlay/slider window");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
PrintAndLogEx(NORMAL, " "_GREEN_("alias")" - Show alias for emoji");
PrintAndLogEx(NORMAL, " "_GREEN_("emoji")" - Show amoji");
PrintAndLogEx(NORMAL, " "_GREEN_("alttext")" - Show alt text for emoji");
PrintAndLogEx(NORMAL, " "_GREEN_("erase")" - Dont show emoji or text");
return PM3_SUCCESS;
}
static int usage_pref_show() {
PrintAndLogEx(NORMAL, "Usage: pref show [help] [emoji|color]");
static int usage_set_color() {
PrintAndLogEx(NORMAL, "Usage: pref set color <off | ansi>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " help - This help");
PrintAndLogEx(NORMAL, " emoji - show current settings for emoji");
PrintAndLogEx(NORMAL, " color - show current settings for color");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
PrintAndLogEx(NORMAL, " "_GREEN_("off")" - Dont use colors");
PrintAndLogEx(NORMAL, " "_GREEN_("ansi")" - Use ANSI colors");
return PM3_SUCCESS;
}
static int usage_set_debug() {
PrintAndLogEx(NORMAL, "Usage: pref set debug <off | simple | full>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
PrintAndLogEx(NORMAL, " "_GREEN_("off")" - no debug messages");
PrintAndLogEx(NORMAL, " "_GREEN_("simple")" - simple debug messages");
PrintAndLogEx(NORMAL, " "_GREEN_("full")" - full debug messages");
return PM3_SUCCESS;
}
static int usage_set_hints() {
PrintAndLogEx(NORMAL, "Usage: pref set hints <off | on>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
PrintAndLogEx(NORMAL, " "_GREEN_("off")" - Dont display hints");
PrintAndLogEx(NORMAL, " "_GREEN_("on")" - Display hints");
return PM3_SUCCESS;
}
// Preference Processing Functions
typedef enum preferenceId {prefNONE,prefHELP,prefEMOJI,prefCOLOR,prefPLOT,prefOVERLAY,prefHINTS,prefCLIENTDEBUG} preferenceId_t;
typedef enum prefShowOpt {prefShowNone,prefShowOLD,prefShowNEW} prefShowOpt_t;
// Enumerate text to ID
preferenceId_t prefGetID (char* cmdOpt)
const char *prefShowMsg (prefShowOpt_t Opt)
{
str_lower (cmdOpt);
if (strncmp (cmdOpt,"hi",2) == 0) return prefHINTS;
if (strncmp (cmdOpt,"h",1) == 0) return prefHELP;
if (strncmp (cmdOpt,"e",1) == 0) return prefEMOJI;
if (strncmp (cmdOpt,"c",1) == 0) return prefCOLOR;
if (strncmp (cmdOpt,"p",1) == 0) return prefPLOT;
if (strncmp (cmdOpt,"o",1) == 0) return prefOVERLAY;
if (strncmp (cmdOpt,"d",1) == 0) return prefCLIENTDEBUG;
return NONE;
switch (Opt) {
case prefShowOLD: return _YELLOW_("[old]"); //strncpy(Msg,"Before ",sizeof(Msg)-1); break;
case prefShowNEW: return _GREEN_("[new]"); // strncpy(Msg,"After ",sizeof(Msg)-1); break;
case prefShowNone: return "";
}
return "";
}
void showEmojiState (void) {
void showEmojiState (prefShowOpt_t Opt) {
switch (session.emoji_mode) {
case ALIAS: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("show alias"));
case ALIAS: PrintAndLogEx(NORMAL, " %s emoji.................. "_GREEN_("alias"),prefShowMsg (Opt));
break;
case EMOJI: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("show emoji"));
case EMOJI: PrintAndLogEx(NORMAL, " %s emoji.................. "_GREEN_("emoji"),prefShowMsg (Opt));
break;
case ALTTEXT: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("show alt text"));
case ALTTEXT: PrintAndLogEx(NORMAL, " %s emoji.................. "_GREEN_("alttext"),prefShowMsg (Opt));
break;
case ERASE: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("dont show emoji"));
case ERASE: PrintAndLogEx(NORMAL, " %s emoji.................. "_GREEN_("erase"),prefShowMsg (Opt));
break;
default:
PrintAndLogEx(NORMAL, " emoji.................. "_RED_("unknown"));
PrintAndLogEx(NORMAL, " %s emoji.................. "_RED_("unknown"),prefShowMsg(Opt));
}
}
void showColorState (void) {
/*
switch (session.supports_colors) {
case false: PrintAndLogEx(NORMAL, "Color : "_GREEN_("off"));
break;
case true: PrintAndLogEx(NORMAL, "Color : "_GREEN_("ansi"));
break;
default:
PrintAndLogEx(NORMAL, "Color support set to : "_RED_("unknown"));
}
*/
// this will change to 1 of a set from bool
void showColorState (prefShowOpt_t Opt) {
if (session.supports_colors)
PrintAndLogEx(NORMAL, " color.................. "_GREEN_("ansi"));
PrintAndLogEx(NORMAL, " %s color.................. "_GREEN_("ansi"),prefShowMsg(Opt));
else
PrintAndLogEx(NORMAL, " color.................. "_GREEN_("off"));
PrintAndLogEx(NORMAL, " %s color.................. "_GREEN_("off"),prefShowMsg(Opt));
}
void showClientDebugState (void) {
void showClientDebugState (prefShowOpt_t Opt) {
switch (session.client_debug_level) {
case OFF: PrintAndLogEx (NORMAL," client debug........... "_GREEN_("off"));
case OFF: PrintAndLogEx (NORMAL," %s client debug........... "_GREEN_("off"),prefShowMsg(Opt));
break;
case SIMPLE: PrintAndLogEx (NORMAL," client debug........... "_GREEN_("simple"));
case SIMPLE: PrintAndLogEx (NORMAL," %s client debug........... "_GREEN_("simple"),prefShowMsg(Opt));
break;
case FULL: PrintAndLogEx (NORMAL," client debug........... "_GREEN_("full"));
case FULL: PrintAndLogEx (NORMAL," %s client debug........... "_GREEN_("full"),prefShowMsg(Opt));
break;
default:
PrintAndLogEx(NORMAL, " client debug........... "_RED_("unknown"));
PrintAndLogEx(NORMAL, " %s client debug........... "_RED_("unknown"),prefShowMsg(Opt));
}
}
@ -328,19 +313,239 @@ void showOverlayPosState (void){
session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_hsize,session.window_overlay_wsize);
}
void showHintsState (void){
void showHintsState (prefShowOpt_t Opt){
if (session.show_hints)
PrintAndLogEx (NORMAL," Hints.................. "_GREEN_("on"));
PrintAndLogEx (NORMAL," %s Hints.................. "_GREEN_("on"),prefShowMsg(Opt));
else
PrintAndLogEx (NORMAL," Hints.................. "_GREEN_("off"));
PrintAndLogEx (NORMAL," %s Hints.................. "_GREEN_("off"),prefShowMsg(Opt));
}
static int setCmdEmoji (const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
bool validValue = false;
char strOpt[50];
emojiMode_t newValue = session.emoji_mode;
if (param_getchar(Cmd, cmdp) == 0x00)
return usage_set_emoji();
while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) {
if (param_getstr(Cmd, cmdp++, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt); // convert to lowercase
if (strncmp (strOpt,"help",4) == 0)
return usage_set_emoji();
if (strncmp (strOpt,"alias",5) == 0) {
validValue = true;
newValue = ALIAS;
}
if (strncmp (strOpt,"emoji",5) == 0) {
validValue = true;
newValue = EMOJI;
}
if (strncmp (strOpt,"alttext",7) == 0) {
validValue = true;
newValue = ALTTEXT;
}
if (strncmp (strOpt,"erase",5) == 0) {
validValue = true;
newValue = ERASE;
}
if (validValue) {
if (session.emoji_mode != newValue) {// changed
showEmojiState (prefShowOLD);
session.emoji_mode = newValue;
showEmojiState (prefShowNEW);
preferences_save ();
} else {
PrintAndLogEx(INFO,"nothing changed");
showEmojiState (prefShowNone);
}
} else {
PrintAndLogEx(ERR,"invalid option");
return usage_set_emoji();
}
}
}
return PM3_SUCCESS;
}
static int setCmdColor (const char *Cmd)
{
uint8_t cmdp = 0;
bool errors = false;
bool validValue = false;
char strOpt[50];
bool newValue = session.supports_colors;
if (param_getchar(Cmd, cmdp) == 0x00)
return usage_set_color();
while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) {
if (param_getstr(Cmd, cmdp++, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt); // convert to lowercase
if (strncmp (strOpt,"help",4) == 0)
return usage_set_color();
if (strncmp (strOpt,"off",3) == 0) {
validValue = true;
newValue = false;
}
if (strncmp (strOpt,"ansi",4) == 0) {
validValue = true;
newValue = true;
}
if (validValue) {
if (session.supports_colors != newValue) {// changed
showColorState (prefShowOLD);
session.supports_colors = newValue;
showColorState (prefShowNEW);
preferences_save ();
} else {
PrintAndLogEx(INFO,"nothing changed");
showColorState (prefShowNone);
}
} else {
PrintAndLogEx(ERR,"invalid option");
return usage_set_color();
}
}
}
return PM3_SUCCESS;
}
static int setCmdDebug (const char *Cmd)
{
uint8_t cmdp = 0;
bool errors = false;
bool validValue = false;
char strOpt[50];
clientdebugLevel_t newValue = session.client_debug_level;
if (param_getchar(Cmd, cmdp) == 0x00)
return usage_set_debug();
while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) {
if (param_getstr(Cmd, cmdp++, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt); // convert to lowercase
if (strncmp (strOpt,"help",4) == 0)
return usage_set_debug();
if (strncmp (strOpt,"off",3) == 0) {
validValue = true;
newValue = OFF;
}
if (strncmp (strOpt,"simple",6) == 0) {
validValue = true;
newValue = SIMPLE;
}
if (strncmp (strOpt,"full",4) == 0) {
validValue = true;
newValue = FULL;
}
if (validValue) {
if (session.client_debug_level != newValue) {// changed
showClientDebugState (prefShowOLD);
session.client_debug_level = newValue;
g_debugMode = newValue;
showClientDebugState (prefShowNEW);
preferences_save ();
} else {
PrintAndLogEx(INFO,"nothing changed");
showClientDebugState (prefShowNone);
}
} else {
PrintAndLogEx(ERR,"invalid option");
return usage_set_debug();
}
}
}
return PM3_SUCCESS;
}
static int setCmdHint (const char *Cmd)
{
uint8_t cmdp = 0;
bool errors = false;
bool validValue = false;
char strOpt[50];
bool newValue = session.show_hints;
if (param_getchar(Cmd, cmdp) == 0x00)
return usage_set_hints();
while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) {
if (param_getstr(Cmd, cmdp++, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt); // convert to lowercase
if (strncmp (strOpt,"help",4) == 0)
return usage_set_hints();
if (strncmp (strOpt,"off",3) == 0) {
validValue = true;
newValue = false;
}
if (strncmp (strOpt,"on",2) == 0) {
validValue = true;
newValue = true;
}
if (validValue) {
if (session.show_hints != newValue) {// changed
showHintsState (prefShowOLD);
session.show_hints = newValue;
showHintsState (prefShowNEW);
preferences_save ();
} else {
PrintAndLogEx(INFO,"nothing changed");
showHintsState (prefShowNone);
}
} else {
PrintAndLogEx(ERR,"invalid option");
return usage_set_hints();
}
}
}
return PM3_SUCCESS;
}
static command_t setCommandTable[] = {
{"help", setCmdHelp, AlwaysAvailable, "This help"},
{"emoji", setCmdEmoji, AlwaysAvailable, "Set emoji display"},
{"color", setCmdColor, AlwaysAvailable, "Set color support"},
{"debug", setCmdDebug, AlwaysAvailable, "Set client debug level"},
{"hints", setCmdHint, AlwaysAvailable, "Set hint display"},
{NULL, NULL, NULL, NULL}
};
static int setCmdHelp(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CmdsHelp(setCommandTable);
return PM3_SUCCESS;
}
int CmdPrefSet (const char *Cmd)
{
clearCommandBuffer();
return CmdsParse(setCommandTable, Cmd);
}
static int CmdPrefShow (const char *Cmd) {
uint8_t cmdp = 0;
preferenceId_t CmdPref;
bool errors = false;
char strOpt[50];
PrintAndLogEx(NORMAL,"");
PrintAndLogEx(NORMAL,_BLUE_("Preferences"));
@ -349,203 +554,29 @@ static int CmdPrefShow (const char *Cmd) {
return PM3_ESOFT;
}
if (param_getchar(Cmd, cmdp) == 0x00) { // No options - Show all
showEmojiState ();
showColorState ();
showPlotPosState ();
showOverlayPosState ();
showClientDebugState();
showHintsState ();
}
else {
while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) {
showEmojiState (prefShowNone);
showColorState (prefShowNone);
// showPlotPosState ();
// showOverlayPosState ();
showClientDebugState(prefShowNone);
showHintsState (prefShowNone);
if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) {
CmdPref = prefGetID(strOpt);
}
else
CmdPref = prefNONE;
switch (CmdPref) {
case prefHELP:
return usage_pref_show();
case prefEMOJI:
showEmojiState ();
break;
case prefCOLOR: // color
showColorState ();
break;
case prefPLOT:
showPlotPosState ();
break;
case prefOVERLAY:
showOverlayPosState ();
break;
case prefCLIENTDEBUG:
showClientDebugState();
break;
case prefHINTS:
showHintsState();
break;
case prefNONE:
PrintAndLogEx (ERR,"Invalid option supplied");
errors = true;
break;
// errors
}
cmdp ++;
}
}
PrintAndLogEx(NORMAL,"");
return PM3_SUCCESS;
}
static int CmdPrefSet (const char *Cmd)
{
uint8_t cmdp = 0;
preferenceId_t CmdPref;
bool errors = false;
// char charOpt;
char strOpt[50];
int x,y,h,w;
if (param_getchar(Cmd, cmdp) == 0x00)
return usage_pref_set();
while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) {
if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) {
CmdPref = prefGetID(strOpt);
}
else
CmdPref = prefNONE;
switch (CmdPref) {
case prefHELP:
return usage_pref_set();
case prefEMOJI:
showEmojiState ();
cmdp++;
if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt);
if (strncmp (strOpt,"ali",3) == 0) { session.emoji_mode = ALIAS; showEmojiState (); break; }
if (strncmp (strOpt,"em",2) == 0) { session.emoji_mode = EMOJI; showEmojiState (); break; }
if (strncmp (strOpt,"alt",3) == 0) { session.emoji_mode = ALTTEXT; showEmojiState (); break; }
if (strncmp (strOpt,"er",2) == 0) { session.emoji_mode = ERASE; showEmojiState (); break; }
// if we get this far, then an error in the mode
PrintAndLogEx(ERR,"Invalid emoji option");
errors = true;
}
else
errors = true;
break;
case prefCOLOR: // color
showColorState ();
cmdp++;
if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt);
if (strncmp(strOpt,"a",1) == 0) { session.supports_colors = true; showColorState (); break; }
if (strncmp(strOpt,"o",1) == 0) { session.supports_colors = false; showColorState (); break; }
// if we get this far, then an error in the mode
PrintAndLogEx(ERR,"Invalid color option");
errors = true;
}
else
errors = true;
break;
case prefPLOT:
showPlotPosState ();
cmdp++;
x = y = h = w = -99999; // Some invalid value
for (int i = 0; i < 4; i++) { // upto 4 values X, Y, H, WARNING
if (param_getchar(Cmd, cmdp) != 0){
switch (tolower(param_getchar(Cmd, cmdp++))) {
case 'x': x = param_get32ex(Cmd,cmdp++,-99999,10); break;
case 'y': y = param_get32ex(Cmd,cmdp++,-99999,10); break;
case 'h': h = param_get32ex(Cmd,cmdp++,-99999,10); break;
case 'w': w = param_get32ex(Cmd,cmdp++,-99999,10); break;
default:
errors = true;
}
}
}
if (x != -99999) session.window_plot_xpos = x;
if (y != -99999) session.window_plot_ypos = y;
if (h != -99999) session.window_plot_hsize = h;
if (w != -99999) session.window_plot_wsize = w;
// Need to work out how to change live....
// calling data plot seems to work
showPlotPosState ();
break;
case prefOVERLAY:
showOverlayPosState ();
cmdp++;
x = y = h = w = -99999; // Some invalid value
for (int i = 0; i < 4; i++) { // upto 4 values X, Y, H, WARNING
if (param_getchar(Cmd, cmdp) != 0){
switch (tolower(param_getchar(Cmd, cmdp++))) {
case 'x': x = param_get32ex(Cmd,cmdp++,-99999,10); break;
case 'y': y = param_get32ex(Cmd,cmdp++,-99999,10); break;
case 'h': h = param_get32ex(Cmd,cmdp++,-99999,10); break;
case 'w': w = param_get32ex(Cmd,cmdp++,-99999,10); break;
default:
errors = true;
}
}
}
if (x != -99999) session.window_overlay_xpos = x;
if (y != -99999) session.window_overlay_ypos = y;
if (h != -99999) session.window_overlay_hsize = h;
if (w != -99999) session.window_overlay_wsize = w;
showOverlayPosState ();
// Need to work out how to change live....
break;
case prefCLIENTDEBUG:
showClientDebugState();
cmdp++;
if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt);
if (strncmp(strOpt,"o",1) == 0) { session.client_debug_level = OFF; g_debugMode = OFF; showClientDebugState(); break; }
if (strncmp(strOpt,"s",1) == 0) { session.client_debug_level = SIMPLE; g_debugMode = SIMPLE; showClientDebugState(); break; }
if (strncmp(strOpt,"f",1) == 0) { session.client_debug_level = FULL; g_debugMode = FULL; showClientDebugState(); break; }
// if we get this far, then an error in the mode
PrintAndLogEx(ERR,"Invalid client debug option");
errors = true;
}
else
errors = true;
break;
case prefHINTS:
showHintsState ();
cmdp++;
if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) {
str_lower(strOpt);
if (strncmp(strOpt,"on",2) == 0) { session.show_hints = true; showHintsState (); break; }
if (strncmp(strOpt,"of",2) == 0) { session.show_hints = false; showHintsState (); break; }
// if we get this far, then an error in the mode
PrintAndLogEx(ERR,"Invalid hint option");
errors = true;
}
else
errors = true;
break;
case prefNONE:
PrintAndLogEx (ERR,"Invalid option supplied");
errors = true;
break;
}
cmdp ++;
}
/*
static int CmdPrefSave (const char *Cmd) {
preferences_save();
return PM3_SUCCESS;
}
*/
static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"set", CmdPrefSet, AlwaysAvailable, "Set a preference"},
{"show", CmdPrefShow, AlwaysAvailable, "Show (a preference)"},
{"show", CmdPrefShow, AlwaysAvailable, "Show preferences"},
// {"save", CmdPrefSave, AlwaysAvailable, "Save preferences now"},
{NULL, NULL, NULL, NULL}
};

View file

@ -1,7 +1,4 @@
//-----------------------------------------------------------------------------
// Copyright (C) 2009 Michael Gernoth <michael at gernoth.net>
// Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
//
// 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.
@ -13,6 +10,7 @@
#include "fileutils.h"
// Current working directory will be prepended.
#define preferencesFilename "preferences.json"
int CmdPreferences (const char *Cmd);

View file

@ -28,6 +28,8 @@
#include <QtGui>
#include "ui.h"
extern "C" int preferences_save (void);
extern "C" {
#include "util_darwin.h"
}
@ -129,6 +131,32 @@ ProxGuiQT::~ProxGuiQT(void) {
}
}
// -------------------------------------------------
// Slider Widget form based on a class to enable
// Event override functions
// -------------------------------------------------
SliderWidget::SliderWidget() {
// Set the initail postion and size from settings
if (session.preferences_loaded)
setGeometry (session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_wsize,session.window_overlay_hsize);
else
resize(800, 400);
}
void SliderWidget::resizeEvent (QResizeEvent *event) {
session.window_overlay_hsize = event->size().height();
session.window_overlay_wsize = event->size().width();
session.window_changed = true;
}
void SliderWidget::moveEvent (QMoveEvent *event) {
session.window_overlay_xpos = event->pos().x();
session.window_overlay_ypos = event->pos().y();
session.window_changed = true;
}
//--------------------
void ProxWidget::applyOperation() {
//printf("ApplyOperation()");
@ -176,7 +204,7 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) {
resize(800, 400);
// Setup the controller widget
controlWidget = new QWidget();
controlWidget = new SliderWidget ();//new QWidget();
opsController = new Ui::Form();
opsController->setupUi(controlWidget);
//Due to quirks in QT Designer, we need to fiddle a bit
@ -189,7 +217,6 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) {
opsController->horizontalSlider_askedge->setValue(25);
opsController->horizontalSlider_window->setValue(4000);
QObject::connect(opsController->pushButton_apply, SIGNAL(clicked()), this, SLOT(applyOperation()));
QObject::connect(opsController->pushButton_sticky, SIGNAL(clicked()), this, SLOT(stickOperation()));
QObject::connect(opsController->horizontalSlider_window, SIGNAL(valueChanged(int)), this, SLOT(vchange_autocorr(int)));
@ -197,6 +224,8 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) {
QObject::connect(opsController->horizontalSlider_dirthr_down, SIGNAL(valueChanged(int)), this, SLOT(vchange_dthr_down(int)));
QObject::connect(opsController->horizontalSlider_askedge, SIGNAL(valueChanged(int)), this, SLOT(vchange_askedge(int)));
controlWidget->setGeometry (session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_wsize,session.window_overlay_hsize);
// Set up the plot widget, which does the actual plotting
plot = new Plot(this);
QVBoxLayout *layout = new QVBoxLayout;
@ -210,9 +239,8 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) {
// shows plot window on the screen.
show();
if (session.preferences_loaded)
controlWidget->setGeometry (session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_wsize,session.window_overlay_hsize);
else {
// Set Slider/Overlay position if no settings.
if (!session.preferences_loaded){
// Move controller widget below plot
controlWidget->move(x(), y() + frameSize().height());
controlWidget->resize(size().width(), 200);
@ -223,6 +251,10 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) {
controlWidget->setWindowTitle(ct);
controlWidget->show();
// now that is up, reset pos/size change flags
session.window_changed = false;
}
// not 100% sure what i need in this block
@ -245,6 +277,7 @@ ProxWidget::~ProxWidget(void) {
plot = NULL;
}
}
void ProxWidget::closeEvent(QCloseEvent *event) {
event->ignore();
this->hide();
@ -258,6 +291,16 @@ void ProxWidget::showEvent(QShowEvent *event) {
controlWidget->show();
plot->show();
}
void ProxWidget::moveEvent(QMoveEvent *event) {
session.window_plot_xpos = event->pos().x();
session.window_plot_ypos = event->pos().y();
session.window_changed = true;
}
void ProxWidget::resizeEvent(QResizeEvent *event) {
session.window_plot_hsize = event->size().height();
session.window_plot_wsize = event->size().width();
session.window_changed = true;
}
//----------- Plotting

View file

@ -56,9 +56,19 @@ class Plot: public QWidget {
};
class ProxGuiQT;
// Added class for SliderWidget to allow move/resize event override
class SliderWidget : public QWidget {
protected:
void resizeEvent (QResizeEvent *event);
void moveEvent (QMoveEvent *event);
public:
SliderWidget();
};
/**
* The window with plot and controls
*/
class ProxWidget : public QWidget {
Q_OBJECT; //needed for slot/signal classes
@ -66,8 +76,8 @@ class ProxWidget : public QWidget {
ProxGuiQT *master;
Plot *plot;
Ui::Form *opsController;
QWidget *controlWidget;
// QWidget *controlWidget;
SliderWidget *controlWidget;
public:
ProxWidget(QWidget *parent = 0, ProxGuiQT *master = NULL);
~ProxWidget(void);
@ -78,6 +88,8 @@ class ProxWidget : public QWidget {
void closeEvent(QCloseEvent *event);
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
void moveEvent(QMoveEvent *event);
void resizeEvent(QResizeEvent *event);
// void mouseMoveEvent(QMouseEvent *event);
// void mousePressEvent(QMouseEvent *event) { mouseMoveEvent(event); }
// void keyPressEvent(QKeyEvent *event);

View file

@ -844,10 +844,20 @@ int main(int argc, char *argv[]) {
// For info, grep --color=auto is doing sth like this, plus test getenv("TERM") != "dumb":
// struct stat tmp_stat;
// if ((fstat (STDOUT_FILENO, &tmp_stat) == 0) && (S_ISCHR (tmp_stat.st_mode)) && isatty(STDIN_FILENO))
#ifdef USE_PREFERENCE_FILE
if (!session.preferences_loaded) {
if (session.stdinOnTTY && session.stdoutOnTTY) {
session.supports_colors = true;
session.emoji_mode = EMOJI;
}
}
#else
if (session.stdinOnTTY && session.stdoutOnTTY) {
session.supports_colors = true;
session.emoji_mode = EMOJI;
}
#endif
#endif
// Let's take a baudrate ok for real UART, USB-CDC & BT don't use that info anyway
if (speed == 0)
@ -904,11 +914,13 @@ int main(int argc, char *argv[]) {
showBanner();
#ifdef USE_PREFERENCE_FILE
// Save settings if not load from settings json file.
// Save settings if not loaded from settings json file.
// Doing this here will ensure other checks and updates are saved to over rule default
// e.g. Linux color use check
if (!session.preferences_loaded)
preferences_save ();
if (!session.preferences_loaded) {
preferences_save (); // Save defaults
session.preferences_loaded = true;
}
#endif
#ifdef HAVE_GUI
@ -936,5 +948,9 @@ int main(int argc, char *argv[]) {
CloseProxmark();
}
#ifdef USE_PREFERENCE_FILE
if (session.window_changed) // Plot/Overlay moved or resized
preferences_save ();
#endif
exit(EXIT_SUCCESS);
}

View file

@ -0,0 +1,18 @@
[
{
"AID": "D3494F",
"Vendor": "HID",
"Country": "United States",
"Name": "SIO DESFire Ev1",
"Description": "",
"Type": ""
},
{
"AID": "4F5931",
"Vendor": "Transport of London",
"Country": "UK",
"Name": "Oyster Card",
"Description": "",
"Type": ""
},
]

View file

@ -30,6 +30,7 @@ typedef struct {
bool pm3_present;
bool help_dump_mode;
bool show_hints;
bool window_changed; // track if plot/overlay pos/size changed to save on exit
int window_plot_xpos;
int window_plot_ypos;
int window_plot_hsize;

View file

@ -90,9 +90,8 @@ typedef enum {
typedef enum {
MFDES_ALGO_DES = 1,
MFDES_ALGO_3DES = 2,
MFDES_ALGO_2K3DES = 3,
MFDES_ALGO_3K3DES = 4,
MFDES_ALGO_AES = 5
MFDES_ALGO_3K3DES = 3,
MFDES_ALGO_AES = 4
} mifare_des_authalgo_t;