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