Merge pull request #969 from pwpiwi/gcc10_fixes
[legacy-proxmark3.git] / armsrc / mifareutil.c
blobe46c5515dd065790876abeeecaeadb15575b0cbc
1 //-----------------------------------------------------------------------------
2 // Merlok, May 2011, 2012
3 // Many authors, whom made it possible
4 //
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
7 // the license.
8 //-----------------------------------------------------------------------------
9 // Work with mifare cards.
10 //-----------------------------------------------------------------------------
12 #include "mifareutil.h"
14 #include <string.h>
15 #include <stdbool.h>
17 #include "proxmark3.h"
18 #include "apps.h"
19 #include "util.h"
20 #include "parity.h"
21 #include "iso14443crc.h"
22 #include "iso14443a.h"
23 #include "crapto1/crapto1.h"
24 #include "mbedtls/des.h"
25 #include "protocols.h"
27 int MF_DBGLEVEL = MF_DBG_INFO;
29 // crypto1 helpers
30 void mf_crypto1_decryptEx(struct Crypto1State *pcs, uint8_t *data_in, int len, uint8_t *data_out){
31 uint8_t bt = 0;
32 int i;
34 if (len != 1) {
35 for (i = 0; i < len; i++)
36 data_out[i] = crypto1_byte(pcs, 0x00, 0) ^ data_in[i];
37 } else {
38 bt = 0;
39 for (i = 0; i < 4; i++)
40 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data_in[0], i)) << i;
42 data_out[0] = bt;
44 return;
47 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len){
48 mf_crypto1_decryptEx(pcs, data, len, data);
51 void mf_crypto1_encryptEx(struct Crypto1State *pcs, uint8_t *data, uint8_t *in, uint16_t len, uint8_t *par) {
52 uint8_t bt = 0;
53 int i;
54 par[0] = 0;
56 for (i = 0; i < len; i++) {
57 bt = data[i];
58 data[i] = crypto1_byte(pcs, in==NULL?0x00:in[i], 0) ^ data[i];
59 if((i&0x0007) == 0)
60 par[i>>3] = 0;
61 par[i>>3] |= (((filter(pcs->odd) ^ oddparity8(bt)) & 0x01)<<(7-(i&0x0007)));
63 return;
66 void mf_crypto1_encrypt(struct Crypto1State *pcs, uint8_t *data, uint16_t len, uint8_t *par) {
67 mf_crypto1_encryptEx(pcs, data, NULL, len, par);
70 uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) {
71 uint8_t bt = 0;
72 int i;
74 for (i = 0; i < 4; i++)
75 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data, i)) << i;
77 return bt;
80 // send X byte basic commands
81 int mifare_sendcmd(uint8_t cmd, uint8_t* data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) {
82 uint8_t dcmd[data_size+3];
83 dcmd[0] = cmd;
84 memcpy(dcmd+1,data,data_size);
85 AppendCrc14443a(dcmd, data_size+1);
86 ReaderTransmit(dcmd, sizeof(dcmd), timing);
87 int len = ReaderReceive(answer, answer_parity);
88 if(!len) {
89 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("%02X Cmd failed. Card timeout.", cmd);
90 len = ReaderReceive(answer,answer_parity);
91 //return 0;
93 return len;
96 // send 2 byte commands
97 int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) {
98 uint8_t dcmd[4], ecmd[4];
99 uint16_t pos, res;
100 uint8_t par[1]; // 1 Byte parity is enough here
101 dcmd[0] = cmd;
102 dcmd[1] = data;
103 AppendCrc14443a(dcmd, 2);
105 memcpy(ecmd, dcmd, sizeof(dcmd));
107 if (crypted) {
108 par[0] = 0;
109 for (pos = 0; pos < 4; pos++)
111 ecmd[pos] = crypto1_byte(pcs, 0x00, 0) ^ dcmd[pos];
112 par[0] |= (((filter(pcs->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7-pos));
114 ReaderTransmitPar(ecmd, sizeof(ecmd), par, timing);
115 } else {
116 ReaderTransmit(dcmd, sizeof(dcmd), timing);
119 int len = ReaderReceive(answer, par);
121 if (answer_parity) *answer_parity = par[0];
123 if (crypted == CRYPT_ALL) {
124 if (len == 1) {
125 res = 0;
126 for (pos = 0; pos < 4; pos++)
127 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], pos)) << pos;
129 answer[0] = res;
131 } else {
132 for (pos = 0; pos < len; pos++)
134 answer[pos] = crypto1_byte(pcs, 0x00, 0) ^ answer[pos];
139 return len;
143 // mifare classic commands
144 int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *auth_timeout) {
146 return mifare_classic_authex(pcs, uid, blockNo, keyType, ui64Key, isNested, NULL, NULL, auth_timeout);
150 int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *ntptr, uint32_t *timing, uint32_t *auth_timeout) {
152 int len;
153 uint32_t pos;
154 uint8_t par[1] = {0x00};
155 byte_t nr[4];
156 uint32_t nt, ntpp; // Supplied tag nonce
158 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
159 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
160 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
162 // Transmit MIFARE_CLASSIC_AUTH
163 len = mifare_sendcmd_short(pcs, isNested, keyType & 0x01 ? MIFARE_AUTH_KEYB : MIFARE_AUTH_KEYA, blockNo, receivedAnswer, receivedAnswerPar, timing);
164 if (MF_DBGLEVEL >= 4) Dbprintf("rand tag nonce len: %x", len);
165 if (len != 4) return 1;
167 // "random" reader nonce:
168 nr[0] = 0x55;
169 nr[1] = 0x41;
170 nr[2] = 0x49;
171 nr[3] = 0x92;
173 // Save the tag nonce (nt)
174 nt = bytes_to_num(receivedAnswer, 4);
176 // ----------------------------- crypto1 create
177 if (isNested)
178 crypto1_destroy(pcs);
180 // Init cipher with key
181 crypto1_create(pcs, ui64Key);
183 if (isNested == AUTH_NESTED) {
184 // decrypt nt with help of new key
185 nt = crypto1_word(pcs, nt ^ uid, 1) ^ nt;
186 } else {
187 // Load (plain) uid^nt into the cipher
188 crypto1_word(pcs, nt ^ uid, 0);
191 // some statistic
192 if (!ntptr && (MF_DBGLEVEL >= 3))
193 Dbprintf("auth uid: %08x nt: %08x", uid, nt);
195 // save Nt
196 if (ntptr)
197 *ntptr = nt;
199 // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
200 par[0] = 0;
201 for (pos = 0; pos < 4; pos++) {
202 mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos];
203 par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos));
206 // Skip 32 bits in pseudo random generator
207 nt = prng_successor(nt,32);
209 // ar+parity
210 for (pos = 4; pos < 8; pos++) {
211 nt = prng_successor(nt,8);
212 mf_nr_ar[pos] = crypto1_byte(pcs, 0x00, 0) ^ (nt & 0xff);
213 par[0] |= (((filter(pcs->odd) ^ oddparity8(nt)) & 0x01) << (7-pos));
216 // Transmit reader nonce and reader answer
217 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
219 // Receive 4 byte tag answer
220 uint32_t save_timeout = iso14a_get_timeout(); // save standard timeout
221 if (auth_timeout && *auth_timeout) {
222 iso14a_set_timeout(*auth_timeout); // set timeout for authentication response
224 uint32_t auth_timeout_start = GetCountSspClk();
225 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
226 iso14a_set_timeout(save_timeout); // restore standard timeout
227 if (!len) {
228 if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout.");
229 return 2;
231 if (auth_timeout && !*auth_timeout) { // measure time for future authentication response timeout
232 *auth_timeout = (GetCountSspClk() - auth_timeout_start - (len * 9 + 2) * 8) / 8 + 1;
235 ntpp = prng_successor(nt, 32) ^ crypto1_word(pcs, 0, 0);
237 if (ntpp != bytes_to_num(receivedAnswer, 4)) {
238 if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Error card response.");
239 return 3;
242 return 0;
246 int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) {
247 // variables
248 int len;
249 uint8_t bt[2];
251 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
252 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
254 // command MIFARE_CLASSIC_READBLOCK
255 len = mifare_sendcmd_short(pcs, 1, MIFARE_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
256 if (len == 1) {
257 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
258 return 1;
260 if (len != 18) {
261 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd Error: card timeout. len: %x", len);
262 return 2;
265 memcpy(bt, receivedAnswer + 16, 2);
266 AppendCrc14443a(receivedAnswer, 16);
267 if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
268 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd CRC response error.");
269 return 3;
272 memcpy(blockData, receivedAnswer, 16);
273 return 0;
276 // mifare ultralight commands
277 int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){
279 uint16_t len;
280 uint8_t resp[4];
281 uint8_t respPar[1];
282 uint8_t key[4] = {0x00};
283 memcpy(key, keybytes, 4);
285 if (MF_DBGLEVEL >= MF_DBG_EXTENDED)
286 Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]);
287 len = mifare_sendcmd(MIFARE_ULEV1_AUTH, key, sizeof(key), resp, respPar, NULL);
288 //len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL);
289 if (len != 4) {
290 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len);
291 return 0;
294 if (MF_DBGLEVEL >= MF_DBG_EXTENDED)
295 Dbprintf("Auth Resp: %02x%02x%02x%02x", resp[0],resp[1],resp[2],resp[3]);
297 memcpy(pack, resp, 4);
298 return 1;
301 int mifare_ultra_auth(uint8_t *keybytes){
303 /// 3des2k
305 mbedtls_des3_context ctx = { {0} };
306 uint8_t random_a[8] = {1,1,1,1,1,1,1,1};
307 uint8_t random_b[8] = {0x00};
308 uint8_t enc_random_b[8] = {0x00};
309 uint8_t rnd_ab[16] = {0x00};
310 uint8_t IV[8] = {0x00};
311 uint8_t key[16] = {0x00};
312 memcpy(key, keybytes, 16);
314 uint16_t len;
315 uint8_t resp[19] = {0x00};
316 uint8_t respPar[3] = {0,0,0};
318 // REQUEST AUTHENTICATION
319 len = mifare_sendcmd_short(NULL, 1, MIFARE_ULC_AUTH_1, 0x00, resp, respPar ,NULL);
320 if (len != 11) {
321 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]);
322 return 0;
325 // tag nonce.
326 memcpy(enc_random_b,resp+1,8);
328 // decrypt nonce.
329 // tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV );
330 mbedtls_des3_set2key_dec(&ctx, key);
331 mbedtls_des3_crypt_cbc(&ctx // des3_context
332 , MBEDTLS_DES_DECRYPT // int mode
333 , sizeof(random_b) // length
334 , IV // iv[8]
335 , enc_random_b // input
336 , random_b // output
339 rol(random_b,8);
340 memcpy(rnd_ab ,random_a,8);
341 memcpy(rnd_ab+8,random_b,8);
343 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
344 Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x",
345 enc_random_b[0],enc_random_b[1],enc_random_b[2],enc_random_b[3],enc_random_b[4],enc_random_b[5],enc_random_b[6],enc_random_b[7]);
347 Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x",
348 random_b[0],random_b[1],random_b[2],random_b[3],random_b[4],random_b[5],random_b[6],random_b[7]);
350 Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x",
351 rnd_ab[0],rnd_ab[1],rnd_ab[2],rnd_ab[3],rnd_ab[4],rnd_ab[5],rnd_ab[6],rnd_ab[7]);
353 Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x",
354 rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11],rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15] );
357 // encrypt out, in, length, key, iv
358 //tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b);
359 mbedtls_des3_set2key_enc(&ctx, key);
360 mbedtls_des3_crypt_cbc(&ctx // des3_context
361 , MBEDTLS_DES_ENCRYPT // int mode
362 , sizeof(rnd_ab) // length
363 , enc_random_b // iv[8]
364 , rnd_ab // input
365 , rnd_ab // output
368 //len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL);
369 len = mifare_sendcmd(MIFARE_ULC_AUTH_2, rnd_ab, sizeof(rnd_ab), resp, respPar, NULL);
370 if (len != 11) {
371 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]);
372 return 0;
375 uint8_t enc_resp[8] = { 0,0,0,0,0,0,0,0 };
376 uint8_t resp_random_a[8] = { 0,0,0,0,0,0,0,0 };
377 memcpy(enc_resp, resp+1, 8);
379 // decrypt out, in, length, key, iv
380 // tdes_2key_dec(resp_random_a, enc_resp, 8, key, enc_random_b);
381 mbedtls_des3_set2key_dec(&ctx, key);
382 mbedtls_des3_crypt_cbc(&ctx // des3_context
383 , MBEDTLS_DES_DECRYPT // int mode
384 , 8 // length
385 , enc_random_b // iv[8]
386 , enc_resp // input
387 , resp_random_a // output
389 if ( memcmp(resp_random_a, random_a, 8) != 0 ) {
390 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("failed authentication");
391 return 0;
394 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
395 Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x",
396 rnd_ab[0],rnd_ab[1],rnd_ab[2],rnd_ab[3],
397 rnd_ab[4],rnd_ab[5],rnd_ab[6],rnd_ab[7]);
399 Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x",
400 rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11],
401 rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15]);
403 Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x",
404 random_a[0],random_a[1],random_a[2],random_a[3],
405 random_a[4],random_a[5],random_a[6],random_a[7]);
407 Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x",
408 resp_random_a[0],resp_random_a[1],resp_random_a[2],resp_random_a[3],
409 resp_random_a[4],resp_random_a[5],resp_random_a[6],resp_random_a[7]);
411 return 1;
415 #define MFU_MAX_RETRIES 5
416 int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData)
418 uint16_t len;
419 uint8_t bt[2];
420 uint8_t receivedAnswer[MAX_FRAME_SIZE];
421 uint8_t receivedAnswerPar[MAX_PARITY_SIZE];
422 uint8_t retries;
423 int result = 0;
425 for (retries = 0; retries < MFU_MAX_RETRIES; retries++) {
426 len = mifare_sendcmd_short(NULL, 1, MIFARE_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
427 if (len == 1) {
428 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
429 result = 1;
430 continue;
432 if (len != 18) {
433 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: card timeout. len: %x", len);
434 result = 2;
435 continue;
438 memcpy(bt, receivedAnswer + 16, 2);
439 AppendCrc14443a(receivedAnswer, 16);
440 if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
441 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd CRC response error.");
442 result = 3;
443 continue;
446 // No errors encountered; don't retry
447 result = 0;
448 break;
451 if (result != 0) {
452 Dbprintf("Cmd Error: too many retries; read failed");
453 return result;
456 memcpy(blockData, receivedAnswer, 16);
457 return 0;
460 int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData)
462 // variables
463 uint16_t len, i;
464 uint32_t pos;
465 uint8_t par[3] = {0}; // enough for 18 Bytes to send
466 byte_t res;
468 uint8_t d_block[18], d_block_enc[18];
469 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
470 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
472 // command MIFARE_CLASSIC_WRITEBLOCK
473 len = mifare_sendcmd_short(pcs, 1, MIFARE_CMD_WRITEBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
475 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
476 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
477 return 1;
480 memcpy(d_block, blockData, 16);
481 AppendCrc14443a(d_block, 16);
483 // crypto
484 for (pos = 0; pos < 18; pos++)
486 d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos];
487 par[pos>>3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos&0x0007)));
490 ReaderTransmitPar(d_block_enc, sizeof(d_block_enc), par, NULL);
492 // Receive the response
493 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
495 res = 0;
496 for (i = 0; i < 4; i++)
497 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], i)) << i;
499 if ((len != 1) || (res != 0x0A)) {
500 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd send data2 Error: %02x", res);
501 return 2;
504 return 0;
507 /* // command not needed, but left for future testing
508 int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData)
510 uint16_t len;
511 uint8_t par[3] = {0}; // enough for 18 parity bits
512 uint8_t d_block[18] = {0x00};
513 uint8_t receivedAnswer[MAX_FRAME_SIZE];
514 uint8_t receivedAnswerPar[MAX_PARITY_SIZE];
516 len = mifare_sendcmd_short(NULL, true, MIFARE_CMD_WRITEBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
518 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
519 if (MF_DBGLEVEL >= MF_DBG_ERROR)
520 Dbprintf("Cmd Addr Error: %02x", receivedAnswer[0]);
521 return 1;
524 memcpy(d_block, blockData, 16);
525 AppendCrc14443a(d_block, 16);
527 ReaderTransmitPar(d_block, sizeof(d_block), par, NULL);
529 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
531 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
532 if (MF_DBGLEVEL >= MF_DBG_ERROR)
533 Dbprintf("Cmd Data Error: %02x %d", receivedAnswer[0],len);
534 return 2;
536 return 0;
540 int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData)
542 uint16_t len;
543 uint8_t d_block[5] = {0x00};
544 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
545 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
547 // command MIFARE_CLASSIC_WRITEBLOCK
548 d_block[0]= blockNo;
549 memcpy(d_block+1,blockData,4);
550 //AppendCrc14443a(d_block, 6);
552 len = mifare_sendcmd(0xA2, d_block, sizeof(d_block), receivedAnswer, receivedAnswerPar, NULL);
554 if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK
555 if (MF_DBGLEVEL >= MF_DBG_ERROR)
556 Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0],len);
557 return 1;
559 return 0;
562 int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid)
564 uint16_t len;
565 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
566 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
568 len = mifare_sendcmd_short(pcs, pcs == NULL ? false:true, ISO14443A_CMD_HALT, 0x00, receivedAnswer, receivedAnswerPar, NULL);
569 if (len != 0) {
570 if (MF_DBGLEVEL >= MF_DBG_ERROR)
571 Dbprintf("halt error. response len: %x", len);
572 return 1;
575 return 0;
578 int mifare_ultra_halt()
580 uint16_t len;
581 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
582 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
584 len = mifare_sendcmd_short(NULL, true, ISO14443A_CMD_HALT, 0x00, receivedAnswer, receivedAnswerPar, NULL);
585 if (len != 0) {
586 if (MF_DBGLEVEL >= MF_DBG_ERROR)
587 Dbprintf("halt error. response len: %x", len);
588 return 1;
590 return 0;
594 // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards),
595 // plus evtl. 8 sectors with 16 blocks each (4k cards)
596 uint8_t NumBlocksPerSector(uint8_t sectorNo)
598 if (sectorNo < 32)
599 return 4;
600 else
601 return 16;
604 uint8_t FirstBlockOfSector(uint8_t sectorNo)
606 if (sectorNo < 32)
607 return sectorNo * 4;
608 else
609 return 32*4 + (sectorNo - 32) * 16;
613 uint8_t SectorTrailer(uint8_t blockNo)
615 if (blockNo < 32*4) {
616 return (blockNo | 0x03);
617 } else {
618 return (blockNo | 0x0f);
622 bool IsSectorTrailer(uint8_t blockNo)
624 return (blockNo == SectorTrailer(blockNo));
627 // work with emulator memory
628 void emlSetMem(uint8_t *data, int blockNum, int blocksCount) {
629 uint8_t* emCARD = BigBuf_get_EM_addr();
630 memcpy(emCARD + blockNum * 16, data, blocksCount * 16);
633 void emlGetMem(uint8_t *data, int blockNum, int blocksCount) {
634 uint8_t* emCARD = BigBuf_get_EM_addr();
635 memcpy(data, emCARD + blockNum * 16, blocksCount * 16);
638 void emlGetMemBt(uint8_t *data, int bytePtr, int byteCount) {
639 uint8_t* emCARD = BigBuf_get_EM_addr();
640 memcpy(data, emCARD + bytePtr, byteCount);
643 int emlCheckValBl(int blockNum) {
644 uint8_t* emCARD = BigBuf_get_EM_addr();
645 uint8_t* data = emCARD + blockNum * 16;
647 if ((data[0] != (data[4] ^ 0xff)) || (data[0] != data[8]) ||
648 (data[1] != (data[5] ^ 0xff)) || (data[1] != data[9]) ||
649 (data[2] != (data[6] ^ 0xff)) || (data[2] != data[10]) ||
650 (data[3] != (data[7] ^ 0xff)) || (data[3] != data[11]) ||
651 (data[12] != (data[13] ^ 0xff)) || (data[12] != data[14]) ||
652 (data[12] != (data[15] ^ 0xff))
654 return 1;
655 return 0;
658 int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum) {
659 uint8_t* emCARD = BigBuf_get_EM_addr();
660 uint8_t* data = emCARD + blockNum * 16;
662 if (emlCheckValBl(blockNum)) {
663 return 1;
666 memcpy(blReg, data, 4);
667 *blBlock = data[12];
668 return 0;
671 int emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum) {
672 uint8_t* emCARD = BigBuf_get_EM_addr();
673 uint8_t* data = emCARD + blockNum * 16;
675 memcpy(data + 0, &blReg, 4);
676 memcpy(data + 8, &blReg, 4);
677 blReg = blReg ^ 0xffffffff;
678 memcpy(data + 4, &blReg, 4);
680 data[12] = blBlock;
681 data[13] = blBlock ^ 0xff;
682 data[14] = blBlock;
683 data[15] = blBlock ^ 0xff;
685 return 0;
688 uint64_t emlGetKey(int sectorNum, int keyType) {
689 uint8_t key[6];
690 uint8_t* emCARD = BigBuf_get_EM_addr();
692 memcpy(key, emCARD + 16 * (FirstBlockOfSector(sectorNum) + NumBlocksPerSector(sectorNum) - 1) + keyType * 10, 6);
693 return bytes_to_num(key, 6);
696 void emlClearMem(void) {
697 int b;
699 const uint8_t trailer[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0x69, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
700 const uint8_t uid[] = {0xe6, 0x84, 0x87, 0xf3, 0x16, 0x88, 0x04, 0x00, 0x46, 0x8e, 0x45, 0x55, 0x4d, 0x70, 0x41, 0x04};
701 uint8_t* emCARD = BigBuf_get_EM_addr();
703 memset(emCARD, 0, CARD_MEMORY_SIZE);
705 // fill sectors trailer data
706 for(b = 3; b < 256; b<127?(b+=4):(b+=16)) {
707 emlSetMem((uint8_t *)trailer, b , 1);
710 // uid
711 emlSetMem((uint8_t *)uid, 0, 1);
712 return;
716 // Mifare desfire commands
717 int mifare_sendcmd_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing)
719 uint8_t dcmd[5] = {0x00};
720 dcmd[0] = cmd;
721 memcpy(dcmd+1,data,2);
722 AppendCrc14443a(dcmd, 3);
724 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
725 int len = ReaderReceive(answer, answer_parity);
726 if(!len) {
727 if (MF_DBGLEVEL >= MF_DBG_ERROR)
728 Dbprintf("Authentication failed. Card timeout.");
729 return 1;
731 return len;
734 int mifare_sendcmd_special2(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer,uint8_t *answer_parity, uint32_t *timing)
736 uint8_t dcmd[20] = {0x00};
737 dcmd[0] = cmd;
738 memcpy(dcmd+1,data,17);
739 AppendCrc14443a(dcmd, 18);
741 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
742 int len = ReaderReceive(answer, answer_parity);
743 if(!len){
744 if (MF_DBGLEVEL >= MF_DBG_ERROR)
745 Dbprintf("Authentication failed. Card timeout.");
746 return 1;
748 return len;
751 int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData){
753 int len;
754 // load key, keynumber
755 uint8_t data[2]={0x0a, 0x00};
756 uint8_t receivedAnswer[MAX_FRAME_SIZE];
757 uint8_t receivedAnswerPar[MAX_PARITY_SIZE];
759 len = mifare_sendcmd_special(NULL, 1, 0x02, data, receivedAnswer,receivedAnswerPar,NULL);
760 if (len == 1) {
761 if (MF_DBGLEVEL >= MF_DBG_ERROR)
762 Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
763 return 1;
766 if (len == 12) {
767 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
768 Dbprintf("Auth1 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
769 receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3],receivedAnswer[4],
770 receivedAnswer[5],receivedAnswer[6],receivedAnswer[7],receivedAnswer[8],receivedAnswer[9],
771 receivedAnswer[10],receivedAnswer[11]);
773 memcpy(blockData, receivedAnswer, 12);
774 return 0;
776 return 1;
779 int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){
781 int len;
782 uint8_t data[17] = {0x00};
783 data[0] = 0xAF;
784 memcpy(data+1,key,16);
786 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
787 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
789 len = mifare_sendcmd_special2(NULL, 1, 0x03, data, receivedAnswer, receivedAnswerPar ,NULL);
791 if ((receivedAnswer[0] == 0x03) && (receivedAnswer[1] == 0xae)) {
792 if (MF_DBGLEVEL >= MF_DBG_ERROR)
793 Dbprintf("Auth Error: %02x %02x", receivedAnswer[0], receivedAnswer[1]);
794 return 1;
797 if (len == 12){
798 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
799 Dbprintf("Auth2 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
800 receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3],receivedAnswer[4],
801 receivedAnswer[5],receivedAnswer[6],receivedAnswer[7],receivedAnswer[8],receivedAnswer[9],
802 receivedAnswer[10],receivedAnswer[11]);
804 memcpy(blockData, receivedAnswer, 12);
805 return 0;
807 return 1;
810 //-----------------------------------------------------------------------------
811 // MIFARE check keys
813 //-----------------------------------------------------------------------------
814 // one key check
815 static int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uint8_t *key, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel, bool fixed_nonce) {
817 struct Crypto1State mpcs = {0, 0};
818 struct Crypto1State *pcs;
819 pcs = &mpcs;
821 if (*cascade_levels == 0) { // need a full select cycle to get the uid first
822 iso14a_card_select_t card_info;
823 if (!iso14443a_select_card(uid, &card_info, cuid, true, 0, true)) {
824 if (debugLevel >= 1) Dbprintf("ChkKeys: Can't select card");
825 return -1;
827 switch (card_info.uidlen) {
828 case 4 : *cascade_levels = 1; break;
829 case 7 : *cascade_levels = 2; break;
830 case 10: *cascade_levels = 3; break;
831 default: break;
833 } else { // no need for anticollision. We can directly select the card
834 if (!iso14443a_select_card(uid, NULL, NULL, false, *cascade_levels, true)) {
835 if (debugLevel >= 1) Dbprintf("ChkKeys: Can't select card (UID) lvl=%d", *cascade_levels);
836 return -1;
840 if (!fixed_nonce) {
841 uint64_t ui64Key = bytes_to_num(key, 6);
842 if (mifare_classic_auth(pcs, *cuid, blockNo, keyType, ui64Key, AUTH_FIRST, auth_timeout)) { // authentication failed
843 return -2;
844 } else {
845 mifare_classic_halt(pcs, *cuid);
847 } else {
848 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
849 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
850 // Transmit MIFARE_CLASSIC_AUTH
851 int len = mifare_sendcmd_short(pcs, false, keyType & 0x01 ? MIFARE_AUTH_KEYB : MIFARE_AUTH_KEYA, blockNo, receivedAnswer, receivedAnswerPar, NULL);
852 if (len != 4) return -2;
853 // Transmit encrypted reader nonce and reader answer
854 uint8_t mf_nr_ar[8] = NESTED_FIXED_NR_ENC;
855 memcpy(mf_nr_ar + 4, key, 4);
856 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), key + 4, NULL);
857 uint32_t save_timeout = iso14a_get_timeout(); // save standard timeout
858 iso14a_set_timeout(*auth_timeout); // set timeout for authentication response
859 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
860 iso14a_set_timeout(save_timeout); // restore standard timeout
861 if (!len) return -2;
864 return 0; // success
867 // multi key check
868 static int MifareChkBlockKeysEx(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel, bool fixed_nonce) {
870 uint8_t uid[10];
871 uint32_t cuid = 0;
872 uint8_t cascade_levels = 0;
874 int retryCount = 0;
875 for (uint8_t i = 0; i < keyCount; i++) {
876 uint8_t bytes_per_key = fixed_nonce ? 5 : 6;
877 int res = MifareChkBlockKey(uid, &cuid, &cascade_levels, keys + i*bytes_per_key, blockNo, keyType, auth_timeout, debugLevel, fixed_nonce);
878 if (res == -1) { // couldn't select
879 retryCount++;
880 if (retryCount >= 5) {
881 Dbprintf("ChkKeys: block=%d key=%d. Couldn't select. Exit...", blockNo, keyType);
882 return -1;
883 } else {
884 --i; // try the same key once again
885 SpinDelay(20);
886 // Dbprintf("ChkKeys: block=%d key=%d. Try the same key once again...", blockNo, keyType);
887 continue;
890 if (res == -2) { // couldn't authenticate with this key
891 retryCount = 0;
892 continue;
895 return i + 1; // successful authentication
899 if (BUTTON_PRESS()) {
900 return -2;
903 return 0; // couldn't authenticate with any key
907 int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel) {
908 return MifareChkBlockKeysEx(keys, keyCount, blockNo, keyType, auth_timeout, debugLevel, false);
912 // fixed nonce check
913 int MifareChkBlockKeysFixedNonce(uint8_t *ar_par, uint8_t ar_par_cnt, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel) {
914 return MifareChkBlockKeysEx(ar_par, ar_par_cnt, blockNo, keyType, auth_timeout, debugLevel, true);
918 // multisector multikey check
919 int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel, TKeyIndex *keyIndex) {
920 int res = 0;
922 // int clk = GetCountSspClk();
924 for(int sc = 0; sc < SectorCount; sc++){
925 WDT_HIT();
927 int keyAB = keyType;
928 do {
929 res = MifareChkBlockKeys(keys, keyCount, FirstBlockOfSector(sc), keyAB & 0x01, auth_timeout, debugLevel);
930 if (res < 0) {
931 return res;
933 if (res > 0) {
934 (*keyIndex)[keyAB & 0x01][sc] = res;
936 } while(--keyAB > 0);
939 // Dbprintf("%d %d", GetCountSspClk() - clk, (GetCountSspClk() - clk)/(SectorCount*keyCount*(keyType==2?2:1)));
941 return 1;