Merge pull request #108 from p-l-/fix-hf-mf-csave
[legacy-proxmark3.git] / armsrc / iso14443.c
blobc7f49f14059293dc46e5a8c845175b5c03d8e6a9
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 //-----------------------------------------------------------------------------
13 #include "proxmark3.h"
14 #include "apps.h"
15 #include "util.h"
16 #include "string.h"
18 #include "iso14443crc.h"
20 //static void GetSamplesFor14443(int weTx, int n);
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
27 //=============================================================================
28 // An ISO 14443 Type B tag. We listen for commands from the reader, using
29 // a UART kind of thing that's implemented in software. When we get a
30 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
31 // If it's good, then we can do something appropriate with it, and send
32 // a response.
33 //=============================================================================
35 //-----------------------------------------------------------------------------
36 // Code up a string of octets at layer 2 (including CRC, we don't generate
37 // that here) so that they can be transmitted to the reader. Doesn't transmit
38 // them yet, just leaves them ready to send in ToSend[].
39 //-----------------------------------------------------------------------------
40 static void CodeIso14443bAsTag(const uint8_t *cmd, int len)
42 int i;
44 ToSendReset();
46 // Transmit a burst of ones, as the initial thing that lets the
47 // reader get phase sync. This (TR1) must be > 80/fs, per spec,
48 // but tag that I've tried (a Paypass) exceeds that by a fair bit,
49 // so I will too.
50 for(i = 0; i < 20; i++) {
51 ToSendStuffBit(1);
52 ToSendStuffBit(1);
53 ToSendStuffBit(1);
54 ToSendStuffBit(1);
57 // Send SOF.
58 for(i = 0; i < 10; i++) {
59 ToSendStuffBit(0);
60 ToSendStuffBit(0);
61 ToSendStuffBit(0);
62 ToSendStuffBit(0);
64 for(i = 0; i < 2; i++) {
65 ToSendStuffBit(1);
66 ToSendStuffBit(1);
67 ToSendStuffBit(1);
68 ToSendStuffBit(1);
71 for(i = 0; i < len; i++) {
72 int j;
73 uint8_t b = cmd[i];
75 // Start bit
76 ToSendStuffBit(0);
77 ToSendStuffBit(0);
78 ToSendStuffBit(0);
79 ToSendStuffBit(0);
81 // Data bits
82 for(j = 0; j < 8; j++) {
83 if(b & 1) {
84 ToSendStuffBit(1);
85 ToSendStuffBit(1);
86 ToSendStuffBit(1);
87 ToSendStuffBit(1);
88 } else {
89 ToSendStuffBit(0);
90 ToSendStuffBit(0);
91 ToSendStuffBit(0);
92 ToSendStuffBit(0);
94 b >>= 1;
97 // Stop bit
98 ToSendStuffBit(1);
99 ToSendStuffBit(1);
100 ToSendStuffBit(1);
101 ToSendStuffBit(1);
104 // Send SOF.
105 for(i = 0; i < 10; i++) {
106 ToSendStuffBit(0);
107 ToSendStuffBit(0);
108 ToSendStuffBit(0);
109 ToSendStuffBit(0);
111 for(i = 0; i < 10; i++) {
112 ToSendStuffBit(1);
113 ToSendStuffBit(1);
114 ToSendStuffBit(1);
115 ToSendStuffBit(1);
118 // Convert from last byte pos to length
119 ToSendMax++;
121 // Add a few more for slop
122 ToSendMax += 2;
125 //-----------------------------------------------------------------------------
126 // The software UART that receives commands from the reader, and its state
127 // variables.
128 //-----------------------------------------------------------------------------
129 static struct {
130 enum {
131 STATE_UNSYNCD,
132 STATE_GOT_FALLING_EDGE_OF_SOF,
133 STATE_AWAITING_START_BIT,
134 STATE_RECEIVING_DATA,
135 STATE_ERROR_WAIT
136 } state;
137 uint16_t shiftReg;
138 int bitCnt;
139 int byteCnt;
140 int byteCntMax;
141 int posCnt;
142 uint8_t *output;
143 } Uart;
145 /* Receive & handle a bit coming from the reader.
147 * LED handling:
148 * LED A -> ON once we have received the SOF and are expecting the rest.
149 * LED A -> OFF once we have received EOF or are in error state or unsynced
151 * Returns: true if we received a EOF
152 * false if we are still waiting for some more
154 static int Handle14443UartBit(int bit)
156 switch(Uart.state) {
157 case STATE_UNSYNCD:
158 LED_A_OFF();
159 if(!bit) {
160 // we went low, so this could be the beginning
161 // of an SOF
162 Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
163 Uart.posCnt = 0;
164 Uart.bitCnt = 0;
166 break;
168 case STATE_GOT_FALLING_EDGE_OF_SOF:
169 Uart.posCnt++;
170 if(Uart.posCnt == 2) {
171 if(bit) {
172 if(Uart.bitCnt >= 10) {
173 // we've seen enough consecutive
174 // zeros that it's a valid SOF
175 Uart.posCnt = 0;
176 Uart.byteCnt = 0;
177 Uart.state = STATE_AWAITING_START_BIT;
178 LED_A_ON(); // Indicate we got a valid SOF
179 } else {
180 // didn't stay down long enough
181 // before going high, error
182 Uart.state = STATE_ERROR_WAIT;
184 } else {
185 // do nothing, keep waiting
187 Uart.bitCnt++;
189 if(Uart.posCnt >= 4) Uart.posCnt = 0;
190 if(Uart.bitCnt > 14) {
191 // Give up if we see too many zeros without
192 // a one, too.
193 Uart.state = STATE_ERROR_WAIT;
195 break;
197 case STATE_AWAITING_START_BIT:
198 Uart.posCnt++;
199 if(bit) {
200 if(Uart.posCnt > 25) {
201 // stayed high for too long between
202 // characters, error
203 Uart.state = STATE_ERROR_WAIT;
205 } else {
206 // falling edge, this starts the data byte
207 Uart.posCnt = 0;
208 Uart.bitCnt = 0;
209 Uart.shiftReg = 0;
210 Uart.state = STATE_RECEIVING_DATA;
211 LED_A_ON(); // Indicate we're receiving
213 break;
215 case STATE_RECEIVING_DATA:
216 Uart.posCnt++;
217 if(Uart.posCnt == 2) {
218 // time to sample a bit
219 Uart.shiftReg >>= 1;
220 if(bit) {
221 Uart.shiftReg |= 0x200;
223 Uart.bitCnt++;
225 if(Uart.posCnt >= 4) {
226 Uart.posCnt = 0;
228 if(Uart.bitCnt == 10) {
229 if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
231 // this is a data byte, with correct
232 // start and stop bits
233 Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
234 Uart.byteCnt++;
236 if(Uart.byteCnt >= Uart.byteCntMax) {
237 // Buffer overflowed, give up
238 Uart.posCnt = 0;
239 Uart.state = STATE_ERROR_WAIT;
240 } else {
241 // so get the next byte now
242 Uart.posCnt = 0;
243 Uart.state = STATE_AWAITING_START_BIT;
245 } else if(Uart.shiftReg == 0x000) {
246 // this is an EOF byte
247 LED_A_OFF(); // Finished receiving
248 return TRUE;
249 } else {
250 // this is an error
251 Uart.posCnt = 0;
252 Uart.state = STATE_ERROR_WAIT;
255 break;
257 case STATE_ERROR_WAIT:
258 // We're all screwed up, so wait a little while
259 // for whatever went wrong to finish, and then
260 // start over.
261 Uart.posCnt++;
262 if(Uart.posCnt > 10) {
263 Uart.state = STATE_UNSYNCD;
265 break;
267 default:
268 Uart.state = STATE_UNSYNCD;
269 break;
272 // This row make the error blew circular buffer in hf 14b snoop
273 //if (Uart.state == STATE_ERROR_WAIT) LED_A_OFF(); // Error
275 return FALSE;
278 //-----------------------------------------------------------------------------
279 // Receive a command (from the reader to us, where we are the simulated tag),
280 // and store it in the given buffer, up to the given maximum length. Keeps
281 // spinning, waiting for a well-framed command, until either we get one
282 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
284 // Assume that we're called with the SSC (to the FPGA) and ADC path set
285 // correctly.
286 //-----------------------------------------------------------------------------
287 static int GetIso14443CommandFromReader(uint8_t *received, int *len, int maxLen)
289 uint8_t mask;
290 int i, bit;
292 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
293 // only, since we are receiving, not transmitting).
294 // Signal field is off with the appropriate LED
295 LED_D_OFF();
296 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
299 // Now run a `software UART' on the stream of incoming samples.
300 Uart.output = received;
301 Uart.byteCntMax = maxLen;
302 Uart.state = STATE_UNSYNCD;
304 for(;;) {
305 WDT_HIT();
307 if(BUTTON_PRESS()) return FALSE;
309 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
310 AT91C_BASE_SSC->SSC_THR = 0x00;
312 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
313 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
315 mask = 0x80;
316 for(i = 0; i < 8; i++, mask >>= 1) {
317 bit = (b & mask);
318 if(Handle14443UartBit(bit)) {
319 *len = Uart.byteCnt;
320 return TRUE;
327 //-----------------------------------------------------------------------------
328 // Main loop of simulated tag: receive commands from reader, decide what
329 // response to send, and send it.
330 //-----------------------------------------------------------------------------
331 void SimulateIso14443Tag(void)
333 static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
334 static const uint8_t response1[] = {
335 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22,
336 0x00, 0x21, 0x85, 0x5e, 0xd7
339 uint8_t *resp;
340 int respLen;
342 uint8_t *resp1 = BigBuf_get_addr() + 800;
343 int resp1Len;
345 uint8_t *receivedCmd = BigBuf_get_addr();
346 int len;
348 int i;
350 int cmdsRecvd = 0;
352 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
353 memset(receivedCmd, 0x44, 400);
355 CodeIso14443bAsTag(response1, sizeof(response1));
356 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
358 // We need to listen to the high-frequency, peak-detected path.
359 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
360 FpgaSetupSsc();
362 cmdsRecvd = 0;
364 for(;;) {
365 uint8_t b1, b2;
367 if(!GetIso14443CommandFromReader(receivedCmd, &len, 100)) {
368 Dbprintf("button pressed, received %d commands", cmdsRecvd);
369 break;
372 // Good, look at the command now.
374 if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len)==0) {
375 resp = resp1; respLen = resp1Len;
376 } else {
377 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd);
378 // And print whether the CRC fails, just for good measure
379 ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2);
380 if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) {
381 // Not so good, try again.
382 DbpString("+++CRC fail");
383 } else {
384 DbpString("CRC passes");
386 break;
389 memset(receivedCmd, 0x44, 32);
391 cmdsRecvd++;
393 if(cmdsRecvd > 0x30) {
394 DbpString("many commands later...");
395 break;
398 if(respLen <= 0) continue;
400 // Modulate BPSK
401 // Signal field is off with the appropriate LED
402 LED_D_OFF();
403 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
404 AT91C_BASE_SSC->SSC_THR = 0xff;
405 FpgaSetupSsc();
407 // Transmit the response.
408 i = 0;
409 for(;;) {
410 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
411 uint8_t b = resp[i];
413 AT91C_BASE_SSC->SSC_THR = b;
415 i++;
416 if(i > respLen) {
417 break;
420 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
421 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
422 (void)b;
428 //=============================================================================
429 // An ISO 14443 Type B reader. We take layer two commands, code them
430 // appropriately, and then send them to the tag. We then listen for the
431 // tag's response, which we leave in the buffer to be demodulated on the
432 // PC side.
433 //=============================================================================
435 static struct {
436 enum {
437 DEMOD_UNSYNCD,
438 DEMOD_PHASE_REF_TRAINING,
439 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
440 DEMOD_GOT_FALLING_EDGE_OF_SOF,
441 DEMOD_AWAITING_START_BIT,
442 DEMOD_RECEIVING_DATA,
443 DEMOD_ERROR_WAIT
444 } state;
445 int bitCount;
446 int posCount;
447 int thisBit;
448 int metric;
449 int metricN;
450 uint16_t shiftReg;
451 uint8_t *output;
452 int len;
453 int sumI;
454 int sumQ;
455 } Demod;
458 * Handles reception of a bit from the tag
460 * LED handling:
461 * LED C -> ON once we have received the SOF and are expecting the rest.
462 * LED C -> OFF once we have received EOF or are unsynced
464 * Returns: true if we received a EOF
465 * false if we are still waiting for some more
468 static RAMFUNC int Handle14443SamplesDemod(int ci, int cq)
470 int v;
472 // The soft decision on the bit uses an estimate of just the
473 // quadrant of the reference angle, not the exact angle.
474 #define MAKE_SOFT_DECISION() { \
475 if(Demod.sumI > 0) { \
476 v = ci; \
477 } else { \
478 v = -ci; \
480 if(Demod.sumQ > 0) { \
481 v += cq; \
482 } else { \
483 v -= cq; \
487 switch(Demod.state) {
488 case DEMOD_UNSYNCD:
489 v = ci;
490 if(v < 0) v = -v;
491 if(cq > 0) {
492 v += cq;
493 } else {
494 v -= cq;
496 if(v > 40) {
497 Demod.posCount = 0;
498 Demod.state = DEMOD_PHASE_REF_TRAINING;
499 Demod.sumI = 0;
500 Demod.sumQ = 0;
502 break;
504 case DEMOD_PHASE_REF_TRAINING:
505 if(Demod.posCount < 8) {
506 Demod.sumI += ci;
507 Demod.sumQ += cq;
508 } else if(Demod.posCount > 100) {
509 // error, waited too long
510 Demod.state = DEMOD_UNSYNCD;
511 } else {
512 MAKE_SOFT_DECISION();
513 if(v < 0) {
514 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
515 Demod.posCount = 0;
518 Demod.posCount++;
519 break;
521 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
522 MAKE_SOFT_DECISION();
523 if(v < 0) {
524 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
525 Demod.posCount = 0;
526 } else {
527 if(Demod.posCount > 100) {
528 Demod.state = DEMOD_UNSYNCD;
531 Demod.posCount++;
532 break;
534 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
535 MAKE_SOFT_DECISION();
536 if(v > 0) {
537 if(Demod.posCount < 12) {
538 Demod.state = DEMOD_UNSYNCD;
539 } else {
540 LED_C_ON(); // Got SOF
541 Demod.state = DEMOD_AWAITING_START_BIT;
542 Demod.posCount = 0;
543 Demod.len = 0;
544 Demod.metricN = 0;
545 Demod.metric = 0;
547 } else {
548 if(Demod.posCount > 100) {
549 Demod.state = DEMOD_UNSYNCD;
552 Demod.posCount++;
553 break;
555 case DEMOD_AWAITING_START_BIT:
556 MAKE_SOFT_DECISION();
557 if(v > 0) {
558 if(Demod.posCount > 10) {
559 Demod.state = DEMOD_UNSYNCD;
561 } else {
562 Demod.bitCount = 0;
563 Demod.posCount = 1;
564 Demod.thisBit = v;
565 Demod.shiftReg = 0;
566 Demod.state = DEMOD_RECEIVING_DATA;
568 break;
570 case DEMOD_RECEIVING_DATA:
571 MAKE_SOFT_DECISION();
572 if(Demod.posCount == 0) {
573 Demod.thisBit = v;
574 Demod.posCount = 1;
575 } else {
576 Demod.thisBit += v;
578 if(Demod.thisBit > 0) {
579 Demod.metric += Demod.thisBit;
580 } else {
581 Demod.metric -= Demod.thisBit;
583 (Demod.metricN)++;
585 Demod.shiftReg >>= 1;
586 if(Demod.thisBit > 0) {
587 Demod.shiftReg |= 0x200;
590 Demod.bitCount++;
591 if(Demod.bitCount == 10) {
592 uint16_t s = Demod.shiftReg;
593 if((s & 0x200) && !(s & 0x001)) {
594 uint8_t b = (s >> 1);
595 Demod.output[Demod.len] = b;
596 Demod.len++;
597 Demod.state = DEMOD_AWAITING_START_BIT;
598 } else if(s == 0x000) {
599 // This is EOF
600 LED_C_OFF();
601 Demod.state = DEMOD_UNSYNCD;
602 return TRUE;
603 } else {
604 Demod.state = DEMOD_UNSYNCD;
607 Demod.posCount = 0;
609 break;
611 default:
612 Demod.state = DEMOD_UNSYNCD;
613 break;
616 if (Demod.state == DEMOD_UNSYNCD) LED_C_OFF(); // Not synchronized...
617 return FALSE;
619 static void DemodReset()
621 // Clear out the state of the "UART" that receives from the tag.
622 Demod.len = 0;
623 Demod.state = DEMOD_UNSYNCD;
624 memset(Demod.output, 0x00, MAX_FRAME_SIZE);
626 static void DemodInit(uint8_t *data)
628 Demod.output = data;
629 DemodReset();
632 static void UartReset()
634 Uart.byteCntMax = MAX_FRAME_SIZE;
635 Uart.state = STATE_UNSYNCD;
636 Uart.byteCnt = 0;
637 Uart.bitCnt = 0;
639 static void UartInit(uint8_t *data)
641 Uart.output = data;
642 UartReset();
646 * Demodulate the samples we received from the tag, also log to tracebuffer
647 * weTx: set to 'TRUE' if we behave like a reader
648 * set to 'FALSE' if we behave like a snooper
649 * quiet: set to 'TRUE' to disable debug output
651 static void GetSamplesFor14443Demod(int weTx, int n, int quiet)
653 int max = 0;
654 int gotFrame = FALSE;
655 int lastRxCounter, ci, cq, samples = 0;
657 // Allocate memory from BigBuf for some buffers
658 // free all previous allocations first
659 BigBuf_free();
661 // The command (reader -> tag) that we're receiving.
662 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
664 // The response (tag -> reader) that we're receiving.
665 uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE);
667 // The DMA buffer, used to stream samples from the FPGA
668 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
670 // Set up the demodulator for tag -> reader responses.
671 DemodInit(receivedResponse);
672 // Set up the demodulator for the reader -> tag commands
673 UartInit(receivedCmd);
675 // Setup and start DMA.
676 FpgaSetupSscDma(dmaBuf, DMA_BUFFER_SIZE);
678 uint8_t *upTo= dmaBuf;
679 lastRxCounter = DMA_BUFFER_SIZE;
681 // Signal field is ON with the appropriate LED:
682 if (weTx) LED_D_ON(); else LED_D_OFF();
683 // And put the FPGA in the appropriate mode
684 FpgaWriteConfWord(
685 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
686 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
688 for(;;) {
689 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
690 if(behindBy > max) max = behindBy;
692 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1))
693 > 2)
695 ci = upTo[0];
696 cq = upTo[1];
697 upTo += 2;
698 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
699 upTo -= DMA_BUFFER_SIZE;
700 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
701 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
703 lastRxCounter -= 2;
704 if(lastRxCounter <= 0) {
705 lastRxCounter += DMA_BUFFER_SIZE;
708 samples += 2;
710 Handle14443UartBit(1);
711 Handle14443UartBit(1);
713 if(Handle14443SamplesDemod(ci, cq)) {
714 gotFrame = 1;
718 if(samples > 2000) {
719 break;
722 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
723 if (!quiet) Dbprintf("%x %x %x", max, gotFrame, Demod.len);
724 //Tracing
725 if (tracing && Demod.len > 0) {
726 uint8_t parity[MAX_PARITY_SIZE];
727 GetParity(Demod.output , Demod.len, parity);
728 LogTrace(Demod.output,Demod.len, 0, 0, parity, FALSE);
732 //-----------------------------------------------------------------------------
733 // Read the tag's response. We just receive a stream of slightly-processed
734 // samples from the FPGA, which we will later do some signal processing on,
735 // to get the bits.
736 //-----------------------------------------------------------------------------
737 /*static void GetSamplesFor14443(int weTx, int n)
739 uint8_t *dest = (uint8_t *)BigBuf;
740 int c;
742 FpgaWriteConfWord(
743 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
744 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
746 c = 0;
747 for(;;) {
748 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
749 AT91C_BASE_SSC->SSC_THR = 0x43;
751 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
752 int8_t b;
753 b = (int8_t)AT91C_BASE_SSC->SSC_RHR;
755 dest[c++] = (uint8_t)b;
757 if(c >= n) {
758 break;
764 //-----------------------------------------------------------------------------
765 // Transmit the command (to the tag) that was placed in ToSend[].
766 //-----------------------------------------------------------------------------
767 static void TransmitFor14443(void)
769 int c;
771 FpgaSetupSsc();
773 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
774 AT91C_BASE_SSC->SSC_THR = 0xff;
777 // Signal field is ON with the appropriate Red LED
778 LED_D_ON();
779 // Signal we are transmitting with the Green LED
780 LED_B_ON();
781 FpgaWriteConfWord(
782 FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
784 for(c = 0; c < 10;) {
785 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
786 AT91C_BASE_SSC->SSC_THR = 0xff;
787 c++;
789 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
790 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
791 (void)r;
793 WDT_HIT();
796 c = 0;
797 for(;;) {
798 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
799 AT91C_BASE_SSC->SSC_THR = ToSend[c];
800 c++;
801 if(c >= ToSendMax) {
802 break;
805 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
806 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
807 (void)r;
809 WDT_HIT();
811 LED_B_OFF(); // Finished sending
814 //-----------------------------------------------------------------------------
815 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
816 // so that it is ready to transmit to the tag using TransmitFor14443().
817 //-----------------------------------------------------------------------------
818 static void CodeIso14443bAsReader(const uint8_t *cmd, int len)
820 int i, j;
821 uint8_t b;
823 ToSendReset();
825 // Establish initial reference level
826 for(i = 0; i < 40; i++) {
827 ToSendStuffBit(1);
829 // Send SOF
830 for(i = 0; i < 10; i++) {
831 ToSendStuffBit(0);
834 for(i = 0; i < len; i++) {
835 // Stop bits/EGT
836 ToSendStuffBit(1);
837 ToSendStuffBit(1);
838 // Start bit
839 ToSendStuffBit(0);
840 // Data bits
841 b = cmd[i];
842 for(j = 0; j < 8; j++) {
843 if(b & 1) {
844 ToSendStuffBit(1);
845 } else {
846 ToSendStuffBit(0);
848 b >>= 1;
851 // Send EOF
852 ToSendStuffBit(1);
853 for(i = 0; i < 10; i++) {
854 ToSendStuffBit(0);
856 for(i = 0; i < 8; i++) {
857 ToSendStuffBit(1);
860 // And then a little more, to make sure that the last character makes
861 // it out before we switch to rx mode.
862 for(i = 0; i < 24; i++) {
863 ToSendStuffBit(1);
866 // Convert from last character reference to length
867 ToSendMax++;
870 //-----------------------------------------------------------------------------
871 // Read an ISO 14443 tag. We send it some set of commands, and record the
872 // responses.
873 // The command name is misleading, it actually decodes the reponse in HEX
874 // into the output buffer (read the result using hexsamples, not hisamples)
876 // obsolete function only for test
877 //-----------------------------------------------------------------------------
878 void AcquireRawAdcSamplesIso14443(uint32_t parameter)
880 uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
882 SendRawCommand14443B(sizeof(cmd1),1,1,cmd1);
886 Convenience function to encode, transmit and trace iso 14443b comms
888 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len)
890 CodeIso14443bAsReader(cmd, len);
891 TransmitFor14443();
892 if (tracing) {
893 uint8_t parity[MAX_PARITY_SIZE];
894 GetParity(cmd, len, parity);
895 LogTrace(cmd,len, 0, 0, parity, TRUE);
899 //-----------------------------------------------------------------------------
900 // Read a SRI512 ISO 14443 tag.
902 // SRI512 tags are just simple memory tags, here we're looking at making a dump
903 // of the contents of the memory. No anticollision algorithm is done, we assume
904 // we have a single tag in the field.
906 // I tried to be systematic and check every answer of the tag, every CRC, etc...
907 //-----------------------------------------------------------------------------
908 void ReadSTMemoryIso14443(uint32_t dwLast)
910 clear_trace();
911 set_tracing(TRUE);
913 uint8_t i = 0x00;
915 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
916 // Make sure that we start from off, since the tags are stateful;
917 // confusing things will happen if we don't reset them between reads.
918 LED_D_OFF();
919 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
920 SpinDelay(200);
922 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
923 FpgaSetupSsc();
925 // Now give it time to spin up.
926 // Signal field is on with the appropriate LED
927 LED_D_ON();
928 FpgaWriteConfWord(
929 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
930 SpinDelay(200);
932 // First command: wake up the tag using the INITIATE command
933 uint8_t cmd1[] = { 0x06, 0x00, 0x97, 0x5b};
935 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1));
936 // LED_A_ON();
937 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
938 // LED_A_OFF();
940 if (Demod.len == 0) {
941 DbpString("No response from tag");
942 return;
943 } else {
944 Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %x %x %x",
945 Demod.output[0], Demod.output[1],Demod.output[2]);
947 // There is a response, SELECT the uid
948 DbpString("Now SELECT tag:");
949 cmd1[0] = 0x0E; // 0x0E is SELECT
950 cmd1[1] = Demod.output[0];
951 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
952 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1));
954 // LED_A_ON();
955 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
956 // LED_A_OFF();
957 if (Demod.len != 3) {
958 Dbprintf("Expected 3 bytes from tag, got %d", Demod.len);
959 return;
961 // Check the CRC of the answer:
962 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
963 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
964 DbpString("CRC Error reading select response.");
965 return;
967 // Check response from the tag: should be the same UID as the command we just sent:
968 if (cmd1[1] != Demod.output[0]) {
969 Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1[1], Demod.output[0]);
970 return;
972 // Tag is now selected,
973 // First get the tag's UID:
974 cmd1[0] = 0x0B;
975 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
976 CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one
978 // LED_A_ON();
979 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
980 // LED_A_OFF();
981 if (Demod.len != 10) {
982 Dbprintf("Expected 10 bytes from tag, got %d", Demod.len);
983 return;
985 // The check the CRC of the answer (use cmd1 as temporary variable):
986 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
987 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
988 Dbprintf("CRC Error reading block! - Below: expected, got %x %x",
989 (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]);
990 // Do not return;, let's go on... (we should retry, maybe ?)
992 Dbprintf("Tag UID (64 bits): %08x %08x",
993 (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4],
994 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]);
996 // Now loop to read all 16 blocks, address from 0 to last block
997 Dbprintf("Tag memory dump, block 0 to %d",dwLast);
998 cmd1[0] = 0x08;
999 i = 0x00;
1000 dwLast++;
1001 for (;;) {
1002 if (i == dwLast) {
1003 DbpString("System area block (0xff):");
1004 i = 0xff;
1006 cmd1[1] = i;
1007 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
1008 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1));
1010 // LED_A_ON();
1011 GetSamplesFor14443Demod(TRUE, 2000,TRUE);
1012 // LED_A_OFF();
1013 if (Demod.len != 6) { // Check if we got an answer from the tag
1014 DbpString("Expected 6 bytes from tag, got less...");
1015 return;
1017 // The check the CRC of the answer (use cmd1 as temporary variable):
1018 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
1019 if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
1020 Dbprintf("CRC Error reading block! - Below: expected, got %x %x",
1021 (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]);
1022 // Do not return;, let's go on... (we should retry, maybe ?)
1024 // Now print out the memory location:
1025 Dbprintf("Address=%x, Contents=%x, CRC=%x", i,
1026 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0],
1027 (Demod.output[4]<<8)+Demod.output[5]);
1028 if (i == 0xff) {
1029 break;
1031 i++;
1036 //=============================================================================
1037 // Finally, the `sniffer' combines elements from both the reader and
1038 // simulated tag, to show both sides of the conversation.
1039 //=============================================================================
1041 //-----------------------------------------------------------------------------
1042 // Record the sequence of commands sent by the reader to the tag, with
1043 // triggering so that we start recording at the point that the tag is moved
1044 // near the reader.
1045 //-----------------------------------------------------------------------------
1047 * Memory usage for this function, (within BigBuf)
1048 * 0-4095 : Demodulated samples receive (4096 bytes) - DEMOD_TRACE_SIZE
1049 * 4096-6143 : Last Received command, 2048 bytes (reader->tag) - READER_TAG_BUFFER_SIZE
1050 * 6144-8191 : Last Received command, 2048 bytes(tag->reader) - TAG_READER_BUFFER_SIZE
1051 * 8192-9215 : DMA Buffer, 1024 bytes (samples) - DEMOD_DMA_BUFFER_SIZE
1053 void RAMFUNC SnoopIso14443(void)
1055 // We won't start recording the frames that we acquire until we trigger;
1056 // a good trigger condition to get started is probably when we see a
1057 // response from the tag.
1058 int triggered = TRUE;
1060 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1061 BigBuf_free();
1063 clear_trace();
1064 set_tracing(TRUE);
1066 // The DMA buffer, used to stream samples from the FPGA
1067 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
1068 int lastRxCounter;
1069 uint8_t *upTo;
1070 int ci, cq;
1071 int maxBehindBy = 0;
1073 // Count of samples received so far, so that we can include timing
1074 // information in the trace buffer.
1075 int samples = 0;
1077 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1078 UartInit(BigBuf_malloc(MAX_FRAME_SIZE));
1080 // Print some debug information about the buffer sizes
1081 Dbprintf("Snooping buffers initialized:");
1082 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1083 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE);
1084 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE);
1085 Dbprintf(" DMA: %i bytes", DMA_BUFFER_SIZE);
1087 // Signal field is off with the appropriate LED
1088 LED_D_OFF();
1090 // And put the FPGA in the appropriate mode
1091 FpgaWriteConfWord(
1092 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
1093 FPGA_HF_READER_RX_XCORR_SNOOP);
1094 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1096 // Setup for the DMA.
1097 FpgaSetupSsc();
1098 upTo = dmaBuf;
1099 lastRxCounter = DMA_BUFFER_SIZE;
1100 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
1101 uint8_t parity[MAX_PARITY_SIZE];
1102 LED_A_ON();
1104 // And now we loop, receiving samples.
1105 for(;;) {
1106 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
1107 (DMA_BUFFER_SIZE-1);
1108 if(behindBy > maxBehindBy) {
1109 maxBehindBy = behindBy;
1110 if(behindBy > (9*DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not?
1111 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
1112 break;
1115 if(behindBy < 2) continue;
1117 ci = upTo[0];
1118 cq = upTo[1];
1119 upTo += 2;
1120 lastRxCounter -= 2;
1121 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
1122 upTo -= DMA_BUFFER_SIZE;
1123 lastRxCounter += DMA_BUFFER_SIZE;
1124 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1125 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1128 samples += 2;
1130 if(Handle14443UartBit(ci & 1)) {
1131 if(triggered && tracing) {
1132 GetParity(Uart.output, Uart.byteCnt, parity);
1133 LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE);
1135 if(Uart.byteCnt==0) Dbprintf("[1] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt);
1137 /* And ready to receive another command. */
1138 UartReset();
1139 /* And also reset the demod code, which might have been */
1140 /* false-triggered by the commands from the reader. */
1141 DemodReset();
1143 if(Handle14443UartBit(cq & 1)) {
1144 if(triggered && tracing) {
1145 GetParity(Uart.output, Uart.byteCnt, parity);
1146 LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE);
1148 if(Uart.byteCnt==0) Dbprintf("[2] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt);
1150 /* And ready to receive another command. */
1151 UartReset();
1152 /* And also reset the demod code, which might have been */
1153 /* false-triggered by the commands from the reader. */
1154 DemodReset();
1157 if(Handle14443SamplesDemod(ci, cq)) {
1159 //Use samples as a time measurement
1160 if(tracing)
1162 uint8_t parity[MAX_PARITY_SIZE];
1163 GetParity(Demod.output, Demod.len, parity);
1164 LogTrace(Demod.output,Demod.len,samples, samples,parity,FALSE);
1166 triggered = TRUE;
1167 LED_A_OFF();
1168 LED_B_ON();
1170 // And ready to receive another response.
1171 DemodReset();
1173 WDT_HIT();
1175 if(!tracing) {
1176 DbpString("Reached trace limit");
1177 break;
1180 if(BUTTON_PRESS()) {
1181 DbpString("cancelled");
1182 break;
1185 FpgaDisableSscDma();
1186 LED_A_OFF();
1187 LED_B_OFF();
1188 LED_C_OFF();
1189 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
1190 DbpString("Snoop statistics:");
1191 Dbprintf(" Max behind by: %i", maxBehindBy);
1192 Dbprintf(" Uart State: %x", Uart.state);
1193 Dbprintf(" Uart ByteCnt: %i", Uart.byteCnt);
1194 Dbprintf(" Uart ByteCntMax: %i", Uart.byteCntMax);
1195 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
1199 * Send raw command to tag ISO14443B
1200 * @Input
1201 * datalen len of buffer data
1202 * recv bool when true wait for data from tag and send to client
1203 * powerfield bool leave the field on when true
1204 * data buffer with byte to send
1206 * @Output
1207 * none
1211 void SendRawCommand14443B(uint32_t datalen, uint32_t recv,uint8_t powerfield, uint8_t data[])
1213 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1214 if(!powerfield)
1216 // Make sure that we start from off, since the tags are stateful;
1217 // confusing things will happen if we don't reset them between reads.
1218 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1219 LED_D_OFF();
1220 SpinDelay(200);
1223 if(!GETBIT(GPIO_LED_D))
1225 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1226 FpgaSetupSsc();
1228 // Now give it time to spin up.
1229 // Signal field is on with the appropriate LED
1230 LED_D_ON();
1231 FpgaWriteConfWord(
1232 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
1233 SpinDelay(200);
1236 CodeAndTransmit14443bAsReader(data, datalen);
1238 if(recv)
1240 uint16_t iLen = MIN(Demod.len,USB_CMD_DATA_SIZE);
1241 GetSamplesFor14443Demod(TRUE, 2000, TRUE);
1242 cmd_send(CMD_ACK,iLen,0,0,Demod.output,iLen);
1244 if(!powerfield)
1246 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1247 LED_D_OFF();