update atrs list
[RRG-proxmark3.git] / armsrc / mifareutil.c
blob9f4b876748857ee44bd63b8a79fd3c92a201cea6
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Gerhard de Koning Gans - May 2008
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // See LICENSE.txt for the text of the license.
16 //-----------------------------------------------------------------------------
17 // Work with mifare cards.
18 //-----------------------------------------------------------------------------
19 #include "mifareutil.h"
21 #include "appmain.h" // tearoff hook
22 #include "string.h"
23 #include "BigBuf.h"
24 #include "iso14443a.h"
25 #include "ticks.h"
26 #include "dbprint.h"
27 #include "parity.h"
28 #include "commonutil.h"
29 #include "crc16.h"
30 #include "protocols.h"
31 #include "desfire_crypto.h"
33 // crypto1 helpers
34 void mf_crypto1_decryptEx(struct Crypto1State *pcs, const uint8_t *data_in, int len, uint8_t *data_out) {
35 if (len != 1) {
36 for (int i = 0; i < len; i++)
37 data_out[i] = crypto1_byte(pcs, 0x00, 0) ^ data_in[i];
38 } else {
39 uint8_t bt = 0;
40 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data_in[0], 0)) << 0;
41 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data_in[0], 1)) << 1;
42 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data_in[0], 2)) << 2;
43 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data_in[0], 3)) << 3;
44 data_out[0] = bt;
46 return;
49 void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len) {
50 mf_crypto1_decryptEx(pcs, data, len, data);
53 void mf_crypto1_encrypt(struct Crypto1State *pcs, uint8_t *data, uint16_t len, uint8_t *par) {
54 mf_crypto1_encryptEx(pcs, data, NULL, data, len, par);
57 void mf_crypto1_encryptEx(struct Crypto1State *pcs, const uint8_t *data_in, uint8_t *keystream, uint8_t *data_out, uint16_t len, uint8_t *par) {
58 int i;
59 par[0] = 0;
61 for (i = 0; i < len; i++) {
62 uint8_t bt = data_in[i];
63 data_out[i] = crypto1_byte(pcs, keystream ? keystream[i] : 0x00, 0) ^ data_in[i];
64 if ((i & 0x0007) == 0)
65 par[ i >> 3 ] = 0;
66 par[ i >> 3 ] |= (((filter(pcs->odd) ^ oddparity8(bt)) & 0x01) << (7 - (i & 0x0007)));
70 uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) {
71 uint8_t bt = 0;
72 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data, 0)) << 0;
73 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data, 1)) << 1;
74 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data, 2)) << 2;
75 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(data, 3)) << 3;
76 return bt;
79 // send X byte basic commands
80 uint16_t mifare_sendcmd(uint8_t cmd, uint8_t *data, uint8_t data_size, uint8_t *answer, uint16_t answer_len, uint8_t *answer_parity, uint32_t *timing) {
82 uint8_t dcmd[data_size + 3];
83 dcmd[0] = cmd;
84 if (data_size > 0) {
85 memcpy(dcmd + 1, data, data_size);
88 AddCrc14A(dcmd, data_size + 1);
89 ReaderTransmit(dcmd, sizeof(dcmd), timing);
90 uint16_t len = ReaderReceive(answer, answer_len, answer_parity);
91 if (len == 0) {
92 if (g_dbglevel >= DBG_ERROR) Dbprintf("%02X Cmd failed. Card timeout.", cmd);
93 len = ReaderReceive(answer, answer_len, answer_parity);
95 return len;
98 // send 2 byte commands
99 uint16_t mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint16_t answer_len, uint8_t *answer_parity, uint32_t *timing) {
100 uint16_t pos;
101 uint8_t dcmd[4] = {cmd, data, 0x00, 0x00};
102 uint8_t ecmd[4] = {0x00, 0x00, 0x00, 0x00};
103 uint8_t par[1] = {0x00}; // 1 Byte parity is enough here
104 AddCrc14A(dcmd, 2);
105 memcpy(ecmd, dcmd, sizeof(dcmd));
107 if (pcs && crypted) {
108 par[0] = 0;
109 for (pos = 0; pos < 4; pos++) {
110 ecmd[pos] = crypto1_byte(pcs, 0x00, 0) ^ dcmd[pos];
111 par[0] |= (((filter(pcs->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7 - pos));
113 ReaderTransmitPar(ecmd, sizeof(ecmd), par, timing);
114 } else {
115 ReaderTransmit(dcmd, sizeof(dcmd), timing);
118 uint16_t len = ReaderReceive(answer, answer_len, par);
120 if (answer_parity) {
121 *answer_parity = par[0];
124 if (pcs && (crypted == CRYPT_ALL)) {
125 if (len == 1) {
126 uint16_t res = 0;
127 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 0)) << 0;
128 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 1)) << 1;
129 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 2)) << 2;
130 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 3)) << 3;
131 answer[0] = res;
132 } else {
133 for (pos = 0; pos < len; pos++) {
134 answer[pos] = crypto1_byte(pcs, 0x00, 0) ^ answer[pos];
138 return len;
141 // mifare classic commands
142 int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested) {
143 return mifare_classic_authex(pcs, uid, blockNo, keyType, ui64Key, isNested, NULL, NULL);
145 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) {
146 return mifare_classic_authex_cmd(pcs, uid, blockNo, MIFARE_AUTH_KEYA + (keyType & 0xF), ui64Key, isNested, ntptr, NULL, NULL, timing, false, false);
148 int mifare_classic_authex_cmd(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t cmd, uint64_t ui64Key, uint8_t isNested,
149 uint32_t *ntptr, uint32_t *ntencptr, uint8_t *ntencparptr, uint32_t *timing, bool corruptnrar, bool corruptnrarparity) {
150 // "random" reader nonce:
151 uint8_t nr[4];
152 num_to_bytes(prng_successor(GetTickCount(), 32), 4, nr);
154 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
155 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
157 // Transmit MIFARE_CLASSIC_AUTH, 0x60 for key A, 0x61 for key B, or 0x80 for GDM backdoor
158 int len = mifare_sendcmd_short(pcs, isNested, cmd, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, timing);
159 if (len != 4) return 1;
161 // Save the tag nonce (nt)
162 uint32_t nt = bytes_to_num(receivedAnswer, 4);
163 if (ntencptr) {
164 *ntencptr = nt;
167 if (ntencparptr) {
168 *ntencparptr = receivedAnswerPar[0];
171 // ----------------------------- crypto1 create
172 if (isNested) {
173 crypto1_deinit(pcs);
176 // Init cipher with key
177 crypto1_init(pcs, ui64Key);
179 if (isNested == AUTH_NESTED) {
180 // decrypt nt with help of new key
181 nt = crypto1_word(pcs, nt ^ uid, 1) ^ nt;
182 } else {
183 // Load (plain) uid^nt into the cipher
184 crypto1_word(pcs, nt ^ uid, 0);
187 // some statistic
188 // if (!ntptr && (g_dbglevel >= DBG_EXTENDED))
189 uint32_t nr32 = nr[0] << 24 | nr[1] << 16 | nr[2] << 8 | nr[3];
190 if (g_dbglevel >= DBG_EXTENDED) {
191 if (!isNested) {
192 Dbprintf("auth cmd: %02x %02x | uid: %08x | nr: %08x %s| nt: %08x %s %5i| par: %i%i%i%i %s",
193 cmd, blockNo, uid,
194 nr32, validate_prng_nonce(nr32) ? "@" : " ",
195 nt, validate_prng_nonce(nt) ? "@idx" : " idx",
196 validate_prng_nonce(nt) ? nonce16_index(nt >> 16) : -1,
197 (receivedAnswerPar[0] >> 7) & 1,
198 (receivedAnswerPar[0] >> 6) & 1,
199 (receivedAnswerPar[0] >> 5) & 1,
200 (receivedAnswerPar[0] >> 4) & 1,
201 validate_parity_nonce(nt, receivedAnswerPar[0], nt) ? "ok " : "bad");
202 } else {
203 Dbprintf("auth nested cmd: %02x %02x | uid: %08x | nr: %08x %s| nt: %08x %s %5i| par: %i%i%i%i %s| ntenc: %08x %s| parerr: %i%i%i%i",
204 cmd, blockNo, uid,
205 nr32, validate_prng_nonce(nr32) ? "@" : " ",
206 nt, validate_prng_nonce(nt) ? "@idx" : " idx",
207 validate_prng_nonce(nt) ? nonce16_index(nt >> 16) : -1,
208 (receivedAnswerPar[0] >> 7) & 1,
209 (receivedAnswerPar[0] >> 6) & 1,
210 (receivedAnswerPar[0] >> 5) & 1,
211 (receivedAnswerPar[0] >> 4) & 1,
212 validate_parity_nonce(*ntencptr, receivedAnswerPar[0], nt) ? "ok " : "bad",
213 *ntencptr, validate_prng_nonce(*ntencptr) ? "@" : " ",
214 ((receivedAnswerPar[0] >> 7) & 1) ^ oddparity8((*ntencptr >> 24) & 0xFF),
215 ((receivedAnswerPar[0] >> 6) & 1) ^ oddparity8((*ntencptr >> 16) & 0xFF),
216 ((receivedAnswerPar[0] >> 5) & 1) ^ oddparity8((*ntencptr >> 8) & 0xFF),
217 ((receivedAnswerPar[0] >> 4) & 1) ^ oddparity8((*ntencptr >> 0) & 0xFF)
221 // save Nt
222 if (ntptr) {
223 *ntptr = nt;
226 // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
227 uint32_t pos;
228 uint8_t par[1] = {0x00};
229 uint8_t mf_nr_ar[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
230 for (pos = 0; pos < 4; pos++) {
231 mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos];
232 par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7 - pos));
234 // Skip 32 bits in pseudo random generator
235 nt = prng_successor(nt, 32);
237 // ar+parity
238 if (corruptnrar) {
239 Dbprintf("Corrupting nRaR...");
240 nt ^= 1;
243 for (pos = 4; pos < 8; pos++) {
244 nt = prng_successor(nt, 8);
245 mf_nr_ar[pos] = crypto1_byte(pcs, 0x00, 0) ^ (nt & 0xff);
246 par[0] |= (((filter(pcs->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7 - pos));
249 if (corruptnrarparity) {
250 Dbprintf("Corrupting nRaR parity...");
251 par[0] ^= 1;
254 // Transmit reader nonce and reader answer
255 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
257 // save standard timeout
258 uint32_t save_timeout = iso14a_get_timeout();
260 // set timeout for authentication response
261 if (save_timeout > 106) {
262 iso14a_set_timeout(106);
265 // Receive 4 byte tag answer
266 len = ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar);
268 iso14a_set_timeout(save_timeout);
270 if (len == 0) {
271 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Authentication failed. Card timeout");
272 return 2;
275 // Supplied tag nonce
276 uint32_t ntpp = prng_successor(nt, 32) ^ crypto1_word(pcs, 0, 0);
277 if (ntpp != bytes_to_num(receivedAnswer, 4)) {
278 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Authentication failed. Error card response");
279 return 3;
281 return 0;
284 int mifare_classic_readblock(struct Crypto1State *pcs, uint8_t blockNo, uint8_t *blockData) {
285 return mifare_classic_readblock_ex(pcs, blockNo, blockData, ISO14443A_CMD_READBLOCK);
287 int mifare_classic_readblock_ex(struct Crypto1State *pcs, uint8_t blockNo, uint8_t *blockData, uint8_t iso_byte) {
289 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
290 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
292 uint16_t len = mifare_sendcmd_short(pcs, 1, iso_byte, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
293 if (len == 1) {
294 if (g_dbglevel >= DBG_ERROR) {
295 Dbprintf("Block " _YELLOW_("%3d") " Cmd 0x%02x Cmd Error %02x", blockNo, iso_byte, receivedAnswer[0]);
297 return 1;
299 if (len != 18) {
300 if (g_dbglevel >= DBG_ERROR) {
301 Dbprintf("Block " _YELLOW_("%3d") " Cmd 0x%02x Wrong response len, expected 18 got " _RED_("%d"), blockNo, iso_byte, len);
303 return 2;
306 uint8_t bt[2] = {0x00, 0x00};
307 memcpy(bt, receivedAnswer + 16, 2);
308 AddCrc14A(receivedAnswer, 16);
309 if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
310 if (g_dbglevel >= DBG_INFO) Dbprintf("CRC response error");
311 return 3;
314 memcpy(blockData, receivedAnswer, 16);
315 return 0;
318 // mifare ultralight commands
319 int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack) {
321 uint16_t len = 0;
322 uint8_t resp[4] = {0x00, 0x00, 0x00, 0x00};
323 uint8_t respPar[1] = {0x00};
324 uint8_t key[4] = {0x00, 0x00, 0x00, 0x00};
325 memcpy(key, keybytes, 4);
327 if (g_dbglevel >= DBG_EXTENDED)
328 Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]);
330 len = mifare_sendcmd(MIFARE_ULEV1_AUTH, key, sizeof(key), resp, sizeof(resp), respPar, NULL);
332 if (len != 4) {
333 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len);
334 return 0;
337 if (g_dbglevel >= DBG_EXTENDED)
338 Dbprintf("Auth Resp: %02x%02x%02x%02x", resp[0], resp[1], resp[2], resp[3]);
340 memcpy(pack, resp, 4);
341 return 1;
344 int mifare_ultra_auth(uint8_t *keybytes) {
346 /// 3des2k
347 uint8_t random_a[8] = {1, 1, 1, 1, 1, 1, 1, 1};
348 uint8_t random_b[8] = {0x00};
349 uint8_t enc_random_b[8] = {0x00};
350 uint8_t rnd_ab[16] = {0x00};
351 uint8_t IV[8] = {0x00};
352 uint8_t key[16] = {0x00};
353 memcpy(key, keybytes, 16);
355 uint16_t len = 0;
356 uint8_t resp[19] = {0x00};
357 uint8_t respPar[3] = {0, 0, 0};
359 // REQUEST AUTHENTICATION
360 len = mifare_sendcmd_short(NULL, CRYPT_NONE, MIFARE_ULC_AUTH_1, 0x00, resp, sizeof(resp), respPar, NULL);
361 if (len != 11) {
362 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]);
363 return 0;
366 // tag nonce.
367 memcpy(enc_random_b, resp + 1, 8);
369 // decrypt nonce.
370 tdes_nxp_receive((void *)enc_random_b, (void *)random_b, sizeof(random_b), (const void *)key, IV, 2);
371 rol(random_b, 8);
372 memcpy(rnd_ab, random_a, 8);
373 memcpy(rnd_ab + 8, random_b, 8);
375 if (g_dbglevel >= DBG_EXTENDED) {
376 Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x",
377 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]);
379 Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x",
380 random_b[0], random_b[1], random_b[2], random_b[3], random_b[4], random_b[5], random_b[6], random_b[7]);
382 Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x",
383 rnd_ab[0], rnd_ab[1], rnd_ab[2], rnd_ab[3], rnd_ab[4], rnd_ab[5], rnd_ab[6], rnd_ab[7]);
385 Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x",
386 rnd_ab[8], rnd_ab[9], rnd_ab[10], rnd_ab[11], rnd_ab[12], rnd_ab[13], rnd_ab[14], rnd_ab[15]);
389 // encrypt out, in, length, key, iv
390 tdes_nxp_send(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b, 2);
392 len = mifare_sendcmd(MIFARE_ULC_AUTH_2, rnd_ab, sizeof(rnd_ab), resp, sizeof(resp), respPar, NULL);
393 if (len != 11) {
394 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]);
395 return 0;
398 uint8_t enc_resp[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
399 uint8_t resp_random_a[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
400 memcpy(enc_resp, resp + 1, 8);
402 // decrypt out, in, length, key, iv
403 tdes_nxp_receive(enc_resp, resp_random_a, 8, key, enc_random_b, 2);
404 if (memcmp(resp_random_a, random_a, 8) != 0) {
405 if (g_dbglevel >= DBG_ERROR) Dbprintf("failed authentication");
406 return 0;
409 if (g_dbglevel >= DBG_EXTENDED) {
410 Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x",
411 rnd_ab[0], rnd_ab[1], rnd_ab[2], rnd_ab[3],
412 rnd_ab[4], rnd_ab[5], rnd_ab[6], rnd_ab[7]);
414 Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x",
415 rnd_ab[8], rnd_ab[9], rnd_ab[10], rnd_ab[11],
416 rnd_ab[12], rnd_ab[13], rnd_ab[14], rnd_ab[15]);
418 Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x",
419 random_a[0], random_a[1], random_a[2], random_a[3],
420 random_a[4], random_a[5], random_a[6], random_a[7]);
422 Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x",
423 resp_random_a[0], resp_random_a[1], resp_random_a[2], resp_random_a[3],
424 resp_random_a[4], resp_random_a[5], resp_random_a[6], resp_random_a[7]);
426 return 1;
429 int mifare_ultra_aes_auth(uint8_t keyno, uint8_t *keybytes) {
431 /// aes-128
432 uint8_t random_a[16] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
433 uint8_t random_b[16] = { 0 };
434 uint8_t rnd_ab[32] = { 0 };
435 uint8_t enc_rnd_ab[32] = { 0 };
436 uint8_t IV[16] = { 0 };
437 uint8_t key[16] = { 0 };
438 memcpy(key, keybytes, sizeof(key));
440 uint16_t len = 0;
442 // 1 cmd + 16 bytes + 2 crc
443 uint8_t resp[19] = {0x00};
444 uint8_t respPar[5] = {0};
447 // setup AES
448 mbedtls_aes_context actx;
449 mbedtls_aes_init(&actx);
450 mbedtls_aes_init(&actx);
451 mbedtls_aes_setkey_dec(&actx, key, 128);
453 // Send REQUEST AUTHENTICATION / receive tag nonce
454 len = mifare_sendcmd_short(NULL, CRYPT_NONE, MIFARE_ULAES_AUTH_1, keyno, resp, sizeof(resp), respPar, NULL);
455 if (len != 19) {
456 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x - expected 19 got " _RED_("%u"), resp[0], len);
457 return 0;
460 // decrypt tag nonce.
461 mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_DECRYPT, sizeof(random_b), IV, resp + 1, random_b);
463 rol(random_b, 16);
464 memcpy(rnd_ab, random_a, 16);
465 memcpy(rnd_ab + 16, random_b, 16);
467 if (g_dbglevel >= DBG_EXTENDED) {
468 Dbprintf("enc_B:");
469 Dbhexdump(16, resp + 1, false);
471 Dbprintf("B:");
472 Dbhexdump(16, random_b, false);
474 Dbprintf("rnd_ab:");
475 Dbhexdump(32, rnd_ab, false);
478 // encrypt reader response
479 memset(IV, 0, 16);
480 mbedtls_aes_setkey_enc(&actx, key, 128);
481 mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_ENCRYPT, sizeof(enc_rnd_ab), IV, rnd_ab, enc_rnd_ab);
483 // send & receive
484 len = mifare_sendcmd(MIFARE_ULAES_AUTH_2, enc_rnd_ab, sizeof(enc_rnd_ab), resp, sizeof(resp), respPar, NULL);
485 if (len != 19) {
486 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x - expected 19 got " _RED_("%u"), resp[0], len);
487 return 0;
490 memset(IV, 0, 16);
491 mbedtls_aes_setkey_dec(&actx, key, 128);
492 mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_DECRYPT, sizeof(random_b), IV, resp + 1, random_b);
494 if (memcmp(random_b, random_a, 16) != 0) {
495 if (g_dbglevel >= DBG_ERROR) Dbprintf("failed authentication");
496 return 0;
499 if (g_dbglevel >= DBG_EXTENDED) {
501 Dbprintf("e_AB:");
502 Dbhexdump(32, enc_rnd_ab, false);
504 Dbprintf("A:");
505 Dbhexdump(16, random_a, false);
507 Dbprintf("B:");
508 Dbhexdump(16, random_b, false);
511 mbedtls_aes_free(&actx);
512 return 1;
515 static int mifare_ultra_readblockEx(uint8_t blockNo, uint8_t *blockData) {
516 uint16_t len = 0;
517 uint8_t bt[2] = {0x00, 0x00};
518 uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00};
519 uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00};
521 len = mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
522 if (len == 1) {
523 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
524 return 1;
526 if (len != 18) {
527 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: card timeout. len: %x", len);
528 return 2;
531 memcpy(bt, receivedAnswer + 16, 2);
532 AddCrc14A(receivedAnswer, 16);
533 if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
534 if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd CRC response error.");
535 return 3;
538 memcpy(blockData, receivedAnswer, 16);
539 return 0;
541 int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) {
542 #define MFU_MAX_RETRIES 5
543 uint8_t res;
545 for (uint8_t retries = 0; retries < MFU_MAX_RETRIES; ++retries) {
546 res = mifare_ultra_readblockEx(blockNo, blockData);
548 // break if OK, or NACK.
549 switch (res) {
550 case 0:
551 case 1:
552 return res;
553 default:
554 continue;
557 return res;
560 int mifare_classic_writeblock(struct Crypto1State *pcs, uint8_t blockNo, uint8_t *blockData) {
561 return mifare_classic_writeblock_ex(pcs, blockNo, blockData, ISO14443A_CMD_WRITEBLOCK);
563 int mifare_classic_writeblock_ex(struct Crypto1State *pcs, uint8_t blockNo, uint8_t *blockData, uint8_t cmd) {
565 // variables
566 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
567 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
569 // cmd is ISO14443A_CMD_WRITEBLOCK for normal tags, but could also be
570 // MIFARE_MAGIC_GDM_WRITEBLOCK or MIFARE_MAGIC_GDM_WRITE_CFG for certain magic tags
571 uint16_t len = mifare_sendcmd_short(pcs, 1, cmd, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
573 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
574 if (g_dbglevel >= DBG_INFO) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
575 return PM3_EFAILED;
578 uint8_t d_block[18], d_block_enc[18];
579 memcpy(d_block, blockData, 16);
580 AddCrc14A(d_block, 16);
582 if (pcs) {
583 // enough for 18 Bytes to send
584 uint8_t par[3] = {0x00, 0x00, 0x00};
585 // crypto
586 for (uint32_t pos = 0; pos < 18; pos++) {
587 d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos];
588 par[pos >> 3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos & 0x0007)));
591 ReaderTransmitPar(d_block_enc, sizeof(d_block_enc), par, NULL);
592 } else {
593 ReaderTransmit(d_block, sizeof(d_block), NULL);
596 // tearoff occurred
597 if (tearoff_hook() == PM3_ETEAROFF) {
598 return PM3_ETEAROFF;
599 } else {
600 // Receive the response
601 len = ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar);
603 uint8_t res = 0;
604 if (pcs) {
605 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 0)) << 0;
606 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 1)) << 1;
607 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 2)) << 2;
608 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 3)) << 3;
609 } else {
610 res = receivedAnswer[0];
613 if ((len != 1) || (res != 0x0A)) {
614 if (g_dbglevel >= DBG_INFO) Dbprintf("Cmd send data2 Error: %02x", res);
615 return PM3_EFAILED;
618 return PM3_SUCCESS;
621 int mifare_classic_value(struct Crypto1State *pcs, uint8_t blockNo, uint8_t *blockData, uint8_t action) {
622 // variables
623 uint16_t len = 0;
624 uint32_t pos = 0;
625 uint8_t par[3] = {0x00, 0x00, 0x00}; // enough for 18 Bytes to send
627 uint8_t d_block[18], d_block_enc[18];
628 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
629 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
631 uint8_t command = MIFARE_CMD_INC;
633 if (action == 0x01)
634 command = MIFARE_CMD_DEC;
635 if (action == 0x02)
636 command = MIFARE_CMD_RESTORE;
638 // Send increment or decrement command
639 len = mifare_sendcmd_short(pcs, 1, command, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
641 if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK
642 if (g_dbglevel >= DBG_INFO) Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
643 return PM3_EFAILED;
646 memcpy(d_block, blockData, 4);
647 AddCrc14A(d_block, 4);
649 // crypto
650 for (pos = 0; pos < 6; pos++) {
651 d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos];
652 par[pos >> 3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos & 0x0007)));
655 ReaderTransmitPar(d_block_enc, 6, par, NULL);
657 // Receive the response NO Response means OK ... i.e. NOT NACK
658 len = ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar);
660 if (len != 0) { // Something not right, len == 0 (no response is ok as its waiting for transfer
661 uint8_t res = 0;
662 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 0)) << 0;
663 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 1)) << 1;
664 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 2)) << 2;
665 res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 3)) << 3;
667 if ((len != 1) || (res != 0x0A)) {
668 if (g_dbglevel >= DBG_INFO) Dbprintf("Cmd send data2 Error: %02x", res);
669 return PM3_EFAILED;
673 return PM3_SUCCESS;
676 int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData) {
677 // variables
678 uint16_t len = 0;
680 uint8_t d_block[18];
681 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
682 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
684 len = mifare_sendcmd_short(NULL, CRYPT_NONE, ISO14443A_CMD_WRITEBLOCK, blockNo, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
686 if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK
687 if (g_dbglevel >= DBG_INFO) {
688 Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0], len);
690 return PM3_EFAILED;
693 memcpy(d_block, blockData, 16);
694 AddCrc14A(d_block, 16);
696 ReaderTransmit(d_block, sizeof(d_block), NULL);
698 // Receive the response
699 len = ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar);
701 if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK
702 if (g_dbglevel >= DBG_INFO) {
703 Dbprintf("Cmd Send Data Error: %02x %d", receivedAnswer[0], len);
705 return PM3_EFAILED;
707 return PM3_SUCCESS;
710 int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) {
711 uint16_t len = 0;
712 uint8_t block[5] = {blockNo, 0x00, 0x00, 0x00, 0x00 };
713 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
714 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
716 // command MIFARE_CLASSIC_WRITEBLOCK
717 memcpy(block + 1, blockData, 4);
719 len = mifare_sendcmd(MIFARE_ULC_WRITE, block, sizeof(block), receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
721 if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK
722 if (g_dbglevel >= DBG_INFO) {
723 Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0], len);
725 return PM3_EFAILED;
727 return PM3_SUCCESS;
730 int mifare_classic_halt(struct Crypto1State *pcs) {
731 uint8_t receivedAnswer[4] = {0x00, 0x00, 0x00, 0x00};
732 uint16_t len = mifare_sendcmd_short(pcs, (pcs == NULL) ? CRYPT_NONE : CRYPT_ALL, ISO14443A_CMD_HALT, 0x00, receivedAnswer, sizeof(receivedAnswer), NULL, NULL);
733 if (len != 0) {
734 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("halt warning. response len: %x", len);
735 return 1;
737 return 0;
740 int mifare_ultra_halt(void) {
741 return mifare_classic_halt(NULL);
745 // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards),
746 // plus evtl. 8 sectors with 16 blocks each (4k cards)
747 uint8_t NumBlocksPerSector(uint8_t sectorNo) {
748 return (sectorNo < 32) ? 4 : 16;
751 uint8_t FirstBlockOfSector(uint8_t sectorNo) {
752 if (sectorNo < 32)
753 return sectorNo * 4;
754 else
755 return 32 * 4 + (sectorNo - 32) * 16;
758 // work with emulator memory
759 void emlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int block_width) {
760 uint32_t offset = blockNum * block_width;
761 uint32_t len = blocksCount * block_width;
762 emlSet(data, offset, len);
765 void emlGetMem(uint8_t *data, int blockNum, int blocksCount) {
766 emlGet(data, (blockNum * 16), (blocksCount * 16));
769 bool emlCheckValBl(int blockNum) {
770 uint8_t *mem = BigBuf_get_EM_addr();
771 uint8_t *d = mem + (blockNum * 16);
773 if ((d[0] != (d[4] ^ 0xff)) || (d[0] != d[8]) ||
774 (d[1] != (d[5] ^ 0xff)) || (d[1] != d[9]) ||
775 (d[2] != (d[6] ^ 0xff)) || (d[2] != d[10]) ||
776 (d[3] != (d[7] ^ 0xff)) || (d[3] != d[11]) ||
777 (d[12] != (d[13] ^ 0xff)) || (d[12] != d[14]) ||
778 (d[12] != (d[15] ^ 0xff))) {
779 return false;
781 return true;
784 int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum) {
785 uint8_t *mem = BigBuf_get_EM_addr();
786 uint8_t *d = mem + blockNum * 16;
788 if (emlCheckValBl(blockNum) == false) {
789 return PM3_ESOFT;
792 memcpy(blReg, d, 4);
793 *blBlock = d[12];
794 return PM3_SUCCESS;
797 void emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum) {
798 uint8_t *mem = BigBuf_get_EM_addr();
799 uint8_t *d = mem + blockNum * 16;
801 memcpy(d + 0, &blReg, 4);
802 memcpy(d + 8, &blReg, 4);
803 blReg = blReg ^ 0xFFFFFFFF;
804 memcpy(d + 4, &blReg, 4);
806 d[12] = blBlock;
807 d[13] = blBlock ^ 0xFF;
808 d[14] = blBlock;
809 d[15] = blBlock ^ 0xFF;
812 uint64_t emlGetKey(int sectorNum, int keyType) {
813 uint8_t key[6] = {0x00};
814 uint8_t *mem = BigBuf_get_EM_addr();
815 memcpy(key, mem + 16 * (FirstBlockOfSector(sectorNum) + NumBlocksPerSector(sectorNum) - 1) + keyType * 10, 6);
816 return bytes_to_num(key, 6);
819 void emlClearMem(void) {
820 const uint8_t trailer[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0x69, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
821 const uint8_t uid[] = {0xe6, 0x84, 0x87, 0xf3, 0x16, 0x88, 0x04, 0x00, 0x46, 0x8e, 0x45, 0x55, 0x4d, 0x70, 0x41, 0x04};
822 uint8_t *mem = BigBuf_get_EM_addr();
823 memset(mem, 0, CARD_MEMORY_SIZE);
825 // fill sectors trailer data
826 for (uint16_t b = 3; b < MIFARE_4K_MAXBLOCK; ((b < MIFARE_2K_MAXBLOCK - 4) ? (b += 4) : (b += 16))) {
827 emlSetMem_xt((uint8_t *)trailer, b, 1, 16);
830 // uid
831 emlSetMem_xt((uint8_t *)uid, 0, 1, 16);
832 return;
835 uint8_t SectorTrailer(uint8_t blockNo) {
836 if (blockNo <= MIFARE_2K_MAXBLOCK) {
837 if (g_dbglevel >= DBG_EXTENDED) {
838 Dbprintf("Sector Trailer for block %d : %d", blockNo, (blockNo | 0x03));
840 return (blockNo | 0x03);
841 } else {
842 if (g_dbglevel >= DBG_EXTENDED) {
843 Dbprintf("Sector Trailer for block %d : %d", blockNo, (blockNo | 0x0F));
845 return (blockNo | 0x0F);
849 bool IsSectorTrailer(uint8_t blockNo) {
850 return (blockNo == SectorTrailer(blockNo));
853 // Mifare desfire commands
854 int mifare_sendcmd_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint16_t answer_len, uint8_t *answer_parity, uint32_t *timing) {
855 uint8_t dcmd[5] = {cmd, data[0], data[1], 0x00, 0x00};
856 AddCrc14A(dcmd, 3);
858 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
859 int len = ReaderReceive(answer, answer_len, answer_parity);
860 if (!len) {
861 if (g_dbglevel >= DBG_ERROR) Dbprintf("Authentication failed. Card timeout.");
862 return 1;
864 return len;
867 int mifare_sendcmd_special2(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint16_t answer_len, uint8_t *answer_parity, uint32_t *timing) {
868 uint8_t dcmd[20] = {0x00};
869 dcmd[0] = cmd;
870 memcpy(dcmd + 1, data, 17);
871 AddCrc14A(dcmd, 18);
873 ReaderTransmit(dcmd, sizeof(dcmd), NULL);
874 int len = ReaderReceive(answer, answer_len, answer_parity);
875 if (!len) {
876 if (g_dbglevel >= DBG_ERROR) Dbprintf("Authentication failed. Card timeout.");
877 return 1;
879 return len;
882 int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData) {
884 int len;
885 // load key, keynumber
886 uint8_t data[2] = {MFDES_AUTHENTICATE, 0x00};
887 uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00};
888 uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00};
890 len = mifare_sendcmd_special(NULL, 1, 0x02, data, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
891 if (len == 1) {
892 if (g_dbglevel >= DBG_INFO) {
893 Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
895 return PM3_EFAILED;
898 if (len == 12) {
899 if (g_dbglevel >= DBG_EXTENDED) {
900 Dbprintf("Auth1 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
901 receivedAnswer[0], receivedAnswer[1], receivedAnswer[2], receivedAnswer[3], receivedAnswer[4],
902 receivedAnswer[5], receivedAnswer[6], receivedAnswer[7], receivedAnswer[8], receivedAnswer[9],
903 receivedAnswer[10], receivedAnswer[11]);
905 memcpy(blockData, receivedAnswer, 12);
906 return PM3_SUCCESS;
908 return PM3_EFAILED;
911 int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData) {
913 int len;
914 uint8_t data[17] = {MFDES_ADDITIONAL_FRAME};
915 memcpy(data + 1, key, 16);
917 uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00};
918 uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00};
920 len = mifare_sendcmd_special2(NULL, 1, 0x03, data, receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar, NULL);
922 if ((receivedAnswer[0] == 0x03) && (receivedAnswer[1] == 0xae)) {
923 if (g_dbglevel >= DBG_ERROR) {
924 Dbprintf("Auth Error: %02x %02x", receivedAnswer[0], receivedAnswer[1]);
926 return PM3_EFAILED;
929 if (len == 12) {
930 if (g_dbglevel >= DBG_EXTENDED) {
931 Dbprintf("Auth2 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
932 receivedAnswer[0], receivedAnswer[1], receivedAnswer[2], receivedAnswer[3], receivedAnswer[4],
933 receivedAnswer[5], receivedAnswer[6], receivedAnswer[7], receivedAnswer[8], receivedAnswer[9],
934 receivedAnswer[10], receivedAnswer[11]);
936 memcpy(blockData, receivedAnswer, 12);
937 return PM3_SUCCESS;
939 return PM3_EFAILED;
942 bool validate_prng_nonce(uint32_t nonce) {
943 uint16_t x = nonce >> 16;
944 x = (x & 0xff) << 8 | x >> 8;
945 for (uint8_t i = 0; i < 16; i++) {
946 x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;
948 x = (x & 0xff) << 8 | x >> 8;
949 return x == (nonce & 0xFFFF);
952 bool validate_parity_nonce(uint32_t ntenc, uint8_t ntparenc, uint32_t nt) {
953 uint32_t ks = nt ^ ntenc;
954 ntparenc >>= 4;
955 uint8_t ksp = (((ks >> 16) & 1) << 3) | (((ks >> 8) & 1) << 2) | (((ks >> 0) & 1) << 1);
956 uint8_t ntpar = ntparenc ^ ksp;
957 return (((ntpar >> 3) & 1) == oddparity8((nt >> 24) & 0xFF)) &&
958 (((ntpar >> 2) & 1) == oddparity8((nt >> 16) & 0xFF)) &&
959 (((ntpar >> 1) & 1) == oddparity8((nt >> 8) & 0xFF));
962 int nonce16_distance(uint16_t x, uint16_t y) {
963 if (x == y)
964 return 0;
965 x = (x & 0xff) << 8 | x >> 8;
966 y = (y & 0xff) << 8 | y >> 8;
967 uint16_t i = 1;
968 for (; i; i++) {
969 x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;
970 if (x == y)
971 return i;
973 // never reached
974 return -1;
977 int nonce_distance(uint32_t from, uint32_t to) {
978 if (!validate_prng_nonce(from) || !validate_prng_nonce(to))
979 return -1;
980 return nonce16_distance(from >> 16, to >> 16);
983 int nonce16_index(uint16_t nt) {
984 return nonce16_distance(0x0100, nt) + 1;