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