]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iso14443.c
fbc3a6d40009b1eca639705548704e613df0412b
[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 ReadSTMemoryIso14443(parameter,0x0F);
877 }
878 void ReadSRIX4KIso14443(DWORD parameter)
879 {
880 ReadSTMemoryIso14443(parameter,0x7F);
881 }
882
883 void ReadSTMemoryIso14443(DWORD parameter,DWORD dwLast)
884 {
885 BYTE i = 0x00;
886
887 // Make sure that we start from off, since the tags are stateful;
888 // confusing things will happen if we don't reset them between reads.
889 LED_D_OFF();
890 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
891 SpinDelay(200);
892
893 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
894 FpgaSetupSsc();
895
896 // Now give it time to spin up.
897 // Signal field is on with the appropriate LED
898 LED_D_ON();
899 FpgaWriteConfWord(
900 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
901 SpinDelay(200);
902
903 // First command: wake up the tag using the INITIATE command
904 BYTE cmd1[] = { 0x06, 0x00, 0x97, 0x5b};
905 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
906 TransmitFor14443();
907 // LED_A_ON();
908 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
909 // LED_A_OFF();
910
911 if (Demod.len == 0) {
912 DbpString("No response from tag");
913 return;
914 } else {
915 DbpString("Randomly generated UID from tag (+ 2 byte CRC):");
916 DbpIntegers(Demod.output[0], Demod.output[1],Demod.output[2]);
917 }
918 // There is a response, SELECT the uid
919 DbpString("Now SELECT tag:");
920 cmd1[0] = 0x0E; // 0x0E is SELECT
921 cmd1[1] = Demod.output[0];
922 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
923 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
924 TransmitFor14443();
925 // LED_A_ON();
926 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
927 // LED_A_OFF();
928 if (Demod.len != 3) {
929 DbpString("Expected 3 bytes from tag, got:");
930 DbpIntegers(Demod.len,0x0,0x0);
931 return;
932 }
933 // Check the CRC of the answer:
934 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
935 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
936 DbpString("CRC Error reading select response.");
937 return;
938 }
939 // Check response from the tag: should be the same UID as the command we just sent:
940 if (cmd1[1] != Demod.output[0]) {
941 DbpString("Bad response to SELECT from Tag, aborting:");
942 DbpIntegers(cmd1[1],Demod.output[0],0x0);
943 return;
944 }
945 // Tag is now selected,
946 // First get the tag's UID:
947 cmd1[0] = 0x0B;
948 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
949 CodeIso14443bAsReader(cmd1, 3); // Only first three bytes for this one
950 TransmitFor14443();
951 // LED_A_ON();
952 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
953 // LED_A_OFF();
954 if (Demod.len != 10) {
955 DbpString("Expected 10 bytes from tag, got:");
956 DbpIntegers(Demod.len,0x0,0x0);
957 return;
958 }
959 // The check the CRC of the answer (use cmd1 as temporary variable):
960 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
961 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
962 DbpString("CRC Error reading block! - Below: expected, got");
963 DbpIntegers( (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9],0);
964 // Do not return;, let's go on... (we should retry, maybe ?)
965 }
966 DbpString("Tag UID (64 bits):");
967 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);
968
969 // Now loop to read all 16 blocks, address from 0 to 15
970 DbpString("Tag memory dump, block 0 to 15");
971 cmd1[0] = 0x08;
972 i = 0x00;
973 dwLast++;
974 for (;;) {
975 if (i == dwLast) {
976 DbpString("System area block (0xff):");
977 i = 0xff;
978 }
979 cmd1[1] = i;
980 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
981 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
982 TransmitFor14443();
983 // LED_A_ON();
984 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
985 // LED_A_OFF();
986 if (Demod.len != 6) { // Check if we got an answer from the tag
987 DbpString("Expected 6 bytes from tag, got less...");
988 return;
989 }
990 // The check the CRC of the answer (use cmd1 as temporary variable):
991 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
992 if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
993 DbpString("CRC Error reading block! - Below: expected, got");
994 DbpIntegers( (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5],0);
995 // Do not return;, let's go on... (we should retry, maybe ?)
996 }
997 // Now print out the memory location:
998 DbpString("Address , Contents, CRC");
999 DbpIntegers(i, (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], (Demod.output[4]<<8)+Demod.output[5]);
1000 if (i == 0xff) {
1001 break;
1002 }
1003 i++;
1004 }
1005 }
1006
1007
1008 //=============================================================================
1009 // Finally, the `sniffer' combines elements from both the reader and
1010 // simulated tag, to show both sides of the conversation.
1011 //=============================================================================
1012
1013 //-----------------------------------------------------------------------------
1014 // Record the sequence of commands sent by the reader to the tag, with
1015 // triggering so that we start recording at the point that the tag is moved
1016 // near the reader.
1017 //-----------------------------------------------------------------------------
1018 /*
1019 * Memory usage for this function, (within BigBuf)
1020 * 0-1023 : Demodulated samples receive (1024 bytes)
1021 * 1024-1535 : Last Received command, 512 bytes (reader->tag)
1022 * 1536-2047 : Last Received command, 512 bytes(tag->reader)
1023 * 2048-2304 : DMA Buffer, 256 bytes (samples)
1024 */
1025 void SnoopIso14443(void)
1026 {
1027 // We won't start recording the frames that we acquire until we trigger;
1028 // a good trigger condition to get started is probably when we see a
1029 // response from the tag.
1030 BOOL triggered = FALSE;
1031
1032 // The command (reader -> tag) that we're working on receiving.
1033 BYTE *receivedCmd = (BYTE *)(BigBuf) + 1024;
1034 // The response (tag -> reader) that we're working on receiving.
1035 BYTE *receivedResponse = (BYTE *)(BigBuf) + 1536;
1036
1037 // As we receive stuff, we copy it from receivedCmd or receivedResponse
1038 // into trace, along with its length and other annotations.
1039 BYTE *trace = (BYTE *)BigBuf;
1040 int traceLen = 0;
1041
1042 // The DMA buffer, used to stream samples from the FPGA.
1043 SBYTE *dmaBuf = (SBYTE *)(BigBuf) + 2048;
1044 int lastRxCounter;
1045 SBYTE *upTo;
1046 int ci, cq;
1047 int maxBehindBy = 0;
1048
1049 // Count of samples received so far, so that we can include timing
1050 // information in the trace buffer.
1051 int samples = 0;
1052
1053 // Initialize the trace buffer
1054 memset(trace, 0x44, 1024);
1055
1056 // Set up the demodulator for tag -> reader responses.
1057 Demod.output = receivedResponse;
1058 Demod.len = 0;
1059 Demod.state = DEMOD_UNSYNCD;
1060
1061 // And the reader -> tag commands
1062 memset(&Uart, 0, sizeof(Uart));
1063 Uart.output = receivedCmd;
1064 Uart.byteCntMax = 100;
1065 Uart.state = STATE_UNSYNCD;
1066
1067 // And put the FPGA in the appropriate mode
1068 // Signal field is off with the appropriate LED
1069 LED_D_OFF();
1070 FpgaWriteConfWord(
1071 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
1072 FPGA_HF_READER_RX_XCORR_SNOOP);
1073 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1074
1075 // Setup for the DMA.
1076 FpgaSetupSsc();
1077 upTo = dmaBuf;
1078 lastRxCounter = DMA_BUFFER_SIZE;
1079 FpgaSetupSscDma((BYTE *)dmaBuf, DMA_BUFFER_SIZE);
1080 // And now we loop, receiving samples.
1081 for(;;) {
1082 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
1083 (DMA_BUFFER_SIZE-1);
1084 if(behindBy > maxBehindBy) {
1085 maxBehindBy = behindBy;
1086 if(behindBy > (DMA_BUFFER_SIZE-2)) { // TODO: understand whether we can increase/decrease as we want or not?
1087 DbpString("blew circular buffer!");
1088 DbpIntegers(behindBy,0,0);
1089 goto done;
1090 }
1091 }
1092 if(behindBy < 2) continue;
1093
1094 ci = upTo[0];
1095 cq = upTo[1];
1096 upTo += 2;
1097 lastRxCounter -= 2;
1098 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
1099 upTo -= DMA_BUFFER_SIZE;
1100 lastRxCounter += DMA_BUFFER_SIZE;
1101 AT91C_BASE_PDC_SSC->PDC_RNPR = (DWORD) upTo;
1102 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1103 }
1104
1105 samples += 2;
1106
1107 #define HANDLE_BIT_IF_BODY \
1108 if(triggered) { \
1109 trace[traceLen++] = ((samples >> 0) & 0xff); \
1110 trace[traceLen++] = ((samples >> 8) & 0xff); \
1111 trace[traceLen++] = ((samples >> 16) & 0xff); \
1112 trace[traceLen++] = ((samples >> 24) & 0xff); \
1113 trace[traceLen++] = 0; \
1114 trace[traceLen++] = 0; \
1115 trace[traceLen++] = 0; \
1116 trace[traceLen++] = 0; \
1117 trace[traceLen++] = Uart.byteCnt; \
1118 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt); \
1119 traceLen += Uart.byteCnt; \
1120 if(traceLen > 1000) break; \
1121 } \
1122 /* And ready to receive another command. */ \
1123 memset(&Uart, 0, sizeof(Uart)); \
1124 Uart.output = receivedCmd; \
1125 Uart.byteCntMax = 100; \
1126 Uart.state = STATE_UNSYNCD; \
1127 /* And also reset the demod code, which might have been */ \
1128 /* false-triggered by the commands from the reader. */ \
1129 memset(&Demod, 0, sizeof(Demod)); \
1130 Demod.output = receivedResponse; \
1131 Demod.state = DEMOD_UNSYNCD; \
1132
1133 if(Handle14443UartBit(ci & 1)) {
1134 HANDLE_BIT_IF_BODY
1135 }
1136 if(Handle14443UartBit(cq & 1)) {
1137 HANDLE_BIT_IF_BODY
1138 }
1139
1140 if(Handle14443SamplesDemod(ci, cq)) {
1141 // timestamp, as a count of samples
1142 trace[traceLen++] = ((samples >> 0) & 0xff);
1143 trace[traceLen++] = ((samples >> 8) & 0xff);
1144 trace[traceLen++] = ((samples >> 16) & 0xff);
1145 trace[traceLen++] = 0x80 | ((samples >> 24) & 0xff);
1146 // correlation metric (~signal strength estimate)
1147 if(Demod.metricN != 0) {
1148 Demod.metric /= Demod.metricN;
1149 }
1150 trace[traceLen++] = ((Demod.metric >> 0) & 0xff);
1151 trace[traceLen++] = ((Demod.metric >> 8) & 0xff);
1152 trace[traceLen++] = ((Demod.metric >> 16) & 0xff);
1153 trace[traceLen++] = ((Demod.metric >> 24) & 0xff);
1154 // length
1155 trace[traceLen++] = Demod.len;
1156 memcpy(trace+traceLen, receivedResponse, Demod.len);
1157 traceLen += Demod.len;
1158 if(traceLen > 1000) break;
1159
1160 triggered = TRUE;
1161
1162 // And ready to receive another response.
1163 memset(&Demod, 0, sizeof(Demod));
1164 Demod.output = receivedResponse;
1165 Demod.state = DEMOD_UNSYNCD;
1166 }
1167 WDT_HIT();
1168
1169 if(BUTTON_PRESS()) {
1170 DbpString("cancelled");
1171 goto done;
1172 }
1173 }
1174
1175 DbpString("in done pt");
1176
1177 DbpIntegers(maxBehindBy, Uart.state, Uart.byteCnt);
1178 DbpIntegers(Uart.byteCntMax, traceLen, 0x23);
1179
1180 done:
1181 LED_D_OFF();
1182 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
1183 }
Impressum, Datenschutz