]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iso14443.c
Add defines for TIMER_CLOCK?
[proxmark3-svn] / armsrc / iso14443.c
1 //-----------------------------------------------------------------------------
2 // Routines to support ISO 14443. This includes both the reader software and
3 // the `fake tag' modes. At the moment only the Type B modulation is
4 // supported.
5 // Jonathan Westhues, split Nov 2006
6 //-----------------------------------------------------------------------------
7 #include <proxmark3.h>
8 #include "apps.h"
9 #include "../common/iso14443_crc.c"
10
11
12 //static void GetSamplesFor14443(BOOL weTx, int n);
13
14 #define DMA_BUFFER_SIZE 256
15
16 //=============================================================================
17 // An ISO 14443 Type B tag. We listen for commands from the reader, using
18 // a UART kind of thing that's implemented in software. When we get a
19 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
20 // If it's good, then we can do something appropriate with it, and send
21 // a response.
22 //=============================================================================
23
24 //-----------------------------------------------------------------------------
25 // Code up a string of octets at layer 2 (including CRC, we don't generate
26 // that here) so that they can be transmitted to the reader. Doesn't transmit
27 // them yet, just leaves them ready to send in ToSend[].
28 //-----------------------------------------------------------------------------
29 static void CodeIso14443bAsTag(const BYTE *cmd, int len)
30 {
31 int i;
32
33 ToSendReset();
34
35 // Transmit a burst of ones, as the initial thing that lets the
36 // reader get phase sync. This (TR1) must be > 80/fs, per spec,
37 // but tag that I've tried (a Paypass) exceeds that by a fair bit,
38 // so I will too.
39 for(i = 0; i < 20; i++) {
40 ToSendStuffBit(1);
41 ToSendStuffBit(1);
42 ToSendStuffBit(1);
43 ToSendStuffBit(1);
44 }
45
46 // Send SOF.
47 for(i = 0; i < 10; i++) {
48 ToSendStuffBit(0);
49 ToSendStuffBit(0);
50 ToSendStuffBit(0);
51 ToSendStuffBit(0);
52 }
53 for(i = 0; i < 2; i++) {
54 ToSendStuffBit(1);
55 ToSendStuffBit(1);
56 ToSendStuffBit(1);
57 ToSendStuffBit(1);
58 }
59
60 for(i = 0; i < len; i++) {
61 int j;
62 BYTE b = cmd[i];
63
64 // Start bit
65 ToSendStuffBit(0);
66 ToSendStuffBit(0);
67 ToSendStuffBit(0);
68 ToSendStuffBit(0);
69
70 // Data bits
71 for(j = 0; j < 8; j++) {
72 if(b & 1) {
73 ToSendStuffBit(1);
74 ToSendStuffBit(1);
75 ToSendStuffBit(1);
76 ToSendStuffBit(1);
77 } else {
78 ToSendStuffBit(0);
79 ToSendStuffBit(0);
80 ToSendStuffBit(0);
81 ToSendStuffBit(0);
82 }
83 b >>= 1;
84 }
85
86 // Stop bit
87 ToSendStuffBit(1);
88 ToSendStuffBit(1);
89 ToSendStuffBit(1);
90 ToSendStuffBit(1);
91 }
92
93 // Send SOF.
94 for(i = 0; i < 10; i++) {
95 ToSendStuffBit(0);
96 ToSendStuffBit(0);
97 ToSendStuffBit(0);
98 ToSendStuffBit(0);
99 }
100 for(i = 0; i < 10; i++) {
101 ToSendStuffBit(1);
102 ToSendStuffBit(1);
103 ToSendStuffBit(1);
104 ToSendStuffBit(1);
105 }
106
107 // Convert from last byte pos to length
108 ToSendMax++;
109
110 // Add a few more for slop
111 ToSendMax += 2;
112 }
113
114 //-----------------------------------------------------------------------------
115 // The software UART that receives commands from the reader, and its state
116 // variables.
117 //-----------------------------------------------------------------------------
118 static struct {
119 enum {
120 STATE_UNSYNCD,
121 STATE_GOT_FALLING_EDGE_OF_SOF,
122 STATE_AWAITING_START_BIT,
123 STATE_RECEIVING_DATA,
124 STATE_ERROR_WAIT
125 } state;
126 WORD shiftReg;
127 int bitCnt;
128 int byteCnt;
129 int byteCntMax;
130 int posCnt;
131 BYTE *output;
132 } Uart;
133
134 /* Receive & handle a bit coming from the reader.
135 *
136 * LED handling:
137 * LED A -> ON once we have received the SOF and are expecting the rest.
138 * LED A -> OFF once we have received EOF or are in error state or unsynced
139 *
140 * Returns: true if we received a EOF
141 * false if we are still waiting for some more
142 */
143 static BOOL Handle14443UartBit(int bit)
144 {
145 switch(Uart.state) {
146 case STATE_UNSYNCD:
147 LED_A_OFF();
148 if(!bit) {
149 // we went low, so this could be the beginning
150 // of an SOF
151 Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
152 Uart.posCnt = 0;
153 Uart.bitCnt = 0;
154 }
155 break;
156
157 case STATE_GOT_FALLING_EDGE_OF_SOF:
158 Uart.posCnt++;
159 if(Uart.posCnt == 2) {
160 if(bit) {
161 if(Uart.bitCnt >= 10) {
162 // we've seen enough consecutive
163 // zeros that it's a valid SOF
164 Uart.posCnt = 0;
165 Uart.byteCnt = 0;
166 Uart.state = STATE_AWAITING_START_BIT;
167 LED_A_ON(); // Indicate we got a valid SOF
168 } else {
169 // didn't stay down long enough
170 // before going high, error
171 Uart.state = STATE_ERROR_WAIT;
172 }
173 } else {
174 // do nothing, keep waiting
175 }
176 Uart.bitCnt++;
177 }
178 if(Uart.posCnt >= 4) Uart.posCnt = 0;
179 if(Uart.bitCnt > 14) {
180 // Give up if we see too many zeros without
181 // a one, too.
182 Uart.state = STATE_ERROR_WAIT;
183 }
184 break;
185
186 case STATE_AWAITING_START_BIT:
187 Uart.posCnt++;
188 if(bit) {
189 if(Uart.posCnt > 25) {
190 // stayed high for too long between
191 // characters, error
192 Uart.state = STATE_ERROR_WAIT;
193 }
194 } else {
195 // falling edge, this starts the data byte
196 Uart.posCnt = 0;
197 Uart.bitCnt = 0;
198 Uart.shiftReg = 0;
199 Uart.state = STATE_RECEIVING_DATA;
200 LED_A_ON(); // Indicate we're receiving
201 }
202 break;
203
204 case STATE_RECEIVING_DATA:
205 Uart.posCnt++;
206 if(Uart.posCnt == 2) {
207 // time to sample a bit
208 Uart.shiftReg >>= 1;
209 if(bit) {
210 Uart.shiftReg |= 0x200;
211 }
212 Uart.bitCnt++;
213 }
214 if(Uart.posCnt >= 4) {
215 Uart.posCnt = 0;
216 }
217 if(Uart.bitCnt == 10) {
218 if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
219 {
220 // this is a data byte, with correct
221 // start and stop bits
222 Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
223 Uart.byteCnt++;
224
225 if(Uart.byteCnt >= Uart.byteCntMax) {
226 // Buffer overflowed, give up
227 Uart.posCnt = 0;
228 Uart.state = STATE_ERROR_WAIT;
229 } else {
230 // so get the next byte now
231 Uart.posCnt = 0;
232 Uart.state = STATE_AWAITING_START_BIT;
233 }
234 } else if(Uart.shiftReg == 0x000) {
235 // this is an EOF byte
236 LED_A_OFF(); // Finished receiving
237 return TRUE;
238 } else {
239 // this is an error
240 Uart.posCnt = 0;
241 Uart.state = STATE_ERROR_WAIT;
242 }
243 }
244 break;
245
246 case STATE_ERROR_WAIT:
247 // We're all screwed up, so wait a little while
248 // for whatever went wrong to finish, and then
249 // start over.
250 Uart.posCnt++;
251 if(Uart.posCnt > 10) {
252 Uart.state = STATE_UNSYNCD;
253 }
254 break;
255
256 default:
257 Uart.state = STATE_UNSYNCD;
258 break;
259 }
260
261 if (Uart.state == STATE_ERROR_WAIT) LED_A_OFF(); // Error
262
263 return FALSE;
264 }
265
266 //-----------------------------------------------------------------------------
267 // Receive a command (from the reader to us, where we are the simulated tag),
268 // and store it in the given buffer, up to the given maximum length. Keeps
269 // spinning, waiting for a well-framed command, until either we get one
270 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
271 //
272 // Assume that we're called with the SSC (to the FPGA) and ADC path set
273 // correctly.
274 //-----------------------------------------------------------------------------
275 static BOOL GetIso14443CommandFromReader(BYTE *received, int *len, int maxLen)
276 {
277 BYTE mask;
278 int i, bit;
279
280 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
281 // only, since we are receiving, not transmitting).
282 // Signal field is off with the appropriate LED
283 LED_D_OFF();
284 FpgaWriteConfWord(
285 FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
286
287
288 // Now run a `software UART' on the stream of incoming samples.
289 Uart.output = received;
290 Uart.byteCntMax = maxLen;
291 Uart.state = STATE_UNSYNCD;
292
293 for(;;) {
294 WDT_HIT();
295
296 if(BUTTON_PRESS()) return FALSE;
297
298 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
299 AT91C_BASE_SSC->SSC_THR = 0x00;
300 }
301 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
302 BYTE b = (BYTE)AT91C_BASE_SSC->SSC_RHR;
303
304 mask = 0x80;
305 for(i = 0; i < 8; i++, mask >>= 1) {
306 bit = (b & mask);
307 if(Handle14443UartBit(bit)) {
308 *len = Uart.byteCnt;
309 return TRUE;
310 }
311 }
312 }
313 }
314 }
315
316 //-----------------------------------------------------------------------------
317 // Main loop of simulated tag: receive commands from reader, decide what
318 // response to send, and send it.
319 //-----------------------------------------------------------------------------
320 void SimulateIso14443Tag(void)
321 {
322 static const BYTE cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
323 static const BYTE response1[] = {
324 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22,
325 0x00, 0x21, 0x85, 0x5e, 0xd7
326 };
327
328 BYTE *resp;
329 int respLen;
330
331 BYTE *resp1 = (((BYTE *)BigBuf) + 800);
332 int resp1Len;
333
334 BYTE *receivedCmd = (BYTE *)BigBuf;
335 int len;
336
337 int i;
338
339 int cmdsRecvd = 0;
340
341 memset(receivedCmd, 0x44, 400);
342
343 CodeIso14443bAsTag(response1, sizeof(response1));
344 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
345
346 // We need to listen to the high-frequency, peak-detected path.
347 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
348 FpgaSetupSsc();
349
350 cmdsRecvd = 0;
351
352 for(;;) {
353 BYTE b1, b2;
354
355 if(!GetIso14443CommandFromReader(receivedCmd, &len, 100)) {
356 DbpIntegers(cmdsRecvd, 0, 0);
357 DbpString("button press");
358 break;
359 }
360
361 // Good, look at the command now.
362
363 if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len)==0) {
364 resp = resp1; respLen = resp1Len;
365 } else {
366 DbpString("new cmd from reader:");
367 DbpIntegers(len, 0x1234, cmdsRecvd);
368 // And print whether the CRC fails, just for good measure
369 ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2);
370 if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) {
371 // Not so good, try again.
372 DbpString("+++CRC fail");
373 } else {
374 DbpString("CRC passes");
375 }
376 break;
377 }
378
379 memset(receivedCmd, 0x44, 32);
380
381 cmdsRecvd++;
382
383 if(cmdsRecvd > 0x30) {
384 DbpString("many commands later...");
385 break;
386 }
387
388 if(respLen <= 0) continue;
389
390 // Modulate BPSK
391 // Signal field is off with the appropriate LED
392 LED_D_OFF();
393 FpgaWriteConfWord(
394 FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
395 AT91C_BASE_SSC->SSC_THR = 0xff;
396 FpgaSetupSsc();
397
398 // Transmit the response.
399 i = 0;
400 for(;;) {
401 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
402 BYTE b = resp[i];
403
404 AT91C_BASE_SSC->SSC_THR = b;
405
406 i++;
407 if(i > respLen) {
408 break;
409 }
410 }
411 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
412 volatile BYTE b = (BYTE)AT91C_BASE_SSC->SSC_RHR;
413 (void)b;
414 }
415 }
416 }
417 }
418
419 //=============================================================================
420 // An ISO 14443 Type B reader. We take layer two commands, code them
421 // appropriately, and then send them to the tag. We then listen for the
422 // tag's response, which we leave in the buffer to be demodulated on the
423 // PC side.
424 //=============================================================================
425
426 static struct {
427 enum {
428 DEMOD_UNSYNCD,
429 DEMOD_PHASE_REF_TRAINING,
430 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
431 DEMOD_GOT_FALLING_EDGE_OF_SOF,
432 DEMOD_AWAITING_START_BIT,
433 DEMOD_RECEIVING_DATA,
434 DEMOD_ERROR_WAIT
435 } state;
436 int bitCount;
437 int posCount;
438 int thisBit;
439 int metric;
440 int metricN;
441 WORD shiftReg;
442 BYTE *output;
443 int len;
444 int sumI;
445 int sumQ;
446 } Demod;
447
448 /*
449 * Handles reception of a bit from the tag
450 *
451 * LED handling:
452 * LED C -> ON once we have received the SOF and are expecting the rest.
453 * LED C -> OFF once we have received EOF or are unsynced
454 *
455 * Returns: true if we received a EOF
456 * false if we are still waiting for some more
457 *
458 */
459 static BOOL Handle14443SamplesDemod(int ci, int cq)
460 {
461 int v;
462
463 // The soft decision on the bit uses an estimate of just the
464 // quadrant of the reference angle, not the exact angle.
465 #define MAKE_SOFT_DECISION() { \
466 if(Demod.sumI > 0) { \
467 v = ci; \
468 } else { \
469 v = -ci; \
470 } \
471 if(Demod.sumQ > 0) { \
472 v += cq; \
473 } else { \
474 v -= cq; \
475 } \
476 }
477
478 switch(Demod.state) {
479 case DEMOD_UNSYNCD:
480 v = ci;
481 if(v < 0) v = -v;
482 if(cq > 0) {
483 v += cq;
484 } else {
485 v -= cq;
486 }
487 if(v > 40) {
488 Demod.posCount = 0;
489 Demod.state = DEMOD_PHASE_REF_TRAINING;
490 Demod.sumI = 0;
491 Demod.sumQ = 0;
492 }
493 break;
494
495 case DEMOD_PHASE_REF_TRAINING:
496 if(Demod.posCount < 8) {
497 Demod.sumI += ci;
498 Demod.sumQ += cq;
499 } else if(Demod.posCount > 100) {
500 // error, waited too long
501 Demod.state = DEMOD_UNSYNCD;
502 } else {
503 MAKE_SOFT_DECISION();
504 if(v < 0) {
505 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
506 Demod.posCount = 0;
507 }
508 }
509 Demod.posCount++;
510 break;
511
512 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
513 MAKE_SOFT_DECISION();
514 if(v < 0) {
515 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
516 Demod.posCount = 0;
517 } else {
518 if(Demod.posCount > 100) {
519 Demod.state = DEMOD_UNSYNCD;
520 }
521 }
522 Demod.posCount++;
523 break;
524
525 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
526 MAKE_SOFT_DECISION();
527 if(v > 0) {
528 if(Demod.posCount < 12) {
529 Demod.state = DEMOD_UNSYNCD;
530 } else {
531 LED_C_ON(); // Got SOF
532 Demod.state = DEMOD_AWAITING_START_BIT;
533 Demod.posCount = 0;
534 Demod.len = 0;
535 Demod.metricN = 0;
536 Demod.metric = 0;
537 }
538 } else {
539 if(Demod.posCount > 100) {
540 Demod.state = DEMOD_UNSYNCD;
541 }
542 }
543 Demod.posCount++;
544 break;
545
546 case DEMOD_AWAITING_START_BIT:
547 MAKE_SOFT_DECISION();
548 if(v > 0) {
549 if(Demod.posCount > 10) {
550 Demod.state = DEMOD_UNSYNCD;
551 }
552 } else {
553 Demod.bitCount = 0;
554 Demod.posCount = 1;
555 Demod.thisBit = v;
556 Demod.shiftReg = 0;
557 Demod.state = DEMOD_RECEIVING_DATA;
558 }
559 break;
560
561 case DEMOD_RECEIVING_DATA:
562 MAKE_SOFT_DECISION();
563 if(Demod.posCount == 0) {
564 Demod.thisBit = v;
565 Demod.posCount = 1;
566 } else {
567 Demod.thisBit += v;
568
569 if(Demod.thisBit > 0) {
570 Demod.metric += Demod.thisBit;
571 } else {
572 Demod.metric -= Demod.thisBit;
573 }
574 (Demod.metricN)++;
575
576 Demod.shiftReg >>= 1;
577 if(Demod.thisBit > 0) {
578 Demod.shiftReg |= 0x200;
579 }
580
581 Demod.bitCount++;
582 if(Demod.bitCount == 10) {
583 WORD s = Demod.shiftReg;
584 if((s & 0x200) && !(s & 0x001)) {
585 BYTE b = (s >> 1);
586 Demod.output[Demod.len] = b;
587 Demod.len++;
588 Demod.state = DEMOD_AWAITING_START_BIT;
589 } else if(s == 0x000) {
590 // This is EOF
591 LED_C_OFF();
592 return TRUE;
593 Demod.state = DEMOD_UNSYNCD;
594 } else {
595 Demod.state = DEMOD_UNSYNCD;
596 }
597 }
598 Demod.posCount = 0;
599 }
600 break;
601
602 default:
603 Demod.state = DEMOD_UNSYNCD;
604 break;
605 }
606
607 if (Demod.state == DEMOD_UNSYNCD) LED_C_OFF(); // Not synchronized...
608 return FALSE;
609 }
610
611 /*
612 * Demodulate the samples we received from the tag
613 * weTx: set to 'TRUE' if we behave like a reader
614 * set to 'FALSE' if we behave like a snooper
615 * quiet: set to 'TRUE' to disable debug output
616 */
617 static void GetSamplesFor14443Demod(BOOL weTx, int n, BOOL quiet)
618 {
619 int max = 0;
620 BOOL gotFrame = FALSE;
621
622 //# define DMA_BUFFER_SIZE 8
623 SBYTE *dmaBuf;
624
625 int lastRxCounter;
626 SBYTE *upTo;
627
628 int ci, cq;
629
630 int samples = 0;
631
632 // Clear out the state of the "UART" that receives from the tag.
633 memset(BigBuf, 0x44, 400);
634 Demod.output = (BYTE *)BigBuf;
635 Demod.len = 0;
636 Demod.state = DEMOD_UNSYNCD;
637
638 // And the UART that receives from the reader
639 Uart.output = (((BYTE *)BigBuf) + 1024);
640 Uart.byteCntMax = 100;
641 Uart.state = STATE_UNSYNCD;
642
643 // Setup for the DMA.
644 dmaBuf = (SBYTE *)(BigBuf + 32);
645 upTo = dmaBuf;
646 lastRxCounter = DMA_BUFFER_SIZE;
647 FpgaSetupSscDma((BYTE *)dmaBuf, DMA_BUFFER_SIZE);
648
649 // Signal field is ON with the appropriate LED:
650 if (weTx) LED_D_ON(); else LED_D_OFF();
651 // And put the FPGA in the appropriate mode
652 FpgaWriteConfWord(
653 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
654 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
655
656 for(;;) {
657 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
658 if(behindBy > max) max = behindBy;
659
660 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1))
661 > 2)
662 {
663 ci = upTo[0];
664 cq = upTo[1];
665 upTo += 2;
666 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
667 upTo -= DMA_BUFFER_SIZE;
668 AT91C_BASE_PDC_SSC->PDC_RNPR = (DWORD)upTo;
669 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
670 }
671 lastRxCounter -= 2;
672 if(lastRxCounter <= 0) {
673 lastRxCounter += DMA_BUFFER_SIZE;
674 }
675
676 samples += 2;
677
678 Handle14443UartBit(1);
679 Handle14443UartBit(1);
680
681 if(Handle14443SamplesDemod(ci, cq)) {
682 gotFrame = 1;
683 }
684 }
685
686 if(samples > 2000) {
687 break;
688 }
689 }
690 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
691 if (!quiet) DbpIntegers(max, gotFrame, Demod.len);
692 }
693
694 //-----------------------------------------------------------------------------
695 // Read the tag's response. We just receive a stream of slightly-processed
696 // samples from the FPGA, which we will later do some signal processing on,
697 // to get the bits.
698 //-----------------------------------------------------------------------------
699 /*static void GetSamplesFor14443(BOOL weTx, int n)
700 {
701 BYTE *dest = (BYTE *)BigBuf;
702 int c;
703
704 FpgaWriteConfWord(
705 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
706 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
707
708 c = 0;
709 for(;;) {
710 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
711 AT91C_BASE_SSC->SSC_THR = 0x43;
712 }
713 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
714 SBYTE b;
715 b = (SBYTE)AT91C_BASE_SSC->SSC_RHR;
716
717 dest[c++] = (BYTE)b;
718
719 if(c >= n) {
720 break;
721 }
722 }
723 }
724 }*/
725
726 //-----------------------------------------------------------------------------
727 // Transmit the command (to the tag) that was placed in ToSend[].
728 //-----------------------------------------------------------------------------
729 static void TransmitFor14443(void)
730 {
731 int c;
732
733 FpgaSetupSsc();
734
735 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
736 AT91C_BASE_SSC->SSC_THR = 0xff;
737 }
738
739 // Signal field is ON with the appropriate Red LED
740 LED_D_ON();
741 // Signal we are transmitting with the Green LED
742 LED_B_ON();
743 FpgaWriteConfWord(
744 FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
745
746 for(c = 0; c < 10;) {
747 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
748 AT91C_BASE_SSC->SSC_THR = 0xff;
749 c++;
750 }
751 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
752 volatile DWORD r = AT91C_BASE_SSC->SSC_RHR;
753 (void)r;
754 }
755 WDT_HIT();
756 }
757
758 c = 0;
759 for(;;) {
760 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
761 AT91C_BASE_SSC->SSC_THR = ToSend[c];
762 c++;
763 if(c >= ToSendMax) {
764 break;
765 }
766 }
767 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
768 volatile DWORD r = AT91C_BASE_SSC->SSC_RHR;
769 (void)r;
770 }
771 WDT_HIT();
772 }
773 LED_B_OFF(); // Finished sending
774 }
775
776 //-----------------------------------------------------------------------------
777 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
778 // so that it is ready to transmit to the tag using TransmitFor14443().
779 //-----------------------------------------------------------------------------
780 void CodeIso14443bAsReader(const BYTE *cmd, int len)
781 {
782 int i, j;
783 BYTE b;
784
785 ToSendReset();
786
787 // Establish initial reference level
788 for(i = 0; i < 40; i++) {
789 ToSendStuffBit(1);
790 }
791 // Send SOF
792 for(i = 0; i < 10; i++) {
793 ToSendStuffBit(0);
794 }
795
796 for(i = 0; i < len; i++) {
797 // Stop bits/EGT
798 ToSendStuffBit(1);
799 ToSendStuffBit(1);
800 // Start bit
801 ToSendStuffBit(0);
802 // Data bits
803 b = cmd[i];
804 for(j = 0; j < 8; j++) {
805 if(b & 1) {
806 ToSendStuffBit(1);
807 } else {
808 ToSendStuffBit(0);
809 }
810 b >>= 1;
811 }
812 }
813 // Send EOF
814 ToSendStuffBit(1);
815 for(i = 0; i < 10; i++) {
816 ToSendStuffBit(0);
817 }
818 for(i = 0; i < 8; i++) {
819 ToSendStuffBit(1);
820 }
821
822 // And then a little more, to make sure that the last character makes
823 // it out before we switch to rx mode.
824 for(i = 0; i < 24; i++) {
825 ToSendStuffBit(1);
826 }
827
828 // Convert from last character reference to length
829 ToSendMax++;
830 }
831
832 //-----------------------------------------------------------------------------
833 // Read an ISO 14443 tag. We send it some set of commands, and record the
834 // responses.
835 // The command name is misleading, it actually decodes the reponse in HEX
836 // into the output buffer (read the result using hexsamples, not hisamples)
837 //-----------------------------------------------------------------------------
838 void AcquireRawAdcSamplesIso14443(DWORD parameter)
839 {
840 BYTE cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
841
842 // Make sure that we start from off, since the tags are stateful;
843 // confusing things will happen if we don't reset them between reads.
844 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
845 LED_D_OFF();
846 SpinDelay(200);
847
848 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
849 FpgaSetupSsc();
850
851 // Now give it time to spin up.
852 // Signal field is on with the appropriate LED
853 LED_D_ON();
854 FpgaWriteConfWord(
855 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
856 SpinDelay(200);
857
858 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
859 TransmitFor14443();
860 // LED_A_ON();
861 GetSamplesFor14443Demod(TRUE, 2000, FALSE);
862 // LED_A_OFF();
863 }
864
865 //-----------------------------------------------------------------------------
866 // Read a SRI512 ISO 14443 tag.
867 //
868 // SRI512 tags are just simple memory tags, here we're looking at making a dump
869 // of the contents of the memory. No anticollision algorithm is done, we assume
870 // we have a single tag in the field.
871 //
872 // I tried to be systematic and check every answer of the tag, every CRC, etc...
873 //-----------------------------------------------------------------------------
874 void ReadSRI512Iso14443(DWORD parameter)
875 {
876 BYTE i = 0x00;
877
878 // Make sure that we start from off, since the tags are stateful;
879 // confusing things will happen if we don't reset them between reads.
880 LED_D_OFF();
881 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
882 SpinDelay(200);
883
884 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
885 FpgaSetupSsc();
886
887 // Now give it time to spin up.
888 // Signal field is on with the appropriate LED
889 LED_D_ON();
890 FpgaWriteConfWord(
891 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
892 SpinDelay(200);
893
894 // First command: wake up the tag using the INITIATE command
895 BYTE cmd1[] = { 0x06, 0x00, 0x97, 0x5b};
896 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
897 TransmitFor14443();
898 // LED_A_ON();
899 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
900 // LED_A_OFF();
901
902 if (Demod.len == 0) {
903 DbpString("No response from tag");
904 return;
905 } else {
906 DbpString("Randomly generated UID from tag (+ 2 byte CRC):");
907 DbpIntegers(Demod.output[0], Demod.output[1],Demod.output[2]);
908 }
909 // There is a response, SELECT the uid
910 DbpString("Now SELECT tag:");
911 cmd1[0] = 0x0E; // 0x0E is SELECT
912 cmd1[1] = Demod.output[0];
913 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
914 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
915 TransmitFor14443();
916 // LED_A_ON();
917 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
918 // LED_A_OFF();
919 if (Demod.len != 3) {
920 DbpString("Expected 3 bytes from tag, got:");
921 DbpIntegers(Demod.len,0x0,0x0);
922 return;
923 }
924 // Check the CRC of the answer:
925 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
926 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
927 DbpString("CRC Error reading select response.");
928 return;
929 }
930 // Check response from the tag: should be the same UID as the command we just sent:
931 if (cmd1[1] != Demod.output[0]) {
932 DbpString("Bad response to SELECT from Tag, aborting:");
933 DbpIntegers(cmd1[1],Demod.output[0],0x0);
934 return;
935 }
936 // Tag is now selected,
937 // First get the tag's UID:
938 cmd1[0] = 0x0B;
939 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
940 CodeIso14443bAsReader(cmd1, 3); // Only first three bytes for this one
941 TransmitFor14443();
942 // LED_A_ON();
943 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
944 // LED_A_OFF();
945 if (Demod.len != 10) {
946 DbpString("Expected 10 bytes from tag, got:");
947 DbpIntegers(Demod.len,0x0,0x0);
948 return;
949 }
950 // The check the CRC of the answer (use cmd1 as temporary variable):
951 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
952 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
953 DbpString("CRC Error reading block! - Below: expected, got");
954 DbpIntegers( (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9],0);
955 // Do not return;, let's go on... (we should retry, maybe ?)
956 }
957 DbpString("Tag UID (64 bits):");
958 DbpIntegers((Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], 0);
959
960 // Now loop to read all 16 blocks, address from 0 to 15
961 DbpString("Tag memory dump, block 0 to 15");
962 cmd1[0] = 0x08;
963 i = 0x00;
964 for (;;) {
965 if (i == 0x10) {
966 DbpString("System area block (0xff):");
967 i = 0xff;
968 }
969 cmd1[1] = i;
970 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
971 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
972 TransmitFor14443();
973 // LED_A_ON();
974 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
975 // LED_A_OFF();
976 if (Demod.len != 6) { // Check if we got an answer from the tag
977 DbpString("Expected 6 bytes from tag, got less...");
978 return;
979 }
980 // The check the CRC of the answer (use cmd1 as temporary variable):
981 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
982 if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
983 DbpString("CRC Error reading block! - Below: expected, got");
984 DbpIntegers( (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5],0);
985 // Do not return;, let's go on... (we should retry, maybe ?)
986 }
987 // Now print out the memory location:
988 DbpString("Address , Contents, CRC");
989 DbpIntegers(i, (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], (Demod.output[4]<<8)+Demod.output[5]);
990 if (i == 0xff) {
991 break;
992 }
993 i++;
994 }
995 }
996
997
998 //=============================================================================
999 // Finally, the `sniffer' combines elements from both the reader and
1000 // simulated tag, to show both sides of the conversation.
1001 //=============================================================================
1002
1003 //-----------------------------------------------------------------------------
1004 // Record the sequence of commands sent by the reader to the tag, with
1005 // triggering so that we start recording at the point that the tag is moved
1006 // near the reader.
1007 //-----------------------------------------------------------------------------
1008 /*
1009 * Memory usage for this function, (within BigBuf)
1010 * 0-1023 : Demodulated samples receive (1024 bytes)
1011 * 1024-1535 : Last Received command, 512 bytes (reader->tag)
1012 * 1536-2047 : Last Received command, 512 bytes(tag->reader)
1013 * 2048-2304 : DMA Buffer, 256 bytes (samples)
1014 */
1015 void SnoopIso14443(void)
1016 {
1017 // We won't start recording the frames that we acquire until we trigger;
1018 // a good trigger condition to get started is probably when we see a
1019 // response from the tag.
1020 BOOL triggered = FALSE;
1021
1022 // The command (reader -> tag) that we're working on receiving.
1023 BYTE *receivedCmd = (BYTE *)(BigBuf) + 1024;
1024 // The response (tag -> reader) that we're working on receiving.
1025 BYTE *receivedResponse = (BYTE *)(BigBuf) + 1536;
1026
1027 // As we receive stuff, we copy it from receivedCmd or receivedResponse
1028 // into trace, along with its length and other annotations.
1029 BYTE *trace = (BYTE *)BigBuf;
1030 int traceLen = 0;
1031
1032 // The DMA buffer, used to stream samples from the FPGA.
1033 SBYTE *dmaBuf = (SBYTE *)(BigBuf) + 2048;
1034 int lastRxCounter;
1035 SBYTE *upTo;
1036 int ci, cq;
1037 int maxBehindBy = 0;
1038
1039 // Count of samples received so far, so that we can include timing
1040 // information in the trace buffer.
1041 int samples = 0;
1042
1043 // Initialize the trace buffer
1044 memset(trace, 0x44, 1024);
1045
1046 // Set up the demodulator for tag -> reader responses.
1047 Demod.output = receivedResponse;
1048 Demod.len = 0;
1049 Demod.state = DEMOD_UNSYNCD;
1050
1051 // And the reader -> tag commands
1052 memset(&Uart, 0, sizeof(Uart));
1053 Uart.output = receivedCmd;
1054 Uart.byteCntMax = 100;
1055 Uart.state = STATE_UNSYNCD;
1056
1057 // And put the FPGA in the appropriate mode
1058 // Signal field is off with the appropriate LED
1059 LED_D_OFF();
1060 FpgaWriteConfWord(
1061 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
1062 FPGA_HF_READER_RX_XCORR_SNOOP);
1063 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1064
1065 // Setup for the DMA.
1066 FpgaSetupSsc();
1067 upTo = dmaBuf;
1068 lastRxCounter = DMA_BUFFER_SIZE;
1069 FpgaSetupSscDma((BYTE *)dmaBuf, DMA_BUFFER_SIZE);
1070 // And now we loop, receiving samples.
1071 for(;;) {
1072 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
1073 (DMA_BUFFER_SIZE-1);
1074 if(behindBy > maxBehindBy) {
1075 maxBehindBy = behindBy;
1076 if(behindBy > (DMA_BUFFER_SIZE-2)) { // TODO: understand whether we can increase/decrease as we want or not?
1077 DbpString("blew circular buffer!");
1078 DbpIntegers(behindBy,0,0);
1079 goto done;
1080 }
1081 }
1082 if(behindBy < 2) continue;
1083
1084 ci = upTo[0];
1085 cq = upTo[1];
1086 upTo += 2;
1087 lastRxCounter -= 2;
1088 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
1089 upTo -= DMA_BUFFER_SIZE;
1090 lastRxCounter += DMA_BUFFER_SIZE;
1091 AT91C_BASE_PDC_SSC->PDC_RNPR = (DWORD) upTo;
1092 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1093 }
1094
1095 samples += 2;
1096
1097 #define HANDLE_BIT_IF_BODY \
1098 if(triggered) { \
1099 trace[traceLen++] = ((samples >> 0) & 0xff); \
1100 trace[traceLen++] = ((samples >> 8) & 0xff); \
1101 trace[traceLen++] = ((samples >> 16) & 0xff); \
1102 trace[traceLen++] = ((samples >> 24) & 0xff); \
1103 trace[traceLen++] = 0; \
1104 trace[traceLen++] = 0; \
1105 trace[traceLen++] = 0; \
1106 trace[traceLen++] = 0; \
1107 trace[traceLen++] = Uart.byteCnt; \
1108 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt); \
1109 traceLen += Uart.byteCnt; \
1110 if(traceLen > 1000) break; \
1111 } \
1112 /* And ready to receive another command. */ \
1113 memset(&Uart, 0, sizeof(Uart)); \
1114 Uart.output = receivedCmd; \
1115 Uart.byteCntMax = 100; \
1116 Uart.state = STATE_UNSYNCD; \
1117 /* And also reset the demod code, which might have been */ \
1118 /* false-triggered by the commands from the reader. */ \
1119 memset(&Demod, 0, sizeof(Demod)); \
1120 Demod.output = receivedResponse; \
1121 Demod.state = DEMOD_UNSYNCD; \
1122
1123 if(Handle14443UartBit(ci & 1)) {
1124 HANDLE_BIT_IF_BODY
1125 }
1126 if(Handle14443UartBit(cq & 1)) {
1127 HANDLE_BIT_IF_BODY
1128 }
1129
1130 if(Handle14443SamplesDemod(ci, cq)) {
1131 // timestamp, as a count of samples
1132 trace[traceLen++] = ((samples >> 0) & 0xff);
1133 trace[traceLen++] = ((samples >> 8) & 0xff);
1134 trace[traceLen++] = ((samples >> 16) & 0xff);
1135 trace[traceLen++] = 0x80 | ((samples >> 24) & 0xff);
1136 // correlation metric (~signal strength estimate)
1137 if(Demod.metricN != 0) {
1138 Demod.metric /= Demod.metricN;
1139 }
1140 trace[traceLen++] = ((Demod.metric >> 0) & 0xff);
1141 trace[traceLen++] = ((Demod.metric >> 8) & 0xff);
1142 trace[traceLen++] = ((Demod.metric >> 16) & 0xff);
1143 trace[traceLen++] = ((Demod.metric >> 24) & 0xff);
1144 // length
1145 trace[traceLen++] = Demod.len;
1146 memcpy(trace+traceLen, receivedResponse, Demod.len);
1147 traceLen += Demod.len;
1148 if(traceLen > 1000) break;
1149
1150 triggered = TRUE;
1151
1152 // And ready to receive another response.
1153 memset(&Demod, 0, sizeof(Demod));
1154 Demod.output = receivedResponse;
1155 Demod.state = DEMOD_UNSYNCD;
1156 }
1157 WDT_HIT();
1158
1159 if(BUTTON_PRESS()) {
1160 DbpString("cancelled");
1161 goto done;
1162 }
1163 }
1164
1165 DbpString("in done pt");
1166
1167 DbpIntegers(maxBehindBy, Uart.state, Uart.byteCnt);
1168 DbpIntegers(Uart.byteCntMax, traceLen, 0x23);
1169
1170 done:
1171 LED_D_OFF();
1172 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
1173 }
Impressum, Datenschutz