]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/mifareutil.c
fe5a748577e41851bd69a447670dc9063976049b
[proxmark3-svn] / armsrc / mifareutil.c
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 //-----------------------------------------------------------------------------
11
12 #include "mifareutil.h"
13
14 #include <string.h>
15 #include <stdbool.h>
16
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"
26
27 int MF_DBGLEVEL = MF_DBG_INFO;
28
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;
33
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;
41
42 data_out[0] = bt;
43 }
44 return;
45 }
46
47 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len){
48 mf_crypto1_decryptEx(pcs, data, len, data);
49 }
50
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;
55
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)));
62 }
63 return;
64 }
65
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);
68 }
69
70 uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) {
71 uint8_t bt = 0;
72 int i;
73
74 for (i = 0; i < 4; i++)
75 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data, i)) << i;
76
77 return bt;
78 }
79
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 {
83 uint8_t dcmd[data_size+3];
84 dcmd[0] = cmd;
85 memcpy(dcmd+1,data,data_size);
86 AppendCrc14443a(dcmd, data_size+1);
87 ReaderTransmit(dcmd, sizeof(dcmd), timing);
88 int len = ReaderReceive(answer, answer_parity);
89 if(!len) {
90 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("%02X Cmd failed. Card timeout.", cmd);
91 len = ReaderReceive(answer,answer_parity);
92 //return 0;
93 }
94 return len;
95 }
96
97 // send 2 byte commands
98 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)
99 {
100 uint8_t dcmd[4], ecmd[4];
101 uint16_t pos, res;
102 uint8_t par[1]; // 1 Byte parity is enough here
103 dcmd[0] = cmd;
104 dcmd[1] = data;
105 AppendCrc14443a(dcmd, 2);
106
107 memcpy(ecmd, dcmd, sizeof(dcmd));
108
109 if (crypted) {
110 par[0] = 0;
111 for (pos = 0; pos < 4; pos++)
112 {
113 ecmd[pos] = crypto1_byte(pcs, 0x00, 0) ^ dcmd[pos];
114 par[0] |= (((filter(pcs->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7-pos));
115 }
116
117 ReaderTransmitPar(ecmd, sizeof(ecmd), par, timing);
118
119 } else {
120 ReaderTransmit(dcmd, sizeof(dcmd), timing);
121 }
122
123 int len = ReaderReceive(answer, par);
124
125 if (answer_parity) *answer_parity = par[0];
126
127 if (crypted == CRYPT_ALL) {
128 if (len == 1) {
129 res = 0;
130 for (pos = 0; pos < 4; pos++)
131 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], pos)) << pos;
132
133 answer[0] = res;
134
135 } else {
136 for (pos = 0; pos < len; pos++)
137 {
138 answer[pos] = crypto1_byte(pcs, 0x00, 0) ^ answer[pos];
139 }
140 }
141 }
142
143 return len;
144 }
145
146 // mifare classic commands
147 int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested)
148 {
149 return mifare_classic_authex(pcs, uid, blockNo, keyType, ui64Key, isNested, NULL, NULL);
150 }
151
152 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)
153 {
154 // variables
155 int len;
156 uint32_t pos;
157 uint8_t tmp4[4];
158 uint8_t par[1] = {0x00};
159 byte_t nr[4];
160 uint32_t nt, ntpp; // Supplied tag nonce
161
162 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
163 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
164 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
165
166 // Transmit MIFARE_CLASSIC_AUTH
167 len = mifare_sendcmd_short(pcs, isNested, keyType & 0x01 ? MIFARE_AUTH_KEYB : MIFARE_AUTH_KEYA, blockNo, receivedAnswer, receivedAnswerPar, timing);
168 if (MF_DBGLEVEL >= 4) Dbprintf("rand tag nonce len: %x", len);
169 if (len != 4) return 1;
170
171 // "random" reader nonce:
172 nr[0] = 0x55;
173 nr[1] = 0x41;
174 nr[2] = 0x49;
175 nr[3] = 0x92;
176
177 // Save the tag nonce (nt)
178 nt = bytes_to_num(receivedAnswer, 4);
179
180 // ----------------------------- crypto1 create
181 if (isNested)
182 crypto1_destroy(pcs);
183
184 // Init cipher with key
185 crypto1_create(pcs, ui64Key);
186
187 if (isNested == AUTH_NESTED) {
188 // decrypt nt with help of new key
189 nt = crypto1_word(pcs, nt ^ uid, 1) ^ nt;
190 } else {
191 // Load (plain) uid^nt into the cipher
192 crypto1_word(pcs, nt ^ uid, 0);
193 }
194
195 // some statistic
196 if (!ntptr && (MF_DBGLEVEL >= 3))
197 Dbprintf("auth uid: %08x nt: %08x", uid, nt);
198
199 // save Nt
200 if (ntptr)
201 *ntptr = nt;
202
203 // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
204 par[0] = 0;
205 for (pos = 0; pos < 4; pos++)
206 {
207 mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos];
208 par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos));
209 }
210
211 // Skip 32 bits in pseudo random generator
212 nt = prng_successor(nt,32);
213
214 // ar+parity
215 for (pos = 4; pos < 8; pos++)
216 {
217 nt = prng_successor(nt,8);
218 mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff);
219 par[0] |= (((filter(pcs->odd) ^ oddparity8(nt)) & 0x01) << (7-pos));
220 }
221
222 // Transmit reader nonce and reader answer
223 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
224
225 // Receive 4 byte tag answer
226 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
227 if (!len)
228 {
229 if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout.");
230 return 2;
231 }
232
233 memcpy(tmp4, receivedAnswer, 4);
234 ntpp = prng_successor(nt, 32) ^ crypto1_word(pcs, 0,0);
235
236 if (ntpp != bytes_to_num(tmp4, 4)) {
237 if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Error card response.");
238 return 3;
239 }
240
241 return 0;
242 }
243
244 int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData)
245 {
246 // variables
247 int len;
248 uint8_t bt[2];
249
250 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
251 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
252
253 // command MIFARE_CLASSIC_READBLOCK
254 len = mifare_sendcmd_short(pcs, 1, MIFARE_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
255 if (len == 1) {
256 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
257 return 1;
258 }
259 if (len != 18) {
260 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd Error: card timeout. len: %x", len);
261 return 2;
262 }
263
264 memcpy(bt, receivedAnswer + 16, 2);
265 AppendCrc14443a(receivedAnswer, 16);
266 if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
267 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd CRC response error.");
268 return 3;
269 }
270
271 memcpy(blockData, receivedAnswer, 16);
272 return 0;
273 }
274
275 // mifare ultralight commands
276 int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){
277
278 uint16_t len;
279 uint8_t resp[4];
280 uint8_t respPar[1];
281 uint8_t key[4] = {0x00};
282 memcpy(key, keybytes, 4);
283
284 if (MF_DBGLEVEL >= MF_DBG_EXTENDED)
285 Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]);
286 len = mifare_sendcmd(MIFARE_ULEV1_AUTH, key, sizeof(key), resp, respPar, NULL);
287 //len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL);
288 if (len != 4) {
289 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len);
290 return 0;
291 }
292
293 if (MF_DBGLEVEL >= MF_DBG_EXTENDED)
294 Dbprintf("Auth Resp: %02x%02x%02x%02x", resp[0],resp[1],resp[2],resp[3]);
295
296 memcpy(pack, resp, 4);
297 return 1;
298 }
299
300 int mifare_ultra_auth(uint8_t *keybytes){
301
302 /// 3des2k
303
304 mbedtls_des3_context ctx = { {0} };
305 uint8_t random_a[8] = {1,1,1,1,1,1,1,1};
306 uint8_t random_b[8] = {0x00};
307 uint8_t enc_random_b[8] = {0x00};
308 uint8_t rnd_ab[16] = {0x00};
309 uint8_t IV[8] = {0x00};
310 uint8_t key[16] = {0x00};
311 memcpy(key, keybytes, 16);
312
313 uint16_t len;
314 uint8_t resp[19] = {0x00};
315 uint8_t respPar[3] = {0,0,0};
316
317 // REQUEST AUTHENTICATION
318 len = mifare_sendcmd_short(NULL, 1, MIFARE_ULC_AUTH_1, 0x00, resp, respPar ,NULL);
319 if (len != 11) {
320 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]);
321 return 0;
322 }
323
324 // tag nonce.
325 memcpy(enc_random_b,resp+1,8);
326
327 // decrypt nonce.
328 // tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV );
329 mbedtls_des3_set2key_dec(&ctx, key);
330 mbedtls_des3_crypt_cbc(&ctx // des3_context
331 , MBEDTLS_DES_DECRYPT // int mode
332 , sizeof(random_b) // length
333 , IV // iv[8]
334 , enc_random_b // input
335 , random_b // output
336 );
337
338 rol(random_b,8);
339 memcpy(rnd_ab ,random_a,8);
340 memcpy(rnd_ab+8,random_b,8);
341
342 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
343 Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x",
344 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]);
345
346 Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x",
347 random_b[0],random_b[1],random_b[2],random_b[3],random_b[4],random_b[5],random_b[6],random_b[7]);
348
349 Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x",
350 rnd_ab[0],rnd_ab[1],rnd_ab[2],rnd_ab[3],rnd_ab[4],rnd_ab[5],rnd_ab[6],rnd_ab[7]);
351
352 Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x",
353 rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11],rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15] );
354 }
355
356 // encrypt out, in, length, key, iv
357 //tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b);
358 mbedtls_des3_set2key_enc(&ctx, key);
359 mbedtls_des3_crypt_cbc(&ctx // des3_context
360 , MBEDTLS_DES_ENCRYPT // int mode
361 , sizeof(rnd_ab) // length
362 , enc_random_b // iv[8]
363 , rnd_ab // input
364 , rnd_ab // output
365 );
366
367 //len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL);
368 len = mifare_sendcmd(MIFARE_ULC_AUTH_2, rnd_ab, sizeof(rnd_ab), resp, respPar, NULL);
369 if (len != 11) {
370 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]);
371 return 0;
372 }
373
374 uint8_t enc_resp[8] = { 0,0,0,0,0,0,0,0 };
375 uint8_t resp_random_a[8] = { 0,0,0,0,0,0,0,0 };
376 memcpy(enc_resp, resp+1, 8);
377
378 // decrypt out, in, length, key, iv
379 // tdes_2key_dec(resp_random_a, enc_resp, 8, key, enc_random_b);
380 mbedtls_des3_set2key_dec(&ctx, key);
381 mbedtls_des3_crypt_cbc(&ctx // des3_context
382 , MBEDTLS_DES_DECRYPT // int mode
383 , 8 // length
384 , enc_random_b // iv[8]
385 , enc_resp // input
386 , resp_random_a // output
387 );
388 if ( memcmp(resp_random_a, random_a, 8) != 0 ) {
389 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("failed authentication");
390 return 0;
391 }
392
393 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
394 Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x",
395 rnd_ab[0],rnd_ab[1],rnd_ab[2],rnd_ab[3],
396 rnd_ab[4],rnd_ab[5],rnd_ab[6],rnd_ab[7]);
397
398 Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x",
399 rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11],
400 rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15]);
401
402 Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x",
403 random_a[0],random_a[1],random_a[2],random_a[3],
404 random_a[4],random_a[5],random_a[6],random_a[7]);
405
406 Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x",
407 resp_random_a[0],resp_random_a[1],resp_random_a[2],resp_random_a[3],
408 resp_random_a[4],resp_random_a[5],resp_random_a[6],resp_random_a[7]);
409 }
410 return 1;
411 }
412
413
414 #define MFU_MAX_RETRIES 5
415 int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData)
416 {
417 uint16_t len;
418 uint8_t bt[2];
419 uint8_t receivedAnswer[MAX_FRAME_SIZE];
420 uint8_t receivedAnswerPar[MAX_PARITY_SIZE];
421 uint8_t retries;
422 int result = 0;
423
424 for (retries = 0; retries < MFU_MAX_RETRIES; retries++) {
425 len = mifare_sendcmd_short(NULL, 1, MIFARE_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
426 if (len == 1) {
427 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
428 result = 1;
429 continue;
430 }
431 if (len != 18) {
432 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: card timeout. len: %x", len);
433 result = 2;
434 continue;
435 }
436
437 memcpy(bt, receivedAnswer + 16, 2);
438 AppendCrc14443a(receivedAnswer, 16);
439 if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
440 if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd CRC response error.");
441 result = 3;
442 continue;
443 }
444
445 // No errors encountered; don't retry
446 result = 0;
447 break;
448 }
449
450 if (result != 0) {
451 Dbprintf("Cmd Error: too many retries; read failed");
452 return result;
453 }
454
455 memcpy(blockData, receivedAnswer, 16);
456 return 0;
457 }
458
459 int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData)
460 {
461 // variables
462 uint16_t len, i;
463 uint32_t pos;
464 uint8_t par[3] = {0}; // enough for 18 Bytes to send
465 byte_t res;
466
467 uint8_t d_block[18], d_block_enc[18];
468 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
469 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
470
471 // command MIFARE_CLASSIC_WRITEBLOCK
472 len = mifare_sendcmd_short(pcs, 1, MIFARE_CMD_WRITEBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
473
474 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
475 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
476 return 1;
477 }
478
479 memcpy(d_block, blockData, 16);
480 AppendCrc14443a(d_block, 16);
481
482 // crypto
483 for (pos = 0; pos < 18; pos++)
484 {
485 d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos];
486 par[pos>>3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos&0x0007)));
487 }
488
489 ReaderTransmitPar(d_block_enc, sizeof(d_block_enc), par, NULL);
490
491 // Receive the response
492 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
493
494 res = 0;
495 for (i = 0; i < 4; i++)
496 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], i)) << i;
497
498 if ((len != 1) || (res != 0x0A)) {
499 if (MF_DBGLEVEL >= 1) Dbprintf("Cmd send data2 Error: %02x", res);
500 return 2;
501 }
502
503 return 0;
504 }
505
506 /* // command not needed, but left for future testing
507 int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData)
508 {
509 uint16_t len;
510 uint8_t par[3] = {0}; // enough for 18 parity bits
511 uint8_t d_block[18] = {0x00};
512 uint8_t receivedAnswer[MAX_FRAME_SIZE];
513 uint8_t receivedAnswerPar[MAX_PARITY_SIZE];
514
515 len = mifare_sendcmd_short(NULL, true, MIFARE_CMD_WRITEBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL);
516
517 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
518 if (MF_DBGLEVEL >= MF_DBG_ERROR)
519 Dbprintf("Cmd Addr Error: %02x", receivedAnswer[0]);
520 return 1;
521 }
522
523 memcpy(d_block, blockData, 16);
524 AppendCrc14443a(d_block, 16);
525
526 ReaderTransmitPar(d_block, sizeof(d_block), par, NULL);
527
528 len = ReaderReceive(receivedAnswer, receivedAnswerPar);
529
530 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
531 if (MF_DBGLEVEL >= MF_DBG_ERROR)
532 Dbprintf("Cmd Data Error: %02x %d", receivedAnswer[0],len);
533 return 2;
534 }
535 return 0;
536 }
537 */
538
539 int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData)
540 {
541 uint16_t len;
542 uint8_t d_block[5] = {0x00};
543 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
544 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
545
546 // command MIFARE_CLASSIC_WRITEBLOCK
547 d_block[0]= blockNo;
548 memcpy(d_block+1,blockData,4);
549 //AppendCrc14443a(d_block, 6);
550
551 len = mifare_sendcmd(0xA2, d_block, sizeof(d_block), receivedAnswer, receivedAnswerPar, NULL);
552
553 if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK
554 if (MF_DBGLEVEL >= MF_DBG_ERROR)
555 Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0],len);
556 return 1;
557 }
558 return 0;
559 }
560
561 int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid)
562 {
563 uint16_t len;
564 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
565 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
566
567 len = mifare_sendcmd_short(pcs, pcs == NULL ? false:true, ISO14443A_CMD_HALT, 0x00, receivedAnswer, receivedAnswerPar, NULL);
568 if (len != 0) {
569 if (MF_DBGLEVEL >= MF_DBG_ERROR)
570 Dbprintf("halt error. response len: %x", len);
571 return 1;
572 }
573
574 return 0;
575 }
576
577 int mifare_ultra_halt()
578 {
579 uint16_t len;
580 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
581 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
582
583 len = mifare_sendcmd_short(NULL, true, ISO14443A_CMD_HALT, 0x00, receivedAnswer, receivedAnswerPar, NULL);
584 if (len != 0) {
585 if (MF_DBGLEVEL >= MF_DBG_ERROR)
586 Dbprintf("halt error. response len: %x", len);
587 return 1;
588 }
589 return 0;
590 }
591
592
593 // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards),
594 // plus evtl. 8 sectors with 16 blocks each (4k cards)
595 uint8_t NumBlocksPerSector(uint8_t sectorNo)
596 {
597 if (sectorNo < 32)
598 return 4;
599 else
600 return 16;
601 }
602
603 uint8_t FirstBlockOfSector(uint8_t sectorNo)
604 {
605 if (sectorNo < 32)
606 return sectorNo * 4;
607 else
608 return 32*4 + (sectorNo - 32) * 16;
609
610 }
611
612 uint8_t SectorTrailer(uint8_t blockNo)
613 {
614 if (blockNo < 32*4) {
615 return (blockNo | 0x03);
616 } else {
617 return (blockNo | 0x0f);
618 }
619 }
620
621 bool IsSectorTrailer(uint8_t blockNo)
622 {
623 return (blockNo == SectorTrailer(blockNo));
624 }
625
626 // work with emulator memory
627 void emlSetMem(uint8_t *data, int blockNum, int blocksCount) {
628 uint8_t* emCARD = BigBuf_get_EM_addr();
629 memcpy(emCARD + blockNum * 16, data, blocksCount * 16);
630 }
631
632 void emlGetMem(uint8_t *data, int blockNum, int blocksCount) {
633 uint8_t* emCARD = BigBuf_get_EM_addr();
634 memcpy(data, emCARD + blockNum * 16, blocksCount * 16);
635 }
636
637 void emlGetMemBt(uint8_t *data, int bytePtr, int byteCount) {
638 uint8_t* emCARD = BigBuf_get_EM_addr();
639 memcpy(data, emCARD + bytePtr, byteCount);
640 }
641
642 int emlCheckValBl(int blockNum) {
643 uint8_t* emCARD = BigBuf_get_EM_addr();
644 uint8_t* data = emCARD + blockNum * 16;
645
646 if ((data[0] != (data[4] ^ 0xff)) || (data[0] != data[8]) ||
647 (data[1] != (data[5] ^ 0xff)) || (data[1] != data[9]) ||
648 (data[2] != (data[6] ^ 0xff)) || (data[2] != data[10]) ||
649 (data[3] != (data[7] ^ 0xff)) || (data[3] != data[11]) ||
650 (data[12] != (data[13] ^ 0xff)) || (data[12] != data[14]) ||
651 (data[12] != (data[15] ^ 0xff))
652 )
653 return 1;
654 return 0;
655 }
656
657 int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum) {
658 uint8_t* emCARD = BigBuf_get_EM_addr();
659 uint8_t* data = emCARD + blockNum * 16;
660
661 if (emlCheckValBl(blockNum)) {
662 return 1;
663 }
664
665 memcpy(blReg, data, 4);
666 *blBlock = data[12];
667 return 0;
668 }
669
670 int emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum) {
671 uint8_t* emCARD = BigBuf_get_EM_addr();
672 uint8_t* data = emCARD + blockNum * 16;
673
674 memcpy(data + 0, &blReg, 4);
675 memcpy(data + 8, &blReg, 4);
676 blReg = blReg ^ 0xffffffff;
677 memcpy(data + 4, &blReg, 4);
678
679 data[12] = blBlock;
680 data[13] = blBlock ^ 0xff;
681 data[14] = blBlock;
682 data[15] = blBlock ^ 0xff;
683
684 return 0;
685 }
686
687 uint64_t emlGetKey(int sectorNum, int keyType) {
688 uint8_t key[6];
689 uint8_t* emCARD = BigBuf_get_EM_addr();
690
691 memcpy(key, emCARD + 16 * (FirstBlockOfSector(sectorNum) + NumBlocksPerSector(sectorNum) - 1) + keyType * 10, 6);
692 return bytes_to_num(key, 6);
693 }
694
695 void emlClearMem(void) {
696 int b;
697
698 const uint8_t trailer[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0x69, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
699 const uint8_t uid[] = {0xe6, 0x84, 0x87, 0xf3, 0x16, 0x88, 0x04, 0x00, 0x46, 0x8e, 0x45, 0x55, 0x4d, 0x70, 0x41, 0x04};
700 uint8_t* emCARD = BigBuf_get_EM_addr();
701
702 memset(emCARD, 0, CARD_MEMORY_SIZE);
703
704 // fill sectors trailer data
705 for(b = 3; b < 256; b<127?(b+=4):(b+=16)) {
706 emlSetMem((uint8_t *)trailer, b , 1);
707 }
708
709 // uid
710 emlSetMem((uint8_t *)uid, 0, 1);
711 return;
712 }
713
714
715 // Mifare desfire commands
716 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)
717 {
718 uint8_t dcmd[5] = {0x00};
719 dcmd[0] = cmd;
720 memcpy(dcmd+1,data,2);
721 AppendCrc14443a(dcmd, 3);
722
723 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
724 int len = ReaderReceive(answer, answer_parity);
725 if(!len) {
726 if (MF_DBGLEVEL >= MF_DBG_ERROR)
727 Dbprintf("Authentication failed. Card timeout.");
728 return 1;
729 }
730 return len;
731 }
732
733 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)
734 {
735 uint8_t dcmd[20] = {0x00};
736 dcmd[0] = cmd;
737 memcpy(dcmd+1,data,17);
738 AppendCrc14443a(dcmd, 18);
739
740 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
741 int len = ReaderReceive(answer, answer_parity);
742 if(!len){
743 if (MF_DBGLEVEL >= MF_DBG_ERROR)
744 Dbprintf("Authentication failed. Card timeout.");
745 return 1;
746 }
747 return len;
748 }
749
750 int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData){
751
752 int len;
753 // load key, keynumber
754 uint8_t data[2]={0x0a, 0x00};
755 uint8_t receivedAnswer[MAX_FRAME_SIZE];
756 uint8_t receivedAnswerPar[MAX_PARITY_SIZE];
757
758 len = mifare_sendcmd_special(NULL, 1, 0x02, data, receivedAnswer,receivedAnswerPar,NULL);
759 if (len == 1) {
760 if (MF_DBGLEVEL >= MF_DBG_ERROR)
761 Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
762 return 1;
763 }
764
765 if (len == 12) {
766 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
767 Dbprintf("Auth1 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
768 receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3],receivedAnswer[4],
769 receivedAnswer[5],receivedAnswer[6],receivedAnswer[7],receivedAnswer[8],receivedAnswer[9],
770 receivedAnswer[10],receivedAnswer[11]);
771 }
772 memcpy(blockData, receivedAnswer, 12);
773 return 0;
774 }
775 return 1;
776 }
777
778 int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){
779
780 int len;
781 uint8_t data[17] = {0x00};
782 data[0] = 0xAF;
783 memcpy(data+1,key,16);
784
785 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
786 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
787
788 len = mifare_sendcmd_special2(NULL, 1, 0x03, data, receivedAnswer, receivedAnswerPar ,NULL);
789
790 if ((receivedAnswer[0] == 0x03) && (receivedAnswer[1] == 0xae)) {
791 if (MF_DBGLEVEL >= MF_DBG_ERROR)
792 Dbprintf("Auth Error: %02x %02x", receivedAnswer[0], receivedAnswer[1]);
793 return 1;
794 }
795
796 if (len == 12){
797 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
798 Dbprintf("Auth2 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
799 receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3],receivedAnswer[4],
800 receivedAnswer[5],receivedAnswer[6],receivedAnswer[7],receivedAnswer[8],receivedAnswer[9],
801 receivedAnswer[10],receivedAnswer[11]);
802 }
803 memcpy(blockData, receivedAnswer, 12);
804 return 0;
805 }
806 return 1;
807 }
808
809 //-----------------------------------------------------------------------------
810 // MIFARE check keys
811 //
812 //-----------------------------------------------------------------------------
813 // one key check
814 int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uint64_t ui64Key, uint8_t blockNo, uint8_t keyType, uint8_t debugLevel) {
815
816 struct Crypto1State mpcs = {0, 0};
817 struct Crypto1State *pcs;
818 pcs = &mpcs;
819
820 // Iceman: use piwi's faster nonce collecting part in hardnested.
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;
826 }
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;
832 }
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;
837 }
838 }
839
840 if(mifare_classic_auth(pcs, *cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
841 // SpinDelayUs(AUTHENTICATION_TIMEOUT); // it not needs because mifare_classic_auth have timeout from iso14a_set_timeout()
842 return 2;
843 } else {
844 /* // let it be here. it like halt command, but maybe it will work in some strange cases
845 uint8_t dummy_answer = 0;
846 ReaderTransmit(&dummy_answer, 1, NULL);
847 int timeout = GetCountSspClk() + AUTHENTICATION_TIMEOUT;
848 // wait for the card to become ready again
849 while(GetCountSspClk() < timeout) {};
850 */
851 // it needs after success authentication
852 mifare_classic_halt(pcs, *cuid);
853 }
854
855 return 0;
856 }
857
858 // multi key check
859 int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint8_t debugLevel) {
860 uint8_t uid[10];
861 uint32_t cuid = 0;
862 uint8_t cascade_levels = 0;
863 uint64_t ui64Key = 0;
864
865 int retryCount = 0;
866 for (uint8_t i = 0; i < keyCount; i++) {
867
868 // Allow button press / usb cmd to interrupt device
869 if (BUTTON_PRESS() && !usb_poll_validate_length()) {
870 Dbprintf("ChkKeys: Cancel operation. Exit...");
871 return -2;
872 }
873
874 ui64Key = bytes_to_num(keys + i * 6, 6);
875 int res = MifareChkBlockKey(uid, &cuid, &cascade_levels, ui64Key, blockNo, keyType, debugLevel);
876
877 // can't select
878 if (res == 1) {
879 retryCount++;
880 if (retryCount >= 5) {
881 Dbprintf("ChkKeys: block=%d key=%d. Can't select. Exit...", blockNo, keyType);
882 return -1;
883 }
884 --i; // try the same key once again
885
886 SpinDelay(20);
887 // Dbprintf("ChkKeys: block=%d key=%d. Try the same key once again...", blockNo, keyType);
888 continue;
889 }
890
891 // can't authenticate
892 if (res == 2) {
893 retryCount = 0;
894 continue; // can't auth. wrong key.
895 }
896
897 return i + 1;
898 }
899
900 return 0;
901 }
902
903 // multisector multikey check
904 int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, uint8_t keyType, uint8_t debugLevel, TKeyIndex *keyIndex) {
905 int res = 0;
906
907 // int clk = GetCountSspClk();
908
909 for(int sc = 0; sc < SectorCount; sc++){
910 WDT_HIT();
911
912 int keyAB = keyType;
913 do {
914 res = MifareChkBlockKeys(keys, keyCount, FirstBlockOfSector(sc), keyAB & 0x01, debugLevel);
915 if (res < 0){
916 return res;
917 }
918 if (res > 0){
919 (*keyIndex)[keyAB & 0x01][sc] = res;
920 }
921 } while(--keyAB > 0);
922 }
923
924 // Dbprintf("%d %d", GetCountSspClk() - clk, (GetCountSspClk() - clk)/(SectorCount*keyCount*(keyType==2?2:1)));
925
926 return 0;
927 }
928
929
Impressum, Datenschutz