]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iso15693.c
d988e2b9e4e6099964c702565d7ccdec3df99903
[proxmark3-svn] / armsrc / iso15693.c
1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, split Nov 2006
3 // Modified by Greg Jones, Jan 2009
4 // Modified by Adrian Dabrowski "atrox", Mar-Sept 2010,Oct 2011
5 // Modified by piwi, Oct 2018
6 //
7 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
8 // at your option, any later version. See the LICENSE.txt file for the text of
9 // the license.
10 //-----------------------------------------------------------------------------
11 // Routines to support ISO 15693. This includes both the reader software and
12 // the `fake tag' modes.
13 //-----------------------------------------------------------------------------
14
15 // The ISO 15693 describes two transmission modes from reader to tag, and four
16 // transmission modes from tag to reader. As of Oct 2018 this code supports
17 // both reader modes and the high speed variant with one subcarrier from card to reader.
18 // As long as the card fully support ISO 15693 this is no problem, since the
19 // reader chooses both data rates, but some non-standard tags do not.
20 // For card simulation, the code supports both high and low speed modes with one subcarrier.
21 //
22 // VCD (reader) -> VICC (tag)
23 // 1 out of 256:
24 // data rate: 1,66 kbit/s (fc/8192)
25 // used for long range
26 // 1 out of 4:
27 // data rate: 26,48 kbit/s (fc/512)
28 // used for short range, high speed
29 //
30 // VICC (tag) -> VCD (reader)
31 // Modulation:
32 // ASK / one subcarrier (423,75 khz)
33 // FSK / two subcarriers (423,75 khz && 484,28 khz)
34 // Data Rates / Modes:
35 // low ASK: 6,62 kbit/s
36 // low FSK: 6.67 kbit/s
37 // high ASK: 26,48 kbit/s
38 // high FSK: 26,69 kbit/s
39 //-----------------------------------------------------------------------------
40
41
42 // Random Remarks:
43 // *) UID is always used "transmission order" (LSB), which is reverse to display order
44
45 // TODO / BUGS / ISSUES:
46 // *) signal decoding is unable to detect collisions.
47 // *) add anti-collision support for inventory-commands
48 // *) read security status of a block
49 // *) sniffing and simulation do not support two subcarrier modes.
50 // *) remove or refactor code under "deprecated"
51 // *) document all the functions
52
53 #include "iso15693.h"
54
55 #include "proxmark3.h"
56 #include "util.h"
57 #include "apps.h"
58 #include "string.h"
59 #include "iso15693tools.h"
60 #include "protocols.h"
61 #include "cmd.h"
62 #include "BigBuf.h"
63 #include "fpgaloader.h"
64
65 #define arraylen(x) (sizeof(x)/sizeof((x)[0]))
66
67 static int DEBUG = 0;
68
69 ///////////////////////////////////////////////////////////////////////
70 // ISO 15693 Part 2 - Air Interface
71 // This section basicly contains transmission and receiving of bits
72 ///////////////////////////////////////////////////////////////////////
73
74 #define Crc(data,datalen) Iso15693Crc(data,datalen)
75 #define AddCrc(data,datalen) Iso15693AddCrc(data,datalen)
76 #define sprintUID(target,uid) Iso15693sprintUID(target,uid)
77
78 // buffers
79 #define ISO15693_DMA_BUFFER_SIZE 2048 // must be a power of 2
80 #define ISO15693_MAX_RESPONSE_LENGTH 36 // allows read single block with the maximum block size of 256bits. Read multiple blocks not supported yet
81 #define ISO15693_MAX_COMMAND_LENGTH 45 // allows write single block with the maximum block size of 256bits. Write multiple blocks not supported yet
82
83 // timing. Delays in SSP_CLK ticks.
84 #define DELAY_READER_TO_ARM 8
85 #define DELAY_ARM_TO_READER 1
86 #define DELAY_ISO15693_VCD_TO_VICC 132 // 132/423.75kHz = 311.5us from end of EOF to start of tag response
87 #define DELAY_ISO15693_VICC_TO_VCD 1017 // 1017/3.39MHz = 300us between end of tag response and next reader command
88
89 // ---------------------------
90 // Signal Processing
91 // ---------------------------
92
93 // prepare data using "1 out of 4" code for later transmission
94 // resulting data rate is 26.48 kbit/s (fc/512)
95 // cmd ... data
96 // n ... length of data
97 static void CodeIso15693AsReader(uint8_t *cmd, int n)
98 {
99 int i, j;
100
101 ToSendReset();
102
103 // Give it a bit of slack at the beginning
104 for(i = 0; i < 24; i++) {
105 ToSendStuffBit(1);
106 }
107
108 // SOF for 1of4
109 ToSendStuffBit(0);
110 ToSendStuffBit(1);
111 ToSendStuffBit(1);
112 ToSendStuffBit(1);
113 ToSendStuffBit(1);
114 ToSendStuffBit(0);
115 ToSendStuffBit(1);
116 ToSendStuffBit(1);
117 for(i = 0; i < n; i++) {
118 for(j = 0; j < 8; j += 2) {
119 int these = (cmd[i] >> j) & 3;
120 switch(these) {
121 case 0:
122 ToSendStuffBit(1);
123 ToSendStuffBit(0);
124 ToSendStuffBit(1);
125 ToSendStuffBit(1);
126 ToSendStuffBit(1);
127 ToSendStuffBit(1);
128 ToSendStuffBit(1);
129 ToSendStuffBit(1);
130 break;
131 case 1:
132 ToSendStuffBit(1);
133 ToSendStuffBit(1);
134 ToSendStuffBit(1);
135 ToSendStuffBit(0);
136 ToSendStuffBit(1);
137 ToSendStuffBit(1);
138 ToSendStuffBit(1);
139 ToSendStuffBit(1);
140 break;
141 case 2:
142 ToSendStuffBit(1);
143 ToSendStuffBit(1);
144 ToSendStuffBit(1);
145 ToSendStuffBit(1);
146 ToSendStuffBit(1);
147 ToSendStuffBit(0);
148 ToSendStuffBit(1);
149 ToSendStuffBit(1);
150 break;
151 case 3:
152 ToSendStuffBit(1);
153 ToSendStuffBit(1);
154 ToSendStuffBit(1);
155 ToSendStuffBit(1);
156 ToSendStuffBit(1);
157 ToSendStuffBit(1);
158 ToSendStuffBit(1);
159 ToSendStuffBit(0);
160 break;
161 }
162 }
163 }
164 // EOF
165 ToSendStuffBit(1);
166 ToSendStuffBit(1);
167 ToSendStuffBit(0);
168 ToSendStuffBit(1);
169
170 // Fill remainder of last byte with 1
171 for(i = 0; i < 4; i++) {
172 ToSendStuffBit(1);
173 }
174
175 ToSendMax++;
176 }
177
178 // encode data using "1 out of 256" scheme
179 // data rate is 1,66 kbit/s (fc/8192)
180 // is designed for more robust communication over longer distances
181 static void CodeIso15693AsReader256(uint8_t *cmd, int n)
182 {
183 int i, j;
184
185 ToSendReset();
186
187 // Give it a bit of slack at the beginning
188 for(i = 0; i < 24; i++) {
189 ToSendStuffBit(1);
190 }
191
192 // SOF for 1of256
193 ToSendStuffBit(0);
194 ToSendStuffBit(1);
195 ToSendStuffBit(1);
196 ToSendStuffBit(1);
197 ToSendStuffBit(1);
198 ToSendStuffBit(1);
199 ToSendStuffBit(1);
200 ToSendStuffBit(0);
201
202 for(i = 0; i < n; i++) {
203 for (j = 0; j<=255; j++) {
204 if (cmd[i]==j) {
205 ToSendStuffBit(1);
206 ToSendStuffBit(0);
207 } else {
208 ToSendStuffBit(1);
209 ToSendStuffBit(1);
210 }
211 }
212 }
213 // EOF
214 ToSendStuffBit(1);
215 ToSendStuffBit(1);
216 ToSendStuffBit(0);
217 ToSendStuffBit(1);
218
219 // Fill remainder of last byte with 1
220 for(i = 0; i < 4; i++) {
221 ToSendStuffBit(1);
222 }
223
224 ToSendMax++;
225 }
226
227
228 static void CodeIso15693AsTag(uint8_t *cmd, int n)
229 {
230 ToSendReset();
231
232 // SOF
233 ToSendStuffBit(0);
234 ToSendStuffBit(0);
235 ToSendStuffBit(0);
236 ToSendStuffBit(1);
237 ToSendStuffBit(1);
238 ToSendStuffBit(1);
239 ToSendStuffBit(0);
240 ToSendStuffBit(1);
241
242 // data
243 for(int i = 0; i < n; i++) {
244 for(int j = 0; j < 8; j++) {
245 if ((cmd[i] >> j) & 0x01) {
246 ToSendStuffBit(0);
247 ToSendStuffBit(1);
248 } else {
249 ToSendStuffBit(1);
250 ToSendStuffBit(0);
251 }
252 }
253 }
254
255 // EOF
256 ToSendStuffBit(1);
257 ToSendStuffBit(0);
258 ToSendStuffBit(1);
259 ToSendStuffBit(1);
260 ToSendStuffBit(1);
261 ToSendStuffBit(0);
262 ToSendStuffBit(0);
263 ToSendStuffBit(0);
264
265 ToSendMax++;
266 }
267
268
269 // Transmit the command (to the tag) that was placed in cmd[].
270 static void TransmitTo15693Tag(const uint8_t *cmd, int len, uint32_t start_time)
271 {
272 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_TX);
273 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
274
275 while (GetCountSspClk() < start_time);
276
277 LED_B_ON();
278 for(int c = 0; c < len; ) {
279 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
280 AT91C_BASE_SSC->SSC_THR = ~cmd[c];
281 c++;
282 }
283 WDT_HIT();
284 }
285 LED_B_OFF();
286 }
287
288 //-----------------------------------------------------------------------------
289 // Transmit the tag response (to the reader) that was placed in cmd[].
290 //-----------------------------------------------------------------------------
291 static void TransmitTo15693Reader(const uint8_t *cmd, size_t len, uint32_t start_time, bool slow)
292 {
293 // don't use the FPGA_HF_SIMULATOR_MODULATE_424K_8BIT minor mode. It would spoil GetCountSspClk()
294 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K);
295
296 uint8_t shift_delay = start_time & 0x00000007;
297 uint8_t bitmask = 0x00;
298 for (int i = 0; i < shift_delay; i++) {
299 bitmask |= (0x01 << i);
300 }
301
302 while (GetCountSspClk() < (start_time & 0xfffffff8)) ;
303
304 AT91C_BASE_SSC->SSC_THR = 0x00; // clear TXRDY
305
306 LED_C_ON();
307 uint8_t bits_to_shift = 0x00;
308 for(size_t c = 0; c <= len; c++) {
309 uint8_t bits_to_send = bits_to_shift << (8 - shift_delay) | (c==len?0x00:cmd[c]) >> shift_delay;
310 bits_to_shift = cmd[c] & bitmask;
311 for (int i = 7; i >= 0; i--) {
312 for (int j = 0; j < (slow?4:1); ) {
313 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
314 if (bits_to_send >> i & 0x01) {
315 AT91C_BASE_SSC->SSC_THR = 0xff;
316 } else {
317 AT91C_BASE_SSC->SSC_THR = 0x00;
318 }
319 j++;
320 }
321 WDT_HIT();
322 }
323 }
324 }
325 LED_C_OFF();
326 }
327
328
329 //=============================================================================
330 // An ISO 15693 decoder for tag responses (one subcarrier only).
331 // Uses cross correlation to identify each bit and EOF.
332 // This function is called 8 times per bit (every 2 subcarrier cycles).
333 // Subcarrier frequency fs is 424kHz, 1/fs = 2,36us,
334 // i.e. function is called every 4,72us
335 // LED handling:
336 // LED C -> ON once we have received the SOF and are expecting the rest.
337 // LED C -> OFF once we have received EOF or are unsynced
338 //
339 // Returns: true if we received a EOF
340 // false if we are still waiting for some more
341 //=============================================================================
342
343 #define NOISE_THRESHOLD 160 // don't try to correlate noise
344
345 typedef struct DecodeTag {
346 enum {
347 STATE_TAG_SOF_LOW,
348 STATE_TAG_SOF_HIGH,
349 STATE_TAG_SOF_HIGH_END,
350 STATE_TAG_RECEIVING_DATA,
351 STATE_TAG_EOF
352 } state;
353 int bitCount;
354 int posCount;
355 enum {
356 LOGIC0,
357 LOGIC1,
358 SOF_PART1,
359 SOF_PART2
360 } lastBit;
361 uint16_t shiftReg;
362 uint16_t max_len;
363 uint8_t *output;
364 int len;
365 int sum1, sum2;
366 } DecodeTag_t;
367
368
369 static int inline __attribute__((always_inline)) Handle15693SamplesFromTag(uint16_t amplitude, DecodeTag_t *DecodeTag)
370 {
371 switch(DecodeTag->state) {
372 case STATE_TAG_SOF_LOW:
373 // waiting for 12 times low (11 times low is accepted as well)
374 if (amplitude < NOISE_THRESHOLD) {
375 DecodeTag->posCount++;
376 } else {
377 if (DecodeTag->posCount > 10) {
378 DecodeTag->posCount = 1;
379 DecodeTag->sum1 = 0;
380 DecodeTag->state = STATE_TAG_SOF_HIGH;
381 } else {
382 DecodeTag->posCount = 0;
383 }
384 }
385 break;
386
387 case STATE_TAG_SOF_HIGH:
388 // waiting for 10 times high. Take average over the last 8
389 if (amplitude > NOISE_THRESHOLD) {
390 DecodeTag->posCount++;
391 if (DecodeTag->posCount > 2) {
392 DecodeTag->sum1 += amplitude; // keep track of average high value
393 }
394 if (DecodeTag->posCount == 10) {
395 DecodeTag->sum1 >>= 4; // calculate half of average high value (8 samples)
396 DecodeTag->state = STATE_TAG_SOF_HIGH_END;
397 }
398 } else { // high phase was too short
399 DecodeTag->posCount = 1;
400 DecodeTag->state = STATE_TAG_SOF_LOW;
401 }
402 break;
403
404 case STATE_TAG_SOF_HIGH_END:
405 // waiting for a falling edge
406 if (amplitude < DecodeTag->sum1) { // signal drops below 50% average high: a falling edge
407 DecodeTag->lastBit = SOF_PART1; // detected 1st part of SOF (12 samples low and 12 samples high)
408 DecodeTag->shiftReg = 0;
409 DecodeTag->bitCount = 0;
410 DecodeTag->len = 0;
411 DecodeTag->sum1 = amplitude;
412 DecodeTag->sum2 = 0;
413 DecodeTag->posCount = 2;
414 DecodeTag->state = STATE_TAG_RECEIVING_DATA;
415 LED_C_ON();
416 } else {
417 DecodeTag->posCount++;
418 if (DecodeTag->posCount > 13) { // high phase too long
419 DecodeTag->posCount = 0;
420 DecodeTag->state = STATE_TAG_SOF_LOW;
421 LED_C_OFF();
422 }
423 }
424 break;
425
426 case STATE_TAG_RECEIVING_DATA:
427 if (DecodeTag->posCount == 1) {
428 DecodeTag->sum1 = 0;
429 DecodeTag->sum2 = 0;
430 }
431 if (DecodeTag->posCount <= 4) {
432 DecodeTag->sum1 += amplitude;
433 } else {
434 DecodeTag->sum2 += amplitude;
435 }
436 if (DecodeTag->posCount == 8) {
437 int32_t corr_1 = DecodeTag->sum2 - DecodeTag->sum1;
438 int32_t corr_0 = -corr_1;
439 int32_t corr_EOF = (DecodeTag->sum1 + DecodeTag->sum2) / 2;
440 if (corr_EOF > corr_0 && corr_EOF > corr_1) {
441 if (DecodeTag->lastBit == LOGIC0) { // this was already part of EOF
442 DecodeTag->state = STATE_TAG_EOF;
443 } else {
444 DecodeTag->posCount = 0;
445 DecodeTag->state = STATE_TAG_SOF_LOW;
446 LED_C_OFF();
447 }
448 } else if (corr_1 > corr_0) {
449 // logic 1
450 if (DecodeTag->lastBit == SOF_PART1) { // still part of SOF
451 DecodeTag->lastBit = SOF_PART2; // SOF completed
452 } else {
453 DecodeTag->lastBit = LOGIC1;
454 DecodeTag->shiftReg >>= 1;
455 DecodeTag->shiftReg |= 0x80;
456 DecodeTag->bitCount++;
457 if (DecodeTag->bitCount == 8) {
458 DecodeTag->output[DecodeTag->len] = DecodeTag->shiftReg;
459 DecodeTag->len++;
460 if (DecodeTag->len > DecodeTag->max_len) {
461 // buffer overflow, give up
462 DecodeTag->posCount = 0;
463 DecodeTag->state = STATE_TAG_SOF_LOW;
464 LED_C_OFF();
465 }
466 DecodeTag->bitCount = 0;
467 DecodeTag->shiftReg = 0;
468 }
469 }
470 } else {
471 // logic 0
472 if (DecodeTag->lastBit == SOF_PART1) { // incomplete SOF
473 DecodeTag->posCount = 0;
474 DecodeTag->state = STATE_TAG_SOF_LOW;
475 LED_C_OFF();
476 } else {
477 DecodeTag->lastBit = LOGIC0;
478 DecodeTag->shiftReg >>= 1;
479 DecodeTag->bitCount++;
480 if (DecodeTag->bitCount == 8) {
481 DecodeTag->output[DecodeTag->len] = DecodeTag->shiftReg;
482 DecodeTag->len++;
483 if (DecodeTag->len > DecodeTag->max_len) {
484 // buffer overflow, give up
485 DecodeTag->posCount = 0;
486 DecodeTag->state = STATE_TAG_SOF_LOW;
487 LED_C_OFF();
488 }
489 DecodeTag->bitCount = 0;
490 DecodeTag->shiftReg = 0;
491 }
492 }
493 }
494 DecodeTag->posCount = 0;
495 }
496 DecodeTag->posCount++;
497 break;
498
499 case STATE_TAG_EOF:
500 if (DecodeTag->posCount == 1) {
501 DecodeTag->sum1 = 0;
502 DecodeTag->sum2 = 0;
503 }
504 if (DecodeTag->posCount <= 4) {
505 DecodeTag->sum1 += amplitude;
506 } else {
507 DecodeTag->sum2 += amplitude;
508 }
509 if (DecodeTag->posCount == 8) {
510 int32_t corr_1 = DecodeTag->sum2 - DecodeTag->sum1;
511 int32_t corr_0 = -corr_1;
512 int32_t corr_EOF = (DecodeTag->sum1 + DecodeTag->sum2) / 2;
513 if (corr_EOF > corr_0 || corr_1 > corr_0) {
514 DecodeTag->posCount = 0;
515 DecodeTag->state = STATE_TAG_SOF_LOW;
516 LED_C_OFF();
517 } else {
518 LED_C_OFF();
519 return true;
520 }
521 }
522 DecodeTag->posCount++;
523 break;
524
525 }
526
527 return false;
528 }
529
530
531 static void DecodeTagInit(DecodeTag_t *DecodeTag, uint8_t *data, uint16_t max_len)
532 {
533 DecodeTag->posCount = 0;
534 DecodeTag->state = STATE_TAG_SOF_LOW;
535 DecodeTag->output = data;
536 DecodeTag->max_len = max_len;
537 }
538
539
540 static void DecodeTagReset(DecodeTag_t *DecodeTag)
541 {
542 DecodeTag->posCount = 0;
543 DecodeTag->state = STATE_TAG_SOF_LOW;
544 }
545
546
547 /*
548 * Receive and decode the tag response, also log to tracebuffer
549 */
550 static int GetIso15693AnswerFromTag(uint8_t* response, uint16_t max_len, int timeout)
551 {
552 int samples = 0;
553 bool gotFrame = false;
554
555 uint16_t *dmaBuf = (uint16_t*)BigBuf_malloc(ISO15693_DMA_BUFFER_SIZE*sizeof(uint16_t));
556
557 // the Decoder data structure
558 DecodeTag_t DecodeTag = { 0 };
559 DecodeTagInit(&DecodeTag, response, max_len);
560
561 // wait for last transfer to complete
562 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
563
564 // And put the FPGA in the appropriate mode
565 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_AMPLITUDE);
566
567 // Setup and start DMA.
568 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
569 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
570 uint16_t *upTo = dmaBuf;
571
572 for(;;) {
573 uint16_t behindBy = ((uint16_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
574
575 if (behindBy == 0) continue;
576
577 uint16_t tagdata = *upTo++;
578
579 if(upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
580 upTo = dmaBuf; // start reading the circular buffer from the beginning
581 if(behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
582 Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy);
583 break;
584 }
585 }
586 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
587 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
588 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO15693_DMA_BUFFER_SIZE; // DMA Next Counter registers
589 }
590
591 samples++;
592
593 if (Handle15693SamplesFromTag(tagdata, &DecodeTag)) {
594 gotFrame = true;
595 break;
596 }
597
598 if (samples > timeout && DecodeTag.state < STATE_TAG_RECEIVING_DATA) {
599 DecodeTag.len = 0;
600 break;
601 }
602
603 }
604
605 FpgaDisableSscDma();
606 BigBuf_free();
607
608 if (DEBUG) Dbprintf("samples = %d, gotFrame = %d, Decoder: state = %d, len = %d, bitCount = %d, posCount = %d",
609 samples, gotFrame, DecodeTag.state, DecodeTag.len, DecodeTag.bitCount, DecodeTag.posCount);
610
611 if (DecodeTag.len > 0) {
612 LogTrace(DecodeTag.output, DecodeTag.len, 0, 0, NULL, false);
613 }
614
615 return DecodeTag.len;
616 }
617
618
619 //=============================================================================
620 // An ISO15693 decoder for reader commands.
621 //
622 // This function is called 4 times per bit (every 2 subcarrier cycles).
623 // Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
624 // LED handling:
625 // LED B -> ON once we have received the SOF and are expecting the rest.
626 // LED B -> OFF once we have received EOF or are in error state or unsynced
627 //
628 // Returns: true if we received a EOF
629 // false if we are still waiting for some more
630 //=============================================================================
631
632 typedef struct DecodeReader {
633 enum {
634 STATE_READER_UNSYNCD,
635 STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF,
636 STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF,
637 STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF,
638 STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4,
639 STATE_READER_RECEIVE_DATA_1_OUT_OF_4,
640 STATE_READER_RECEIVE_DATA_1_OUT_OF_256
641 } state;
642 enum {
643 CODING_1_OUT_OF_4,
644 CODING_1_OUT_OF_256
645 } Coding;
646 uint8_t shiftReg;
647 uint8_t bitCount;
648 int byteCount;
649 int byteCountMax;
650 int posCount;
651 int sum1, sum2;
652 uint8_t *output;
653 } DecodeReader_t;
654
655
656 static void DecodeReaderInit(DecodeReader_t* DecodeReader, uint8_t *data, uint16_t max_len)
657 {
658 DecodeReader->output = data;
659 DecodeReader->byteCountMax = max_len;
660 DecodeReader->state = STATE_READER_UNSYNCD;
661 DecodeReader->byteCount = 0;
662 DecodeReader->bitCount = 0;
663 DecodeReader->posCount = 1;
664 DecodeReader->shiftReg = 0;
665 }
666
667
668 static void DecodeReaderReset(DecodeReader_t* DecodeReader)
669 {
670 DecodeReader->state = STATE_READER_UNSYNCD;
671 }
672
673
674 static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uint8_t bit, DecodeReader_t *restrict DecodeReader)
675 {
676 switch(DecodeReader->state) {
677 case STATE_READER_UNSYNCD:
678 if(!bit) {
679 // we went low, so this could be the beginning of a SOF
680 DecodeReader->posCount = 1;
681 DecodeReader->state = STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF;
682 }
683 break;
684
685 case STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF:
686 DecodeReader->posCount++;
687 if(bit) { // detected rising edge
688 if(DecodeReader->posCount < 4) { // rising edge too early (nominally expected at 5)
689 DecodeReaderReset(DecodeReader);
690 } else { // SOF
691 DecodeReader->state = STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF;
692 }
693 } else {
694 if(DecodeReader->posCount > 5) { // stayed low for too long
695 DecodeReaderReset(DecodeReader);
696 } else {
697 // do nothing, keep waiting
698 }
699 }
700 break;
701
702 case STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF:
703 DecodeReader->posCount++;
704 if(!bit) { // detected a falling edge
705 if (DecodeReader->posCount < 20) { // falling edge too early (nominally expected at 21 earliest)
706 DecodeReaderReset(DecodeReader);
707 } else if (DecodeReader->posCount < 23) { // SOF for 1 out of 4 coding
708 DecodeReader->Coding = CODING_1_OUT_OF_4;
709 DecodeReader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
710 } else if (DecodeReader->posCount < 28) { // falling edge too early (nominally expected at 29 latest)
711 DecodeReaderReset(DecodeReader);
712 } else { // SOF for 1 out of 4 coding
713 DecodeReader->Coding = CODING_1_OUT_OF_256;
714 DecodeReader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
715 }
716 } else {
717 if(DecodeReader->posCount > 29) { // stayed high for too long
718 DecodeReaderReset(DecodeReader);
719 } else {
720 // do nothing, keep waiting
721 }
722 }
723 break;
724
725 case STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF:
726 DecodeReader->posCount++;
727 if (bit) { // detected rising edge
728 if (DecodeReader->Coding == CODING_1_OUT_OF_256) {
729 if (DecodeReader->posCount < 32) { // rising edge too early (nominally expected at 33)
730 DecodeReaderReset(DecodeReader);
731 } else {
732 DecodeReader->posCount = 1;
733 DecodeReader->bitCount = 0;
734 DecodeReader->byteCount = 0;
735 DecodeReader->sum1 = 1;
736 DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
737 LED_B_ON();
738 }
739 } else { // CODING_1_OUT_OF_4
740 if (DecodeReader->posCount < 24) { // rising edge too early (nominally expected at 25)
741 DecodeReaderReset(DecodeReader);
742 } else {
743 DecodeReader->state = STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4;
744 }
745 }
746 } else {
747 if (DecodeReader->Coding == CODING_1_OUT_OF_256) {
748 if (DecodeReader->posCount > 34) { // signal stayed low for too long
749 DecodeReaderReset(DecodeReader);
750 } else {
751 // do nothing, keep waiting
752 }
753 } else { // CODING_1_OUT_OF_4
754 if (DecodeReader->posCount > 26) { // signal stayed low for too long
755 DecodeReaderReset(DecodeReader);
756 } else {
757 // do nothing, keep waiting
758 }
759 }
760 }
761 break;
762
763 case STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4:
764 DecodeReader->posCount++;
765 if (bit) {
766 if (DecodeReader->posCount == 33) {
767 DecodeReader->posCount = 1;
768 DecodeReader->bitCount = 0;
769 DecodeReader->byteCount = 0;
770 DecodeReader->sum1 = 1;
771 DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
772 LED_B_ON();
773 } else {
774 // do nothing, keep waiting
775 }
776 } else { // unexpected falling edge
777 DecodeReaderReset(DecodeReader);
778 }
779 break;
780
781 case STATE_READER_RECEIVE_DATA_1_OUT_OF_4:
782 DecodeReader->posCount++;
783 if (DecodeReader->posCount == 1) {
784 DecodeReader->sum1 = bit;
785 } else if (DecodeReader->posCount <= 4) {
786 DecodeReader->sum1 += bit;
787 } else if (DecodeReader->posCount == 5) {
788 DecodeReader->sum2 = bit;
789 } else {
790 DecodeReader->sum2 += bit;
791 }
792 if (DecodeReader->posCount == 8) {
793 DecodeReader->posCount = 0;
794 int corr10 = DecodeReader->sum1 - DecodeReader->sum2;
795 int corr01 = DecodeReader->sum2 - DecodeReader->sum1;
796 int corr11 = (DecodeReader->sum1 + DecodeReader->sum2) / 2;
797 if (corr01 > corr11 && corr01 > corr10) { // EOF
798 LED_B_OFF(); // Finished receiving
799 DecodeReaderReset(DecodeReader);
800 if (DecodeReader->byteCount != 0) {
801 return true;
802 }
803 }
804 if (corr10 > corr11) { // detected a 2bit position
805 DecodeReader->shiftReg >>= 2;
806 DecodeReader->shiftReg |= (DecodeReader->bitCount << 6);
807 }
808 if (DecodeReader->bitCount == 15) { // we have a full byte
809 DecodeReader->output[DecodeReader->byteCount++] = DecodeReader->shiftReg;
810 if (DecodeReader->byteCount > DecodeReader->byteCountMax) {
811 // buffer overflow, give up
812 LED_B_OFF();
813 DecodeReaderReset(DecodeReader);
814 }
815 DecodeReader->bitCount = 0;
816 DecodeReader->shiftReg = 0;
817 } else {
818 DecodeReader->bitCount++;
819 }
820 }
821 break;
822
823 case STATE_READER_RECEIVE_DATA_1_OUT_OF_256:
824 DecodeReader->posCount++;
825 if (DecodeReader->posCount == 1) {
826 DecodeReader->sum1 = bit;
827 } else if (DecodeReader->posCount <= 4) {
828 DecodeReader->sum1 += bit;
829 } else if (DecodeReader->posCount == 5) {
830 DecodeReader->sum2 = bit;
831 } else {
832 DecodeReader->sum2 += bit;
833 }
834 if (DecodeReader->posCount == 8) {
835 DecodeReader->posCount = 0;
836 int corr10 = DecodeReader->sum1 - DecodeReader->sum2;
837 int corr01 = DecodeReader->sum2 - DecodeReader->sum1;
838 int corr11 = (DecodeReader->sum1 + DecodeReader->sum2) / 2;
839 if (corr01 > corr11 && corr01 > corr10) { // EOF
840 LED_B_OFF(); // Finished receiving
841 DecodeReaderReset(DecodeReader);
842 if (DecodeReader->byteCount != 0) {
843 return true;
844 }
845 }
846 if (corr10 > corr11) { // detected the bit position
847 DecodeReader->shiftReg = DecodeReader->bitCount;
848 }
849 if (DecodeReader->bitCount == 255) { // we have a full byte
850 DecodeReader->output[DecodeReader->byteCount++] = DecodeReader->shiftReg;
851 if (DecodeReader->byteCount > DecodeReader->byteCountMax) {
852 // buffer overflow, give up
853 LED_B_OFF();
854 DecodeReaderReset(DecodeReader);
855 }
856 }
857 DecodeReader->bitCount++;
858 }
859 break;
860
861 default:
862 LED_B_OFF();
863 DecodeReaderReset(DecodeReader);
864 break;
865 }
866
867 return false;
868 }
869
870
871 //-----------------------------------------------------------------------------
872 // Receive a command (from the reader to us, where we are the simulated tag),
873 // and store it in the given buffer, up to the given maximum length. Keeps
874 // spinning, waiting for a well-framed command, until either we get one
875 // (returns true) or someone presses the pushbutton on the board (false).
876 //
877 // Assume that we're called with the SSC (to the FPGA) and ADC path set
878 // correctly.
879 //-----------------------------------------------------------------------------
880
881 static int GetIso15693CommandFromReader(uint8_t *received, size_t max_len, uint32_t *eof_time)
882 {
883 int samples = 0;
884 bool gotFrame = false;
885 uint8_t b;
886
887 uint8_t *dmaBuf = BigBuf_malloc(ISO15693_DMA_BUFFER_SIZE);
888
889 // the decoder data structure
890 DecodeReader_t DecodeReader = {0};
891 DecodeReaderInit(&DecodeReader, received, max_len);
892
893 // wait for last transfer to complete
894 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
895
896 LED_D_OFF();
897 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
898
899 // clear receive register and wait for next transfer
900 uint32_t temp = AT91C_BASE_SSC->SSC_RHR;
901 (void) temp;
902 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) ;
903
904 uint32_t bit_time = GetCountSspClk() & 0xfffffff8;
905
906 // Setup and start DMA.
907 FpgaSetupSscDma(dmaBuf, ISO15693_DMA_BUFFER_SIZE);
908 uint8_t *upTo = dmaBuf;
909
910 for(;;) {
911 uint16_t behindBy = ((uint8_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
912
913 if (behindBy == 0) continue;
914
915 b = *upTo++;
916 if(upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
917 upTo = dmaBuf; // start reading the circular buffer from the beginning
918 if(behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
919 Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy);
920 break;
921 }
922 }
923 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
924 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
925 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO15693_DMA_BUFFER_SIZE; // DMA Next Counter registers
926 }
927
928 for (int i = 7; i >= 0; i--) {
929 if (Handle15693SampleFromReader((b >> i) & 0x01, &DecodeReader)) {
930 *eof_time = bit_time + samples - DELAY_READER_TO_ARM; // end of EOF
931 gotFrame = true;
932 break;
933 }
934 samples++;
935 }
936
937 if (gotFrame) {
938 break;
939 }
940
941 if (BUTTON_PRESS()) {
942 DecodeReader.byteCount = 0;
943 break;
944 }
945
946 WDT_HIT();
947 }
948
949
950 FpgaDisableSscDma();
951 BigBuf_free_keep_EM();
952
953 if (DEBUG) Dbprintf("samples = %d, gotFrame = %d, Decoder: state = %d, len = %d, bitCount = %d, posCount = %d",
954 samples, gotFrame, DecodeReader.state, DecodeReader.byteCount, DecodeReader.bitCount, DecodeReader.posCount);
955
956 if (DecodeReader.byteCount > 0) {
957 LogTrace(DecodeReader.output, DecodeReader.byteCount, 0, 0, NULL, true);
958 }
959
960 return DecodeReader.byteCount;
961 }
962
963
964 // Encode (into the ToSend buffers) an identify request, which is the first
965 // thing that you must send to a tag to get a response.
966 static void BuildIdentifyRequest(void)
967 {
968 uint8_t cmd[5];
969
970 uint16_t crc;
971 // one sub-carrier, inventory, 1 slot, fast rate
972 // AFI is at bit 5 (1<<4) when doing an INVENTORY
973 cmd[0] = (1 << 2) | (1 << 5) | (1 << 1);
974 // inventory command code
975 cmd[1] = 0x01;
976 // no mask
977 cmd[2] = 0x00;
978 //Now the CRC
979 crc = Crc(cmd, 3);
980 cmd[3] = crc & 0xff;
981 cmd[4] = crc >> 8;
982
983 CodeIso15693AsReader(cmd, sizeof(cmd));
984 }
985
986
987 //-----------------------------------------------------------------------------
988 // Start to read an ISO 15693 tag. We send an identify request, then wait
989 // for the response. The response is not demodulated, just left in the buffer
990 // so that it can be downloaded to a PC and processed there.
991 //-----------------------------------------------------------------------------
992 void AcquireRawAdcSamplesIso15693(void)
993 {
994 LEDsoff();
995 LED_A_ON();
996
997 uint8_t *dest = BigBuf_get_addr();
998
999 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1000 BuildIdentifyRequest();
1001
1002 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1003
1004 // Give the tags time to energize
1005 LED_D_ON();
1006 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1007 SpinDelay(100);
1008
1009 // Now send the command
1010 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_TX);
1011 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
1012
1013 LED_B_ON();
1014 for(int c = 0; c < ToSendMax; ) {
1015 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1016 AT91C_BASE_SSC->SSC_THR = ~ToSend[c];
1017 c++;
1018 }
1019 WDT_HIT();
1020 }
1021 LED_B_OFF();
1022
1023 // wait for last transfer to complete
1024 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
1025
1026 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1027 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_AMPLITUDE);
1028
1029 for(int c = 0; c < 4000; ) {
1030 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1031 uint16_t r = AT91C_BASE_SSC->SSC_RHR;
1032 dest[c++] = r >> 5;
1033 }
1034 }
1035
1036 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1037 LEDsoff();
1038 }
1039
1040
1041 void SnoopIso15693(void)
1042 {
1043 LED_A_ON();
1044 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1045 BigBuf_free();
1046
1047 clear_trace();
1048 set_tracing(true);
1049
1050
1051 // The DMA buffer, used to stream samples from the FPGA
1052 uint16_t* dmaBuf = (uint16_t*)BigBuf_malloc(ISO15693_DMA_BUFFER_SIZE*sizeof(uint16_t));
1053 uint16_t *upTo;
1054
1055 // Count of samples received so far, so that we can include timing
1056 // information in the trace buffer.
1057 int samples = 0;
1058
1059 DecodeTag_t DecodeTag = {0};
1060 uint8_t response[ISO15693_MAX_RESPONSE_LENGTH];
1061 DecodeTagInit(&DecodeTag, response, sizeof(response));
1062
1063 DecodeReader_t DecodeReader = {0};;
1064 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
1065 DecodeReaderInit(&DecodeReader, cmd, sizeof(cmd));
1066
1067 // Print some debug information about the buffer sizes
1068 if (DEBUG) {
1069 Dbprintf("Snooping buffers initialized:");
1070 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1071 Dbprintf(" Reader -> tag: %i bytes", ISO15693_MAX_COMMAND_LENGTH);
1072 Dbprintf(" tag -> Reader: %i bytes", ISO15693_MAX_RESPONSE_LENGTH);
1073 Dbprintf(" DMA: %i bytes", ISO15693_DMA_BUFFER_SIZE * sizeof(uint16_t));
1074 }
1075 Dbprintf("Snoop started. Press button to stop.");
1076
1077 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_SNOOP | FPGA_HF_READER_RX_XCORR_AMPLITUDE);
1078 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1079
1080 // Setup for the DMA.
1081 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1082 upTo = dmaBuf;
1083 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1084
1085 bool TagIsActive = false;
1086 bool ReaderIsActive = false;
1087 bool ExpectTagAnswer = false;
1088
1089 // And now we loop, receiving samples.
1090 for(;;) {
1091 uint16_t behindBy = ((uint16_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
1092
1093 if (behindBy == 0) continue;
1094
1095 uint16_t snoopdata = *upTo++;
1096
1097 if(upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
1098 upTo = dmaBuf; // start reading the circular buffer from the beginning
1099 if(behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
1100 Dbprintf("About to blow circular buffer - aborted! behindBy=%d, samples=%d", behindBy, samples);
1101 break;
1102 }
1103 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
1104 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
1105 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO15693_DMA_BUFFER_SIZE; // DMA Next Counter registers
1106 WDT_HIT();
1107 if(BUTTON_PRESS()) {
1108 DbpString("Snoop stopped.");
1109 break;
1110 }
1111 }
1112 }
1113 samples++;
1114
1115 if (!TagIsActive) { // no need to try decoding reader data if the tag is sending
1116 if (Handle15693SampleFromReader(snoopdata & 0x02, &DecodeReader)) {
1117 FpgaDisableSscDma();
1118 ExpectTagAnswer = true;
1119 LogTrace(DecodeReader.output, DecodeReader.byteCount, samples, samples, NULL, true);
1120 /* And ready to receive another command. */
1121 DecodeReaderReset(&DecodeReader);
1122 /* And also reset the demod code, which might have been */
1123 /* false-triggered by the commands from the reader. */
1124 DecodeTagReset(&DecodeTag);
1125 upTo = dmaBuf;
1126 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1127 }
1128 if (Handle15693SampleFromReader(snoopdata & 0x01, &DecodeReader)) {
1129 FpgaDisableSscDma();
1130 ExpectTagAnswer = true;
1131 LogTrace(DecodeReader.output, DecodeReader.byteCount, samples, samples, NULL, true);
1132 /* And ready to receive another command. */
1133 DecodeReaderReset(&DecodeReader);
1134 /* And also reset the demod code, which might have been */
1135 /* false-triggered by the commands from the reader. */
1136 DecodeTagReset(&DecodeTag);
1137 upTo = dmaBuf;
1138 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1139 }
1140 ReaderIsActive = (DecodeReader.state >= STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF);
1141 }
1142
1143 if (!ReaderIsActive && ExpectTagAnswer) { // no need to try decoding tag data if the reader is currently sending or no answer expected yet
1144 if (Handle15693SamplesFromTag(snoopdata >> 2, &DecodeTag)) {
1145 FpgaDisableSscDma();
1146 //Use samples as a time measurement
1147 LogTrace(DecodeTag.output, DecodeTag.len, samples, samples, NULL, false);
1148 // And ready to receive another response.
1149 DecodeTagReset(&DecodeTag);
1150 DecodeReaderReset(&DecodeReader);
1151 ExpectTagAnswer = false;
1152 upTo = dmaBuf;
1153 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1154 }
1155 TagIsActive = (DecodeTag.state >= STATE_TAG_RECEIVING_DATA);
1156 }
1157
1158 }
1159
1160 FpgaDisableSscDma();
1161 BigBuf_free();
1162
1163 LEDsoff();
1164
1165 DbpString("Snoop statistics:");
1166 Dbprintf(" ExpectTagAnswer: %d", ExpectTagAnswer);
1167 Dbprintf(" DecodeTag State: %d", DecodeTag.state);
1168 Dbprintf(" DecodeTag byteCnt: %d", DecodeTag.len);
1169 Dbprintf(" DecodeReader State: %d", DecodeReader.state);
1170 Dbprintf(" DecodeReader byteCnt: %d", DecodeReader.byteCount);
1171 Dbprintf(" Trace length: %d", BigBuf_get_traceLen());
1172 }
1173
1174
1175 // Initialize the proxmark as iso15k reader
1176 // (this might produces glitches that confuse some tags
1177 static void Iso15693InitReader() {
1178 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1179 // Setup SSC
1180 // FpgaSetupSsc();
1181
1182 // Start from off (no field generated)
1183 LED_D_OFF();
1184 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1185 SpinDelay(10);
1186
1187 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1188 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1189
1190 // Give the tags time to energize
1191 LED_D_ON();
1192 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1193 SpinDelay(250);
1194 }
1195
1196 ///////////////////////////////////////////////////////////////////////
1197 // ISO 15693 Part 3 - Air Interface
1198 // This section basically contains transmission and receiving of bits
1199 ///////////////////////////////////////////////////////////////////////
1200
1201
1202 // uid is in transmission order (which is reverse of display order)
1203 static void BuildReadBlockRequest(uint8_t *uid, uint8_t blockNumber )
1204 {
1205 uint8_t cmd[13];
1206
1207 uint16_t crc;
1208 // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
1209 // followed by the block data
1210 cmd[0] = ISO15693_REQ_OPTION | ISO15693_REQ_ADDRESS | ISO15693_REQ_DATARATE_HIGH;
1211 // READ BLOCK command code
1212 cmd[1] = ISO15693_READBLOCK;
1213 // UID may be optionally specified here
1214 // 64-bit UID
1215 cmd[2] = uid[0];
1216 cmd[3] = uid[1];
1217 cmd[4] = uid[2];
1218 cmd[5] = uid[3];
1219 cmd[6] = uid[4];
1220 cmd[7] = uid[5];
1221 cmd[8] = uid[6];
1222 cmd[9] = uid[7]; // 0xe0; // always e0 (not exactly unique)
1223 // Block number to read
1224 cmd[10] = blockNumber;
1225 //Now the CRC
1226 crc = Crc(cmd, 11); // the crc needs to be calculated over 11 bytes
1227 cmd[11] = crc & 0xff;
1228 cmd[12] = crc >> 8;
1229
1230 CodeIso15693AsReader(cmd, sizeof(cmd));
1231 }
1232
1233
1234 // Now the VICC>VCD responses when we are simulating a tag
1235 static void BuildInventoryResponse(uint8_t *uid)
1236 {
1237 uint8_t cmd[12];
1238
1239 uint16_t crc;
1240
1241 cmd[0] = 0; // No error, no protocol format extension
1242 cmd[1] = 0; // DSFID (data storage format identifier). 0x00 = not supported
1243 // 64-bit UID
1244 cmd[2] = uid[7]; //0x32;
1245 cmd[3] = uid[6]; //0x4b;
1246 cmd[4] = uid[5]; //0x03;
1247 cmd[5] = uid[4]; //0x01;
1248 cmd[6] = uid[3]; //0x00;
1249 cmd[7] = uid[2]; //0x10;
1250 cmd[8] = uid[1]; //0x05;
1251 cmd[9] = uid[0]; //0xe0;
1252 //Now the CRC
1253 crc = Crc(cmd, 10);
1254 cmd[10] = crc & 0xff;
1255 cmd[11] = crc >> 8;
1256
1257 CodeIso15693AsTag(cmd, sizeof(cmd));
1258 }
1259
1260 // Universal Method for sending to and recv bytes from a tag
1261 // init ... should we initialize the reader?
1262 // speed ... 0 low speed, 1 hi speed
1263 // *recv will contain the tag's answer
1264 // return: lenght of received data
1265 int SendDataTag(uint8_t *send, int sendlen, bool init, int speed, uint8_t *recv, uint16_t max_recv_len, uint32_t start_time) {
1266
1267 LED_A_ON();
1268 LED_B_OFF();
1269 LED_C_OFF();
1270
1271 if (init) Iso15693InitReader();
1272
1273 int answerLen=0;
1274
1275 if (!speed) {
1276 // low speed (1 out of 256)
1277 CodeIso15693AsReader256(send, sendlen);
1278 } else {
1279 // high speed (1 out of 4)
1280 CodeIso15693AsReader(send, sendlen);
1281 }
1282
1283 TransmitTo15693Tag(ToSend, ToSendMax, start_time);
1284
1285 // Now wait for a response
1286 if (recv != NULL) {
1287 answerLen = GetIso15693AnswerFromTag(recv, max_recv_len, DELAY_ISO15693_VCD_TO_VICC * 2);
1288 }
1289
1290 LED_A_OFF();
1291
1292 return answerLen;
1293 }
1294
1295
1296 // --------------------------------------------------------------------
1297 // Debug Functions
1298 // --------------------------------------------------------------------
1299
1300 // Decodes a message from a tag and displays its metadata and content
1301 #define DBD15STATLEN 48
1302 void DbdecodeIso15693Answer(int len, uint8_t *d) {
1303 char status[DBD15STATLEN+1]={0};
1304 uint16_t crc;
1305
1306 if (len > 3) {
1307 if (d[0] & ISO15693_RES_EXT)
1308 strncat(status,"ProtExt ", DBD15STATLEN);
1309 if (d[0] & ISO15693_RES_ERROR) {
1310 // error
1311 strncat(status,"Error ", DBD15STATLEN);
1312 switch (d[1]) {
1313 case 0x01:
1314 strncat(status,"01:notSupp", DBD15STATLEN);
1315 break;
1316 case 0x02:
1317 strncat(status,"02:notRecog", DBD15STATLEN);
1318 break;
1319 case 0x03:
1320 strncat(status,"03:optNotSupp", DBD15STATLEN);
1321 break;
1322 case 0x0f:
1323 strncat(status,"0f:noInfo", DBD15STATLEN);
1324 break;
1325 case 0x10:
1326 strncat(status,"10:doesn'tExist", DBD15STATLEN);
1327 break;
1328 case 0x11:
1329 strncat(status,"11:lockAgain", DBD15STATLEN);
1330 break;
1331 case 0x12:
1332 strncat(status,"12:locked", DBD15STATLEN);
1333 break;
1334 case 0x13:
1335 strncat(status,"13:progErr", DBD15STATLEN);
1336 break;
1337 case 0x14:
1338 strncat(status,"14:lockErr", DBD15STATLEN);
1339 break;
1340 default:
1341 strncat(status,"unknownErr", DBD15STATLEN);
1342 }
1343 strncat(status," ", DBD15STATLEN);
1344 } else {
1345 strncat(status,"NoErr ", DBD15STATLEN);
1346 }
1347
1348 crc=Crc(d,len-2);
1349 if ( (( crc & 0xff ) == d[len-2]) && (( crc >> 8 ) == d[len-1]) )
1350 strncat(status,"CrcOK",DBD15STATLEN);
1351 else
1352 strncat(status,"CrcFail!",DBD15STATLEN);
1353
1354 Dbprintf("%s",status);
1355 }
1356 }
1357
1358
1359
1360 ///////////////////////////////////////////////////////////////////////
1361 // Functions called via USB/Client
1362 ///////////////////////////////////////////////////////////////////////
1363
1364 void SetDebugIso15693(uint32_t debug) {
1365 DEBUG=debug;
1366 Dbprintf("Iso15693 Debug is now %s",DEBUG?"on":"off");
1367 return;
1368 }
1369
1370
1371 //-----------------------------------------------------------------------------
1372 // Simulate an ISO15693 reader, perform anti-collision and then attempt to read a sector
1373 // all demodulation performed in arm rather than host. - greg
1374 //-----------------------------------------------------------------------------
1375 void ReaderIso15693(uint32_t parameter)
1376 {
1377 LEDsoff();
1378 LED_A_ON();
1379
1380 set_tracing(true);
1381
1382 int answerLen = 0;
1383 uint8_t TagUID[8] = {0x00};
1384
1385 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1386
1387 uint8_t answer[ISO15693_MAX_RESPONSE_LENGTH];
1388
1389 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1390 // Setup SSC
1391 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1392
1393 // Start from off (no field generated)
1394 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1395 SpinDelay(200);
1396
1397 // Give the tags time to energize
1398 LED_D_ON();
1399 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1400 SpinDelay(200);
1401 StartCountSspClk();
1402
1403
1404 // FIRST WE RUN AN INVENTORY TO GET THE TAG UID
1405 // THIS MEANS WE CAN PRE-BUILD REQUESTS TO SAVE CPU TIME
1406
1407 // Now send the IDENTIFY command
1408 BuildIdentifyRequest();
1409 TransmitTo15693Tag(ToSend, ToSendMax, 0);
1410
1411 // Now wait for a response
1412 answerLen = GetIso15693AnswerFromTag(answer, sizeof(answer), DELAY_ISO15693_VCD_TO_VICC * 2) ;
1413 uint32_t start_time = GetCountSspClk() + DELAY_ISO15693_VICC_TO_VCD;
1414
1415 if (answerLen >=12) // we should do a better check than this
1416 {
1417 TagUID[0] = answer[2];
1418 TagUID[1] = answer[3];
1419 TagUID[2] = answer[4];
1420 TagUID[3] = answer[5];
1421 TagUID[4] = answer[6];
1422 TagUID[5] = answer[7];
1423 TagUID[6] = answer[8]; // IC Manufacturer code
1424 TagUID[7] = answer[9]; // always E0
1425
1426 }
1427
1428 Dbprintf("%d octets read from IDENTIFY request:", answerLen);
1429 DbdecodeIso15693Answer(answerLen, answer);
1430 Dbhexdump(answerLen, answer, false);
1431
1432 // UID is reverse
1433 if (answerLen >= 12)
1434 Dbprintf("UID = %02hX%02hX%02hX%02hX%02hX%02hX%02hX%02hX",
1435 TagUID[7],TagUID[6],TagUID[5],TagUID[4],
1436 TagUID[3],TagUID[2],TagUID[1],TagUID[0]);
1437
1438
1439 // Dbprintf("%d octets read from SELECT request:", answerLen2);
1440 // DbdecodeIso15693Answer(answerLen2,answer2);
1441 // Dbhexdump(answerLen2,answer2,true);
1442
1443 // Dbprintf("%d octets read from XXX request:", answerLen3);
1444 // DbdecodeIso15693Answer(answerLen3,answer3);
1445 // Dbhexdump(answerLen3,answer3,true);
1446
1447 // read all pages
1448 if (answerLen >= 12 && DEBUG) {
1449
1450 // debugptr = BigBuf_get_addr();
1451
1452 int i = 0;
1453 while (i < 32) { // sanity check, assume max 32 pages
1454 BuildReadBlockRequest(TagUID, i);
1455 TransmitTo15693Tag(ToSend, ToSendMax, start_time);
1456 int answerLen = GetIso15693AnswerFromTag(answer, sizeof(answer), DELAY_ISO15693_VCD_TO_VICC * 2);
1457 start_time = GetCountSspClk() + DELAY_ISO15693_VICC_TO_VCD;
1458 if (answerLen > 0) {
1459 Dbprintf("READ SINGLE BLOCK %d returned %d octets:", i, answerLen);
1460 DbdecodeIso15693Answer(answerLen, answer);
1461 Dbhexdump(answerLen, answer, false);
1462 if ( *((uint32_t*) answer) == 0x07160101 ) break; // exit on NoPageErr
1463 }
1464 i++;
1465 }
1466 }
1467
1468 // for the time being, switch field off to protect rdv4.0
1469 // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
1470 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1471 LED_D_OFF();
1472
1473 LED_A_OFF();
1474 }
1475
1476
1477 // Simulate an ISO15693 TAG.
1478 // For Inventory command: print command and send Inventory Response with given UID
1479 // TODO: interpret other reader commands and send appropriate response
1480 void SimTagIso15693(uint32_t parameter, uint8_t *uid)
1481 {
1482 LEDsoff();
1483 LED_A_ON();
1484
1485 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1486 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1487 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
1488 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
1489
1490 StartCountSspClk();
1491
1492 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
1493
1494 // Build a suitable response to the reader INVENTORY command
1495 BuildInventoryResponse(uid);
1496
1497 // Listen to reader
1498 while (!BUTTON_PRESS()) {
1499 uint32_t eof_time = 0, start_time = 0;
1500 int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &eof_time);
1501
1502 if ((cmd_len >= 5) && (cmd[0] & ISO15693_REQ_INVENTORY) && (cmd[1] == ISO15693_INVENTORY)) { // TODO: check more flags
1503 bool slow = !(cmd[0] & ISO15693_REQ_DATARATE_HIGH);
1504 start_time = eof_time + DELAY_ISO15693_VCD_TO_VICC - DELAY_ARM_TO_READER;
1505 TransmitTo15693Reader(ToSend, ToSendMax, start_time, slow);
1506 }
1507
1508 Dbprintf("%d bytes read from reader:", cmd_len);
1509 Dbhexdump(cmd_len, cmd, false);
1510 }
1511
1512 LEDsoff();
1513 }
1514
1515
1516 // Since there is no standardized way of reading the AFI out of a tag, we will brute force it
1517 // (some manufactures offer a way to read the AFI, though)
1518 void BruteforceIso15693Afi(uint32_t speed)
1519 {
1520 LEDsoff();
1521 LED_A_ON();
1522
1523 uint8_t data[6];
1524 uint8_t recv[ISO15693_MAX_RESPONSE_LENGTH];
1525
1526 int datalen=0, recvlen=0;
1527
1528 Iso15693InitReader();
1529 StartCountSspClk();
1530
1531 // first without AFI
1532 // Tags should respond without AFI and with AFI=0 even when AFI is active
1533
1534 data[0] = ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_INVENTORY | ISO15693_REQINV_SLOT1;
1535 data[1] = ISO15693_INVENTORY;
1536 data[2] = 0; // mask length
1537 datalen = AddCrc(data,3);
1538 recvlen = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), 0);
1539 uint32_t start_time = GetCountSspClk() + DELAY_ISO15693_VCD_TO_VICC;
1540 WDT_HIT();
1541 if (recvlen>=12) {
1542 Dbprintf("NoAFI UID=%s", sprintUID(NULL, &recv[2]));
1543 }
1544
1545 // now with AFI
1546
1547 data[0] = ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_INVENTORY | ISO15693_REQINV_AFI | ISO15693_REQINV_SLOT1;
1548 data[1] = ISO15693_INVENTORY;
1549 data[2] = 0; // AFI
1550 data[3] = 0; // mask length
1551
1552 for (int i = 0; i < 256; i++) {
1553 data[2] = i & 0xFF;
1554 datalen = AddCrc(data,4);
1555 recvlen = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), start_time);
1556 start_time = GetCountSspClk() + DELAY_ISO15693_VCD_TO_VICC;
1557 WDT_HIT();
1558 if (recvlen >= 12) {
1559 Dbprintf("AFI=%i UID=%s", i, sprintUID(NULL, &recv[2]));
1560 }
1561 }
1562 Dbprintf("AFI Bruteforcing done.");
1563
1564 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1565 LEDsoff();
1566 }
1567
1568 // Allows to directly send commands to the tag via the client
1569 void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint8_t data[]) {
1570
1571 int recvlen = 0;
1572 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
1573
1574 LED_A_ON();
1575
1576 if (DEBUG) {
1577 Dbprintf("SEND:");
1578 Dbhexdump(datalen, data, false);
1579 }
1580
1581 recvlen = SendDataTag(data, datalen, true, speed, (recv?recvbuf:NULL), sizeof(recvbuf), 0);
1582
1583 if (recv) {
1584 if (DEBUG) {
1585 Dbprintf("RECV:");
1586 Dbhexdump(recvlen, recvbuf, false);
1587 DbdecodeIso15693Answer(recvlen, recvbuf);
1588 }
1589
1590 cmd_send(CMD_ACK, recvlen>ISO15693_MAX_RESPONSE_LENGTH?ISO15693_MAX_RESPONSE_LENGTH:recvlen, 0, 0, recvbuf, ISO15693_MAX_RESPONSE_LENGTH);
1591
1592 }
1593
1594 // for the time being, switch field off to protect rdv4.0
1595 // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
1596 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1597 LED_D_OFF();
1598
1599 LED_A_OFF();
1600 }
1601
1602
1603
1604
1605 // --------------------------------------------------------------------
1606 // -- Misc & deprecated functions
1607 // --------------------------------------------------------------------
1608
1609 /*
1610
1611 // do not use; has a fix UID
1612 static void __attribute__((unused)) BuildSysInfoRequest(uint8_t *uid)
1613 {
1614 uint8_t cmd[12];
1615
1616 uint16_t crc;
1617 // If we set the Option_Flag in this request, the VICC will respond with the secuirty status of the block
1618 // followed by teh block data
1619 // one sub-carrier, inventory, 1 slot, fast rate
1620 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1621 // System Information command code
1622 cmd[1] = 0x2B;
1623 // UID may be optionally specified here
1624 // 64-bit UID
1625 cmd[2] = 0x32;
1626 cmd[3]= 0x4b;
1627 cmd[4] = 0x03;
1628 cmd[5] = 0x01;
1629 cmd[6] = 0x00;
1630 cmd[7] = 0x10;
1631 cmd[8] = 0x05;
1632 cmd[9]= 0xe0; // always e0 (not exactly unique)
1633 //Now the CRC
1634 crc = Crc(cmd, 10); // the crc needs to be calculated over 2 bytes
1635 cmd[10] = crc & 0xff;
1636 cmd[11] = crc >> 8;
1637
1638 CodeIso15693AsReader(cmd, sizeof(cmd));
1639 }
1640
1641
1642 // do not use; has a fix UID
1643 static void __attribute__((unused)) BuildReadMultiBlockRequest(uint8_t *uid)
1644 {
1645 uint8_t cmd[14];
1646
1647 uint16_t crc;
1648 // If we set the Option_Flag in this request, the VICC will respond with the secuirty status of the block
1649 // followed by teh block data
1650 // one sub-carrier, inventory, 1 slot, fast rate
1651 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1652 // READ Multi BLOCK command code
1653 cmd[1] = 0x23;
1654 // UID may be optionally specified here
1655 // 64-bit UID
1656 cmd[2] = 0x32;
1657 cmd[3]= 0x4b;
1658 cmd[4] = 0x03;
1659 cmd[5] = 0x01;
1660 cmd[6] = 0x00;
1661 cmd[7] = 0x10;
1662 cmd[8] = 0x05;
1663 cmd[9]= 0xe0; // always e0 (not exactly unique)
1664 // First Block number to read
1665 cmd[10] = 0x00;
1666 // Number of Blocks to read
1667 cmd[11] = 0x2f; // read quite a few
1668 //Now the CRC
1669 crc = Crc(cmd, 12); // the crc needs to be calculated over 2 bytes
1670 cmd[12] = crc & 0xff;
1671 cmd[13] = crc >> 8;
1672
1673 CodeIso15693AsReader(cmd, sizeof(cmd));
1674 }
1675
1676 // do not use; has a fix UID
1677 static void __attribute__((unused)) BuildArbitraryRequest(uint8_t *uid,uint8_t CmdCode)
1678 {
1679 uint8_t cmd[14];
1680
1681 uint16_t crc;
1682 // If we set the Option_Flag in this request, the VICC will respond with the secuirty status of the block
1683 // followed by teh block data
1684 // one sub-carrier, inventory, 1 slot, fast rate
1685 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1686 // READ BLOCK command code
1687 cmd[1] = CmdCode;
1688 // UID may be optionally specified here
1689 // 64-bit UID
1690 cmd[2] = 0x32;
1691 cmd[3]= 0x4b;
1692 cmd[4] = 0x03;
1693 cmd[5] = 0x01;
1694 cmd[6] = 0x00;
1695 cmd[7] = 0x10;
1696 cmd[8] = 0x05;
1697 cmd[9]= 0xe0; // always e0 (not exactly unique)
1698 // Parameter
1699 cmd[10] = 0x00;
1700 cmd[11] = 0x0a;
1701
1702 // cmd[12] = 0x00;
1703 // cmd[13] = 0x00; //Now the CRC
1704 crc = Crc(cmd, 12); // the crc needs to be calculated over 2 bytes
1705 cmd[12] = crc & 0xff;
1706 cmd[13] = crc >> 8;
1707
1708 CodeIso15693AsReader(cmd, sizeof(cmd));
1709 }
1710
1711 // do not use; has a fix UID
1712 static void __attribute__((unused)) BuildArbitraryCustomRequest(uint8_t uid[], uint8_t CmdCode)
1713 {
1714 uint8_t cmd[14];
1715
1716 uint16_t crc;
1717 // If we set the Option_Flag in this request, the VICC will respond with the secuirty status of the block
1718 // followed by teh block data
1719 // one sub-carrier, inventory, 1 slot, fast rate
1720 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1721 // READ BLOCK command code
1722 cmd[1] = CmdCode;
1723 // UID may be optionally specified here
1724 // 64-bit UID
1725 cmd[2] = 0x32;
1726 cmd[3]= 0x4b;
1727 cmd[4] = 0x03;
1728 cmd[5] = 0x01;
1729 cmd[6] = 0x00;
1730 cmd[7] = 0x10;
1731 cmd[8] = 0x05;
1732 cmd[9]= 0xe0; // always e0 (not exactly unique)
1733 // Parameter
1734 cmd[10] = 0x05; // for custom codes this must be manufcturer code
1735 cmd[11] = 0x00;
1736
1737 // cmd[12] = 0x00;
1738 // cmd[13] = 0x00; //Now the CRC
1739 crc = Crc(cmd, 12); // the crc needs to be calculated over 2 bytes
1740 cmd[12] = crc & 0xff;
1741 cmd[13] = crc >> 8;
1742
1743 CodeIso15693AsReader(cmd, sizeof(cmd));
1744 }
1745
1746
1747
1748
1749 */
1750
1751
Impressum, Datenschutz