]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443a.c
alpha2 mifare emulator
[proxmark3-svn] / armsrc / iso14443a.c
CommitLineData
15c4dc5a 1//-----------------------------------------------------------------------------
f89c7050 2// Merlok - June 2011
15c4dc5a 3// Gerhard de Koning Gans - May 2008
534983d7 4// Hagen Fritsch - June 2010
bd20f8f4 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.
15c4dc5a 9//-----------------------------------------------------------------------------
bd20f8f4 10// Routines to support ISO 14443 type A.
11//-----------------------------------------------------------------------------
12
e30c654b 13#include "proxmark3.h"
15c4dc5a 14#include "apps.h"
f7e3ed82 15#include "util.h"
9ab7a6c7 16#include "string.h"
17
15c4dc5a 18#include "iso14443crc.h"
534983d7 19#include "iso14443a.h"
20f9a2a1
M
20#include "crapto1.h"
21#include "mifareutil.h"
15c4dc5a 22
f7e3ed82 23static uint8_t *trace = (uint8_t *) BigBuf;
15c4dc5a 24static int traceLen = 0;
25static int rsamples = 0;
f7e3ed82 26static int tracing = TRUE;
534983d7 27static uint32_t iso14a_timeout;
15c4dc5a 28
72934aa3 29// CARD TO READER
30// Sequence D: 11110000 modulation with subcarrier during first half
31// Sequence E: 00001111 modulation with subcarrier during second half
32// Sequence F: 00000000 no modulation with subcarrier
33// READER TO CARD
34// Sequence X: 00001100 drop after half a period
35// Sequence Y: 00000000 no drop
36// Sequence Z: 11000000 drop at start
37#define SEC_D 0xf0
38#define SEC_E 0x0f
39#define SEC_F 0x00
40#define SEC_X 0x0c
41#define SEC_Y 0x00
42#define SEC_Z 0xc0
15c4dc5a 43
f7e3ed82 44static const uint8_t OddByteParity[256] = {
15c4dc5a 45 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
46 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
47 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
48 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
49 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
50 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
51 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
52 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
57 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
58 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
59 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
60 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
61};
62
63// BIG CHANGE - UNDERSTAND THIS BEFORE WE COMMIT
64#define RECV_CMD_OFFSET 3032
65#define RECV_RES_OFFSET 3096
66#define DMA_BUFFER_OFFSET 3160
67#define DMA_BUFFER_SIZE 4096
68#define TRACE_LENGTH 3000
0a39986e
M
69// card emulator memory
70#define CARD_MEMORY 7260
71#define CARD_MEMORY_LEN 1024
15c4dc5a 72
534983d7 73uint8_t trigger = 0;
74void iso14a_set_trigger(int enable) {
75 trigger = enable;
76}
77
15c4dc5a 78//-----------------------------------------------------------------------------
79// Generate the parity value for a byte sequence
e30c654b 80//
15c4dc5a 81//-----------------------------------------------------------------------------
20f9a2a1
M
82byte_t oddparity (const byte_t bt)
83{
84 return OddByteParity[bt];
85}
86
f7e3ed82 87uint32_t GetParity(const uint8_t * pbtCmd, int iLen)
15c4dc5a 88{
89 int i;
f7e3ed82 90 uint32_t dwPar = 0;
72934aa3 91
15c4dc5a 92 // Generate the encrypted data
93 for (i = 0; i < iLen; i++) {
94 // Save the encrypted parity bit
95 dwPar |= ((OddByteParity[pbtCmd[i]]) << i);
96 }
97 return dwPar;
98}
99
534983d7 100void AppendCrc14443a(uint8_t* data, int len)
15c4dc5a 101{
102 ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
103}
104
ed82636b 105int LogTrace(const uint8_t * btBytes, int iLen, int iSamples, uint32_t dwParity, int bReader)
15c4dc5a 106{
107 // Return when trace is full
108 if (traceLen >= TRACE_LENGTH) return FALSE;
e30c654b 109
15c4dc5a 110 // Trace the random, i'm curious
111 rsamples += iSamples;
112 trace[traceLen++] = ((rsamples >> 0) & 0xff);
113 trace[traceLen++] = ((rsamples >> 8) & 0xff);
114 trace[traceLen++] = ((rsamples >> 16) & 0xff);
115 trace[traceLen++] = ((rsamples >> 24) & 0xff);
116 if (!bReader) {
117 trace[traceLen - 1] |= 0x80;
118 }
119 trace[traceLen++] = ((dwParity >> 0) & 0xff);
120 trace[traceLen++] = ((dwParity >> 8) & 0xff);
121 trace[traceLen++] = ((dwParity >> 16) & 0xff);
122 trace[traceLen++] = ((dwParity >> 24) & 0xff);
123 trace[traceLen++] = iLen;
124 memcpy(trace + traceLen, btBytes, iLen);
125 traceLen += iLen;
126 return TRUE;
127}
128
15c4dc5a 129//-----------------------------------------------------------------------------
130// The software UART that receives commands from the reader, and its state
131// variables.
132//-----------------------------------------------------------------------------
133static struct {
134 enum {
135 STATE_UNSYNCD,
136 STATE_START_OF_COMMUNICATION,
137 STATE_MILLER_X,
138 STATE_MILLER_Y,
139 STATE_MILLER_Z,
140 STATE_ERROR_WAIT
141 } state;
f7e3ed82 142 uint16_t shiftReg;
15c4dc5a 143 int bitCnt;
144 int byteCnt;
145 int byteCntMax;
146 int posCnt;
147 int syncBit;
148 int parityBits;
149 int samples;
150 int highCnt;
151 int bitBuffer;
152 enum {
153 DROP_NONE,
154 DROP_FIRST_HALF,
155 DROP_SECOND_HALF
156 } drop;
f7e3ed82 157 uint8_t *output;
15c4dc5a 158} Uart;
159
6c1e2d95 160static RAMFUNC int MillerDecoding(int bit)
15c4dc5a 161{
162 int error = 0;
163 int bitright;
164
165 if(!Uart.bitBuffer) {
166 Uart.bitBuffer = bit ^ 0xFF0;
167 return FALSE;
168 }
169 else {
170 Uart.bitBuffer <<= 4;
171 Uart.bitBuffer ^= bit;
172 }
173
f7e3ed82 174 int EOC = FALSE;
15c4dc5a 175
176 if(Uart.state != STATE_UNSYNCD) {
177 Uart.posCnt++;
178
179 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
180 bit = 0x00;
181 }
182 else {
183 bit = 0x01;
184 }
185 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
186 bitright = 0x00;
187 }
188 else {
189 bitright = 0x01;
190 }
191 if(bit != bitright) { bit = bitright; }
192
193 if(Uart.posCnt == 1) {
194 // measurement first half bitperiod
195 if(!bit) {
196 Uart.drop = DROP_FIRST_HALF;
197 }
198 }
199 else {
200 // measurement second half bitperiod
201 if(!bit & (Uart.drop == DROP_NONE)) {
202 Uart.drop = DROP_SECOND_HALF;
203 }
204 else if(!bit) {
205 // measured a drop in first and second half
206 // which should not be possible
207 Uart.state = STATE_ERROR_WAIT;
208 error = 0x01;
209 }
210
211 Uart.posCnt = 0;
212
213 switch(Uart.state) {
214 case STATE_START_OF_COMMUNICATION:
215 Uart.shiftReg = 0;
216 if(Uart.drop == DROP_SECOND_HALF) {
217 // error, should not happen in SOC
218 Uart.state = STATE_ERROR_WAIT;
219 error = 0x02;
220 }
221 else {
222 // correct SOC
223 Uart.state = STATE_MILLER_Z;
224 }
225 break;
226
227 case STATE_MILLER_Z:
228 Uart.bitCnt++;
229 Uart.shiftReg >>= 1;
230 if(Uart.drop == DROP_NONE) {
231 // logic '0' followed by sequence Y
232 // end of communication
233 Uart.state = STATE_UNSYNCD;
234 EOC = TRUE;
235 }
236 // if(Uart.drop == DROP_FIRST_HALF) {
237 // Uart.state = STATE_MILLER_Z; stay the same
238 // we see a logic '0' }
239 if(Uart.drop == DROP_SECOND_HALF) {
240 // we see a logic '1'
241 Uart.shiftReg |= 0x100;
242 Uart.state = STATE_MILLER_X;
243 }
244 break;
245
246 case STATE_MILLER_X:
247 Uart.shiftReg >>= 1;
248 if(Uart.drop == DROP_NONE) {
249 // sequence Y, we see a '0'
250 Uart.state = STATE_MILLER_Y;
251 Uart.bitCnt++;
252 }
253 if(Uart.drop == DROP_FIRST_HALF) {
254 // Would be STATE_MILLER_Z
255 // but Z does not follow X, so error
256 Uart.state = STATE_ERROR_WAIT;
257 error = 0x03;
258 }
259 if(Uart.drop == DROP_SECOND_HALF) {
260 // We see a '1' and stay in state X
261 Uart.shiftReg |= 0x100;
262 Uart.bitCnt++;
263 }
264 break;
265
266 case STATE_MILLER_Y:
267 Uart.bitCnt++;
268 Uart.shiftReg >>= 1;
269 if(Uart.drop == DROP_NONE) {
270 // logic '0' followed by sequence Y
271 // end of communication
272 Uart.state = STATE_UNSYNCD;
273 EOC = TRUE;
274 }
275 if(Uart.drop == DROP_FIRST_HALF) {
276 // we see a '0'
277 Uart.state = STATE_MILLER_Z;
278 }
279 if(Uart.drop == DROP_SECOND_HALF) {
280 // We see a '1' and go to state X
281 Uart.shiftReg |= 0x100;
282 Uart.state = STATE_MILLER_X;
283 }
284 break;
285
286 case STATE_ERROR_WAIT:
287 // That went wrong. Now wait for at least two bit periods
288 // and try to sync again
289 if(Uart.drop == DROP_NONE) {
290 Uart.highCnt = 6;
291 Uart.state = STATE_UNSYNCD;
292 }
293 break;
294
295 default:
296 Uart.state = STATE_UNSYNCD;
297 Uart.highCnt = 0;
298 break;
299 }
300
301 Uart.drop = DROP_NONE;
302
303 // should have received at least one whole byte...
304 if((Uart.bitCnt == 2) && EOC && (Uart.byteCnt > 0)) {
305 return TRUE;
306 }
307
308 if(Uart.bitCnt == 9) {
309 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
310 Uart.byteCnt++;
311
312 Uart.parityBits <<= 1;
313 Uart.parityBits ^= ((Uart.shiftReg >> 8) & 0x01);
314
315 if(EOC) {
316 // when End of Communication received and
317 // all data bits processed..
318 return TRUE;
319 }
320 Uart.bitCnt = 0;
321 }
322
323 /*if(error) {
324 Uart.output[Uart.byteCnt] = 0xAA;
325 Uart.byteCnt++;
326 Uart.output[Uart.byteCnt] = error & 0xFF;
327 Uart.byteCnt++;
328 Uart.output[Uart.byteCnt] = 0xAA;
329 Uart.byteCnt++;
330 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
331 Uart.byteCnt++;
332 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
333 Uart.byteCnt++;
334 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
335 Uart.byteCnt++;
336 Uart.output[Uart.byteCnt] = 0xAA;
337 Uart.byteCnt++;
338 return TRUE;
339 }*/
340 }
341
342 }
343 else {
344 bit = Uart.bitBuffer & 0xf0;
345 bit >>= 4;
346 bit ^= 0x0F;
347 if(bit) {
348 // should have been high or at least (4 * 128) / fc
349 // according to ISO this should be at least (9 * 128 + 20) / fc
350 if(Uart.highCnt == 8) {
351 // we went low, so this could be start of communication
352 // it turns out to be safer to choose a less significant
353 // syncbit... so we check whether the neighbour also represents the drop
354 Uart.posCnt = 1; // apparently we are busy with our first half bit period
355 Uart.syncBit = bit & 8;
356 Uart.samples = 3;
357 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
358 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
359 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
360 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
361 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
2f2d9fc5 362 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
15c4dc5a 363 Uart.syncBit = 8;
364
365 // the first half bit period is expected in next sample
366 Uart.posCnt = 0;
367 Uart.samples = 3;
368 }
369 }
370 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
371
372 Uart.syncBit <<= 4;
373 Uart.state = STATE_START_OF_COMMUNICATION;
374 Uart.drop = DROP_FIRST_HALF;
375 Uart.bitCnt = 0;
376 Uart.byteCnt = 0;
377 Uart.parityBits = 0;
378 error = 0;
379 }
380 else {
381 Uart.highCnt = 0;
382 }
383 }
384 else {
385 if(Uart.highCnt < 8) {
386 Uart.highCnt++;
387 }
388 }
389 }
390
391 return FALSE;
392}
393
394//=============================================================================
395// ISO 14443 Type A - Manchester
396//=============================================================================
397
398static struct {
399 enum {
400 DEMOD_UNSYNCD,
401 DEMOD_START_OF_COMMUNICATION,
402 DEMOD_MANCHESTER_D,
403 DEMOD_MANCHESTER_E,
404 DEMOD_MANCHESTER_F,
405 DEMOD_ERROR_WAIT
406 } state;
407 int bitCount;
408 int posCount;
409 int syncBit;
410 int parityBits;
f7e3ed82 411 uint16_t shiftReg;
15c4dc5a 412 int buffer;
413 int buff;
414 int samples;
415 int len;
416 enum {
417 SUB_NONE,
418 SUB_FIRST_HALF,
419 SUB_SECOND_HALF
420 } sub;
f7e3ed82 421 uint8_t *output;
15c4dc5a 422} Demod;
423
6c1e2d95 424static RAMFUNC int ManchesterDecoding(int v)
15c4dc5a 425{
426 int bit;
427 int modulation;
428 int error = 0;
429
430 if(!Demod.buff) {
431 Demod.buff = 1;
432 Demod.buffer = v;
433 return FALSE;
434 }
435 else {
436 bit = Demod.buffer;
437 Demod.buffer = v;
438 }
439
440 if(Demod.state==DEMOD_UNSYNCD) {
441 Demod.output[Demod.len] = 0xfa;
442 Demod.syncBit = 0;
443 //Demod.samples = 0;
444 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
2f2d9fc5 445
446 if(bit & 0x08) {
447 Demod.syncBit = 0x08;
15c4dc5a 448 }
15c4dc5a 449
2f2d9fc5 450 if(bit & 0x04) {
451 if(Demod.syncBit) {
452 bit <<= 4;
453 }
454 Demod.syncBit = 0x04;
455 }
15c4dc5a 456
2f2d9fc5 457 if(bit & 0x02) {
458 if(Demod.syncBit) {
459 bit <<= 2;
15c4dc5a 460 }
2f2d9fc5 461 Demod.syncBit = 0x02;
15c4dc5a 462 }
15c4dc5a 463
593924e7 464 if(bit & 0x01 && Demod.syncBit) {
2f2d9fc5 465 Demod.syncBit = 0x01;
466 }
467
15c4dc5a 468 if(Demod.syncBit) {
469 Demod.len = 0;
470 Demod.state = DEMOD_START_OF_COMMUNICATION;
471 Demod.sub = SUB_FIRST_HALF;
472 Demod.bitCount = 0;
473 Demod.shiftReg = 0;
474 Demod.parityBits = 0;
475 Demod.samples = 0;
476 if(Demod.posCount) {
534983d7 477 if(trigger) LED_A_OFF();
15c4dc5a 478 switch(Demod.syncBit) {
479 case 0x08: Demod.samples = 3; break;
480 case 0x04: Demod.samples = 2; break;
481 case 0x02: Demod.samples = 1; break;
482 case 0x01: Demod.samples = 0; break;
483 }
484 }
485 error = 0;
486 }
487 }
488 else {
489 //modulation = bit & Demod.syncBit;
490 modulation = ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
491
492 Demod.samples += 4;
493
494 if(Demod.posCount==0) {
495 Demod.posCount = 1;
496 if(modulation) {
497 Demod.sub = SUB_FIRST_HALF;
498 }
499 else {
500 Demod.sub = SUB_NONE;
501 }
502 }
503 else {
504 Demod.posCount = 0;
505 if(modulation && (Demod.sub == SUB_FIRST_HALF)) {
506 if(Demod.state!=DEMOD_ERROR_WAIT) {
507 Demod.state = DEMOD_ERROR_WAIT;
508 Demod.output[Demod.len] = 0xaa;
509 error = 0x01;
510 }
511 }
512 else if(modulation) {
513 Demod.sub = SUB_SECOND_HALF;
514 }
515
516 switch(Demod.state) {
517 case DEMOD_START_OF_COMMUNICATION:
518 if(Demod.sub == SUB_FIRST_HALF) {
519 Demod.state = DEMOD_MANCHESTER_D;
520 }
521 else {
522 Demod.output[Demod.len] = 0xab;
523 Demod.state = DEMOD_ERROR_WAIT;
524 error = 0x02;
525 }
526 break;
527
528 case DEMOD_MANCHESTER_D:
529 case DEMOD_MANCHESTER_E:
530 if(Demod.sub == SUB_FIRST_HALF) {
531 Demod.bitCount++;
532 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
533 Demod.state = DEMOD_MANCHESTER_D;
534 }
535 else if(Demod.sub == SUB_SECOND_HALF) {
536 Demod.bitCount++;
537 Demod.shiftReg >>= 1;
538 Demod.state = DEMOD_MANCHESTER_E;
539 }
540 else {
541 Demod.state = DEMOD_MANCHESTER_F;
542 }
543 break;
544
545 case DEMOD_MANCHESTER_F:
546 // Tag response does not need to be a complete byte!
547 if(Demod.len > 0 || Demod.bitCount > 0) {
548 if(Demod.bitCount > 0) {
549 Demod.shiftReg >>= (9 - Demod.bitCount);
550 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
551 Demod.len++;
552 // No parity bit, so just shift a 0
553 Demod.parityBits <<= 1;
554 }
555
556 Demod.state = DEMOD_UNSYNCD;
557 return TRUE;
558 }
559 else {
560 Demod.output[Demod.len] = 0xad;
561 Demod.state = DEMOD_ERROR_WAIT;
562 error = 0x03;
563 }
564 break;
565
566 case DEMOD_ERROR_WAIT:
567 Demod.state = DEMOD_UNSYNCD;
568 break;
569
570 default:
571 Demod.output[Demod.len] = 0xdd;
572 Demod.state = DEMOD_UNSYNCD;
573 break;
574 }
575
576 if(Demod.bitCount>=9) {
577 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
578 Demod.len++;
579
580 Demod.parityBits <<= 1;
581 Demod.parityBits ^= ((Demod.shiftReg >> 8) & 0x01);
582
583 Demod.bitCount = 0;
584 Demod.shiftReg = 0;
585 }
586
587 /*if(error) {
588 Demod.output[Demod.len] = 0xBB;
589 Demod.len++;
590 Demod.output[Demod.len] = error & 0xFF;
591 Demod.len++;
592 Demod.output[Demod.len] = 0xBB;
593 Demod.len++;
594 Demod.output[Demod.len] = bit & 0xFF;
595 Demod.len++;
596 Demod.output[Demod.len] = Demod.buffer & 0xFF;
597 Demod.len++;
598 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
599 Demod.len++;
600 Demod.output[Demod.len] = 0xBB;
601 Demod.len++;
602 return TRUE;
603 }*/
604
605 }
606
607 } // end (state != UNSYNCED)
608
609 return FALSE;
610}
611
612//=============================================================================
613// Finally, a `sniffer' for ISO 14443 Type A
614// Both sides of communication!
615//=============================================================================
616
617//-----------------------------------------------------------------------------
618// Record the sequence of commands sent by the reader to the tag, with
619// triggering so that we start recording at the point that the tag is moved
620// near the reader.
621//-----------------------------------------------------------------------------
6c1e2d95 622void RAMFUNC SnoopIso14443a(void)
15c4dc5a 623{
624// #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
625// #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
626// #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
627// #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
628// #define TRACE_LENGTH 2000 // original (working as of 21/2/09) values
629
630 // We won't start recording the frames that we acquire until we trigger;
631 // a good trigger condition to get started is probably when we see a
632 // response from the tag.
7e758047 633 int triggered = FALSE; // FALSE to wait first for card
15c4dc5a 634
635 // The command (reader -> tag) that we're receiving.
636 // The length of a received command will in most cases be no more than 18 bytes.
637 // So 32 should be enough!
f7e3ed82 638 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
15c4dc5a 639 // The response (tag -> reader) that we're receiving.
f7e3ed82 640 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
15c4dc5a 641
642 // As we receive stuff, we copy it from receivedCmd or receivedResponse
643 // into trace, along with its length and other annotations.
f7e3ed82 644 //uint8_t *trace = (uint8_t *)BigBuf;
d82c6ebb 645
646 traceLen = 0; // uncommented to fix ISSUE 15 - gerhard - jan2011
15c4dc5a 647
648 // The DMA buffer, used to stream samples from the FPGA
f7e3ed82 649 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
15c4dc5a 650 int lastRxCounter;
f7e3ed82 651 int8_t *upTo;
15c4dc5a 652 int smpl;
653 int maxBehindBy = 0;
654
655 // Count of samples received so far, so that we can include timing
656 // information in the trace buffer.
657 int samples = 0;
cee5a30d 658 int rsamples = 0;
15c4dc5a 659
660 memset(trace, 0x44, RECV_CMD_OFFSET);
661
662 // Set up the demodulator for tag -> reader responses.
663 Demod.output = receivedResponse;
664 Demod.len = 0;
665 Demod.state = DEMOD_UNSYNCD;
666
7e758047 667 // Setup for the DMA.
668 FpgaSetupSsc();
669 upTo = dmaBuf;
670 lastRxCounter = DMA_BUFFER_SIZE;
671 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
672
15c4dc5a 673 // And the reader -> tag commands
674 memset(&Uart, 0, sizeof(Uart));
675 Uart.output = receivedCmd;
676 Uart.byteCntMax = 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
677 Uart.state = STATE_UNSYNCD;
678
679 // And put the FPGA in the appropriate mode
680 // Signal field is off with the appropriate LED
681 LED_D_OFF();
682 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
683 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
684
15c4dc5a 685
686 // And now we loop, receiving samples.
687 for(;;) {
7e758047 688 LED_A_ON();
689 WDT_HIT();
15c4dc5a 690 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
691 (DMA_BUFFER_SIZE-1);
692 if(behindBy > maxBehindBy) {
693 maxBehindBy = behindBy;
694 if(behindBy > 400) {
7e758047 695 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
15c4dc5a 696 goto done;
697 }
698 }
699 if(behindBy < 1) continue;
700
7e758047 701 LED_A_OFF();
15c4dc5a 702 smpl = upTo[0];
703 upTo++;
704 lastRxCounter -= 1;
705 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
706 upTo -= DMA_BUFFER_SIZE;
707 lastRxCounter += DMA_BUFFER_SIZE;
f7e3ed82 708 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
15c4dc5a 709 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
710 }
711
712 samples += 4;
7e758047 713 if(MillerDecoding((smpl & 0xF0) >> 4)) {
15c4dc5a 714 rsamples = samples - Uart.samples;
72934aa3 715 LED_C_ON();
7e758047 716 if(triggered) {
717 trace[traceLen++] = ((rsamples >> 0) & 0xff);
72934aa3 718 trace[traceLen++] = ((rsamples >> 8) & 0xff);
719 trace[traceLen++] = ((rsamples >> 16) & 0xff);
720 trace[traceLen++] = ((rsamples >> 24) & 0xff);
7e758047 721 trace[traceLen++] = ((Uart.parityBits >> 0) & 0xff);
722 trace[traceLen++] = ((Uart.parityBits >> 8) & 0xff);
723 trace[traceLen++] = ((Uart.parityBits >> 16) & 0xff);
724 trace[traceLen++] = ((Uart.parityBits >> 24) & 0xff);
72934aa3 725 trace[traceLen++] = Uart.byteCnt;
726 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt);
727 traceLen += Uart.byteCnt;
728 if(traceLen > TRACE_LENGTH) break;
729 }
730 /* And ready to receive another command. */
731 Uart.state = STATE_UNSYNCD;
732 /* And also reset the demod code, which might have been */
733 /* false-triggered by the commands from the reader. */
734 Demod.state = DEMOD_UNSYNCD;
7e758047 735 LED_B_OFF();
15c4dc5a 736 }
7e758047 737
738 if(ManchesterDecoding(smpl & 0x0F)) {
739 rsamples = samples - Demod.samples;
740 LED_B_ON();
741
742 // timestamp, as a count of samples
743 trace[traceLen++] = ((rsamples >> 0) & 0xff);
744 trace[traceLen++] = ((rsamples >> 8) & 0xff);
745 trace[traceLen++] = ((rsamples >> 16) & 0xff);
746 trace[traceLen++] = 0x80 | ((rsamples >> 24) & 0xff);
747 trace[traceLen++] = ((Demod.parityBits >> 0) & 0xff);
748 trace[traceLen++] = ((Demod.parityBits >> 8) & 0xff);
749 trace[traceLen++] = ((Demod.parityBits >> 16) & 0xff);
750 trace[traceLen++] = ((Demod.parityBits >> 24) & 0xff);
751 // length
752 trace[traceLen++] = Demod.len;
753 memcpy(trace+traceLen, receivedResponse, Demod.len);
754 traceLen += Demod.len;
755 if(traceLen > TRACE_LENGTH) break;
756
757 triggered = TRUE;
15c4dc5a 758
759 // And ready to receive another response.
760 memset(&Demod, 0, sizeof(Demod));
761 Demod.output = receivedResponse;
762 Demod.state = DEMOD_UNSYNCD;
7e758047 763 LED_C_OFF();
764 }
15c4dc5a 765
766 if(BUTTON_PRESS()) {
767 DbpString("cancelled_a");
768 goto done;
769 }
770 }
771
772 DbpString("COMMAND FINISHED");
773
774 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
775 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
776
777done:
778 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
779 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
780 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
781 LED_A_OFF();
782 LED_B_OFF();
783 LED_C_OFF();
784 LED_D_OFF();
785}
786
15c4dc5a 787//-----------------------------------------------------------------------------
788// Prepare tag messages
789//-----------------------------------------------------------------------------
f7e3ed82 790static void CodeIso14443aAsTag(const uint8_t *cmd, int len)
15c4dc5a 791{
792 int i;
793 int oddparity;
794
795 ToSendReset();
796
797 // Correction bit, might be removed when not needed
798 ToSendStuffBit(0);
799 ToSendStuffBit(0);
800 ToSendStuffBit(0);
801 ToSendStuffBit(0);
802 ToSendStuffBit(1); // 1
803 ToSendStuffBit(0);
804 ToSendStuffBit(0);
805 ToSendStuffBit(0);
806
807 // Send startbit
72934aa3 808 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 809
810 for(i = 0; i < len; i++) {
811 int j;
f7e3ed82 812 uint8_t b = cmd[i];
15c4dc5a 813
814 // Data bits
815 oddparity = 0x01;
816 for(j = 0; j < 8; j++) {
817 oddparity ^= (b & 1);
818 if(b & 1) {
72934aa3 819 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 820 } else {
72934aa3 821 ToSend[++ToSendMax] = SEC_E;
15c4dc5a 822 }
823 b >>= 1;
824 }
825
826 // Parity bit
827 if(oddparity) {
72934aa3 828 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 829 } else {
72934aa3 830 ToSend[++ToSendMax] = SEC_E;
15c4dc5a 831 }
832 }
833
834 // Send stopbit
72934aa3 835 ToSend[++ToSendMax] = SEC_F;
15c4dc5a 836
837 // Flush the buffer in FPGA!!
838 for(i = 0; i < 5; i++) {
72934aa3 839 ToSend[++ToSendMax] = SEC_F;
15c4dc5a 840 }
841
842 // Convert from last byte pos to length
843 ToSendMax++;
844
845 // Add a few more for slop
846 ToSend[ToSendMax++] = 0x00;
847 ToSend[ToSendMax++] = 0x00;
848 //ToSendMax += 2;
849}
850
851//-----------------------------------------------------------------------------
852// This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
853//-----------------------------------------------------------------------------
854static void CodeStrangeAnswer()
855{
856 int i;
857
858 ToSendReset();
859
860 // Correction bit, might be removed when not needed
861 ToSendStuffBit(0);
862 ToSendStuffBit(0);
863 ToSendStuffBit(0);
864 ToSendStuffBit(0);
865 ToSendStuffBit(1); // 1
866 ToSendStuffBit(0);
867 ToSendStuffBit(0);
868 ToSendStuffBit(0);
869
870 // Send startbit
72934aa3 871 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 872
873 // 0
72934aa3 874 ToSend[++ToSendMax] = SEC_E;
15c4dc5a 875
876 // 0
72934aa3 877 ToSend[++ToSendMax] = SEC_E;
15c4dc5a 878
879 // 1
72934aa3 880 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 881
882 // Send stopbit
72934aa3 883 ToSend[++ToSendMax] = SEC_F;
15c4dc5a 884
885 // Flush the buffer in FPGA!!
886 for(i = 0; i < 5; i++) {
72934aa3 887 ToSend[++ToSendMax] = SEC_F;
15c4dc5a 888 }
889
890 // Convert from last byte pos to length
891 ToSendMax++;
892
893 // Add a few more for slop
894 ToSend[ToSendMax++] = 0x00;
895 ToSend[ToSendMax++] = 0x00;
896 //ToSendMax += 2;
897}
898
899//-----------------------------------------------------------------------------
900// Wait for commands from reader
901// Stop when button is pressed
902// Or return TRUE when command is captured
903//-----------------------------------------------------------------------------
f7e3ed82 904static int GetIso14443aCommandFromReader(uint8_t *received, int *len, int maxLen)
15c4dc5a 905{
906 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
907 // only, since we are receiving, not transmitting).
908 // Signal field is off with the appropriate LED
909 LED_D_OFF();
910 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
911
912 // Now run a `software UART' on the stream of incoming samples.
913 Uart.output = received;
914 Uart.byteCntMax = maxLen;
915 Uart.state = STATE_UNSYNCD;
916
917 for(;;) {
918 WDT_HIT();
919
920 if(BUTTON_PRESS()) return FALSE;
921
922 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
923 AT91C_BASE_SSC->SSC_THR = 0x00;
924 }
925 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 926 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 927 if(MillerDecoding((b & 0xf0) >> 4)) {
928 *len = Uart.byteCnt;
929 return TRUE;
930 }
931 if(MillerDecoding(b & 0x0f)) {
932 *len = Uart.byteCnt;
933 return TRUE;
934 }
935 }
936 }
937}
9ca155ba 938static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded);
15c4dc5a 939
940//-----------------------------------------------------------------------------
941// Main loop of simulated tag: receive commands from reader, decide what
942// response to send, and send it.
943//-----------------------------------------------------------------------------
944void SimulateIso14443aTag(int tagType, int TagUid)
945{
946 // This function contains the tag emulation
947
948 // Prepare protocol messages
f7e3ed82 949 // static const uint8_t cmd1[] = { 0x26 };
950// static const uint8_t response1[] = { 0x02, 0x00 }; // Says: I am Mifare 4k - original line - greg
15c4dc5a 951//
f7e3ed82 952 static const uint8_t response1[] = { 0x44, 0x03 }; // Says: I am a DESFire Tag, ph33r me
953// static const uint8_t response1[] = { 0x44, 0x00 }; // Says: I am a ULTRALITE Tag, 0wn me
15c4dc5a 954
955 // UID response
f7e3ed82 956 // static const uint8_t cmd2[] = { 0x93, 0x20 };
957 //static const uint8_t response2[] = { 0x9a, 0xe5, 0xe4, 0x43, 0xd8 }; // original value - greg
15c4dc5a 958
15c4dc5a 959// my desfire
f7e3ed82 960 static const uint8_t response2[] = { 0x88, 0x04, 0x21, 0x3f, 0x4d }; // known uid - note cascade (0x88), 2nd byte (0x04) = NXP/Phillips
15c4dc5a 961
962
963// When reader selects us during cascade1 it will send cmd3
f7e3ed82 964//uint8_t response3[] = { 0x04, 0x00, 0x00 }; // SAK Select (cascade1) successful response (ULTRALITE)
965uint8_t response3[] = { 0x24, 0x00, 0x00 }; // SAK Select (cascade1) successful response (DESFire)
15c4dc5a 966ComputeCrc14443(CRC_14443_A, response3, 1, &response3[1], &response3[2]);
967
968// send cascade2 2nd half of UID
f7e3ed82 969static const uint8_t response2a[] = { 0x51, 0x48, 0x1d, 0x80, 0x84 }; // uid - cascade2 - 2nd half (4 bytes) of UID+ BCCheck
15c4dc5a 970// NOTE : THE CRC on the above may be wrong as I have obfuscated the actual UID
971
15c4dc5a 972// When reader selects us during cascade2 it will send cmd3a
f7e3ed82 973//uint8_t response3a[] = { 0x00, 0x00, 0x00 }; // SAK Select (cascade2) successful response (ULTRALITE)
974uint8_t response3a[] = { 0x20, 0x00, 0x00 }; // SAK Select (cascade2) successful response (DESFire)
15c4dc5a 975ComputeCrc14443(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]);
976
f7e3ed82 977 static const uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
15c4dc5a 978
f7e3ed82 979 uint8_t *resp;
15c4dc5a 980 int respLen;
981
982 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
983 // This will need
984 // 144 data bits (18 * 8)
985 // 18 parity bits
986 // 2 Start and stop
987 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
988 // 1 just for the case
989 // ----------- +
990 // 166
991 //
992 // 166 bytes, since every bit that needs to be send costs us a byte
993 //
994
15c4dc5a 995 // Respond with card type
f7e3ed82 996 uint8_t *resp1 = (((uint8_t *)BigBuf) + 800);
15c4dc5a 997 int resp1Len;
998
999 // Anticollision cascade1 - respond with uid
f7e3ed82 1000 uint8_t *resp2 = (((uint8_t *)BigBuf) + 970);
15c4dc5a 1001 int resp2Len;
1002
1003 // Anticollision cascade2 - respond with 2nd half of uid if asked
1004 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
f7e3ed82 1005 uint8_t *resp2a = (((uint8_t *)BigBuf) + 1140);
15c4dc5a 1006 int resp2aLen;
1007
1008 // Acknowledge select - cascade 1
f7e3ed82 1009 uint8_t *resp3 = (((uint8_t *)BigBuf) + 1310);
15c4dc5a 1010 int resp3Len;
1011
1012 // Acknowledge select - cascade 2
f7e3ed82 1013 uint8_t *resp3a = (((uint8_t *)BigBuf) + 1480);
15c4dc5a 1014 int resp3aLen;
1015
1016 // Response to a read request - not implemented atm
f7e3ed82 1017 uint8_t *resp4 = (((uint8_t *)BigBuf) + 1550);
15c4dc5a 1018 int resp4Len;
1019
1020 // Authenticate response - nonce
f7e3ed82 1021 uint8_t *resp5 = (((uint8_t *)BigBuf) + 1720);
15c4dc5a 1022 int resp5Len;
1023
f7e3ed82 1024 uint8_t *receivedCmd = (uint8_t *)BigBuf;
15c4dc5a 1025 int len;
1026
1027 int i;
1028 int u;
f7e3ed82 1029 uint8_t b;
15c4dc5a 1030
1031 // To control where we are in the protocol
1032 int order = 0;
1033 int lastorder;
1034
1035 // Just to allow some checks
1036 int happened = 0;
1037 int happened2 = 0;
1038
1039 int cmdsRecvd = 0;
1040
f7e3ed82 1041 int fdt_indicator;
15c4dc5a 1042
1043 memset(receivedCmd, 0x44, 400);
1044
1045 // Prepare the responses of the anticollision phase
1046 // there will be not enough time to do this at the moment the reader sends it REQA
1047
1048 // Answer to request
1049 CodeIso14443aAsTag(response1, sizeof(response1));
1050 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
1051
1052 // Send our UID (cascade 1)
1053 CodeIso14443aAsTag(response2, sizeof(response2));
1054 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
1055
1056 // Answer to select (cascade1)
1057 CodeIso14443aAsTag(response3, sizeof(response3));
1058 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
1059
1060 // Send the cascade 2 2nd part of the uid
1061 CodeIso14443aAsTag(response2a, sizeof(response2a));
1062 memcpy(resp2a, ToSend, ToSendMax); resp2aLen = ToSendMax;
1063
1064 // Answer to select (cascade 2)
1065 CodeIso14443aAsTag(response3a, sizeof(response3a));
1066 memcpy(resp3a, ToSend, ToSendMax); resp3aLen = ToSendMax;
1067
1068 // Strange answer is an example of rare message size (3 bits)
1069 CodeStrangeAnswer();
1070 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1071
1072 // Authentication answer (random nonce)
1073 CodeIso14443aAsTag(response5, sizeof(response5));
1074 memcpy(resp5, ToSend, ToSendMax); resp5Len = ToSendMax;
1075
1076 // We need to listen to the high-frequency, peak-detected path.
1077 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1078 FpgaSetupSsc();
1079
1080 cmdsRecvd = 0;
1081
1082 LED_A_ON();
1083 for(;;) {
1084
1085 if(!GetIso14443aCommandFromReader(receivedCmd, &len, 100)) {
1086 DbpString("button press");
1087 break;
1088 }
1089 // doob - added loads of debug strings so we can see what the reader is saying to us during the sim as hi14alist is not populated
1090 // Okay, look at the command now.
1091 lastorder = order;
1092 i = 1; // first byte transmitted
1093 if(receivedCmd[0] == 0x26) {
1094 // Received a REQUEST
1095 resp = resp1; respLen = resp1Len; order = 1;
1096 //DbpString("Hello request from reader:");
1097 } else if(receivedCmd[0] == 0x52) {
1098 // Received a WAKEUP
1099 resp = resp1; respLen = resp1Len; order = 6;
1100// //DbpString("Wakeup request from reader:");
1101
1102 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // greg - cascade 1 anti-collision
1103 // Received request for UID (cascade 1)
1104 resp = resp2; respLen = resp2Len; order = 2;
1105// DbpString("UID (cascade 1) request from reader:");
1106// DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1107
1108
1109 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] ==0x95) { // greg - cascade 2 anti-collision
1110 // Received request for UID (cascade 2)
1111 resp = resp2a; respLen = resp2aLen; order = 20;
1112// DbpString("UID (cascade 2) request from reader:");
1113// DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1114
1115
1116 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] ==0x93) { // greg - cascade 1 select
1117 // Received a SELECT
1118 resp = resp3; respLen = resp3Len; order = 3;
1119// DbpString("Select (cascade 1) request from reader:");
1120// DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1121
1122
1123 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] ==0x95) { // greg - cascade 2 select
1124 // Received a SELECT
1125 resp = resp3a; respLen = resp3aLen; order = 30;
1126// DbpString("Select (cascade 2) request from reader:");
1127// DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1128
1129
1130 } else if(receivedCmd[0] == 0x30) {
1131 // Received a READ
1132 resp = resp4; respLen = resp4Len; order = 4; // Do nothing
1133 Dbprintf("Read request from reader: %x %x %x",
1134 receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1135
1136
1137 } else if(receivedCmd[0] == 0x50) {
1138 // Received a HALT
1139 resp = resp1; respLen = 0; order = 5; // Do nothing
1140 DbpString("Reader requested we HALT!:");
1141
1142 } else if(receivedCmd[0] == 0x60) {
1143 // Received an authentication request
1144 resp = resp5; respLen = resp5Len; order = 7;
1145 Dbprintf("Authenticate request from reader: %x %x %x",
1146 receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1147
1148 } else if(receivedCmd[0] == 0xE0) {
1149 // Received a RATS request
1150 resp = resp1; respLen = 0;order = 70;
1151 Dbprintf("RATS request from reader: %x %x %x",
1152 receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1153 } else {
1154 // Never seen this command before
20f9a2a1
M
1155 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1156 len,
15c4dc5a 1157 receivedCmd[0], receivedCmd[1], receivedCmd[2],
20f9a2a1
M
1158 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1159 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
15c4dc5a 1160 // Do not respond
1161 resp = resp1; respLen = 0; order = 0;
1162 }
1163
1164 // Count number of wakeups received after a halt
1165 if(order == 6 && lastorder == 5) { happened++; }
1166
1167 // Count number of other messages after a halt
1168 if(order != 6 && lastorder == 5) { happened2++; }
1169
1170 // Look at last parity bit to determine timing of answer
1171 if((Uart.parityBits & 0x01) || receivedCmd[0] == 0x52) {
1172 // 1236, so correction bit needed
1173 i = 0;
1174 }
1175
1176 memset(receivedCmd, 0x44, 32);
1177
1178 if(cmdsRecvd > 999) {
1179 DbpString("1000 commands later...");
1180 break;
1181 }
1182 else {
1183 cmdsRecvd++;
1184 }
1185
1186 if(respLen <= 0) continue;
9ca155ba
M
1187 //----------------------------
1188 u = 0;
1189 b = 0x00;
1190 fdt_indicator = FALSE;
15c4dc5a 1191
9ca155ba
M
1192 EmSendCmd14443aRaw(resp, respLen, receivedCmd[0] == 0x52);
1193/* // Modulate Manchester
15c4dc5a 1194 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1195 AT91C_BASE_SSC->SSC_THR = 0x00;
1196 FpgaSetupSsc();
1197
1198 // ### Transmit the response ###
1199 u = 0;
1200 b = 0x00;
1201 fdt_indicator = FALSE;
1202 for(;;) {
1203 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 1204 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 1205 (void)b;
1206 }
1207 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1208 if(i > respLen) {
1209 b = 0x00;
1210 u++;
1211 } else {
1212 b = resp[i];
1213 i++;
1214 }
1215 AT91C_BASE_SSC->SSC_THR = b;
1216
1217 if(u > 4) {
1218 break;
1219 }
1220 }
1221 if(BUTTON_PRESS()) {
1222 break;
1223 }
1224 }
9ca155ba 1225*/
15c4dc5a 1226 }
1227
1228 Dbprintf("%x %x %x", happened, happened2, cmdsRecvd);
1229 LED_A_OFF();
1230}
1231
1232//-----------------------------------------------------------------------------
1233// Transmit the command (to the tag) that was placed in ToSend[].
1234//-----------------------------------------------------------------------------
f7e3ed82 1235static void TransmitFor14443a(const uint8_t *cmd, int len, int *samples, int *wait)
15c4dc5a 1236{
1237 int c;
e30c654b 1238
15c4dc5a 1239 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
e30c654b 1240
15c4dc5a 1241 if (wait)
1242 if(*wait < 10)
1243 *wait = 10;
e30c654b 1244
15c4dc5a 1245 for(c = 0; c < *wait;) {
1246 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1247 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1248 c++;
1249 }
1250 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 1251 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 1252 (void)r;
1253 }
1254 WDT_HIT();
1255 }
e30c654b 1256
15c4dc5a 1257 c = 0;
1258 for(;;) {
1259 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1260 AT91C_BASE_SSC->SSC_THR = cmd[c];
1261 c++;
1262 if(c >= len) {
1263 break;
1264 }
1265 }
1266 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 1267 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 1268 (void)r;
1269 }
1270 WDT_HIT();
1271 }
1272 if (samples) *samples = (c + *wait) << 3;
1273}
1274
15c4dc5a 1275//-----------------------------------------------------------------------------
1276// Code a 7-bit command without parity bit
1277// This is especially for 0x26 and 0x52 (REQA and WUPA)
1278//-----------------------------------------------------------------------------
f7e3ed82 1279void ShortFrameFromReader(const uint8_t bt)
15c4dc5a 1280{
1281 int j;
1282 int last;
f7e3ed82 1283 uint8_t b;
15c4dc5a 1284
1285 ToSendReset();
1286
1287 // Start of Communication (Seq. Z)
72934aa3 1288 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1289 last = 0;
1290
1291 b = bt;
1292 for(j = 0; j < 7; j++) {
1293 if(b & 1) {
1294 // Sequence X
72934aa3 1295 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1296 last = 1;
1297 } else {
1298 if(last == 0) {
1299 // Sequence Z
72934aa3 1300 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1301 }
1302 else {
1303 // Sequence Y
72934aa3 1304 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1305 last = 0;
1306 }
1307 }
1308 b >>= 1;
1309 }
1310
1311 // End of Communication
1312 if(last == 0) {
1313 // Sequence Z
72934aa3 1314 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1315 }
1316 else {
1317 // Sequence Y
72934aa3 1318 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1319 last = 0;
1320 }
1321 // Sequence Y
72934aa3 1322 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1323
1324 // Just to be sure!
72934aa3 1325 ToSend[++ToSendMax] = SEC_Y;
1326 ToSend[++ToSendMax] = SEC_Y;
1327 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1328
1329 // Convert from last character reference to length
1330 ToSendMax++;
1331}
1332
1333//-----------------------------------------------------------------------------
1334// Prepare reader command to send to FPGA
e30c654b 1335//
15c4dc5a 1336//-----------------------------------------------------------------------------
f7e3ed82 1337void CodeIso14443aAsReaderPar(const uint8_t * cmd, int len, uint32_t dwParity)
15c4dc5a 1338{
1339 int i, j;
1340 int last;
f7e3ed82 1341 uint8_t b;
e30c654b 1342
15c4dc5a 1343 ToSendReset();
e30c654b 1344
15c4dc5a 1345 // Start of Communication (Seq. Z)
72934aa3 1346 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1347 last = 0;
e30c654b 1348
15c4dc5a 1349 // Generate send structure for the data bits
1350 for (i = 0; i < len; i++) {
1351 // Get the current byte to send
1352 b = cmd[i];
e30c654b 1353
15c4dc5a 1354 for (j = 0; j < 8; j++) {
1355 if (b & 1) {
1356 // Sequence X
72934aa3 1357 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1358 last = 1;
1359 } else {
1360 if (last == 0) {
1361 // Sequence Z
72934aa3 1362 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1363 } else {
1364 // Sequence Y
72934aa3 1365 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1366 last = 0;
1367 }
1368 }
1369 b >>= 1;
1370 }
e30c654b 1371
15c4dc5a 1372 // Get the parity bit
1373 if ((dwParity >> i) & 0x01) {
1374 // Sequence X
72934aa3 1375 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1376 last = 1;
1377 } else {
1378 if (last == 0) {
1379 // Sequence Z
72934aa3 1380 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1381 } else {
1382 // Sequence Y
72934aa3 1383 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1384 last = 0;
1385 }
1386 }
1387 }
e30c654b 1388
15c4dc5a 1389 // End of Communication
1390 if (last == 0) {
1391 // Sequence Z
72934aa3 1392 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1393 } else {
1394 // Sequence Y
72934aa3 1395 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1396 last = 0;
1397 }
1398 // Sequence Y
72934aa3 1399 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1400
15c4dc5a 1401 // Just to be sure!
72934aa3 1402 ToSend[++ToSendMax] = SEC_Y;
1403 ToSend[++ToSendMax] = SEC_Y;
1404 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1405
15c4dc5a 1406 // Convert from last character reference to length
1407 ToSendMax++;
1408}
1409
9ca155ba
M
1410//-----------------------------------------------------------------------------
1411// Wait for commands from reader
1412// Stop when button is pressed (return 1) or field was gone (return 2)
1413// Or return 0 when command is captured
1414//-----------------------------------------------------------------------------
1415static int EmGetCmd(uint8_t *received, int *len, int maxLen)
1416{
1417 *len = 0;
1418
1419 uint32_t timer = 0, vtime = 0;
1420 int analogCnt = 0;
1421 int analogAVG = 0;
1422
1423 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1424 // only, since we are receiving, not transmitting).
1425 // Signal field is off with the appropriate LED
1426 LED_D_OFF();
1427 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1428
1429 // Set ADC to read field strength
1430 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
1431 AT91C_BASE_ADC->ADC_MR =
1432 ADC_MODE_PRESCALE(32) |
1433 ADC_MODE_STARTUP_TIME(16) |
1434 ADC_MODE_SAMPLE_HOLD_TIME(8);
1435 AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF);
1436 // start ADC
1437 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1438
1439 // Now run a 'software UART' on the stream of incoming samples.
1440 Uart.output = received;
1441 Uart.byteCntMax = maxLen;
1442 Uart.state = STATE_UNSYNCD;
1443
1444 for(;;) {
1445 WDT_HIT();
1446
1447 if (BUTTON_PRESS()) return 1;
1448
1449 // test if the field exists
1450 if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF)) {
1451 analogCnt++;
1452 analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF];
1453 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1454 if (analogCnt >= 32) {
1455 if ((33000 * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
1456 vtime = GetTickCount();
1457 if (!timer) timer = vtime;
1458 // 50ms no field --> card to idle state
1459 if (vtime - timer > 50) return 2;
1460 } else
1461 if (timer) timer = 0;
1462 analogCnt = 0;
1463 analogAVG = 0;
1464 }
1465 }
1466 // transmit none
1467 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1468 AT91C_BASE_SSC->SSC_THR = 0x00;
1469 }
1470 // receive and test the miller decoding
1471 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1472 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1473 if(MillerDecoding((b & 0xf0) >> 4)) {
1474 *len = Uart.byteCnt;
0a39986e 1475 if (tracing) LogTrace(received, *len, 0, GetParity(received, *len), TRUE);
9ca155ba
M
1476 return 0;
1477 }
1478 if(MillerDecoding(b & 0x0f)) {
1479 *len = Uart.byteCnt;
0a39986e 1480 if (tracing) LogTrace(received, *len, 0, GetParity(received, *len), TRUE);
9ca155ba
M
1481 return 0;
1482 }
1483 }
1484 }
1485}
1486
1487static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded)
1488{
1489 int i, u = 0;
1490 uint8_t b = 0;
1491
1492 // Modulate Manchester
1493 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1494 AT91C_BASE_SSC->SSC_THR = 0x00;
1495 FpgaSetupSsc();
1496
1497 // include correction bit
1498 i = 1;
1499 if((Uart.parityBits & 0x01) || correctionNeeded) {
1500 // 1236, so correction bit needed
1501 i = 0;
1502 }
1503
1504 // send cycle
1505 for(;;) {
1506 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1507 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1508 (void)b;
1509 }
1510 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1511 if(i > respLen) {
1512 b = 0x00;
1513 u++;
1514 } else {
1515 b = resp[i];
1516 i++;
1517 }
1518 AT91C_BASE_SSC->SSC_THR = b;
1519
1520 if(u > 4) break;
1521 }
1522 if(BUTTON_PRESS()) {
1523 break;
1524 }
1525 }
1526
1527 return 0;
1528}
1529
1530static int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded){
1531 CodeIso14443aAsTag(resp, respLen);
0a39986e
M
1532 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
1533 if (tracing) LogTrace(resp, respLen, 0, GetParity(resp, respLen), FALSE);
1534 return res;
9ca155ba
M
1535}
1536
1537static int EmSendCmd(uint8_t *resp, int respLen){
1538 return EmSendCmdEx(resp, respLen, 0);
1539}
1540
15c4dc5a 1541//-----------------------------------------------------------------------------
1542// Wait a certain time for tag response
1543// If a response is captured return TRUE
1544// If it takes to long return FALSE
1545//-----------------------------------------------------------------------------
f7e3ed82 1546static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
15c4dc5a 1547{
1548 // buffer needs to be 512 bytes
1549 int c;
1550
1551 // Set FPGA mode to "reader listen mode", no modulation (listen
534983d7 1552 // only, since we are receiving, not transmitting).
1553 // Signal field is on with the appropriate LED
1554 LED_D_ON();
1555 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
15c4dc5a 1556
534983d7 1557 // Now get the answer from the card
1558 Demod.output = receivedResponse;
1559 Demod.len = 0;
1560 Demod.state = DEMOD_UNSYNCD;
15c4dc5a 1561
f7e3ed82 1562 uint8_t b;
15c4dc5a 1563 if (elapsed) *elapsed = 0;
1564
1565 c = 0;
1566 for(;;) {
534983d7 1567 WDT_HIT();
15c4dc5a 1568
534983d7 1569 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1570 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
15c4dc5a 1571 if (elapsed) (*elapsed)++;
534983d7 1572 }
1573 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1574 if(c < iso14a_timeout) { c++; } else { return FALSE; }
1575 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
72934aa3 1576 if(ManchesterDecoding((b>>4) & 0xf)) {
15c4dc5a 1577 *samples = ((c - 1) << 3) + 4;
1578 return TRUE;
1579 }
1580 if(ManchesterDecoding(b & 0x0f)) {
1581 *samples = c << 3;
1582 return TRUE;
1583 }
534983d7 1584 }
1585 }
15c4dc5a 1586}
1587
f7e3ed82 1588void ReaderTransmitShort(const uint8_t* bt)
15c4dc5a 1589{
1590 int wait = 0;
1591 int samples = 0;
1592
1593 ShortFrameFromReader(*bt);
e30c654b 1594
15c4dc5a 1595 // Select the card
e30c654b 1596 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
1597
15c4dc5a 1598 // Store reader command in buffer
1599 if (tracing) LogTrace(bt,1,0,GetParity(bt,1),TRUE);
1600}
1601
f7e3ed82 1602void ReaderTransmitPar(uint8_t* frame, int len, uint32_t par)
15c4dc5a 1603{
1604 int wait = 0;
1605 int samples = 0;
e30c654b 1606
15c4dc5a 1607 // This is tied to other size changes
f7e3ed82 1608 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
15c4dc5a 1609 CodeIso14443aAsReaderPar(frame,len,par);
e30c654b 1610
15c4dc5a 1611 // Select the card
e30c654b 1612 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
534983d7 1613 if(trigger)
1614 LED_A_ON();
e30c654b 1615
15c4dc5a 1616 // Store reader command in buffer
1617 if (tracing) LogTrace(frame,len,0,par,TRUE);
1618}
1619
1620
f7e3ed82 1621void ReaderTransmit(uint8_t* frame, int len)
15c4dc5a 1622{
1623 // Generate parity and redirect
1624 ReaderTransmitPar(frame,len,GetParity(frame,len));
1625}
1626
f7e3ed82 1627int ReaderReceive(uint8_t* receivedAnswer)
15c4dc5a 1628{
1629 int samples = 0;
20f9a2a1 1630 if (!GetIso14443aAnswerFromTag(receivedAnswer,160,&samples,0)) return FALSE;
15c4dc5a 1631 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
7e758047 1632 if(samples == 0) return FALSE;
1633 return Demod.len;
15c4dc5a 1634}
1635
f89c7050
M
1636int ReaderReceivePar(uint8_t* receivedAnswer, uint32_t * parptr)
1637{
1638 int samples = 0;
1639 if (!GetIso14443aAnswerFromTag(receivedAnswer,160,&samples,0)) return FALSE;
1640 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1641 *parptr = Demod.parityBits;
1642 if(samples == 0) return FALSE;
1643 return Demod.len;
1644}
1645
7e758047 1646/* performs iso14443a anticolision procedure
534983d7 1647 * fills the uid pointer unless NULL
1648 * fills resp_data unless NULL */
20f9a2a1
M
1649int iso14443a_select_card(uint8_t * uid_ptr, iso14a_card_select_t * resp_data, uint32_t * cuid_ptr) {
1650 uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
f7e3ed82 1651 uint8_t sel_all[] = { 0x93,0x20 };
1652 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
7e758047 1653 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
15c4dc5a 1654
7e758047 1655 uint8_t* resp = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
15c4dc5a 1656
534983d7 1657 uint8_t sak = 0x04; // cascade uid
1658 int cascade_level = 0;
1659
7e758047 1660 int len;
20f9a2a1
M
1661
1662 // clear uid
1663 memset(uid_ptr, 0, 8);
15c4dc5a 1664
7e758047 1665 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1666 ReaderTransmitShort(wupa);
1667 // Receive the ATQA
1668 if(!ReaderReceive(resp)) return 0;
15c4dc5a 1669
534983d7 1670 if(resp_data)
1671 memcpy(resp_data->atqa, resp, 2);
1672
534983d7 1673 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
7e758047 1674 // which case we need to make a cascade 2 request and select - this is a long UID
534983d7 1675 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1676 for(; sak & 0x04; cascade_level++)
7e758047 1677 {
534983d7 1678 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1679 sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
1680
1681 // SELECT_ALL
1682 ReaderTransmit(sel_all,sizeof(sel_all));
1683 if (!ReaderReceive(resp)) return 0;
1684 if(uid_ptr) memcpy(uid_ptr + cascade_level*4, resp, 4);
20f9a2a1
M
1685
1686 // calculate crypto UID
1687 if(cuid_ptr) *cuid_ptr = bytes_to_num(resp, 4);
e30c654b 1688
7e758047 1689 // Construct SELECT UID command
534983d7 1690 memcpy(sel_uid+2,resp,5);
1691 AppendCrc14443a(sel_uid,7);
1692 ReaderTransmit(sel_uid,sizeof(sel_uid));
1693
7e758047 1694 // Receive the SAK
1695 if (!ReaderReceive(resp)) return 0;
534983d7 1696 sak = resp[0];
7e758047 1697 }
534983d7 1698 if(resp_data) {
1699 resp_data->sak = sak;
1700 resp_data->ats_len = 0;
1701 }
20f9a2a1
M
1702 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1703 if (uid_ptr[0] == 0x88) {
1704 memcpy(uid_ptr, uid_ptr + 1, 7);
1705 uid_ptr[7] = 0;
1706 }
534983d7 1707
1708 if( (sak & 0x20) == 0)
7e758047 1709 return 2; // non iso14443a compliant tag
534983d7 1710
7e758047 1711 // Request for answer to select
20f9a2a1
M
1712 if(resp_data) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1713 AppendCrc14443a(rats, 2);
1714 ReaderTransmit(rats, sizeof(rats));
1715
1716 if (!(len = ReaderReceive(resp))) return 0;
1717
534983d7 1718 memcpy(resp_data->ats, resp, sizeof(resp_data->ats));
1719 resp_data->ats_len = len;
1720 }
20f9a2a1 1721
7e758047 1722 return 1;
1723}
15c4dc5a 1724
7e758047 1725void iso14443a_setup() {
1726 // Setup SSC
1727 FpgaSetupSsc();
1728 // Start from off (no field generated)
1729 // Signal field is off with the appropriate LED
1730 LED_D_OFF();
1731 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1732 SpinDelay(200);
15c4dc5a 1733
7e758047 1734 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
e30c654b 1735
7e758047 1736 // Now give it time to spin up.
1737 // Signal field is on with the appropriate LED
1738 LED_D_ON();
1739 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1740 SpinDelay(200);
534983d7 1741
1742 iso14a_timeout = 2048; //default
7e758047 1743}
15c4dc5a 1744
534983d7 1745int iso14_apdu(uint8_t * cmd, size_t cmd_len, void * data) {
1746 uint8_t real_cmd[cmd_len+4];
1747 real_cmd[0] = 0x0a; //I-Block
1748 real_cmd[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1749 memcpy(real_cmd+2, cmd, cmd_len);
1750 AppendCrc14443a(real_cmd,cmd_len+2);
1751
1752 ReaderTransmit(real_cmd, cmd_len+4);
1753 size_t len = ReaderReceive(data);
1754 if(!len)
1755 return -1; //DATA LINK ERROR
1756
1757 return len;
1758}
1759
1760
7e758047 1761//-----------------------------------------------------------------------------
1762// Read an ISO 14443a tag. Send out commands and store answers.
1763//
1764//-----------------------------------------------------------------------------
534983d7 1765void ReaderIso14443a(UsbCommand * c, UsbCommand * ack)
7e758047 1766{
534983d7 1767 iso14a_command_t param = c->arg[0];
1768 uint8_t * cmd = c->d.asBytes;
1769 size_t len = c->arg[1];
e30c654b 1770
534983d7 1771 if(param & ISO14A_REQUEST_TRIGGER) iso14a_set_trigger(1);
15c4dc5a 1772
534983d7 1773 if(param & ISO14A_CONNECT) {
1774 iso14443a_setup();
20f9a2a1 1775 ack->arg[0] = iso14443a_select_card(ack->d.asBytes, (iso14a_card_select_t *) (ack->d.asBytes+12), NULL);
534983d7 1776 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1777 }
e30c654b 1778
534983d7 1779 if(param & ISO14A_SET_TIMEOUT) {
1780 iso14a_timeout = c->arg[2];
1781 }
e30c654b 1782
534983d7 1783 if(param & ISO14A_SET_TIMEOUT) {
1784 iso14a_timeout = c->arg[2];
1785 }
e30c654b 1786
534983d7 1787 if(param & ISO14A_APDU) {
1788 ack->arg[0] = iso14_apdu(cmd, len, ack->d.asBytes);
1789 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1790 }
e30c654b 1791
534983d7 1792 if(param & ISO14A_RAW) {
1793 if(param & ISO14A_APPEND_CRC) {
1794 AppendCrc14443a(cmd,len);
1795 len += 2;
15c4dc5a 1796 }
534983d7 1797 ReaderTransmit(cmd,len);
1798 ack->arg[0] = ReaderReceive(ack->d.asBytes);
1799 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1800 }
15c4dc5a 1801
534983d7 1802 if(param & ISO14A_REQUEST_TRIGGER) iso14a_set_trigger(0);
15c4dc5a 1803
534983d7 1804 if(param & ISO14A_NO_DISCONNECT)
1805 return;
15c4dc5a 1806
15c4dc5a 1807 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1808 LEDsoff();
15c4dc5a 1809}
15c4dc5a 1810//-----------------------------------------------------------------------------
1811// Read an ISO 14443a tag. Send out commands and store answers.
1812//
1813//-----------------------------------------------------------------------------
f7e3ed82 1814void ReaderMifare(uint32_t parameter)
15c4dc5a 1815{
15c4dc5a 1816 // Mifare AUTH
f7e3ed82 1817 uint8_t mf_auth[] = { 0x60,0x00,0xf5,0x7b };
f89c7050 1818 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
e30c654b 1819
f89c7050
M
1820 uint8_t* receivedAnswer = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1821 traceLen = 0;
1822 tracing = false;
e30c654b 1823
7e758047 1824 iso14443a_setup();
e30c654b 1825
15c4dc5a 1826 LED_A_ON();
1827 LED_B_OFF();
1828 LED_C_OFF();
e30c654b 1829
f89c7050
M
1830 byte_t nt_diff = 0;
1831 LED_A_OFF();
1832 byte_t par = 0;
1833 byte_t par_mask = 0xff;
1834 byte_t par_low = 0;
1835 int led_on = TRUE;
50193c1e 1836 uint8_t uid[8];
f89c7050 1837 uint32_t cuid;
e30c654b 1838
f89c7050
M
1839 tracing = FALSE;
1840 byte_t nt[4] = {0,0,0,0};
f397b5cc 1841 byte_t nt_attacked[4], nt_noattack[4];
f89c7050
M
1842 byte_t par_list[8] = {0,0,0,0,0,0,0,0};
1843 byte_t ks_list[8] = {0,0,0,0,0,0,0,0};
f397b5cc 1844 num_to_bytes(parameter, 4, nt_noattack);
50193c1e 1845 int isOK = 0, isNULL = 0;
f397b5cc 1846
f89c7050
M
1847 while(TRUE)
1848 {
50193c1e 1849 LED_C_ON();
f89c7050
M
1850 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1851 SpinDelay(200);
1852 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
50193c1e 1853 LED_C_OFF();
e30c654b 1854
f89c7050
M
1855 // Test if the action was cancelled
1856 if(BUTTON_PRESS()) {
1857 break;
1858 }
e30c654b 1859
f89c7050 1860 if(!iso14443a_select_card(uid, NULL, &cuid)) continue;
e30c654b 1861
f89c7050
M
1862 // Transmit MIFARE_CLASSIC_AUTH
1863 ReaderTransmit(mf_auth, sizeof(mf_auth));
15c4dc5a 1864
f89c7050
M
1865 // Receive the (16 bit) "random" nonce
1866 if (!ReaderReceive(receivedAnswer)) continue;
1867 memcpy(nt, receivedAnswer, 4);
e30c654b 1868
f89c7050
M
1869 // Transmit reader nonce and reader answer
1870 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar),par);
15c4dc5a 1871
f89c7050
M
1872 // Receive 4 bit answer
1873 if (ReaderReceive(receivedAnswer))
1874 {
f397b5cc
M
1875 if ( (parameter != 0) && (memcmp(nt, nt_noattack, 4) == 0) ) continue;
1876
50193c1e
M
1877 isNULL = (nt_attacked[0] = 0) && (nt_attacked[1] = 0) && (nt_attacked[2] = 0) && (nt_attacked[3] = 0);
1878 if ( (isNULL != 0 ) && (memcmp(nt, nt_attacked, 4) != 0) ) continue;
1879
f89c7050
M
1880 if (nt_diff == 0)
1881 {
1882 LED_A_ON();
1883 memcpy(nt_attacked, nt, 4);
1884 par_mask = 0xf8;
1885 par_low = par & 0x07;
1886 }
15c4dc5a 1887
f89c7050
M
1888 led_on = !led_on;
1889 if(led_on) LED_B_ON(); else LED_B_OFF();
1890 par_list[nt_diff] = par;
1891 ks_list[nt_diff] = receivedAnswer[0] ^ 0x05;
e30c654b 1892
f89c7050
M
1893 // Test if the information is complete
1894 if (nt_diff == 0x07) {
1895 isOK = 1;
1896 break;
1897 }
1898
1899 nt_diff = (nt_diff + 1) & 0x07;
1900 mf_nr_ar[3] = nt_diff << 5;
1901 par = par_low;
1902 } else {
1903 if (nt_diff == 0)
1904 {
1905 par++;
1906 } else {
1907 par = (((par >> 3) + 1) << 3) | par_low;
1908 }
1909 }
1910 }
e30c654b 1911
f89c7050
M
1912 LogTrace(nt, 4, 0, GetParity(nt, 4), TRUE);
1913 LogTrace(par_list, 8, 0, GetParity(par_list, 8), TRUE);
1914 LogTrace(ks_list, 8, 0, GetParity(ks_list, 8), TRUE);
e30c654b 1915
f89c7050
M
1916 UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
1917 memcpy(ack.d.asBytes + 0, uid, 4);
1918 memcpy(ack.d.asBytes + 4, nt, 4);
1919 memcpy(ack.d.asBytes + 8, par_list, 8);
1920 memcpy(ack.d.asBytes + 16, ks_list, 8);
1921
1922 LED_B_ON();
1923 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
1924 LED_B_OFF();
1925
1926 // Thats it...
15c4dc5a 1927 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1928 LEDsoff();
f89c7050
M
1929 tracing = TRUE;
1930
f397b5cc 1931 if (MF_DBGLEVEL >= 1) DbpString("COMMAND mifare FINISHED");
20f9a2a1
M
1932}
1933
1934//-----------------------------------------------------------------------------
1935// Select, Authenticaate, Read an MIFARE tag.
1936// read block
1937//-----------------------------------------------------------------------------
1938void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
1939{
1940 // params
1941 uint8_t blockNo = arg0;
1942 uint8_t keyType = arg1;
1943 uint64_t ui64Key = 0;
1944 ui64Key = bytes_to_num(datain, 6);
1945
1946 // variables
4abe4f58
M
1947 byte_t isOK = 0;
1948 byte_t dataoutbuf[16];
50193c1e 1949 uint8_t uid[8];
20f9a2a1 1950 uint32_t cuid;
4abe4f58 1951 struct Crypto1State mpcs = {0, 0};
20f9a2a1
M
1952 struct Crypto1State *pcs;
1953 pcs = &mpcs;
1954
1955 // clear trace
4abe4f58
M
1956 traceLen = 0;
1957// tracing = false;
20f9a2a1
M
1958
1959 iso14443a_setup();
1960
1961 LED_A_ON();
1962 LED_B_OFF();
1963 LED_C_OFF();
1964
1965 while (true) {
1966 if(!iso14443a_select_card(uid, NULL, &cuid)) {
f397b5cc 1967 if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
20f9a2a1
M
1968 break;
1969 };
1970
4abe4f58 1971 if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
f397b5cc 1972 if (MF_DBGLEVEL >= 1) Dbprintf("Auth error");
20f9a2a1
M
1973 break;
1974 };
1975
1976 if(mifare_classic_readblock(pcs, cuid, blockNo, dataoutbuf)) {
f397b5cc 1977 if (MF_DBGLEVEL >= 1) Dbprintf("Read block error");
20f9a2a1
M
1978 break;
1979 };
1980
1981 if(mifare_classic_halt(pcs, cuid)) {
f397b5cc 1982 if (MF_DBGLEVEL >= 1) Dbprintf("Halt error");
20f9a2a1
M
1983 break;
1984 };
1985
1986 isOK = 1;
1987 break;
1988 }
1989
1990 // ----------------------------- crypto1 destroy
1991 crypto1_destroy(pcs);
1992
f397b5cc 1993 if (MF_DBGLEVEL >= 2) DbpString("READ BLOCK FINISHED");
20f9a2a1
M
1994
1995 // add trace trailer
1996 uid[0] = 0xff;
1997 uid[1] = 0xff;
1998 uid[2] = 0xff;
1999 uid[3] = 0xff;
4abe4f58 2000 LogTrace(uid, 4, 0, 0, TRUE);
20f9a2a1
M
2001
2002 UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
2003 memcpy(ack.d.asBytes, dataoutbuf, 16);
2004
2005 LED_B_ON();
2006 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
4abe4f58 2007 LED_B_OFF();
20f9a2a1
M
2008
2009
2010 // Thats it...
2011 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2012 LEDsoff();
2013// tracing = TRUE;
2014
2015}
2016
2017//-----------------------------------------------------------------------------
2018// Select, Authenticaate, Read an MIFARE tag.
2019// read sector (data = 4 x 16 bytes = 64 bytes)
2020//-----------------------------------------------------------------------------
2021void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
2022{
2023 // params
2024 uint8_t sectorNo = arg0;
2025 uint8_t keyType = arg1;
2026 uint64_t ui64Key = 0;
2027 ui64Key = bytes_to_num(datain, 6);
2028
2029 // variables
4abe4f58
M
2030 byte_t isOK = 0;
2031 byte_t dataoutbuf[16 * 4];
20f9a2a1
M
2032 uint8_t uid[8];
2033 uint32_t cuid;
4abe4f58 2034 struct Crypto1State mpcs = {0, 0};
20f9a2a1
M
2035 struct Crypto1State *pcs;
2036 pcs = &mpcs;
2037
2038 // clear trace
4abe4f58
M
2039 traceLen = 0;
2040// tracing = false;
20f9a2a1
M
2041
2042 iso14443a_setup();
2043
2044 LED_A_ON();
2045 LED_B_OFF();
2046 LED_C_OFF();
2047
2048 while (true) {
2049 if(!iso14443a_select_card(uid, NULL, &cuid)) {
f397b5cc 2050 if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
20f9a2a1
M
2051 break;
2052 };
2053
4abe4f58 2054 if(mifare_classic_auth(pcs, cuid, sectorNo * 4, keyType, ui64Key, AUTH_FIRST)) {
f397b5cc 2055 if (MF_DBGLEVEL >= 1) Dbprintf("Auth error");
20f9a2a1
M
2056 break;
2057 };
2058
2059 if(mifare_classic_readblock(pcs, cuid, sectorNo * 4 + 0, dataoutbuf + 16 * 0)) {
f397b5cc 2060 if (MF_DBGLEVEL >= 1) Dbprintf("Read block 0 error");
20f9a2a1
M
2061 break;
2062 };
2063 if(mifare_classic_readblock(pcs, cuid, sectorNo * 4 + 1, dataoutbuf + 16 * 1)) {
f397b5cc 2064 if (MF_DBGLEVEL >= 1) Dbprintf("Read block 1 error");
20f9a2a1
M
2065 break;
2066 };
2067 if(mifare_classic_readblock(pcs, cuid, sectorNo * 4 + 2, dataoutbuf + 16 * 2)) {
f397b5cc 2068 if (MF_DBGLEVEL >= 1) Dbprintf("Read block 2 error");
20f9a2a1
M
2069 break;
2070 };
2071 if(mifare_classic_readblock(pcs, cuid, sectorNo * 4 + 3, dataoutbuf + 16 * 3)) {
f397b5cc 2072 if (MF_DBGLEVEL >= 1) Dbprintf("Read block 3 error");
20f9a2a1
M
2073 break;
2074 };
2075
2076 if(mifare_classic_halt(pcs, cuid)) {
f397b5cc 2077 if (MF_DBGLEVEL >= 1) Dbprintf("Halt error");
20f9a2a1
M
2078 break;
2079 };
2080
2081 isOK = 1;
2082 break;
2083 }
2084
2085 // ----------------------------- crypto1 destroy
2086 crypto1_destroy(pcs);
2087
f397b5cc 2088 if (MF_DBGLEVEL >= 2) DbpString("READ SECTOR FINISHED");
20f9a2a1
M
2089
2090 // add trace trailer
2091 uid[0] = 0xff;
2092 uid[1] = 0xff;
2093 uid[2] = 0xff;
2094 uid[3] = 0xff;
4abe4f58 2095 LogTrace(uid, 4, 0, 0, TRUE);
20f9a2a1
M
2096
2097 UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
2098 memcpy(ack.d.asBytes, dataoutbuf, 16 * 2);
2099
2100 LED_B_ON();
2101 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
2102
2103 SpinDelay(100);
2104
2105 memcpy(ack.d.asBytes, dataoutbuf + 16 * 2, 16 * 2);
2106 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
2107 LED_B_OFF();
2108
4abe4f58 2109 // Thats it...
20f9a2a1
M
2110 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2111 LEDsoff();
2112// tracing = TRUE;
2113
2114}
2115
2116//-----------------------------------------------------------------------------
2117// Select, Authenticaate, Read an MIFARE tag.
2118// read block
2119//-----------------------------------------------------------------------------
2120void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
2121{
4abe4f58 2122 // params
20f9a2a1
M
2123 uint8_t blockNo = arg0;
2124 uint8_t keyType = arg1;
2125 uint64_t ui64Key = 0;
4abe4f58 2126 byte_t blockdata[16];
20f9a2a1
M
2127
2128 ui64Key = bytes_to_num(datain, 6);
2129 memcpy(blockdata, datain + 10, 16);
2130
2131 // variables
4abe4f58 2132 byte_t isOK = 0;
20f9a2a1
M
2133 uint8_t uid[8];
2134 uint32_t cuid;
4abe4f58 2135 struct Crypto1State mpcs = {0, 0};
20f9a2a1
M
2136 struct Crypto1State *pcs;
2137 pcs = &mpcs;
2138
2139 // clear trace
4abe4f58 2140 traceLen = 0;
20f9a2a1
M
2141// tracing = false;
2142
2143 iso14443a_setup();
2144
2145 LED_A_ON();
2146 LED_B_OFF();
2147 LED_C_OFF();
2148
2149 while (true) {
f397b5cc
M
2150 if(!iso14443a_select_card(uid, NULL, &cuid)) {
2151 if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
20f9a2a1
M
2152 break;
2153 };
2154
4abe4f58 2155 if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
f397b5cc 2156 if (MF_DBGLEVEL >= 1) Dbprintf("Auth error");
20f9a2a1
M
2157 break;
2158 };
2159
2160 if(mifare_classic_writeblock(pcs, cuid, blockNo, blockdata)) {
f397b5cc 2161 if (MF_DBGLEVEL >= 1) Dbprintf("Write block error");
20f9a2a1
M
2162 break;
2163 };
2164
2165 if(mifare_classic_halt(pcs, cuid)) {
f397b5cc 2166 if (MF_DBGLEVEL >= 1) Dbprintf("Halt error");
20f9a2a1
M
2167 break;
2168 };
2169
2170 isOK = 1;
2171 break;
2172 }
2173
2174 // ----------------------------- crypto1 destroy
2175 crypto1_destroy(pcs);
2176
f397b5cc 2177 if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED");
20f9a2a1
M
2178
2179 // add trace trailer
2180 uid[0] = 0xff;
2181 uid[1] = 0xff;
2182 uid[2] = 0xff;
2183 uid[3] = 0xff;
4abe4f58 2184 LogTrace(uid, 4, 0, 0, TRUE);
20f9a2a1
M
2185
2186 UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
2187
2188 LED_B_ON();
2189 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
2190 LED_B_OFF();
2191
2192
4abe4f58 2193 // Thats it...
20f9a2a1
M
2194 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2195 LEDsoff();
2196// tracing = TRUE;
2197
2198}
2199
f89c7050
M
2200// Return 1 if the nonce is invalid else return 0
2201int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, byte_t * parity) {
2202 return ((oddparity((Nt >> 24) & 0xFF) == ((parity[0]) ^ oddparity((NtEnc >> 24) & 0xFF) ^ BIT(Ks1,16))) & \
2203 (oddparity((Nt >> 16) & 0xFF) == ((parity[1]) ^ oddparity((NtEnc >> 16) & 0xFF) ^ BIT(Ks1,8))) & \
2204 (oddparity((Nt >> 8) & 0xFF) == ((parity[2]) ^ oddparity((NtEnc >> 8) & 0xFF) ^ BIT(Ks1,0)))) ? 1 : 0;
2205}
2206
2207
20f9a2a1
M
2208//-----------------------------------------------------------------------------
2209// MIFARE nested authentication.
2210//
2211//-----------------------------------------------------------------------------
f397b5cc 2212void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
20f9a2a1 2213{
4abe4f58 2214 // params
20f9a2a1
M
2215 uint8_t blockNo = arg0;
2216 uint8_t keyType = arg1;
f397b5cc
M
2217 uint8_t targetBlockNo = arg2 & 0xff;
2218 uint8_t targetKeyType = (arg2 >> 8) & 0xff;
20f9a2a1
M
2219 uint64_t ui64Key = 0;
2220
2221 ui64Key = bytes_to_num(datain, 6);
2222
2223 // variables
50193c1e 2224 int rtr, i, j, m, len;
f89c7050 2225 int davg, dmin, dmax;
20f9a2a1 2226 uint8_t uid[8];
f89c7050
M
2227 uint32_t cuid, nt1, nt2, nttmp, nttest, par, ks1;
2228 uint8_t par_array[4];
f397b5cc
M
2229 nestedVector nvector[NES_MAX_INFO + 1][10];
2230 int nvectorcount[NES_MAX_INFO + 1];
f89c7050 2231 int ncount = 0;
50193c1e 2232 UsbCommand ack = {CMD_ACK, {0, 0, 0}};
4abe4f58 2233 struct Crypto1State mpcs = {0, 0};
20f9a2a1
M
2234 struct Crypto1State *pcs;
2235 pcs = &mpcs;
f89c7050 2236 uint8_t* receivedAnswer = mifare_get_bigbufptr();
20f9a2a1 2237
f397b5cc
M
2238 //init
2239 for (i = 0; i < NES_MAX_INFO + 1; i++) nvectorcount[i] = 11; // 11 - empty block;
2240
20f9a2a1 2241 // clear trace
4abe4f58 2242 traceLen = 0;
f89c7050 2243 tracing = false;
f397b5cc 2244
20f9a2a1
M
2245 iso14443a_setup();
2246
2247 LED_A_ON();
f89c7050 2248 LED_B_ON();
20f9a2a1
M
2249 LED_C_OFF();
2250
f89c7050
M
2251 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2252 SpinDelay(200);
2253
2254 davg = dmax = 0;
2255 dmin = 2000;
2256
2257 // test nonce distance
2258 for (rtr = 0; rtr < 10; rtr++) {
2259 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2260 SpinDelay(100);
2261 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
2262
2263 // Test if the action was cancelled
2264 if(BUTTON_PRESS()) {
2265 break;
2266 }
2267
20f9a2a1 2268 if(!iso14443a_select_card(uid, NULL, &cuid)) {
f397b5cc 2269 if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
20f9a2a1
M
2270 break;
2271 };
2272
f89c7050 2273 if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1)) {
f397b5cc 2274 if (MF_DBGLEVEL >= 1) Dbprintf("Auth1 error");
20f9a2a1
M
2275 break;
2276 };
2277
f89c7050 2278 if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2)) {
f397b5cc 2279 if (MF_DBGLEVEL >= 1) Dbprintf("Auth2 error");
20f9a2a1
M
2280 break;
2281 };
2282
f89c7050
M
2283 nttmp = prng_successor(nt1, 500);
2284 for (i = 501; i < 2000; i++) {
2285 nttmp = prng_successor(nttmp, 1);
2286 if (nttmp == nt2) break;
2287 }
2288
2289 if (i != 2000) {
2290 davg += i;
2291 if (dmin > i) dmin = i;
2292 if (dmax < i) dmax = i;
f397b5cc 2293 if (MF_DBGLEVEL >= 4) Dbprintf("r=%d nt1=%08x nt2=%08x distance=%d", rtr, nt1, nt2, i);
f89c7050
M
2294 }
2295 }
2296
2297 if (rtr == 0) return;
2298
2299 davg = davg / rtr;
f397b5cc 2300 if (MF_DBGLEVEL >= 3) Dbprintf("distance: min=%d max=%d avg=%d", dmin, dmax, davg);
f89c7050
M
2301
2302 LED_B_OFF();
2303
f397b5cc 2304// -------------------------------------------------------------------------------------------------
f89c7050
M
2305
2306 LED_C_ON();
2307
2308 // get crypted nonces for target sector
f397b5cc
M
2309 for (rtr = 0; rtr < NS_RETRIES_GETNONCE; rtr++) {
2310 if (MF_DBGLEVEL >= 4) Dbprintf("------------------------------");
f89c7050
M
2311
2312 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2313 SpinDelay(100);
2314 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
2315
2316 // Test if the action was cancelled
2317 if(BUTTON_PRESS()) {
2318 break;
2319 }
2320
2321 if(!iso14443a_select_card(uid, NULL, &cuid)) {
f397b5cc 2322 if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
f89c7050
M
2323 break;
2324 };
2325
2326 if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1)) {
f397b5cc 2327 if (MF_DBGLEVEL >= 1) Dbprintf("Auth1 error");
20f9a2a1
M
2328 break;
2329 };
2330
f89c7050 2331 // nested authentication
50193c1e 2332 len = mifare_sendcmd_shortex(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, &par);
f89c7050 2333 if (len != 4) {
f397b5cc 2334 if (MF_DBGLEVEL >= 1) Dbprintf("Auth2 error len=%d", len);
20f9a2a1
M
2335 break;
2336 };
f89c7050
M
2337
2338 nt2 = bytes_to_num(receivedAnswer, 4);
f397b5cc 2339 if (MF_DBGLEVEL >= 4) Dbprintf("r=%d nt1=%08x nt2enc=%08x nt2par=%08x", rtr, nt1, nt2, par);
f89c7050
M
2340
2341 // Parity validity check
2342 for (i = 0; i < 4; i++) {
2343 par_array[i] = (oddparity(receivedAnswer[i]) != ((par & 0x08) >> 3));
2344 par = par << 1;
2345 }
2346
2347 ncount = 0;
f397b5cc 2348 for (m = dmin - NS_TOLERANCE; m < dmax + NS_TOLERANCE; m++) {
f89c7050
M
2349 nttest = prng_successor(nt1, m);
2350 ks1 = nt2 ^ nttest;
2351
f89c7050
M
2352 if (valid_nonce(nttest, nt2, ks1, par_array) && (ncount < 11)){
2353
f397b5cc
M
2354 nvector[NES_MAX_INFO][ncount].nt = nttest;
2355 nvector[NES_MAX_INFO][ncount].ks1 = ks1;
f89c7050 2356 ncount++;
f397b5cc
M
2357 nvectorcount[NES_MAX_INFO] = ncount;
2358 if (MF_DBGLEVEL >= 4) Dbprintf("valid m=%d ks1=%08x nttest=%08x", m, ks1, nttest);
f89c7050
M
2359 }
2360
2361 }
2362
2363 // select vector with length less than got
f397b5cc
M
2364 if (nvectorcount[NES_MAX_INFO] != 0) {
2365 m = NES_MAX_INFO;
2366
2367 for (i = 0; i < NES_MAX_INFO; i++)
2368 if (nvectorcount[i] > 10) {
2369 m = i;
2370 break;
2371 }
2372
2373 if (m == NES_MAX_INFO)
2374 for (i = 0; i < NES_MAX_INFO; i++)
2375 if (nvectorcount[NES_MAX_INFO] < nvectorcount[i]) {
2376 m = i;
2377 break;
2378 }
2379
2380 if (m != NES_MAX_INFO) {
50193c1e 2381 for (i = 0; i < nvectorcount[m]; i++) {
f397b5cc 2382 nvector[m][i] = nvector[NES_MAX_INFO][i];
50193c1e 2383 }
f397b5cc 2384 nvectorcount[m] = nvectorcount[NES_MAX_INFO];
f89c7050 2385 }
f89c7050 2386 }
20f9a2a1 2387 }
f89c7050
M
2388
2389 LED_C_OFF();
20f9a2a1
M
2390
2391 // ----------------------------- crypto1 destroy
2392 crypto1_destroy(pcs);
2393
20f9a2a1
M
2394 // add trace trailer
2395 uid[0] = 0xff;
2396 uid[1] = 0xff;
2397 uid[2] = 0xff;
2398 uid[3] = 0xff;
4abe4f58 2399 LogTrace(uid, 4, 0, 0, TRUE);
20f9a2a1 2400
f397b5cc
M
2401 for (i = 0; i < NES_MAX_INFO; i++) {
2402 if (nvectorcount[i] > 10) continue;
2403
50193c1e
M
2404 for (j = 0; j < nvectorcount[i]; j += 5) {
2405 ncount = nvectorcount[i] - j;
2406 if (ncount > 5) ncount = 5;
2407
2408 ack.arg[0] = 0; // isEOF = 0
2409 ack.arg[1] = ncount;
2410 ack.arg[2] = targetBlockNo + (targetKeyType * 0x100);
2411 memset(ack.d.asBytes, 0x00, sizeof(ack.d.asBytes));
2412
2413 memcpy(ack.d.asBytes, &cuid, 4);
2414 for (m = 0; m < ncount; m++) {
2415 memcpy(ack.d.asBytes + 8 + m * 8 + 0, &nvector[i][m + j].nt, 4);
2416 memcpy(ack.d.asBytes + 8 + m * 8 + 4, &nvector[i][m + j].ks1, 4);
2417 }
f89c7050 2418
50193c1e
M
2419 LED_B_ON();
2420 SpinDelay(100);
2421 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
2422 LED_B_OFF();
2423 }
f89c7050
M
2424 }
2425
2426 // finalize list
50193c1e
M
2427 ack.arg[0] = 1; // isEOF = 1
2428 ack.arg[1] = 0;
2429 ack.arg[2] = 0;
2430 memset(ack.d.asBytes, 0x00, sizeof(ack.d.asBytes));
20f9a2a1
M
2431
2432 LED_B_ON();
50193c1e 2433 SpinDelay(300);
20f9a2a1
M
2434 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
2435 LED_B_OFF();
2436
f397b5cc 2437 if (MF_DBGLEVEL >= 4) DbpString("NESTED FINISHED");
f89c7050 2438
4abe4f58 2439 // Thats it...
20f9a2a1
M
2440 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2441 LEDsoff();
f397b5cc
M
2442
2443 tracing = TRUE;
2444}
2445
2446//-----------------------------------------------------------------------------
2447// MIFARE check keys. key count up to 8.
2448//
2449//-----------------------------------------------------------------------------
2450void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
2451{
2452 // params
2453 uint8_t blockNo = arg0;
2454 uint8_t keyType = arg1;
2455 uint8_t keyCount = arg2;
2456 uint64_t ui64Key = 0;
2457
2458 // variables
2459 int i;
2460 byte_t isOK = 0;
2461 uint8_t uid[8];
2462 uint32_t cuid;
2463 struct Crypto1State mpcs = {0, 0};
2464 struct Crypto1State *pcs;
2465 pcs = &mpcs;
2466
2467 // clear debug level
2468 int OLD_MF_DBGLEVEL = MF_DBGLEVEL;
2469 MF_DBGLEVEL = MF_DBG_NONE;
2470
2471 // clear trace
2472 traceLen = 0;
2473 tracing = TRUE;
2474
2475 iso14443a_setup();
2476
2477 LED_A_ON();
2478 LED_B_OFF();
2479 LED_C_OFF();
2480
2481 SpinDelay(300);
2482 for (i = 0; i < keyCount; i++) {
2483 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2484 SpinDelay(100);
2485 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
2486
2487 if(!iso14443a_select_card(uid, NULL, &cuid)) {
2488 if (OLD_MF_DBGLEVEL >= 1) Dbprintf("Can't select card");
2489 break;
2490 };
2491
2492 ui64Key = bytes_to_num(datain + i * 6, 6);
2493 if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {
2494 continue;
2495 };
2496
2497 isOK = 1;
2498 break;
2499 }
2500
2501 // ----------------------------- crypto1 destroy
2502 crypto1_destroy(pcs);
2503
2504 // add trace trailer
2505 uid[0] = 0xff;
2506 uid[1] = 0xff;
2507 uid[2] = 0xff;
2508 uid[3] = 0xff;
2509 LogTrace(uid, 4, 0, 0, TRUE);
2510
2511 UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
2512 if (isOK) memcpy(ack.d.asBytes, datain + i * 6, 6);
2513
2514 LED_B_ON();
2515 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
2516 LED_B_OFF();
2517
2518 // Thats it...
2519 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2520 LEDsoff();
20f9a2a1 2521
f397b5cc
M
2522 // restore debug level
2523 MF_DBGLEVEL = OLD_MF_DBGLEVEL;
20f9a2a1
M
2524}
2525
2526//-----------------------------------------------------------------------------
2527// MIFARE 1K simulate.
2528//
2529//-----------------------------------------------------------------------------
2530void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
2531{
50193c1e 2532 int cardSTATE = MFEMUL_NOFIELD;
9ca155ba 2533 int vHf = 0; // in mV
0a39986e 2534 int res, i;
9ca155ba 2535 uint32_t timer = 0;
0a39986e
M
2536 uint32_t selTimer = 0;
2537 uint32_t authTimer = 0;
2538 uint32_t par = 0;
9ca155ba 2539 int len = 0;
0a39986e 2540 uint8_t bt;
9ca155ba
M
2541 uint8_t cardAUTHSC = 0;
2542 uint8_t cardAUTHKEY = 0xff; // no authentication
2543 uint32_t cuid = 0;
2544 struct Crypto1State mpcs = {0, 0};
2545 struct Crypto1State *pcs;
2546 pcs = &mpcs;
2547
2548 uint64_t key64 = 0xffffffffffffULL;
2549
2550 uint8_t* receivedCmd = mifare_get_bigbufptr();
2551
2552 static uint8_t rATQA[] = {0x04, 0x00}; // Mifare classic 1k
2553
0a39986e
M
2554 static uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2555 static uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
9ca155ba 2556
0a39986e 2557 static uint8_t rSAK[] = {0x08, 0xb6, 0xdd};
9ca155ba 2558
0a39986e
M
2559 static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
2560 static uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
2561 static uint8_t cmdBuf[18];
2562
2563 // clear trace
2564 traceLen = 0;
2565 tracing = true;
9ca155ba
M
2566
2567// -------------------------------------- test area
50193c1e 2568
0a39986e
M
2569 // Authenticate response - nonce
2570 uint8_t *resp1 = (((uint8_t *)BigBuf) + CARD_MEMORY);
2571 int resp1Len;
2572 uint8_t *resp2 = (((uint8_t *)BigBuf) + CARD_MEMORY + 200);
2573 int resp2Len;
2574 CodeIso14443aAsTag(rAUTH_NT, sizeof(rAUTH_NT));
2575 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
2576
2577 timer = GetTickCount();
2578 uint32_t nonce = bytes_to_num(rAUTH_NT, 4);
2579 uint32_t rn_enc = 0x98d76b77; // !!!!!!!!!!!!!!!!!
2580 uint32_t ans = 0;
2581 cuid = bytes_to_num(rUIDBCC1, 4);
2582
2583 crypto1_create(pcs, key64);
2584 crypto1_word(pcs, cuid ^ nonce, 0);
2585 crypto1_word(pcs, rn_enc , 1);
2586 crypto1_word(pcs, 0, 0);
2587 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2588 num_to_bytes(ans, 4, rAUTH_AT);
2589 CodeIso14443aAsTag(rAUTH_AT, sizeof(rAUTH_AT));
2590 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
2591 Dbprintf("crypto auth time: %d", GetTickCount() - timer);
50193c1e 2592
9ca155ba
M
2593// -------------------------------------- END test area
2594
2595 // We need to listen to the high-frequency, peak-detected path.
2596 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2597 FpgaSetupSsc();
2598
2599 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
2600 SpinDelay(200);
2601
2602Dbprintf("--> start");
2603 while (true) {
2604 WDT_HIT();
9ca155ba
M
2605
2606 // find reader field
2607 // Vref = 3300mV, and an 10:1 voltage divider on the input
2608 // can measure voltages up to 33000 mV
2609 if (cardSTATE == MFEMUL_NOFIELD) {
2610 vHf = (33000 * AvgAdc(ADC_CHAN_HF)) >> 10;
2611 if (vHf > MF_MINFIELDV) {
2612 cardSTATE = MFEMUL_IDLE;
2613 LED_A_ON();
2614 }
2615 }
2616
2617 if (cardSTATE != MFEMUL_NOFIELD) {
2618 res = EmGetCmd(receivedCmd, &len, 100);
2619 if (res == 2) {
2620 cardSTATE = MFEMUL_NOFIELD;
2621 LEDsoff();
2622 continue;
2623 }
2624 if(res) break;
2625 }
2626
50193c1e 2627 if(BUTTON_PRESS()) {
9ca155ba
M
2628 break;
2629 }
9ca155ba 2630// if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
0a39986e
M
2631
2632 if (len != 4 && cardSTATE != MFEMUL_NOFIELD) { // len != 4 <---- speed up the code 4 authentication
2633 // REQ or WUP request in ANY state and WUP in HALTED state
2634 if (len == 1 && ((receivedCmd[0] == 0x26 && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == 0x52)) {
2635 selTimer = GetTickCount();
2636 EmSendCmdEx(rATQA, sizeof(rATQA), (receivedCmd[0] == 0x52));
2637 cardSTATE = MFEMUL_SELECT1;
2638
2639 // init crypto block
2640 LED_B_OFF();
2641 LED_C_OFF();
2642 crypto1_destroy(pcs);
2643 cardAUTHKEY = 0xff;
2644 }
2645 }
9ca155ba 2646
50193c1e
M
2647 switch (cardSTATE) {
2648 case MFEMUL_NOFIELD:{
2649 break;
2650 }
9ca155ba 2651 case MFEMUL_HALTED:{
0a39986e 2652 break;
9ca155ba 2653 }
50193c1e
M
2654 case MFEMUL_IDLE:{
2655 break;
2656 }
2657 case MFEMUL_SELECT1:{
9ca155ba
M
2658 // select all
2659 if (len == 2 && (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x20)) {
2660 EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
2661
2662 if (rUIDBCC1[0] == 0x88) {
2663 cardSTATE = MFEMUL_SELECT2;
2664 }
2665 }
2666
2667 // select card
0a39986e
M
2668 if (len == 9 &&
2669 (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
9ca155ba
M
2670 EmSendCmd(rSAK, sizeof(rSAK));
2671
2672 cuid = bytes_to_num(rUIDBCC1, 4);
2673 cardSTATE = MFEMUL_WORK;
2674 LED_B_ON();
0a39986e 2675 Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
9ca155ba
M
2676 }
2677
50193c1e
M
2678 break;
2679 }
2680 case MFEMUL_SELECT2:{
9ca155ba
M
2681 EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
2682
2683 cuid = bytes_to_num(rUIDBCC2, 4);
2684 cardSTATE = MFEMUL_WORK;
2685 LED_B_ON();
2686Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - timer);
50193c1e
M
2687 break;
2688 }
2689 case MFEMUL_AUTH1:{
9ca155ba 2690 if (len == 8) {
0a39986e
M
2691timer = GetTickCount();
2692// ---------------------------------
2693 rn_enc = bytes_to_num(receivedCmd, 4);
2694 crypto1_create(pcs, key64);
2695 crypto1_word(pcs, cuid ^ nonce, 0);
2696 crypto1_word(pcs, rn_enc , 1);
2697 crypto1_word(pcs, 0, 0);
2698 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2699 num_to_bytes(ans, 4, rAUTH_AT);
2700// ---------------------------------
2701 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2702// EmSendCmd14443aRaw(resp2, resp2Len, 0);
2703 cardSTATE = MFEMUL_AUTH2;
2704 } else {
2705 cardSTATE = MFEMUL_IDLE;
2706 LED_B_OFF();
2707 LED_C_OFF();
9ca155ba 2708 }
0a39986e 2709 if (cardSTATE != MFEMUL_AUTH2) break;
50193c1e
M
2710 }
2711 case MFEMUL_AUTH2:{
0a39986e 2712 // test auth info here...
9ca155ba
M
2713
2714 LED_C_ON();
0a39986e
M
2715 cardSTATE = MFEMUL_WORK;
2716Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d a=%d", cardAUTHSC, cardAUTHKEY, GetTickCount() - authTimer, GetTickCount() - timer);
50193c1e
M
2717 break;
2718 }
9ca155ba
M
2719 case MFEMUL_WORK:{
2720 // auth
2721 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
0a39986e
M
2722 authTimer = GetTickCount();
2723// EmSendCmd(rAUTH_NT, sizeof(rAUTH_NT));
2724//SpinDelayUs(30);
2725 EmSendCmd14443aRaw(resp1, resp1Len, 0);
2726// crypto1_create(pcs, key64);
9ca155ba 2727// if (cardAUTHKEY == 0xff) { // first auth
0a39986e 2728// crypto1_word(pcs, cuid ^ bytes_to_num(rAUTH_NT, 4), 0); // uid ^ nonce
9ca155ba
M
2729// } else { // nested auth
2730// }
2731
0a39986e 2732 cardAUTHSC = receivedCmd[1] / 4; // received block num
9ca155ba
M
2733 cardAUTHKEY = receivedCmd[0] - 0x60;
2734 cardSTATE = MFEMUL_AUTH1;
0a39986e
M
2735 break;
2736 }
2737
2738 if (len == 0) break;
2739
2740 // decrypt seqence
2741 if (cardAUTHKEY != 0xff){
2742 if (len != 1) {
2743 for (i = 0; i < len; i++)
2744 receivedCmd[i] = crypto1_byte(pcs, 0x00, 0) ^ receivedCmd[i];
2745 } else {
2746 bt = 0;
2747 for (i = 0; i < 4; i++)
2748 bt |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedCmd[0], i)) << i;
2749
2750 receivedCmd[0] = bt;
2751 }
2752 }
2753
2754 // read block
2755 if (len == 4 && receivedCmd[0] == 0x30) {
2756 cmdBuf[0] = 0;
2757 par = 0;
2758/* memcpy(cmdBuf, blockData, 16);
2759 AppendCrc14443a(cmdBuf, 16);
2760
2761 // crypto
2762 par = 0;
2763 for (i = 0; i < 18; i++) {
2764 d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ cmdBuf[pos];
2765 par = (par >> 1) | ( ((filter(pcs->odd) ^ oddparity(cmdBuf[pos])) & 0x01) * 0x20000 );
2766 }
2767*/
2768 //ReaderTransmitPar(d_block_enc, sizeof(d_block_enc), par);
2769Dbprintf("read block: %d", receivedCmd[1]);
2770 break;
2771 }
2772
2773 // write block
2774 if (len == 4 && receivedCmd[0] == 0xA0) {
2775Dbprintf("write block: %d", receivedCmd[1]);
2776 break;
9ca155ba
M
2777 }
2778
2779 // halt
0a39986e 2780 if (len == 4 && (receivedCmd[0] == 0x50 && receivedCmd[1] == 0x00)) {
9ca155ba
M
2781 cardSTATE = MFEMUL_HALTED;
2782 LED_B_OFF();
0a39986e
M
2783 LED_C_OFF();
2784 Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
2785 break;
9ca155ba 2786 }
50193c1e
M
2787 break;
2788 }
2789
2790 }
2791
2792 }
2793
9ca155ba
M
2794 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2795 LEDsoff();
2796
0a39986e
M
2797 // add trace trailer
2798 LogTrace(rAUTH_NT, 4, 0, 0, TRUE);
2799
9ca155ba 2800 DbpString("Emulator stopped.");
15c4dc5a 2801}
Impressum, Datenschutz