]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iso14443.c
fix broken formatting in command table
[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 Dbprintf("button pressed, received %d commands", cmdsRecvd);
357 break;
358 }
359
360 // Good, look at the command now.
361
362 if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len)==0) {
363 resp = resp1; respLen = resp1Len;
364 } else {
365 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd);
366 // And print whether the CRC fails, just for good measure
367 ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2);
368 if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) {
369 // Not so good, try again.
370 DbpString("+++CRC fail");
371 } else {
372 DbpString("CRC passes");
373 }
374 break;
375 }
376
377 memset(receivedCmd, 0x44, 32);
378
379 cmdsRecvd++;
380
381 if(cmdsRecvd > 0x30) {
382 DbpString("many commands later...");
383 break;
384 }
385
386 if(respLen <= 0) continue;
387
388 // Modulate BPSK
389 // Signal field is off with the appropriate LED
390 LED_D_OFF();
391 FpgaWriteConfWord(
392 FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
393 AT91C_BASE_SSC->SSC_THR = 0xff;
394 FpgaSetupSsc();
395
396 // Transmit the response.
397 i = 0;
398 for(;;) {
399 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
400 BYTE b = resp[i];
401
402 AT91C_BASE_SSC->SSC_THR = b;
403
404 i++;
405 if(i > respLen) {
406 break;
407 }
408 }
409 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
410 volatile BYTE b = (BYTE)AT91C_BASE_SSC->SSC_RHR;
411 (void)b;
412 }
413 }
414 }
415 }
416
417 //=============================================================================
418 // An ISO 14443 Type B reader. We take layer two commands, code them
419 // appropriately, and then send them to the tag. We then listen for the
420 // tag's response, which we leave in the buffer to be demodulated on the
421 // PC side.
422 //=============================================================================
423
424 static struct {
425 enum {
426 DEMOD_UNSYNCD,
427 DEMOD_PHASE_REF_TRAINING,
428 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
429 DEMOD_GOT_FALLING_EDGE_OF_SOF,
430 DEMOD_AWAITING_START_BIT,
431 DEMOD_RECEIVING_DATA,
432 DEMOD_ERROR_WAIT
433 } state;
434 int bitCount;
435 int posCount;
436 int thisBit;
437 int metric;
438 int metricN;
439 WORD shiftReg;
440 BYTE *output;
441 int len;
442 int sumI;
443 int sumQ;
444 } Demod;
445
446 /*
447 * Handles reception of a bit from the tag
448 *
449 * LED handling:
450 * LED C -> ON once we have received the SOF and are expecting the rest.
451 * LED C -> OFF once we have received EOF or are unsynced
452 *
453 * Returns: true if we received a EOF
454 * false if we are still waiting for some more
455 *
456 */
457 static BOOL Handle14443SamplesDemod(int ci, int cq)
458 {
459 int v;
460
461 // The soft decision on the bit uses an estimate of just the
462 // quadrant of the reference angle, not the exact angle.
463 #define MAKE_SOFT_DECISION() { \
464 if(Demod.sumI > 0) { \
465 v = ci; \
466 } else { \
467 v = -ci; \
468 } \
469 if(Demod.sumQ > 0) { \
470 v += cq; \
471 } else { \
472 v -= cq; \
473 } \
474 }
475
476 switch(Demod.state) {
477 case DEMOD_UNSYNCD:
478 v = ci;
479 if(v < 0) v = -v;
480 if(cq > 0) {
481 v += cq;
482 } else {
483 v -= cq;
484 }
485 if(v > 40) {
486 Demod.posCount = 0;
487 Demod.state = DEMOD_PHASE_REF_TRAINING;
488 Demod.sumI = 0;
489 Demod.sumQ = 0;
490 }
491 break;
492
493 case DEMOD_PHASE_REF_TRAINING:
494 if(Demod.posCount < 8) {
495 Demod.sumI += ci;
496 Demod.sumQ += cq;
497 } else if(Demod.posCount > 100) {
498 // error, waited too long
499 Demod.state = DEMOD_UNSYNCD;
500 } else {
501 MAKE_SOFT_DECISION();
502 if(v < 0) {
503 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
504 Demod.posCount = 0;
505 }
506 }
507 Demod.posCount++;
508 break;
509
510 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
511 MAKE_SOFT_DECISION();
512 if(v < 0) {
513 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
514 Demod.posCount = 0;
515 } else {
516 if(Demod.posCount > 100) {
517 Demod.state = DEMOD_UNSYNCD;
518 }
519 }
520 Demod.posCount++;
521 break;
522
523 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
524 MAKE_SOFT_DECISION();
525 if(v > 0) {
526 if(Demod.posCount < 12) {
527 Demod.state = DEMOD_UNSYNCD;
528 } else {
529 LED_C_ON(); // Got SOF
530 Demod.state = DEMOD_AWAITING_START_BIT;
531 Demod.posCount = 0;
532 Demod.len = 0;
533 Demod.metricN = 0;
534 Demod.metric = 0;
535 }
536 } else {
537 if(Demod.posCount > 100) {
538 Demod.state = DEMOD_UNSYNCD;
539 }
540 }
541 Demod.posCount++;
542 break;
543
544 case DEMOD_AWAITING_START_BIT:
545 MAKE_SOFT_DECISION();
546 if(v > 0) {
547 if(Demod.posCount > 10) {
548 Demod.state = DEMOD_UNSYNCD;
549 }
550 } else {
551 Demod.bitCount = 0;
552 Demod.posCount = 1;
553 Demod.thisBit = v;
554 Demod.shiftReg = 0;
555 Demod.state = DEMOD_RECEIVING_DATA;
556 }
557 break;
558
559 case DEMOD_RECEIVING_DATA:
560 MAKE_SOFT_DECISION();
561 if(Demod.posCount == 0) {
562 Demod.thisBit = v;
563 Demod.posCount = 1;
564 } else {
565 Demod.thisBit += v;
566
567 if(Demod.thisBit > 0) {
568 Demod.metric += Demod.thisBit;
569 } else {
570 Demod.metric -= Demod.thisBit;
571 }
572 (Demod.metricN)++;
573
574 Demod.shiftReg >>= 1;
575 if(Demod.thisBit > 0) {
576 Demod.shiftReg |= 0x200;
577 }
578
579 Demod.bitCount++;
580 if(Demod.bitCount == 10) {
581 WORD s = Demod.shiftReg;
582 if((s & 0x200) && !(s & 0x001)) {
583 BYTE b = (s >> 1);
584 Demod.output[Demod.len] = b;
585 Demod.len++;
586 Demod.state = DEMOD_AWAITING_START_BIT;
587 } else if(s == 0x000) {
588 // This is EOF
589 LED_C_OFF();
590 return TRUE;
591 Demod.state = DEMOD_UNSYNCD;
592 } else {
593 Demod.state = DEMOD_UNSYNCD;
594 }
595 }
596 Demod.posCount = 0;
597 }
598 break;
599
600 default:
601 Demod.state = DEMOD_UNSYNCD;
602 break;
603 }
604
605 if (Demod.state == DEMOD_UNSYNCD) LED_C_OFF(); // Not synchronized...
606 return FALSE;
607 }
608
609 /*
610 * Demodulate the samples we received from the tag
611 * weTx: set to 'TRUE' if we behave like a reader
612 * set to 'FALSE' if we behave like a snooper
613 * quiet: set to 'TRUE' to disable debug output
614 */
615 static void GetSamplesFor14443Demod(BOOL weTx, int n, BOOL quiet)
616 {
617 int max = 0;
618 BOOL gotFrame = FALSE;
619
620 //# define DMA_BUFFER_SIZE 8
621 SBYTE *dmaBuf;
622
623 int lastRxCounter;
624 SBYTE *upTo;
625
626 int ci, cq;
627
628 int samples = 0;
629
630 // Clear out the state of the "UART" that receives from the tag.
631 memset(BigBuf, 0x44, 400);
632 Demod.output = (BYTE *)BigBuf;
633 Demod.len = 0;
634 Demod.state = DEMOD_UNSYNCD;
635
636 // And the UART that receives from the reader
637 Uart.output = (((BYTE *)BigBuf) + 1024);
638 Uart.byteCntMax = 100;
639 Uart.state = STATE_UNSYNCD;
640
641 // Setup for the DMA.
642 dmaBuf = (SBYTE *)(BigBuf + 32);
643 upTo = dmaBuf;
644 lastRxCounter = DMA_BUFFER_SIZE;
645 FpgaSetupSscDma((BYTE *)dmaBuf, DMA_BUFFER_SIZE);
646
647 // Signal field is ON with the appropriate LED:
648 if (weTx) LED_D_ON(); else LED_D_OFF();
649 // And put the FPGA in the appropriate mode
650 FpgaWriteConfWord(
651 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
652 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
653
654 for(;;) {
655 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
656 if(behindBy > max) max = behindBy;
657
658 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1))
659 > 2)
660 {
661 ci = upTo[0];
662 cq = upTo[1];
663 upTo += 2;
664 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
665 upTo -= DMA_BUFFER_SIZE;
666 AT91C_BASE_PDC_SSC->PDC_RNPR = (DWORD)upTo;
667 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
668 }
669 lastRxCounter -= 2;
670 if(lastRxCounter <= 0) {
671 lastRxCounter += DMA_BUFFER_SIZE;
672 }
673
674 samples += 2;
675
676 Handle14443UartBit(1);
677 Handle14443UartBit(1);
678
679 if(Handle14443SamplesDemod(ci, cq)) {
680 gotFrame = 1;
681 }
682 }
683
684 if(samples > 2000) {
685 break;
686 }
687 }
688 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
689 if (!quiet) Dbprintf("%x %x %x", max, gotFrame, Demod.len);
690 }
691
692 //-----------------------------------------------------------------------------
693 // Read the tag's response. We just receive a stream of slightly-processed
694 // samples from the FPGA, which we will later do some signal processing on,
695 // to get the bits.
696 //-----------------------------------------------------------------------------
697 /*static void GetSamplesFor14443(BOOL weTx, int n)
698 {
699 BYTE *dest = (BYTE *)BigBuf;
700 int c;
701
702 FpgaWriteConfWord(
703 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
704 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
705
706 c = 0;
707 for(;;) {
708 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
709 AT91C_BASE_SSC->SSC_THR = 0x43;
710 }
711 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
712 SBYTE b;
713 b = (SBYTE)AT91C_BASE_SSC->SSC_RHR;
714
715 dest[c++] = (BYTE)b;
716
717 if(c >= n) {
718 break;
719 }
720 }
721 }
722 }*/
723
724 //-----------------------------------------------------------------------------
725 // Transmit the command (to the tag) that was placed in ToSend[].
726 //-----------------------------------------------------------------------------
727 static void TransmitFor14443(void)
728 {
729 int c;
730
731 FpgaSetupSsc();
732
733 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
734 AT91C_BASE_SSC->SSC_THR = 0xff;
735 }
736
737 // Signal field is ON with the appropriate Red LED
738 LED_D_ON();
739 // Signal we are transmitting with the Green LED
740 LED_B_ON();
741 FpgaWriteConfWord(
742 FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
743
744 for(c = 0; c < 10;) {
745 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
746 AT91C_BASE_SSC->SSC_THR = 0xff;
747 c++;
748 }
749 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
750 volatile DWORD r = AT91C_BASE_SSC->SSC_RHR;
751 (void)r;
752 }
753 WDT_HIT();
754 }
755
756 c = 0;
757 for(;;) {
758 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
759 AT91C_BASE_SSC->SSC_THR = ToSend[c];
760 c++;
761 if(c >= ToSendMax) {
762 break;
763 }
764 }
765 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
766 volatile DWORD r = AT91C_BASE_SSC->SSC_RHR;
767 (void)r;
768 }
769 WDT_HIT();
770 }
771 LED_B_OFF(); // Finished sending
772 }
773
774 //-----------------------------------------------------------------------------
775 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
776 // so that it is ready to transmit to the tag using TransmitFor14443().
777 //-----------------------------------------------------------------------------
778 void CodeIso14443bAsReader(const BYTE *cmd, int len)
779 {
780 int i, j;
781 BYTE b;
782
783 ToSendReset();
784
785 // Establish initial reference level
786 for(i = 0; i < 40; i++) {
787 ToSendStuffBit(1);
788 }
789 // Send SOF
790 for(i = 0; i < 10; i++) {
791 ToSendStuffBit(0);
792 }
793
794 for(i = 0; i < len; i++) {
795 // Stop bits/EGT
796 ToSendStuffBit(1);
797 ToSendStuffBit(1);
798 // Start bit
799 ToSendStuffBit(0);
800 // Data bits
801 b = cmd[i];
802 for(j = 0; j < 8; j++) {
803 if(b & 1) {
804 ToSendStuffBit(1);
805 } else {
806 ToSendStuffBit(0);
807 }
808 b >>= 1;
809 }
810 }
811 // Send EOF
812 ToSendStuffBit(1);
813 for(i = 0; i < 10; i++) {
814 ToSendStuffBit(0);
815 }
816 for(i = 0; i < 8; i++) {
817 ToSendStuffBit(1);
818 }
819
820 // And then a little more, to make sure that the last character makes
821 // it out before we switch to rx mode.
822 for(i = 0; i < 24; i++) {
823 ToSendStuffBit(1);
824 }
825
826 // Convert from last character reference to length
827 ToSendMax++;
828 }
829
830 //-----------------------------------------------------------------------------
831 // Read an ISO 14443 tag. We send it some set of commands, and record the
832 // responses.
833 // The command name is misleading, it actually decodes the reponse in HEX
834 // into the output buffer (read the result using hexsamples, not hisamples)
835 //-----------------------------------------------------------------------------
836 void AcquireRawAdcSamplesIso14443(DWORD parameter)
837 {
838 BYTE cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
839
840 // Make sure that we start from off, since the tags are stateful;
841 // confusing things will happen if we don't reset them between reads.
842 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
843 LED_D_OFF();
844 SpinDelay(200);
845
846 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
847 FpgaSetupSsc();
848
849 // Now give it time to spin up.
850 // Signal field is on with the appropriate LED
851 LED_D_ON();
852 FpgaWriteConfWord(
853 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
854 SpinDelay(200);
855
856 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
857 TransmitFor14443();
858 // LED_A_ON();
859 GetSamplesFor14443Demod(TRUE, 2000, FALSE);
860 // LED_A_OFF();
861 }
862
863 //-----------------------------------------------------------------------------
864 // Read a SRI512 ISO 14443 tag.
865 //
866 // SRI512 tags are just simple memory tags, here we're looking at making a dump
867 // of the contents of the memory. No anticollision algorithm is done, we assume
868 // we have a single tag in the field.
869 //
870 // I tried to be systematic and check every answer of the tag, every CRC, etc...
871 //-----------------------------------------------------------------------------
872 void ReadSRI512Iso14443(DWORD parameter)
873 {
874 ReadSTMemoryIso14443(parameter,0x0F);
875 }
876 void ReadSRIX4KIso14443(DWORD parameter)
877 {
878 ReadSTMemoryIso14443(parameter,0x7F);
879 }
880
881 void ReadSTMemoryIso14443(DWORD parameter,DWORD dwLast)
882 {
883 BYTE i = 0x00;
884
885 // Make sure that we start from off, since the tags are stateful;
886 // confusing things will happen if we don't reset them between reads.
887 LED_D_OFF();
888 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
889 SpinDelay(200);
890
891 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
892 FpgaSetupSsc();
893
894 // Now give it time to spin up.
895 // Signal field is on with the appropriate LED
896 LED_D_ON();
897 FpgaWriteConfWord(
898 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
899 SpinDelay(200);
900
901 // First command: wake up the tag using the INITIATE command
902 BYTE cmd1[] = { 0x06, 0x00, 0x97, 0x5b};
903 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
904 TransmitFor14443();
905 // LED_A_ON();
906 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
907 // LED_A_OFF();
908
909 if (Demod.len == 0) {
910 DbpString("No response from tag");
911 return;
912 } else {
913 Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %x %x %x",
914 Demod.output[0], Demod.output[1],Demod.output[2]);
915 }
916 // There is a response, SELECT the uid
917 DbpString("Now SELECT tag:");
918 cmd1[0] = 0x0E; // 0x0E is SELECT
919 cmd1[1] = Demod.output[0];
920 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
921 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
922 TransmitFor14443();
923 // LED_A_ON();
924 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
925 // LED_A_OFF();
926 if (Demod.len != 3) {
927 Dbprintf("Expected 3 bytes from tag, got %d", Demod.len);
928 return;
929 }
930 // Check the CRC of the answer:
931 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
932 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
933 DbpString("CRC Error reading select response.");
934 return;
935 }
936 // Check response from the tag: should be the same UID as the command we just sent:
937 if (cmd1[1] != Demod.output[0]) {
938 Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1[1], Demod.output[0]);
939 return;
940 }
941 // Tag is now selected,
942 // First get the tag's UID:
943 cmd1[0] = 0x0B;
944 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
945 CodeIso14443bAsReader(cmd1, 3); // Only first three bytes for this one
946 TransmitFor14443();
947 // LED_A_ON();
948 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
949 // LED_A_OFF();
950 if (Demod.len != 10) {
951 Dbprintf("Expected 10 bytes from tag, got %d", Demod.len);
952 return;
953 }
954 // The check the CRC of the answer (use cmd1 as temporary variable):
955 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
956 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
957 Dbprintf("CRC Error reading block! - Below: expected, got %x %x",
958 (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]);
959 // Do not return;, let's go on... (we should retry, maybe ?)
960 }
961 Dbprintf("Tag UID (64 bits): %08x %08x",
962 (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4],
963 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]);
964
965 // Now loop to read all 16 blocks, address from 0 to 15
966 DbpString("Tag memory dump, block 0 to 15");
967 cmd1[0] = 0x08;
968 i = 0x00;
969 dwLast++;
970 for (;;) {
971 if (i == dwLast) {
972 DbpString("System area block (0xff):");
973 i = 0xff;
974 }
975 cmd1[1] = i;
976 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
977 CodeIso14443bAsReader(cmd1, sizeof(cmd1));
978 TransmitFor14443();
979 // LED_A_ON();
980 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
981 // LED_A_OFF();
982 if (Demod.len != 6) { // Check if we got an answer from the tag
983 DbpString("Expected 6 bytes from tag, got less...");
984 return;
985 }
986 // The check the CRC of the answer (use cmd1 as temporary variable):
987 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
988 if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
989 Dbprintf("CRC Error reading block! - Below: expected, got %x %x",
990 (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]);
991 // Do not return;, let's go on... (we should retry, maybe ?)
992 }
993 // Now print out the memory location:
994 Dbprintf("Address=%x, Contents=%x, CRC=%x", i,
995 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0],
996 (Demod.output[4]<<8)+Demod.output[5]);
997 if (i == 0xff) {
998 break;
999 }
1000 i++;
1001 }
1002 }
1003
1004
1005 //=============================================================================
1006 // Finally, the `sniffer' combines elements from both the reader and
1007 // simulated tag, to show both sides of the conversation.
1008 //=============================================================================
1009
1010 //-----------------------------------------------------------------------------
1011 // Record the sequence of commands sent by the reader to the tag, with
1012 // triggering so that we start recording at the point that the tag is moved
1013 // near the reader.
1014 //-----------------------------------------------------------------------------
1015 /*
1016 * Memory usage for this function, (within BigBuf)
1017 * 0-1023 : Demodulated samples receive (1024 bytes)
1018 * 1024-1535 : Last Received command, 512 bytes (reader->tag)
1019 * 1536-2047 : Last Received command, 512 bytes(tag->reader)
1020 * 2048-2304 : DMA Buffer, 256 bytes (samples)
1021 */
1022 void SnoopIso14443(void)
1023 {
1024 // We won't start recording the frames that we acquire until we trigger;
1025 // a good trigger condition to get started is probably when we see a
1026 // response from the tag.
1027 BOOL triggered = FALSE;
1028
1029 // The command (reader -> tag) that we're working on receiving.
1030 BYTE *receivedCmd = (BYTE *)(BigBuf) + 1024;
1031 // The response (tag -> reader) that we're working on receiving.
1032 BYTE *receivedResponse = (BYTE *)(BigBuf) + 1536;
1033
1034 // As we receive stuff, we copy it from receivedCmd or receivedResponse
1035 // into trace, along with its length and other annotations.
1036 BYTE *trace = (BYTE *)BigBuf;
1037 int traceLen = 0;
1038
1039 // The DMA buffer, used to stream samples from the FPGA.
1040 SBYTE *dmaBuf = (SBYTE *)(BigBuf) + 2048;
1041 int lastRxCounter;
1042 SBYTE *upTo;
1043 int ci, cq;
1044 int maxBehindBy = 0;
1045
1046 // Count of samples received so far, so that we can include timing
1047 // information in the trace buffer.
1048 int samples = 0;
1049
1050 // Initialize the trace buffer
1051 memset(trace, 0x44, 1024);
1052
1053 // Set up the demodulator for tag -> reader responses.
1054 Demod.output = receivedResponse;
1055 Demod.len = 0;
1056 Demod.state = DEMOD_UNSYNCD;
1057
1058 // And the reader -> tag commands
1059 memset(&Uart, 0, sizeof(Uart));
1060 Uart.output = receivedCmd;
1061 Uart.byteCntMax = 100;
1062 Uart.state = STATE_UNSYNCD;
1063
1064 // And put the FPGA in the appropriate mode
1065 // Signal field is off with the appropriate LED
1066 LED_D_OFF();
1067 FpgaWriteConfWord(
1068 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
1069 FPGA_HF_READER_RX_XCORR_SNOOP);
1070 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1071
1072 // Setup for the DMA.
1073 FpgaSetupSsc();
1074 upTo = dmaBuf;
1075 lastRxCounter = DMA_BUFFER_SIZE;
1076 FpgaSetupSscDma((BYTE *)dmaBuf, DMA_BUFFER_SIZE);
1077 // And now we loop, receiving samples.
1078 for(;;) {
1079 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
1080 (DMA_BUFFER_SIZE-1);
1081 if(behindBy > maxBehindBy) {
1082 maxBehindBy = behindBy;
1083 if(behindBy > (DMA_BUFFER_SIZE-2)) { // TODO: understand whether we can increase/decrease as we want or not?
1084 Dbprintf("blew circular buffer! behindBy=%x", behindBy);
1085 goto done;
1086 }
1087 }
1088 if(behindBy < 2) continue;
1089
1090 ci = upTo[0];
1091 cq = upTo[1];
1092 upTo += 2;
1093 lastRxCounter -= 2;
1094 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
1095 upTo -= DMA_BUFFER_SIZE;
1096 lastRxCounter += DMA_BUFFER_SIZE;
1097 AT91C_BASE_PDC_SSC->PDC_RNPR = (DWORD) upTo;
1098 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1099 }
1100
1101 samples += 2;
1102
1103 #define HANDLE_BIT_IF_BODY \
1104 if(triggered) { \
1105 trace[traceLen++] = ((samples >> 0) & 0xff); \
1106 trace[traceLen++] = ((samples >> 8) & 0xff); \
1107 trace[traceLen++] = ((samples >> 16) & 0xff); \
1108 trace[traceLen++] = ((samples >> 24) & 0xff); \
1109 trace[traceLen++] = 0; \
1110 trace[traceLen++] = 0; \
1111 trace[traceLen++] = 0; \
1112 trace[traceLen++] = 0; \
1113 trace[traceLen++] = Uart.byteCnt; \
1114 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt); \
1115 traceLen += Uart.byteCnt; \
1116 if(traceLen > 1000) break; \
1117 } \
1118 /* And ready to receive another command. */ \
1119 memset(&Uart, 0, sizeof(Uart)); \
1120 Uart.output = receivedCmd; \
1121 Uart.byteCntMax = 100; \
1122 Uart.state = STATE_UNSYNCD; \
1123 /* And also reset the demod code, which might have been */ \
1124 /* false-triggered by the commands from the reader. */ \
1125 memset(&Demod, 0, sizeof(Demod)); \
1126 Demod.output = receivedResponse; \
1127 Demod.state = DEMOD_UNSYNCD; \
1128
1129 if(Handle14443UartBit(ci & 1)) {
1130 HANDLE_BIT_IF_BODY
1131 }
1132 if(Handle14443UartBit(cq & 1)) {
1133 HANDLE_BIT_IF_BODY
1134 }
1135
1136 if(Handle14443SamplesDemod(ci, cq)) {
1137 // timestamp, as a count of samples
1138 trace[traceLen++] = ((samples >> 0) & 0xff);
1139 trace[traceLen++] = ((samples >> 8) & 0xff);
1140 trace[traceLen++] = ((samples >> 16) & 0xff);
1141 trace[traceLen++] = 0x80 | ((samples >> 24) & 0xff);
1142 // correlation metric (~signal strength estimate)
1143 if(Demod.metricN != 0) {
1144 Demod.metric /= Demod.metricN;
1145 }
1146 trace[traceLen++] = ((Demod.metric >> 0) & 0xff);
1147 trace[traceLen++] = ((Demod.metric >> 8) & 0xff);
1148 trace[traceLen++] = ((Demod.metric >> 16) & 0xff);
1149 trace[traceLen++] = ((Demod.metric >> 24) & 0xff);
1150 // length
1151 trace[traceLen++] = Demod.len;
1152 memcpy(trace+traceLen, receivedResponse, Demod.len);
1153 traceLen += Demod.len;
1154 if(traceLen > 1000) break;
1155
1156 triggered = TRUE;
1157
1158 // And ready to receive another response.
1159 memset(&Demod, 0, sizeof(Demod));
1160 Demod.output = receivedResponse;
1161 Demod.state = DEMOD_UNSYNCD;
1162 }
1163 WDT_HIT();
1164
1165 if(BUTTON_PRESS()) {
1166 DbpString("cancelled");
1167 goto done;
1168 }
1169 }
1170
1171 DbpString("in done pt");
1172 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
1173 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, 0x23);
1174
1175 done:
1176 LED_D_OFF();
1177 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
1178 }
Impressum, Datenschutz