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