Merge pull request #673 from bkerler/Auth_Impl

Fix des/3des/3k3des/aes auth. Add auth to both client and device. Move to mbedtls crypt.
This commit is contained in:
Iceman 2020-04-12 21:51:29 +02:00 committed by GitHub
commit 02165e081f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 1829 additions and 956 deletions

View file

@ -3,6 +3,7 @@ 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]
- 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,7 +328,7 @@ 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;
@ -335,6 +339,8 @@ void MifareDES_Auth1(uint8_t *datain) {
expectedlen = 1 + 16 + 2 + 2;
}
int rndlen = len - 1 - 2 - 2;
if (len != expectedlen) {
if (DBGLEVEL >= DBG_ERROR) {
DbpString("Authentication failed. Length of answer doesn't match algo.");
@ -346,9 +352,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 +367,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 +425,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 +433,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 +461,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 +491,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 +603,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

@ -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 };
@ -331,6 +337,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 +347,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 +362,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 +401,303 @@ 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
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) {
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 +706,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 +721,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
@ -1013,7 +1319,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;
@ -1488,14 +1794,16 @@ 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\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES(2K2DES), 3=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 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("tT", "algo", "Crypt algo (1=DES, 2=3DES(2K2DES), 4=3K3DES, 5=AES)", NULL),
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)"),
@ -1536,7 +1844,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 +1867,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 +1909,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 +1918,15 @@ 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,8 +1937,48 @@ 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"},

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

@ -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;