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