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