]> cvs.zerfleddert.de Git - proxmark3-svn/blame - armsrc/mifaresim.c
Merge pull request #884 from pwpiwi/fix_iclass_snoop
[proxmark3-svn] / armsrc / mifaresim.c
CommitLineData
6e49717b 1//-----------------------------------------------------------------------------
2// Merlok - June 2011, 2012
3// Gerhard de Koning Gans - May 2008
4// Hagen Fritsch - June 2010
5//
6// This code is licensed to you under the terms of the GNU GPL, version 2 or,
7// at your option, any later version. See the LICENSE.txt file for the text of
8// the license.
9//-----------------------------------------------------------------------------
10// Mifare Classic Card Simulation
11//-----------------------------------------------------------------------------
12
13#include "mifaresim.h"
14#include "iso14443a.h"
15#include "iso14443crc.h"
16#include "crapto1/crapto1.h"
17#include "BigBuf.h"
18#include "string.h"
19#include "mifareutil.h"
20#include "fpgaloader.h"
21#include "proxmark3.h"
22#include "usb_cdc.h"
23#include "cmd.h"
24#include "protocols.h"
25#include "apps.h"
26
27//mifare emulator states
a8561e35 28#define MFEMUL_NOFIELD 0
29#define MFEMUL_IDLE 1
30#define MFEMUL_SELECT1 2
31#define MFEMUL_SELECT2 3
32#define MFEMUL_SELECT3 4
33#define MFEMUL_AUTH1 5
34#define MFEMUL_AUTH2 6
35#define MFEMUL_WORK 7
36#define MFEMUL_WRITEBL2 8
37#define MFEMUL_INTREG_INC 9
38#define MFEMUL_INTREG_DEC 10
39#define MFEMUL_INTREG_REST 11
40#define MFEMUL_HALTED 12
6e49717b 41
b35e04a7 42#define AC_DATA_READ 0
43#define AC_DATA_WRITE 1
a8561e35 44#define AC_DATA_INC 2
45#define AC_DATA_DEC_TRANS_REST 3
b35e04a7 46#define AC_KEYA_READ 0
47#define AC_KEYA_WRITE 1
48#define AC_KEYB_READ 2
49#define AC_KEYB_WRITE 3
50#define AC_AC_READ 4
51#define AC_AC_WRITE 5
52
53#define AUTHKEYA 0
54#define AUTHKEYB 1
55#define AUTHKEYNONE 0xff
56
57
a8561e35 58static int ParamCardSizeBlocks(const char c) {
59 int numBlocks = 16 * 4;
60 switch (c) {
61 case '0' : numBlocks = 5 * 4; break;
62 case '2' : numBlocks = 32 * 4; break;
63 case '4' : numBlocks = 32 * 4 + 8 * 16; break;
64 default: numBlocks = 16 * 4;
65 }
66 return numBlocks;
67}
68
69static uint8_t BlockToSector(int block_num) {
70 if (block_num < 32 * 4) { // 4 blocks per sector
71 return (block_num / 4);
72 } else { // 16 blocks per sector
73 return 32 + (block_num - 32 * 4) / 16;
74 }
75}
76
b35e04a7 77static bool IsTrailerAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
78 uint8_t sector_trailer[16];
79 emlGetMem(sector_trailer, blockNo, 1);
80 uint8_t AC = ((sector_trailer[7] >> 5) & 0x04)
a8561e35 81 | ((sector_trailer[8] >> 2) & 0x02)
b35e04a7 82 | ((sector_trailer[8] >> 7) & 0x01);
83 switch (action) {
84 case AC_KEYA_READ: {
85 return false;
86 break;
87 }
88 case AC_KEYA_WRITE: {
a8561e35 89 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
90 || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
b35e04a7 91 break;
92 }
93 case AC_KEYB_READ: {
94 return (keytype == AUTHKEYA && (AC == 0x00 || AC == 0x02 || AC == 0x01));
95 break;
96 }
97 case AC_KEYB_WRITE: {
faa35ae0 98 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x01))
a8561e35 99 || (keytype == AUTHKEYB && (AC == 0x04 || AC == 0x03)));
b35e04a7 100 break;
101 }
102 case AC_AC_READ: {
103 return ((keytype == AUTHKEYA)
a8561e35 104 || (keytype == AUTHKEYB && !(AC == 0x00 || AC == 0x02 || AC == 0x01)));
b35e04a7 105 break;
106 }
107 case AC_AC_WRITE: {
108 return ((keytype == AUTHKEYA && (AC == 0x01))
a8561e35 109 || (keytype == AUTHKEYB && (AC == 0x03 || AC == 0x05)));
b35e04a7 110 break;
111 }
112 default: return false;
113 }
114}
115
116
117static bool IsDataAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action)
118{
119 uint8_t sector_trailer[16];
120 emlGetMem(sector_trailer, SectorTrailer(blockNo), 1);
121
122 uint8_t sector_block;
123 if (blockNo < 32*4) {
124 sector_block = blockNo & 0x03;
125 } else {
126 sector_block = (blockNo & 0x0f) / 5;
127 }
128
129 uint8_t AC;
130 switch (sector_block) {
131 case 0x00: {
132 AC = ((sector_trailer[7] >> 2) & 0x04)
133 | ((sector_trailer[8] << 1) & 0x02)
134 | ((sector_trailer[8] >> 4) & 0x01);
135 break;
136 }
137 case 0x01: {
138 AC = ((sector_trailer[7] >> 3) & 0x04)
139 | ((sector_trailer[8] >> 0) & 0x02)
140 | ((sector_trailer[8] >> 5) & 0x01);
141 break;
142 }
143 case 0x02: {
144 AC = ((sector_trailer[7] >> 4) & 0x04)
145 | ((sector_trailer[8] >> 1) & 0x02)
146 | ((sector_trailer[8] >> 6) & 0x01);
147 break;
148 }
a8561e35 149 default:
b35e04a7 150 return false;
151 }
a8561e35 152
b35e04a7 153 switch (action) {
154 case AC_DATA_READ: {
155 return ((keytype == AUTHKEYA && !(AC == 0x03 || AC == 0x05 || AC == 0x07))
a8561e35 156 || (keytype == AUTHKEYB && !(AC == 0x07)));
b35e04a7 157 break;
158 }
159 case AC_DATA_WRITE: {
160 return ((keytype == AUTHKEYA && (AC == 0x00))
a8561e35 161 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03)));
b35e04a7 162 break;
163 }
164 case AC_DATA_INC: {
165 return ((keytype == AUTHKEYA && (AC == 0x00))
a8561e35 166 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06)));
b35e04a7 167 break;
168 }
169 case AC_DATA_DEC_TRANS_REST: {
170 return ((keytype == AUTHKEYA && (AC == 0x00 || AC == 0x06 || AC == 0x01))
a8561e35 171 || (keytype == AUTHKEYB && (AC == 0x00 || AC == 0x06 || AC == 0x01)));
b35e04a7 172 break;
173 }
174 }
a8561e35 175
b35e04a7 176 return false;
177}
178
179
180static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) {
181 if (IsSectorTrailer(blockNo)) {
182 return IsTrailerAccessAllowed(blockNo, keytype, action);
183 } else {
184 return IsDataAccessAllowed(blockNo, keytype, action);
185 }
186}
6e49717b 187
188
a8561e35 189static void MifareSimInit(uint8_t flags, uint8_t *datain, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len, uint8_t cardsize) {
6e49717b 190
a8561e35 191 #define TAG_RESPONSE_COUNT 5 // number of precompiled responses
192 static uint8_t rATQA[] = {0x00, 0x00};
193 static uint8_t rUIDBCC1[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 1st cascade level
194 static uint8_t rUIDBCC2[] = {0x00, 0x00, 0x00, 0x00, 0x00}; // UID 2nd cascade level
195 static uint8_t rSAKfinal[]= {0x00, 0x00, 0x00}; // SAK after UID complete
196 static uint8_t rSAK1[] = {0x00, 0x00, 0x00}; // indicate UID not finished
6e49717b 197
198 *uid_len = 4;
199 // UID can be set from emulator memory or incoming data and can be 4 or 7 bytes long
a8561e35 200 if (flags & FLAG_4B_UID_IN_DATA) { // get UID from datain
6e49717b 201 memcpy(rUIDBCC1, datain, 4);
202 } else if (flags & FLAG_7B_UID_IN_DATA) {
203 rUIDBCC1[0] = 0x88;
204 memcpy(rUIDBCC1+1, datain, 3);
205 memcpy(rUIDBCC2, datain+3, 4);
206 *uid_len = 7;
207 } else {
208 uint8_t probable_atqa;
a8561e35 209 emlGetMemBt(&probable_atqa, 7, 1); // get UID from emul memory - weak guess at length
210 if (probable_atqa == 0x00) { // ---------- 4BUID
6e49717b 211 emlGetMemBt(rUIDBCC1, 0, 4);
a8561e35 212 } else { // ---------- 7BUID
6e49717b 213 rUIDBCC1[0] = 0x88;
214 emlGetMemBt(rUIDBCC1+1, 0, 3);
215 emlGetMemBt(rUIDBCC2, 3, 4);
216 *uid_len = 7;
217 }
218 }
219
220 switch (*uid_len) {
221 case 4:
222 *cuid = bytes_to_num(rUIDBCC1, 4);
223 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
a8561e35 224 if (MF_DBGLEVEL >= MF_DBG_INFO) {
225 Dbprintf("4B UID: %02x%02x%02x%02x",
226 rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3] );
6e49717b 227 }
228 break;
229 case 7:
6e49717b 230 *cuid = bytes_to_num(rUIDBCC2, 4);
a8561e35 231 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
232 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
233 if (MF_DBGLEVEL >= MF_DBG_INFO) {
6e49717b 234 Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x",
235 rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3], rUIDBCC2[0], rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3] );
236 }
237 break;
a8561e35 238 default:
6e49717b 239 break;
240 }
a8561e35 241
242 // set SAK based on cardsize
243 switch (cardsize) {
244 case '0': rSAKfinal[0] = 0x09; break; // Mifare Mini
245 case '2': rSAKfinal[0] = 0x10; break; // Mifare 2K
246 case '4': rSAKfinal[0] = 0x18; break; // Mifare 4K
247 default: rSAKfinal[0] = 0x08; // Mifare 1K
248 }
249 ComputeCrc14443(CRC_14443_A, rSAKfinal, 1, rSAKfinal + 1, rSAKfinal + 2);
250 if (MF_DBGLEVEL >= MF_DBG_INFO) {
251 Dbprintf("SAK: %02x", rSAKfinal[0]);
252 }
253
254 // set SAK for incomplete UID
255 rSAK1[0] = 0x04; // Bit 3 indicates incomplete UID
256 ComputeCrc14443(CRC_14443_A, rSAK1, 1, rSAK1 + 1, rSAK1 + 2);
257
258 // set ATQA based on cardsize and UIDlen
259 if (cardsize == '4') {
260 rATQA[0] = 0x02;
261 } else {
262 rATQA[0] = 0x04;
263 }
264 if (*uid_len == 7) {
265 rATQA[0] |= 0x40;
266 }
267 if (MF_DBGLEVEL >= MF_DBG_INFO) {
268 Dbprintf("ATQA: %02x %02x", rATQA[1], rATQA[0]);
269 }
270
6e49717b 271 static tag_response_info_t responses_init[TAG_RESPONSE_COUNT] = {
a8561e35 272 { .response = rATQA, .response_n = sizeof(rATQA) }, // Answer to request - respond with card type
273 { .response = rUIDBCC1, .response_n = sizeof(rUIDBCC1) }, // Anticollision cascade1 - respond with first part of uid
274 { .response = rUIDBCC2, .response_n = sizeof(rUIDBCC2) }, // Anticollision cascade2 - respond with 2nd part of uid
275 { .response = rSAKfinal, .response_n = sizeof(rSAKfinal) }, // Acknowledge select - last cascade
276 { .response = rSAK1, .response_n = sizeof(rSAK1) } // Acknowledge select - previous cascades
6e49717b 277 };
278
279 // Prepare ("precompile") the responses of the anticollision phase. There will be not enough time to do this at the moment the reader sends its REQA or SELECT
a8561e35 280 // There are 5 predefined responses with a total of 18 bytes data to transmit. Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
6e49717b 281 // 18 * 8 data bits, 18 * 1 parity bits, 5 start bits, 5 stop bits, 5 correction bits -> need 177 bytes buffer
a8561e35 282 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 177 // number of bytes required for precompiled responses
6e49717b 283
284 uint8_t *free_buffer_pointer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
285 size_t free_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
286 for (size_t i = 0; i < TAG_RESPONSE_COUNT; i++) {
287 prepare_allocated_tag_modulation(&responses_init[i], &free_buffer_pointer, &free_buffer_size);
288 }
289
290 *responses = responses_init;
291
292 // indices into responses array:
293 #define ATQA 0
294 #define UIDBCC1 1
295 #define UIDBCC2 2
296 #define SAKfinal 3
297 #define SAK1 4
298
299}
300
301
302static bool HasValidCRC(uint8_t *receivedCmd, uint16_t receivedCmd_len) {
303 uint8_t CRC_byte_1, CRC_byte_2;
304 ComputeCrc14443(CRC_14443_A, receivedCmd, receivedCmd_len-2, &CRC_byte_1, &CRC_byte_2);
305 return (receivedCmd[receivedCmd_len-2] == CRC_byte_1 && receivedCmd[receivedCmd_len-1] == CRC_byte_2);
306}
307
308
309/**
a8561e35 310 *MIFARE simulate.
6e49717b 311 *
312 *@param flags :
a8561e35 313 * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
6e49717b 314 * FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
315 * FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
a8561e35 316 * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
6e49717b 317 * FLAG_RANDOM_NONCE - means we should generate some pseudo-random nonce data (only allows moebius attack)
318 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
319 * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted)
320 */
a8561e35 321void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t *datain)
6e49717b 322{
a8561e35 323 LED_A_ON();
324
6e49717b 325 tag_response_info_t *responses;
a8561e35 326 uint8_t uid_len = 4;
6e49717b 327 uint32_t cuid = 0;
328 uint8_t cardWRBL = 0;
329 uint8_t cardAUTHSC = 0;
b35e04a7 330 uint8_t cardAUTHKEY = AUTHKEYNONE; // no authentication
6e49717b 331 uint32_t cardRr = 0;
332 //uint32_t rn_enc = 0;
333 uint32_t ans = 0;
334 uint32_t cardINTREG = 0;
335 uint8_t cardINTBLOCK = 0;
336 struct Crypto1State mpcs = {0, 0};
a8561e35 337 struct Crypto1State *pcs = &mpcs;
338 uint32_t numReads = 0; //Counts numer of times reader reads a block
6e49717b 339 uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE];
340 uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE];
341 uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE];
342 uint16_t receivedCmd_len;
343 uint8_t response[MAX_MIFARE_FRAME_SIZE];
344 uint8_t response_par[MAX_MIFARE_PARITY_SIZE];
a8561e35 345 uint8_t fixed_nonce[] = {0x01, 0x02, 0x03, 0x04};
346
347 int num_blocks = ParamCardSizeBlocks(cardsize);
348
349 // Here we collect UID, sector, keytype, NT, AR, NR, NT2, AR2, NR2
6e49717b 350 // This will be used in the reader-only attack.
351
a8561e35 352 // allow collecting up to 7 sets of nonces to allow recovery of up to 7 keys
6e49717b 353 #define ATTACK_KEY_COUNT 7 // keep same as define in cmdhfmf.c -> readerAttack() (Cannot be more than 7)
a8561e35 354 nonces_t ar_nr_resp[ATTACK_KEY_COUNT*2]; // *2 for 2 separate attack types (nml, moebius) 36 * 7 * 2 bytes = 504 bytes
6e49717b 355 memset(ar_nr_resp, 0x00, sizeof(ar_nr_resp));
356
a8561e35 357 uint8_t ar_nr_collected[ATTACK_KEY_COUNT*2]; // *2 for 2nd attack type (moebius)
6e49717b 358 memset(ar_nr_collected, 0x00, sizeof(ar_nr_collected));
a8561e35 359 uint8_t nonce1_count = 0;
360 uint8_t nonce2_count = 0;
361 uint8_t moebius_n_count = 0;
6e49717b 362 bool gettingMoebius = false;
a8561e35 363 uint8_t mM = 0; // moebius_modifier for collection storage
6e49717b 364
365 // Authenticate response - nonce
366 uint32_t nonce;
367 if (flags & FLAG_RANDOM_NONCE) {
368 nonce = prand();
369 } else {
a8561e35 370 nonce = bytes_to_num(fixed_nonce, 4);
6e49717b 371 }
372
373 // free eventually allocated BigBuf memory but keep Emulator Memory
374 BigBuf_free_keep_EM();
375
a8561e35 376 MifareSimInit(flags, datain, &responses, &cuid, &uid_len, cardsize);
377
6e49717b 378 // We need to listen to the high-frequency, peak-detected path.
379 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
380
381 // clear trace
382 clear_trace();
383 set_tracing(true);
384 ResetSspClk();
a8561e35 385
6e49717b 386 bool finished = false;
387 bool button_pushed = BUTTON_PRESS();
388 int cardSTATE = MFEMUL_NOFIELD;
389
390 while (!button_pushed && !finished && !usb_poll_validate_length()) {
391 WDT_HIT();
392
6e49717b 393 if (cardSTATE == MFEMUL_NOFIELD) {
a8561e35 394 // wait for reader HF field
050aa18b 395 int vHf = (MAX_ADC_HF_VOLTAGE_LOW * AvgAdc(ADC_CHAN_HF_LOW)) >> 10;
6e49717b 396 if (vHf > MF_MINFIELDV) {
a8561e35 397 LED_D_ON();
398 cardSTATE = MFEMUL_IDLE;
6e49717b 399 }
400 button_pushed = BUTTON_PRESS();
401 continue;
402 }
403
404 //Now, get data
a8561e35 405 FpgaEnableTracing();
6e49717b 406 int res = EmGetCmd(receivedCmd, &receivedCmd_len, receivedCmd_par);
a8561e35 407
408 if (res == 2) { // Reader has dropped the HF field. Power off.
409 FpgaDisableTracing();
410 LED_D_OFF();
6e49717b 411 cardSTATE = MFEMUL_NOFIELD;
412 continue;
413 } else if (res == 1) { // button pressed
a8561e35 414 FpgaDisableTracing();
6e49717b 415 button_pushed = true;
416 break;
417 }
418
419 // WUPA in HALTED state or REQA or WUPA in any other state
420 if (receivedCmd_len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) {
b35e04a7 421 EmSendPrecompiledCmd(&responses[ATQA]);
a8561e35 422 FpgaDisableTracing();
6e49717b 423
424 // init crypto block
425 crypto1_destroy(pcs);
b35e04a7 426 cardAUTHKEY = AUTHKEYNONE;
6e49717b 427 if (flags & FLAG_RANDOM_NONCE) {
428 nonce = prand();
429 }
6e49717b 430 cardSTATE = MFEMUL_SELECT1;
431 continue;
432 }
a8561e35 433
6e49717b 434 switch (cardSTATE) {
435 case MFEMUL_NOFIELD:
436 case MFEMUL_HALTED:
437 case MFEMUL_IDLE:{
438 break;
439 }
a8561e35 440
6e49717b 441 case MFEMUL_SELECT1:{
442 // select all - 0x93 0x20
443 if (receivedCmd_len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x20)) {
b35e04a7 444 EmSendPrecompiledCmd(&responses[UIDBCC1]);
a8561e35 445 FpgaDisableTracing();
446 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SELECT ALL CL1 received");
6e49717b 447 break;
448 }
449 // select card - 0x93 0x70 ...
450 if (receivedCmd_len == 9 &&
451 (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], responses[UIDBCC1].response, 4) == 0)) {
6e49717b 452 if (uid_len == 4) {
b35e04a7 453 EmSendPrecompiledCmd(&responses[SAKfinal]);
6e49717b 454 cardSTATE = MFEMUL_WORK;
6e49717b 455 } else if (uid_len == 7) {
b35e04a7 456 EmSendPrecompiledCmd(&responses[SAK1]);
a8561e35 457 cardSTATE = MFEMUL_SELECT2;
6e49717b 458 }
a8561e35 459 FpgaDisableTracing();
460 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SELECT CL1 %02x%02x%02x%02x received",receivedCmd[2],receivedCmd[3],receivedCmd[4],receivedCmd[5]);
461 break;
6e49717b 462 }
a8561e35 463 cardSTATE = MFEMUL_IDLE;
6e49717b 464 break;
465 }
a8561e35 466
6e49717b 467 case MFEMUL_SELECT2:{
468 // select all cl2 - 0x95 0x20
469 if (receivedCmd_len == 2 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x20)) {
b35e04a7 470 EmSendPrecompiledCmd(&responses[UIDBCC2]);
a8561e35 471 FpgaDisableTracing();
472 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SELECT ALL CL2 received");
6e49717b 473 break;
474 }
475 // select cl2 card - 0x95 0x70 xxxxxxxxxxxx
a8561e35 476 if (receivedCmd_len == 9 &&
6e49717b 477 (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], responses[UIDBCC2].response, 4) == 0)) {
478 if (uid_len == 7) {
b35e04a7 479 EmSendPrecompiledCmd(&responses[SAKfinal]);
a8561e35 480 FpgaDisableTracing();
481 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SELECT CL2 %02x%02x%02x%02x received",receivedCmd[2],receivedCmd[3],receivedCmd[4],receivedCmd[5]);
6e49717b 482 cardSTATE = MFEMUL_WORK;
483 break;
484 }
485 }
a8561e35 486 cardSTATE = MFEMUL_IDLE;
6e49717b 487 break;
488 }
a8561e35 489
6e49717b 490 case MFEMUL_WORK:{
a8561e35 491 if (receivedCmd_len != 4) { // all commands must have exactly 4 bytes
6e49717b 492 break;
493 }
b35e04a7 494 bool encrypted_data = (cardAUTHKEY != AUTHKEYNONE) ;
6e49717b 495 if (encrypted_data) {
496 // decrypt seqence
497 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
498 } else {
499 memcpy(receivedCmd_dec, receivedCmd, receivedCmd_len);
500 }
501 if (!HasValidCRC(receivedCmd_dec, receivedCmd_len)) { // all commands must have a valid CRC
a8561e35 502 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_TR));
6e49717b 503 break;
504 }
a8561e35 505
6e49717b 506 if (receivedCmd_dec[0] == MIFARE_AUTH_KEYA || receivedCmd_dec[0] == MIFARE_AUTH_KEYB) {
507 // if authenticating to a block that shouldn't exist - as long as we are not doing the reader attack
a8561e35 508 if (receivedCmd_dec[1] >= num_blocks && !(flags & FLAG_NR_AR_ATTACK)) {
6e49717b 509 //is this the correct response to an auth on a out of range block? marshmellow
510 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 511 FpgaDisableTracing();
512 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking", receivedCmd_dec[0], receivedCmd_dec[1], receivedCmd_dec[1]);
6e49717b 513 break;
514 }
a8561e35 515 cardAUTHSC = BlockToSector(receivedCmd_dec[1]); // received block num
6e49717b 516 cardAUTHKEY = receivedCmd_dec[0] & 0x01;
517 crypto1_destroy(pcs);//Added by martin
518 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
519 if (!encrypted_data) { // first authentication
a8561e35 520 crypto1_word(pcs, cuid ^ nonce, 0); // Update crypto state
521 num_to_bytes(nonce, 4, response); // Send unencrypted nonce
522 EmSendCmd(response, sizeof(nonce));
523 FpgaDisableTracing();
524 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader authenticating for block %d (0x%02x) with key %d", receivedCmd_dec[1], receivedCmd_dec[1], cardAUTHKEY);
6e49717b 525 } else { // nested authentication
a8561e35 526 num_to_bytes(nonce, sizeof(nonce), response);
527 uint8_t pcs_in[4] = {0};
528 num_to_bytes(cuid ^ nonce, sizeof(nonce), pcs_in);
529 mf_crypto1_encryptEx(pcs, response, pcs_in, sizeof(nonce), response_par);
530 EmSendCmdPar(response, sizeof(nonce), response_par); // send encrypted nonce
531 FpgaDisableTracing();
532 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader doing nested authentication for block %d (0x%02x) with key %d", receivedCmd_dec[1], receivedCmd_dec[1], cardAUTHKEY);
6e49717b 533 }
6e49717b 534 cardSTATE = MFEMUL_AUTH1;
535 break;
536 }
a8561e35 537
538 // halt can be sent encrypted or in clear
539 if (receivedCmd_dec[0] == ISO14443A_CMD_HALT && receivedCmd_dec[1] == 0x00) {
540 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("--> HALTED.");
541 cardSTATE = MFEMUL_HALTED;
6e49717b 542 break;
543 }
a8561e35 544
b8dd1ef6 545 if(receivedCmd_dec[0] == MIFARE_CMD_READBLOCK
546 || receivedCmd_dec[0] == MIFARE_CMD_WRITEBLOCK
6e49717b 547 || receivedCmd_dec[0] == MIFARE_CMD_INC
548 || receivedCmd_dec[0] == MIFARE_CMD_DEC
549 || receivedCmd_dec[0] == MIFARE_CMD_RESTORE
550 || receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
a8561e35 551 if (receivedCmd_dec[1] >= num_blocks) {
6e49717b 552 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 553 FpgaDisableTracing();
554 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking",receivedCmd_dec[0],receivedCmd_dec[1],receivedCmd_dec[1]);
6e49717b 555 break;
556 }
a8561e35 557 if (BlockToSector(receivedCmd_dec[1]) != cardAUTHSC) {
6e49717b 558 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 559 FpgaDisableTracing();
560 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader tried to operate (0x%02x) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd_dec[0],receivedCmd_dec[1],cardAUTHSC);
6e49717b 561 break;
562 }
563 }
a8561e35 564
b8dd1ef6 565 if (receivedCmd_dec[0] == MIFARE_CMD_READBLOCK) {
b35e04a7 566 uint8_t blockNo = receivedCmd_dec[1];
b35e04a7 567 emlGetMem(response, blockNo, 1);
568 if (IsSectorTrailer(blockNo)) {
a8561e35 569 memset(response, 0x00, 6); // keyA can never be read
b35e04a7 570 if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_KEYB_READ)) {
a8561e35 571 memset(response+10, 0x00, 6); // keyB cannot be read
b35e04a7 572 }
573 if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_AC_READ)) {
a8561e35 574 memset(response+6, 0x00, 4); // AC bits cannot be read
b35e04a7 575 }
576 } else {
577 if (!IsAccessAllowed(blockNo, cardAUTHKEY, AC_DATA_READ)) {
a8561e35 578 memset(response, 0x00, 16); // datablock cannot be read
b35e04a7 579 }
6e49717b 580 }
6e49717b 581 AppendCrc14443a(response, 16);
582 mf_crypto1_encrypt(pcs, response, 18, response_par);
583 EmSendCmdPar(response, 18, response_par);
a8561e35 584 FpgaDisableTracing();
585 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
586 Dbprintf("Reader reading block %d (0x%02x)", blockNo, blockNo);
587 }
6e49717b 588 numReads++;
589 if(exitAfterNReads > 0 && numReads == exitAfterNReads) {
590 Dbprintf("%d reads done, exiting", numReads);
591 finished = true;
592 }
593 break;
594 }
a8561e35 595
b8dd1ef6 596 if (receivedCmd_dec[0] == MIFARE_CMD_WRITEBLOCK) {
b35e04a7 597 uint8_t blockNo = receivedCmd_dec[1];
6e49717b 598 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
a8561e35 599 FpgaDisableTracing();
600 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("RECV 0xA0 write block %d (%02x)", blockNo, blockNo);
b35e04a7 601 cardWRBL = blockNo;
6e49717b 602 cardSTATE = MFEMUL_WRITEBL2;
603 break;
604 }
a8561e35 605
6e49717b 606 if (receivedCmd_dec[0] == MIFARE_CMD_INC || receivedCmd_dec[0] == MIFARE_CMD_DEC || receivedCmd_dec[0] == MIFARE_CMD_RESTORE) {
b35e04a7 607 uint8_t blockNo = receivedCmd_dec[1];
b35e04a7 608 if (emlCheckValBl(blockNo)) {
6e49717b 609 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 610 FpgaDisableTracing();
611 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
612 Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd_dec[0], blockNo, blockNo);
613 }
614 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader tried to operate on block, but emlCheckValBl failed, nacking");
6e49717b 615 break;
616 }
617 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
a8561e35 618 FpgaDisableTracing();
619 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) {
620 Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd_dec[0], blockNo, blockNo);
621 }
b35e04a7 622 cardWRBL = blockNo;
6e49717b 623 if (receivedCmd_dec[0] == MIFARE_CMD_INC)
624 cardSTATE = MFEMUL_INTREG_INC;
625 if (receivedCmd_dec[0] == MIFARE_CMD_DEC)
626 cardSTATE = MFEMUL_INTREG_DEC;
627 if (receivedCmd_dec[0] == MIFARE_CMD_RESTORE)
628 cardSTATE = MFEMUL_INTREG_REST;
629 break;
630 }
a8561e35 631
6e49717b 632 if (receivedCmd_dec[0] == MIFARE_CMD_TRANSFER) {
b35e04a7 633 uint8_t blockNo = receivedCmd_dec[1];
6e49717b 634 if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd_dec[1]))
635 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
636 else
637 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
a8561e35 638 FpgaDisableTracing();
639 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("RECV 0x%02x transfer block %d (%02x)",receivedCmd_dec[0], blockNo, blockNo);
6e49717b 640 break;
641 }
a8561e35 642
6e49717b 643 // command not allowed
6e49717b 644 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 645 FpgaDisableTracing();
646 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Received command not allowed, nacking");
647 cardSTATE = MFEMUL_IDLE;
6e49717b 648 break;
649 }
a8561e35 650
6e49717b 651 case MFEMUL_AUTH1:{
652 if (receivedCmd_len != 8) {
a8561e35 653 cardSTATE = MFEMUL_IDLE;
6e49717b 654 break;
655 }
656
657 uint32_t nr = bytes_to_num(receivedCmd, 4);
658 uint32_t ar = bytes_to_num(&receivedCmd[4], 4);
659
660 // Collect AR/NR per keytype & sector
661 if(flags & FLAG_NR_AR_ATTACK) {
662 for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
663 if ( ar_nr_collected[i+mM]==0 || ((cardAUTHSC == ar_nr_resp[i+mM].sector) && (cardAUTHKEY == ar_nr_resp[i+mM].keytype) && (ar_nr_collected[i+mM] > 0)) ) {
664 // if first auth for sector, or matches sector and keytype of previous auth
665 if (ar_nr_collected[i+mM] < 2) {
666 // if we haven't already collected 2 nonces for this sector
667 if (ar_nr_resp[ar_nr_collected[i+mM]].ar != ar) {
a8561e35 668 // Avoid duplicates... probably not necessary, ar should vary.
6e49717b 669 if (ar_nr_collected[i+mM]==0) {
670 // first nonce collect
671 ar_nr_resp[i+mM].cuid = cuid;
672 ar_nr_resp[i+mM].sector = cardAUTHSC;
673 ar_nr_resp[i+mM].keytype = cardAUTHKEY;
674 ar_nr_resp[i+mM].nonce = nonce;
675 ar_nr_resp[i+mM].nr = nr;
676 ar_nr_resp[i+mM].ar = ar;
677 nonce1_count++;
678 // add this nonce to first moebius nonce
679 ar_nr_resp[i+ATTACK_KEY_COUNT].cuid = cuid;
680 ar_nr_resp[i+ATTACK_KEY_COUNT].sector = cardAUTHSC;
681 ar_nr_resp[i+ATTACK_KEY_COUNT].keytype = cardAUTHKEY;
682 ar_nr_resp[i+ATTACK_KEY_COUNT].nonce = nonce;
683 ar_nr_resp[i+ATTACK_KEY_COUNT].nr = nr;
684 ar_nr_resp[i+ATTACK_KEY_COUNT].ar = ar;
685 ar_nr_collected[i+ATTACK_KEY_COUNT]++;
686 } else { // second nonce collect (std and moebius)
687 ar_nr_resp[i+mM].nonce2 = nonce;
688 ar_nr_resp[i+mM].nr2 = nr;
689 ar_nr_resp[i+mM].ar2 = ar;
690 if (!gettingMoebius) {
691 nonce2_count++;
692 // check if this was the last second nonce we need for std attack
693 if ( nonce2_count == nonce1_count ) {
694 // done collecting std test switch to moebius
695 // first finish incrementing last sample
a8561e35 696 ar_nr_collected[i+mM]++;
6e49717b 697 // switch to moebius collection
698 gettingMoebius = true;
699 mM = ATTACK_KEY_COUNT;
700 if (flags & FLAG_RANDOM_NONCE) {
701 nonce = prand();
702 } else {
703 nonce = nonce*7;
704 }
705 break;
706 }
707 } else {
708 moebius_n_count++;
709 // if we've collected all the nonces we need - finish.
710 if (nonce1_count == moebius_n_count) finished = true;
711 }
712 }
713 ar_nr_collected[i+mM]++;
714 }
715 }
716 // we found right spot for this nonce stop looking
717 break;
718 }
719 }
720 }
721
722 // --- crypto
723 crypto1_word(pcs, nr , 1);
724 cardRr = ar ^ crypto1_word(pcs, 0, 0);
725
726 // test if auth OK
727 if (cardRr != prng_successor(nonce, 64)){
a8561e35 728 FpgaDisableTracing();
729 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("AUTH FAILED for sector %d with key %c. cardRr=%08x, succ=%08x",
b35e04a7 730 cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B',
6e49717b 731 cardRr, prng_successor(nonce, 64));
732 // Shouldn't we respond anything here?
733 // Right now, we don't nack or anything, which causes the
734 // reader to do a WUPA after a while. /Martin
735 // -- which is the correct response. /piwi
a8561e35 736 cardAUTHKEY = AUTHKEYNONE; // not authenticated
737 cardSTATE = MFEMUL_IDLE;
6e49717b 738 break;
739 }
a8561e35 740 ans = prng_successor(nonce, 96);
741 num_to_bytes(ans, 4, response);
742 mf_crypto1_encrypt(pcs, response, 4, response_par);
743 EmSendCmdPar(response, 4, response_par);
744 FpgaDisableTracing();
745 if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("AUTH COMPLETED for sector %d with key %c.", cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B');
6e49717b 746 cardSTATE = MFEMUL_WORK;
747 break;
748 }
a8561e35 749
6e49717b 750 case MFEMUL_WRITEBL2:{
751 if (receivedCmd_len == 18) {
752 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, receivedCmd_dec);
753 if (HasValidCRC(receivedCmd_dec, receivedCmd_len)) {
b35e04a7 754 if (IsSectorTrailer(cardWRBL)) {
755 emlGetMem(response, cardWRBL, 1);
756 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYA_WRITE)) {
a8561e35 757 memcpy(receivedCmd_dec, response, 6); // don't change KeyA
b35e04a7 758 }
759 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_KEYB_WRITE)) {
a8561e35 760 memcpy(receivedCmd_dec+10, response+10, 6); // don't change KeyA
b35e04a7 761 }
762 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_AC_WRITE)) {
a8561e35 763 memcpy(receivedCmd_dec+6, response+6, 4); // don't change AC bits
b35e04a7 764 }
765 } else {
766 if (!IsAccessAllowed(cardWRBL, cardAUTHKEY, AC_DATA_WRITE)) {
a8561e35 767 memcpy(receivedCmd_dec, response, 16); // don't change anything
b35e04a7 768 }
769 }
6e49717b 770 emlSetMem(receivedCmd_dec, cardWRBL, 1);
a8561e35 771 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK)); // always ACK?
6e49717b 772 cardSTATE = MFEMUL_WORK;
773 break;
774 }
775 }
a8561e35 776 cardSTATE = MFEMUL_IDLE;
6e49717b 777 break;
778 }
a8561e35 779
6e49717b 780 case MFEMUL_INTREG_INC:{
781 if (receivedCmd_len == 6) {
782 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t*)&ans);
783 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
784 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 785 cardSTATE = MFEMUL_IDLE;
6e49717b 786 break;
787 }
788 cardINTREG = cardINTREG + ans;
a8561e35 789 cardSTATE = MFEMUL_WORK;
6e49717b 790 }
6e49717b 791 break;
792 }
a8561e35 793
6e49717b 794 case MFEMUL_INTREG_DEC:{
795 if (receivedCmd_len == 6) {
796 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t*)&ans);
797 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
798 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 799 cardSTATE = MFEMUL_IDLE;
6e49717b 800 break;
801 }
a8561e35 802 cardINTREG = cardINTREG - ans;
803 cardSTATE = MFEMUL_WORK;
6e49717b 804 }
6e49717b 805 break;
806 }
a8561e35 807
6e49717b 808 case MFEMUL_INTREG_REST:{
809 mf_crypto1_decryptEx(pcs, receivedCmd, receivedCmd_len, (uint8_t*)&ans);
810 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
811 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
a8561e35 812 cardSTATE = MFEMUL_IDLE;
6e49717b 813 break;
814 }
815 cardSTATE = MFEMUL_WORK;
816 break;
817 }
a8561e35 818
819 } // end of switch
820
821 FpgaDisableTracing();
6e49717b 822 button_pushed = BUTTON_PRESS();
a8561e35 823
824 } // end of while
6e49717b 825
826 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
827 LEDsoff();
828
a8561e35 829 if(flags & FLAG_NR_AR_ATTACK && MF_DBGLEVEL >= MF_DBG_INFO) {
830 for ( uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) {
6e49717b 831 if (ar_nr_collected[i] == 2) {
832 Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i<ATTACK_KEY_COUNT/2) ? "keyA" : "keyB", ar_nr_resp[i].sector);
833 Dbprintf("../tools/mfkey/mfkey32 %08x %08x %08x %08x %08x %08x",
834 ar_nr_resp[i].cuid, //UID
835 ar_nr_resp[i].nonce, //NT
836 ar_nr_resp[i].nr, //NR1
837 ar_nr_resp[i].ar, //AR1
838 ar_nr_resp[i].nr2, //NR2
839 ar_nr_resp[i].ar2 //AR2
840 );
841 }
a8561e35 842 }
843 for ( uint8_t i = ATTACK_KEY_COUNT; i < ATTACK_KEY_COUNT*2; i++) {
6e49717b 844 if (ar_nr_collected[i] == 2) {
845 Dbprintf("Collected two pairs of AR/NR which can be used to extract %s from reader for sector %d:", (i<ATTACK_KEY_COUNT/2) ? "keyA" : "keyB", ar_nr_resp[i].sector);
a8561e35 846 Dbprintf("../tools/mfkey/mfkey32 %08x %08x %08x %08x %08x %08x %08x",
6e49717b 847 ar_nr_resp[i].cuid, //UID
848 ar_nr_resp[i].nonce, //NT
849 ar_nr_resp[i].nr, //NR1
850 ar_nr_resp[i].ar, //AR1
851 ar_nr_resp[i].nonce2,//NT2
852 ar_nr_resp[i].nr2, //NR2
853 ar_nr_resp[i].ar2 //AR2
854 );
855 }
856 }
857 }
a8561e35 858 if (MF_DBGLEVEL >= MF_DBG_INFO) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
6e49717b 859
860 if(flags & FLAG_INTERACTIVE) { // Interactive mode flag, means we need to send ACK
861 //Send the collected ar_nr in the response
a8561e35 862 cmd_send(CMD_ACK, CMD_SIMULATE_MIFARE_CARD, button_pushed, 0, &ar_nr_resp, sizeof(ar_nr_resp));
6e49717b 863 }
a8561e35 864
865 LED_A_OFF();
6e49717b 866}
Impressum, Datenschutz