text
[RRG-proxmark3.git] / armsrc / iso15693.c
blob4d292d70c95575ff56b8ebc43e02f5e23d6198eb
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 Christian Herrmann "iceman", 2017, 2020
6 // Modified by piwi, Oct 2018
7 //
8 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
9 // at your option, any later version. See the LICENSE.txt file for the text of
10 // the license.
11 //-----------------------------------------------------------------------------
12 // Routines to support ISO 15693. This includes both the reader software and
13 // the `fake tag' modes.
14 //-----------------------------------------------------------------------------
16 // The ISO 15693 describes two transmission modes from reader to tag, and four
17 // transmission modes from tag to reader. As of Oct 2018 this code supports
18 // both reader modes and the high speed variant with one subcarrier from card to reader.
19 // As long as the card fully support ISO 15693 this is no problem, since the
20 // reader chooses both data rates, but some non-standard tags do not.
21 // For card simulation, the code supports both high and low speed modes with one subcarrier.
23 // VCD (reader) -> VICC (tag)
24 // 1 out of 256:
25 // data rate: 1,66 kbit/s (fc/8192)
26 // used for long range
27 // 1 out of 4:
28 // data rate: 26,48 kbit/s (fc/512)
29 // used for short range, high speed
31 // VICC (tag) -> VCD (reader)
32 // Modulation:
33 // ASK / one subcarrier (423,75 kHz)
34 // FSK / two subcarriers (423,75 kHz && 484,28 kHz)
35 // Data Rates / Modes:
36 // low ASK: 6,62 kbit/s
37 // low FSK: 6.67 kbit/s
38 // high ASK: 26,48 kbit/s
39 // high FSK: 26,69 kbit/s
40 //-----------------------------------------------------------------------------
41 // added "1 out of 256" mode (for VCD->PICC) - atrox 20100911
44 // Random Remarks:
45 // *) UID is always used "transmission order" (LSB), which is reverse to display order
47 // TODO / BUGS / ISSUES:
48 // *) signal decoding is unable to detect collisions.
49 // *) add anti-collision support for inventory-commands
50 // *) read security status of a block
51 // *) sniffing and simulation do not support two subcarrier modes.
52 // *) remove or refactor code under "deprecated"
53 // *) document all the functions
55 #include "iso15693.h"
57 #include "proxmark3_arm.h"
58 #include "util.h"
59 #include "string.h"
60 #include "iso15693tools.h"
61 #include "protocols.h"
62 #include "cmd.h"
63 #include "appmain.h"
64 #include "dbprint.h"
65 #include "fpgaloader.h"
66 #include "commonutil.h"
67 #include "ticks.h"
68 #include "BigBuf.h"
69 #include "crc16.h"
71 // Delays in SSP_CLK ticks.
72 // SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
73 #define DELAY_READER_TO_ARM 8
74 #define DELAY_ARM_TO_READER 0
76 //SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader. All values should be multiples of 16
77 #define DELAY_ARM_TO_TAG 16
78 #define DELAY_TAG_TO_ARM 32
80 //SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when sniffing. All values should be multiples of 16
81 #define DELAY_TAG_TO_ARM_SNIFF 32
82 #define DELAY_READER_TO_ARM_SNIFF 32
84 // times in samples @ 212kHz when acting as reader
85 #define ISO15693_READER_TIMEOUT 330 // 330/212kHz = 1558us
86 #define ISO15693_READER_TIMEOUT_WRITE 4700 // 4700/212kHz = 22ms, nominal 20ms
88 // iceman: This defines below exists in the header file, just here for my easy reading
89 // Delays in SSP_CLK ticks.
90 // SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
91 //#define DELAY_ISO15693_VCD_TO_VICC_SIM 132 // 132/423.75kHz = 311.5us from end of command EOF to start of tag response
93 //SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader. All values should be multiples of 16
94 //#define DELAY_ISO15693_VCD_TO_VICC_READER 1056 // 1056/3,39MHz = 311.5us from end of command EOF to start of tag response
95 //#define DELAY_ISO15693_VICC_TO_VCD_READER 1024 // 1024/3.39MHz = 302.1us between end of tag response and next reader command
98 ///////////////////////////////////////////////////////////////////////
99 // ISO 15693 Part 2 - Air Interface
100 // This section basically contains transmission and receiving of bits
101 ///////////////////////////////////////////////////////////////////////
103 // buffers
104 #define ISO15693_MAX_RESPONSE_LENGTH 36 // allows read single block with the maximum block size of 256bits. Read multiple blocks not supported yet
105 #define ISO15693_MAX_COMMAND_LENGTH 45 // allows write single block with the maximum block size of 256bits. Write multiple blocks not supported yet
107 // 32 + 2 crc + 1
108 #define ISO15_MAX_FRAME 35
109 #define CMD_ID_RESP 5
110 #define CMD_READ_RESP 13
111 #define CMD_INV_RESP 12
112 #define CMD_SYSINFO_RESP 17
113 #define CMD_READBLOCK_RESP 7
115 //#define Crc(data, len) Crc(CRC_15693, (data), (len))
116 #define CheckCrc15(data, len) check_crc(CRC_15693, (data), (len))
117 #define AddCrc15(data, len) compute_crc(CRC_15693, (data), (len), (data)+(len), (data)+(len)+1)
119 static void BuildIdentifyRequest(uint8_t *cmd);
121 // ---------------------------
123 // Signal Processing
124 // ---------------------------
126 // prepare data using "1 out of 4" code for later transmission
127 // resulting data rate is 26.48 kbit/s (fc/512)
128 // cmd ... data
129 // n ... length of data
130 static uint8_t encode15_lut[] = {
131 0x40, // 01000000
132 0x10, // 00010000
133 0x04, // 00000100
134 0x01 // 00000001
137 void CodeIso15693AsReader(uint8_t *cmd, int n) {
139 tosend_reset();
140 tosend_t *ts = get_tosend();
142 // SOF for 1of4
143 ts->buf[++ts->max] = 0x84; //10000100
145 // data
146 for (int i = 0; i < n; i++) {
148 volatile uint8_t b = (cmd[i] >> 0) & 0x03;
149 ts->buf[++ts->max] = encode15_lut[b];
151 b = (cmd[i] >> 2) & 0x03;
152 ts->buf[++ts->max] = encode15_lut[b];
154 b = (cmd[i] >> 4) & 0x03;
155 ts->buf[++ts->max] = encode15_lut[b];
157 b = (cmd[i] >> 6) & 0x03;
158 ts->buf[++ts->max] = encode15_lut[b];
161 // EOF
162 ts->buf[++ts->max] = 0x20; //0010 + 0000 padding
163 ts->max++;
166 // Encode EOF only
167 static void CodeIso15693AsReaderEOF(void) {
168 tosend_reset();
169 tosend_t *ts = get_tosend();
170 ts->buf[++ts->max] = 0x20;
171 ts->max++;
175 // encode data using "1 out of 256" scheme
176 // data rate is 1,66 kbit/s (fc/8192)
177 // is designed for more robust communication over longer distances
178 static void CodeIso15693AsReader256(uint8_t *cmd, int n) {
180 tosend_reset();
181 tosend_t *ts = get_tosend();
183 // SOF for 1of256
184 ts->buf[++ts->max] = 0x81; //10000001
186 // data
187 for (int i = 0; i < n; i++) {
188 for (int j = 0; j <= 255; j++) {
189 if (cmd[i] == j) {
190 tosend_stuffbit(0);
191 tosend_stuffbit(1);
192 } else {
193 tosend_stuffbit(0);
194 tosend_stuffbit(0);
199 // EOF
200 ts->buf[++ts->max] = 0x20; //0010 + 0000 padding
201 ts->max++;
204 static const uint8_t encode_4bits[16] = {
205 // 0 1 2 3
206 0xaa, 0x6a, 0x9a, 0x5a,
207 // 4 5 6 7
208 0xa6, 0x66, 0x96, 0x56,
209 // 8 9 A B
210 0xa9, 0x69, 0x99, 0x59,
211 // C D E F
212 0xa5, 0x65, 0x95, 0x55
215 void CodeIso15693AsTag(uint8_t *cmd, size_t len) {
217 * SOF comprises 3 parts;
218 * * An unmodulated time of 56.64 us
219 * * 24 pulses of 423.75 kHz (fc/32)
220 * * A logic 1, which starts with an unmodulated time of 18.88us
221 * followed by 8 pulses of 423.75kHz (fc/32)
223 * EOF comprises 3 parts:
224 * - A logic 0 (which starts with 8 pulses of fc/32 followed by an unmodulated
225 * time of 18.88us.
226 * - 24 pulses of fc/32
227 * - An unmodulated time of 56.64 us
229 * A logic 0 starts with 8 pulses of fc/32
230 * followed by an unmodulated time of 256/fc (~18,88us).
232 * A logic 0 starts with unmodulated time of 256/fc (~18,88us) followed by
233 * 8 pulses of fc/32 (also 18.88us)
235 * A bit here becomes 8 pulses of fc/32. Therefore:
236 * The SOF can be written as 00011101 = 0x1D
237 * The EOF can be written as 10111000 = 0xb8
238 * A logic 1 is 01
239 * A logic 0 is 10
241 * */
242 tosend_reset();
243 tosend_t *ts = get_tosend();
245 // SOF
246 ts->buf[++ts->max] = 0x1D; // 00011101
248 // data
249 for (size_t i = 0; i < len; i += 2) {
250 ts->buf[++ts->max] = encode_4bits[cmd[i] & 0xF];
251 ts->buf[++ts->max] = encode_4bits[cmd[i] >> 4];
252 ts->buf[++ts->max] = encode_4bits[cmd[i + 1] & 0xF];
253 ts->buf[++ts->max] = encode_4bits[cmd[i + 1] >> 4];
256 // EOF
257 ts->buf[++ts->max] = 0xB8; // 10111000
258 ts->max++;
261 // Transmit the command (to the tag) that was placed in cmd[].
262 void TransmitTo15693Tag(const uint8_t *cmd, int len, uint32_t *start_time) {
264 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_FULL_MOD);
266 if (*start_time < DELAY_ARM_TO_TAG) {
267 *start_time = DELAY_ARM_TO_TAG;
270 *start_time = (*start_time - DELAY_ARM_TO_TAG) & 0xfffffff0;
272 if (GetCountSspClk() > *start_time) { // we may miss the intended time
273 *start_time = (GetCountSspClk() + 16) & 0xfffffff0; // next possible time
276 // wait
277 while (GetCountSspClk() < *start_time) ;
279 LED_B_ON();
280 for (int c = 0; c < len; c++) {
281 volatile uint8_t data = cmd[c];
283 for (uint8_t i = 0; i < 8; i++) {
284 uint16_t send_word = (data & 0x80) ? 0xffff : 0x0000;
285 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
286 AT91C_BASE_SSC->SSC_THR = send_word;
287 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
288 AT91C_BASE_SSC->SSC_THR = send_word;
289 data <<= 1;
291 WDT_HIT();
293 LED_B_OFF();
295 *start_time = *start_time + DELAY_ARM_TO_TAG;
296 FpgaDisableTracing();
299 //-----------------------------------------------------------------------------
300 // Transmit the tag response (to the reader) that was placed in cmd[].
301 //-----------------------------------------------------------------------------
302 void TransmitTo15693Reader(const uint8_t *cmd, size_t len, uint32_t *start_time, uint32_t slot_time, bool slow) {
304 // don't use the FPGA_HF_SIMULATOR_MODULATE_424K_8BIT minor mode. It would spoil GetCountSspClk()
305 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K);
307 uint32_t modulation_start_time = *start_time - DELAY_ARM_TO_READER + 3 * 8; // no need to transfer the unmodulated start of SOF
309 while (GetCountSspClk() > (modulation_start_time & 0xfffffff8) + 3) { // we will miss the intended time
310 if (slot_time) {
311 modulation_start_time += slot_time; // use next available slot
312 } else {
313 modulation_start_time = (modulation_start_time & 0xfffffff8) + 8; // next possible time
317 // wait
318 while (GetCountSspClk() < (modulation_start_time & 0xfffffff8)) ;
320 uint8_t shift_delay = modulation_start_time & 0x00000007;
322 *start_time = modulation_start_time + DELAY_ARM_TO_READER - 3 * 8;
324 LED_C_ON();
325 uint8_t bits_to_shift = 0x00;
326 uint8_t bits_to_send = 0x00;
328 for (size_t c = 0; c < len; c++) {
329 for (int i = (c == 0 ? 4 : 7); i >= 0; i--) {
331 uint8_t cmd_bits = ((cmd[c] >> i) & 0x01) ? 0xff : 0x00;
333 for (int j = 0; j < (slow ? 4 : 1);) {
334 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
335 bits_to_send = bits_to_shift << (8 - shift_delay) | cmd_bits >> shift_delay;
336 AT91C_BASE_SSC->SSC_THR = bits_to_send;
337 bits_to_shift = cmd_bits;
338 j++;
342 WDT_HIT();
345 // send the remaining bits, padded with 0:
346 bits_to_send = bits_to_shift << (8 - shift_delay);
347 if (bits_to_send) {
348 for (; ;) {
349 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
350 AT91C_BASE_SSC->SSC_THR = bits_to_send;
351 break;
355 LED_C_OFF();
358 //=============================================================================
359 // An ISO 15693 decoder for tag responses (one subcarrier only).
360 // Uses cross correlation to identify each bit and EOF.
361 // This function is called 8 times per bit (every 2 subcarrier cycles).
362 // Subcarrier frequency fs is 424kHz, 1/fs = 2,36us,
363 // i.e. function is called every 4,72us
364 // LED handling:
365 // LED C -> ON once we have received the SOF and are expecting the rest.
366 // LED C -> OFF once we have received EOF or are unsynced
368 // Returns: true if we received a EOF
369 // false if we are still waiting for some more
370 //=============================================================================
372 #define NOISE_THRESHOLD 80 // don't try to correlate noise
373 #define MAX_PREVIOUS_AMPLITUDE (-1 - NOISE_THRESHOLD)
375 typedef struct {
376 enum {
377 STATE_TAG_SOF_LOW,
378 STATE_TAG_SOF_RISING_EDGE,
379 STATE_TAG_SOF_HIGH,
380 STATE_TAG_SOF_HIGH_END,
381 STATE_TAG_RECEIVING_DATA,
382 STATE_TAG_EOF,
383 STATE_TAG_EOF_TAIL
384 } state;
385 int bitCount;
386 int posCount;
387 enum {
388 LOGIC0,
389 LOGIC1,
390 SOF_PART1,
391 SOF_PART2
392 } lastBit;
393 uint16_t shiftReg;
394 uint16_t max_len;
395 uint8_t *output;
396 int len;
397 int sum1;
398 int sum2;
399 int threshold_sof;
400 int threshold_half;
401 uint16_t previous_amplitude;
402 } DecodeTag_t;
404 //-----------------------------------------------------------------------------
405 // DEMODULATE tag answer
406 //-----------------------------------------------------------------------------
407 static RAMFUNC int Handle15693SamplesFromTag(uint16_t amplitude, DecodeTag_t *tag) {
409 switch (tag->state) {
411 case STATE_TAG_SOF_LOW: {
412 // waiting for a rising edge
413 if (amplitude > NOISE_THRESHOLD + tag->previous_amplitude) {
414 if (tag->posCount > 10) {
415 tag->threshold_sof = amplitude - tag->previous_amplitude; // to be divided by 2
416 tag->threshold_half = 0;
417 tag->state = STATE_TAG_SOF_RISING_EDGE;
418 } else {
419 tag->posCount = 0;
421 } else {
422 tag->posCount++;
423 tag->previous_amplitude = amplitude;
425 break;
428 case STATE_TAG_SOF_RISING_EDGE: {
429 if (amplitude > tag->threshold_sof + tag->previous_amplitude) { // edge still rising
430 if (amplitude > tag->threshold_sof + tag->threshold_sof) { // steeper edge, take this as time reference
431 tag->posCount = 1;
432 } else {
433 tag->posCount = 2;
435 tag->threshold_sof = (amplitude - tag->previous_amplitude) / 2;
436 } else {
437 tag->posCount = 2;
438 tag->threshold_sof = tag->threshold_sof / 2;
440 tag->state = STATE_TAG_SOF_HIGH;
441 break;
444 case STATE_TAG_SOF_HIGH: {
445 // waiting for 10 times high. Take average over the last 8
446 if (amplitude > tag->threshold_sof) {
447 tag->posCount++;
448 if (tag->posCount > 2) {
449 tag->threshold_half += amplitude; // keep track of average high value
451 if (tag->posCount == 10) {
452 tag->threshold_half >>= 2; // (4 times 1/2 average)
453 tag->state = STATE_TAG_SOF_HIGH_END;
455 } else { // high phase was too short
456 tag->posCount = 1;
457 tag->previous_amplitude = amplitude;
458 tag->state = STATE_TAG_SOF_LOW;
460 break;
463 case STATE_TAG_SOF_HIGH_END: {
464 // check for falling edge
465 if (tag->posCount == 13 && amplitude < tag->threshold_sof) {
466 tag->lastBit = SOF_PART1; // detected 1st part of SOF (12 samples low and 12 samples high)
467 tag->shiftReg = 0;
468 tag->bitCount = 0;
469 tag->len = 0;
470 tag->sum1 = amplitude;
471 tag->sum2 = 0;
472 tag->posCount = 2;
473 tag->state = STATE_TAG_RECEIVING_DATA;
474 LED_C_ON();
475 } else {
476 tag->posCount++;
477 if (tag->posCount > 13) { // high phase too long
478 tag->posCount = 0;
479 tag->previous_amplitude = amplitude;
480 tag->state = STATE_TAG_SOF_LOW;
481 LED_C_OFF();
484 break;
487 case STATE_TAG_RECEIVING_DATA: {
488 if (tag->posCount == 1) {
489 tag->sum1 = 0;
490 tag->sum2 = 0;
493 if (tag->posCount <= 4) {
494 tag->sum1 += amplitude;
495 } else {
496 tag->sum2 += amplitude;
499 if (tag->posCount == 8) {
500 if (tag->sum1 > tag->threshold_half && tag->sum2 > tag->threshold_half) { // modulation in both halves
501 if (tag->lastBit == LOGIC0) { // this was already part of EOF
502 tag->state = STATE_TAG_EOF;
503 } else {
504 tag->posCount = 0;
505 tag->previous_amplitude = amplitude;
506 tag->state = STATE_TAG_SOF_LOW;
507 LED_C_OFF();
509 } else if (tag->sum1 < tag->threshold_half && tag->sum2 > tag->threshold_half) { // modulation in second half
510 // logic 1
511 if (tag->lastBit == SOF_PART1) { // still part of SOF
512 tag->lastBit = SOF_PART2; // SOF completed
513 } else {
514 tag->lastBit = LOGIC1;
515 tag->shiftReg >>= 1;
516 tag->shiftReg |= 0x80;
517 tag->bitCount++;
518 if (tag->bitCount == 8) {
519 tag->output[tag->len] = tag->shiftReg & 0xFF;
520 tag->len++;
522 if (tag->len > tag->max_len) {
523 // buffer overflow, give up
524 LED_C_OFF();
525 return true;
527 tag->bitCount = 0;
528 tag->shiftReg = 0;
531 } else if (tag->sum1 > tag->threshold_half && tag->sum2 < tag->threshold_half) { // modulation in first half
532 // logic 0
533 if (tag->lastBit == SOF_PART1) { // incomplete SOF
534 tag->posCount = 0;
535 tag->previous_amplitude = amplitude;
536 tag->state = STATE_TAG_SOF_LOW;
537 LED_C_OFF();
538 } else {
539 tag->lastBit = LOGIC0;
540 tag->shiftReg >>= 1;
541 tag->bitCount++;
543 if (tag->bitCount == 8) {
544 tag->output[tag->len] = (tag->shiftReg & 0xFF);
545 tag->len++;
547 if (tag->len > tag->max_len) {
548 // buffer overflow, give up
549 tag->posCount = 0;
550 tag->previous_amplitude = amplitude;
551 tag->state = STATE_TAG_SOF_LOW;
552 LED_C_OFF();
554 tag->bitCount = 0;
555 tag->shiftReg = 0;
558 } else { // no modulation
559 if (tag->lastBit == SOF_PART2) { // only SOF (this is OK for iClass)
560 LED_C_OFF();
561 return true;
562 } else {
563 tag->posCount = 0;
564 tag->state = STATE_TAG_SOF_LOW;
565 LED_C_OFF();
568 tag->posCount = 0;
570 tag->posCount++;
571 break;
574 case STATE_TAG_EOF: {
575 if (tag->posCount == 1) {
576 tag->sum1 = 0;
577 tag->sum2 = 0;
580 if (tag->posCount <= 4) {
581 tag->sum1 += amplitude;
582 } else {
583 tag->sum2 += amplitude;
586 if (tag->posCount == 8) {
587 if (tag->sum1 > tag->threshold_half && tag->sum2 < tag->threshold_half) { // modulation in first half
588 tag->posCount = 0;
589 tag->state = STATE_TAG_EOF_TAIL;
590 } else {
591 tag->posCount = 0;
592 tag->previous_amplitude = amplitude;
593 tag->state = STATE_TAG_SOF_LOW;
594 LED_C_OFF();
597 tag->posCount++;
598 break;
601 case STATE_TAG_EOF_TAIL: {
602 if (tag->posCount == 1) {
603 tag->sum1 = 0;
604 tag->sum2 = 0;
607 if (tag->posCount <= 4) {
608 tag->sum1 += amplitude;
609 } else {
610 tag->sum2 += amplitude;
613 if (tag->posCount == 8) {
614 if (tag->sum1 < tag->threshold_half && tag->sum2 < tag->threshold_half) { // no modulation in both halves
615 LED_C_OFF();
616 return true;
617 } else {
618 tag->posCount = 0;
619 tag->previous_amplitude = amplitude;
620 tag->state = STATE_TAG_SOF_LOW;
621 LED_C_OFF();
624 tag->posCount++;
625 break;
629 return false;
632 static void DecodeTagReset(DecodeTag_t *tag) {
633 tag->posCount = 0;
634 tag->state = STATE_TAG_SOF_LOW;
635 tag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
638 static void DecodeTagInit(DecodeTag_t *tag, uint8_t *data, uint16_t max_len) {
639 tag->output = data;
640 tag->max_len = max_len;
641 DecodeTagReset(tag);
645 * Receive and decode the tag response, also log to tracebuffer
647 int GetIso15693AnswerFromTag(uint8_t *response, uint16_t max_len, uint16_t timeout, uint32_t *eof_time) {
649 int samples = 0, ret = 0;
651 // the Decoder data structure
652 DecodeTag_t dtm = { 0 };
653 DecodeTag_t *dt = &dtm;
654 DecodeTagInit(dt, response, max_len);
656 // wait for last transfer to complete
657 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
659 // And put the FPGA in the appropriate mode
660 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_424_KHZ | FPGA_HF_READER_MODE_RECEIVE_AMPLITUDE);
662 // Setup and start DMA.
663 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
665 // The DMA buffer, used to stream samples from the FPGA
666 dmabuf16_t *dma = get_dma16();
668 // Setup and start DMA.
669 if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) {
670 if (DBGLEVEL > DBG_ERROR) Dbprintf("FpgaSetupSscDma failed. Exiting");
671 return -4;
674 uint32_t dma_start_time = 0;
675 uint16_t *upTo = dma->buf;
677 for (;;) {
679 volatile uint16_t behindBy = ((uint16_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
680 if (behindBy == 0)
681 continue;
683 samples++;
684 if (samples == 1) {
685 // DMA has transferred the very first data
686 dma_start_time = GetCountSspClk() & 0xfffffff0;
689 volatile uint16_t tagdata = *upTo++;
691 if (upTo >= dma->buf + DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
692 upTo = dma->buf; // start reading the circular buffer from the beginning
694 // DMA Counter Register had reached 0, already rotated.
695 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) {
697 // primary buffer was stopped
698 if (AT91C_BASE_PDC_SSC->PDC_RCR == false) {
699 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf;
700 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
702 // secondary buffer sets as primary, secondary buffer was stopped
703 if (AT91C_BASE_PDC_SSC->PDC_RNCR == false) {
704 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf;
705 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
708 WDT_HIT();
709 if (BUTTON_PRESS()) {
710 DbpString("stopped");
711 break;
716 if (Handle15693SamplesFromTag(tagdata, dt)) {
718 *eof_time = dma_start_time + (samples * 16) - DELAY_TAG_TO_ARM; // end of EOF
720 if (dt->lastBit == SOF_PART2) {
721 *eof_time -= (8 * 16); // needed 8 additional samples to confirm single SOF (iCLASS)
723 if (dt->len > dt->max_len) {
724 ret = -2; // buffer overflow
725 Dbprintf("overflow (%d > %d", dt->len, dt->max_len);
727 break;
730 // timeout
731 if (samples > timeout && dt->state < STATE_TAG_RECEIVING_DATA) {
732 ret = -3;
733 break;
738 FpgaDisableSscDma();
739 FpgaDisableTracing();
741 uint32_t sof_time = *eof_time
742 - (dt->len * 8 * 8 * 16) // time for byte transfers
743 - (32 * 16) // time for SOF transfer
744 - (dt->lastBit != SOF_PART2 ? (32 * 16) : 0); // time for EOF transfer
746 if (DBGLEVEL >= DBG_EXTENDED) {
747 Dbprintf("samples = %d, ret = %d, Decoder: state = %d, lastBit = %d, len = %d, bitCount = %d, posCount = %d, maxlen = %u",
748 samples,
749 ret,
750 dt->state,
751 dt->lastBit,
752 dt->len,
753 dt->bitCount,
754 dt->posCount,
755 dt->max_len
757 Dbprintf("timing: sof_time = %d, eof_time = %d", (sof_time * 4), (*eof_time * 4));
760 if (ret < 0) {
761 return ret;
764 LogTrace_ISO15693(dt->output, dt->len, (sof_time * 4), (*eof_time * 4), NULL, false);
765 return dt->len;
769 //=============================================================================
770 // An ISO15693 decoder for reader commands.
772 // This function is called 4 times per bit (every 2 subcarrier cycles).
773 // Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
774 // LED handling:
775 // LED B -> ON once we have received the SOF and are expecting the rest.
776 // LED B -> OFF once we have received EOF or are in error state or unsynced
778 // Returns: true if we received a EOF
779 // false if we are still waiting for some more
780 //=============================================================================
782 typedef struct {
783 enum {
784 STATE_READER_UNSYNCD,
785 STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF,
786 STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF,
787 STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF,
788 STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF,
789 STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4,
790 STATE_READER_RECEIVE_DATA_1_OUT_OF_4,
791 STATE_READER_RECEIVE_DATA_1_OUT_OF_256,
792 STATE_READER_RECEIVE_JAMMING
793 } state;
794 enum {
795 CODING_1_OUT_OF_4,
796 CODING_1_OUT_OF_256
797 } Coding;
798 uint8_t shiftReg;
799 uint8_t bitCount;
800 int byteCount;
801 int byteCountMax;
802 int posCount;
803 int sum1, sum2;
804 uint8_t *output;
805 uint8_t jam_search_len;
806 uint8_t *jam_search_string;
807 } DecodeReader_t;
809 static void DecodeReaderInit(DecodeReader_t *reader, uint8_t *data, uint16_t max_len, uint8_t jam_search_len, uint8_t *jam_search_string) {
810 reader->output = data;
811 reader->byteCountMax = max_len;
812 reader->state = STATE_READER_UNSYNCD;
813 reader->byteCount = 0;
814 reader->bitCount = 0;
815 reader->posCount = 1;
816 reader->shiftReg = 0;
817 reader->jam_search_len = jam_search_len;
818 reader->jam_search_string = jam_search_string;
821 static void DecodeReaderReset(DecodeReader_t *reader) {
822 reader->state = STATE_READER_UNSYNCD;
825 //static inline __attribute__((always_inline))
826 static int RAMFUNC Handle15693SampleFromReader(bool bit, DecodeReader_t *reader) {
827 switch (reader->state) {
828 case STATE_READER_UNSYNCD:
829 // wait for unmodulated carrier
830 if (bit) {
831 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
833 break;
835 case STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF:
836 if (!bit) {
837 // we went low, so this could be the beginning of a SOF
838 reader->posCount = 1;
839 reader->state = STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF;
841 break;
843 case STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF:
844 reader->posCount++;
845 if (bit) { // detected rising edge
846 if (reader->posCount < 4) { // rising edge too early (nominally expected at 5)
847 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
848 } else { // SOF
849 reader->state = STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF;
851 } else {
852 if (reader->posCount > 5) { // stayed low for too long
853 DecodeReaderReset(reader);
854 } else {
855 // do nothing, keep waiting
858 break;
860 case STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF:
862 reader->posCount++;
864 if (bit == false) { // detected a falling edge
866 if (reader->posCount < 20) { // falling edge too early (nominally expected at 21 earliest)
867 DecodeReaderReset(reader);
868 } else if (reader->posCount < 23) { // SOF for 1 out of 4 coding
869 reader->Coding = CODING_1_OUT_OF_4;
870 reader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
871 } else if (reader->posCount < 28) { // falling edge too early (nominally expected at 29 latest)
872 DecodeReaderReset(reader);
873 } else { // SOF for 1 out of 256 coding
874 reader->Coding = CODING_1_OUT_OF_256;
875 reader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
878 } else {
879 if (reader->posCount > 29) { // stayed high for too long
880 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
881 } else {
882 // do nothing, keep waiting
885 break;
887 case STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF:
889 reader->posCount++;
891 if (bit) { // detected rising edge
892 if (reader->Coding == CODING_1_OUT_OF_256) {
893 if (reader->posCount < 32) { // rising edge too early (nominally expected at 33)
894 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
895 } else {
896 reader->posCount = 1;
897 reader->bitCount = 0;
898 reader->byteCount = 0;
899 reader->sum1 = 1;
900 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
901 LED_B_ON();
903 } else { // CODING_1_OUT_OF_4
904 if (reader->posCount < 24) { // rising edge too early (nominally expected at 25)
905 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
906 } else {
907 reader->posCount = 1;
908 reader->state = STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4;
911 } else {
912 if (reader->Coding == CODING_1_OUT_OF_256) {
913 if (reader->posCount > 34) { // signal stayed low for too long
914 DecodeReaderReset(reader);
915 } else {
916 // do nothing, keep waiting
918 } else { // CODING_1_OUT_OF_4
919 if (reader->posCount > 26) { // signal stayed low for too long
920 DecodeReaderReset(reader);
921 } else {
922 // do nothing, keep waiting
926 break;
928 case STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4:
930 reader->posCount++;
932 if (bit) {
933 if (reader->posCount == 9) {
934 reader->posCount = 1;
935 reader->bitCount = 0;
936 reader->byteCount = 0;
937 reader->sum1 = 1;
938 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
939 LED_B_ON();
940 } else {
941 // do nothing, keep waiting
943 } else { // unexpected falling edge
944 DecodeReaderReset(reader);
946 break;
948 case STATE_READER_RECEIVE_DATA_1_OUT_OF_4:
950 reader->posCount++;
952 if (reader->posCount == 1) {
954 reader->sum1 = bit ? 1 : 0;
956 } else if (reader->posCount <= 4) {
958 if (bit)
959 reader->sum1++;
961 } else if (reader->posCount == 5) {
963 reader->sum2 = bit ? 1 : 0;
965 } else {
966 if (bit)
967 reader->sum2++;
970 if (reader->posCount == 8) {
971 reader->posCount = 0;
972 if (reader->sum1 <= 1 && reader->sum2 >= 3) { // EOF
973 LED_B_OFF(); // Finished receiving
974 DecodeReaderReset(reader);
975 if (reader->byteCount != 0) {
976 return true;
979 } else if (reader->sum1 >= 3 && reader->sum2 <= 1) { // detected a 2bit position
980 reader->shiftReg >>= 2;
981 reader->shiftReg |= (reader->bitCount << 6);
984 if (reader->bitCount == 15) { // we have a full byte
986 reader->output[reader->byteCount++] = reader->shiftReg;
987 if (reader->byteCount > reader->byteCountMax) {
988 // buffer overflow, give up
989 LED_B_OFF();
990 DecodeReaderReset(reader);
993 reader->bitCount = 0;
994 reader->shiftReg = 0;
995 if (reader->byteCount == reader->jam_search_len) {
996 if (!memcmp(reader->output, reader->jam_search_string, reader->jam_search_len)) {
997 LED_D_ON();
998 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_JAM);
999 reader->state = STATE_READER_RECEIVE_JAMMING;
1003 } else {
1004 reader->bitCount++;
1007 break;
1009 case STATE_READER_RECEIVE_DATA_1_OUT_OF_256:
1011 reader->posCount++;
1013 if (reader->posCount == 1) {
1014 reader->sum1 = bit ? 1 : 0;
1015 } else if (reader->posCount <= 4) {
1016 if (bit) reader->sum1++;
1017 } else if (reader->posCount == 5) {
1018 reader->sum2 = bit ? 1 : 0;
1019 } else if (bit) {
1020 reader->sum2++;
1023 if (reader->posCount == 8) {
1024 reader->posCount = 0;
1025 if (reader->sum1 <= 1 && reader->sum2 >= 3) { // EOF
1026 LED_B_OFF(); // Finished receiving
1027 DecodeReaderReset(reader);
1028 if (reader->byteCount != 0) {
1029 return true;
1032 } else if (reader->sum1 >= 3 && reader->sum2 <= 1) { // detected the bit position
1033 reader->shiftReg = reader->bitCount;
1036 if (reader->bitCount == 255) { // we have a full byte
1037 reader->output[reader->byteCount++] = reader->shiftReg;
1038 if (reader->byteCount > reader->byteCountMax) {
1039 // buffer overflow, give up
1040 LED_B_OFF();
1041 DecodeReaderReset(reader);
1044 if (reader->byteCount == reader->jam_search_len) {
1045 if (!memcmp(reader->output, reader->jam_search_string, reader->jam_search_len)) {
1046 LED_D_ON();
1047 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_JAM);
1048 reader->state = STATE_READER_RECEIVE_JAMMING;
1052 reader->bitCount++;
1054 break;
1056 case STATE_READER_RECEIVE_JAMMING:
1058 reader->posCount++;
1060 if (reader->Coding == CODING_1_OUT_OF_4) {
1061 if (reader->posCount == 7 * 16) { // 7 bits jammed
1062 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE); // stop jamming
1063 // FpgaDisableTracing();
1064 LED_D_OFF();
1065 } else if (reader->posCount == 8 * 16) {
1066 reader->posCount = 0;
1067 reader->output[reader->byteCount++] = 0x00;
1068 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
1070 } else {
1071 if (reader->posCount == 7 * 256) { // 7 bits jammend
1072 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE); // stop jamming
1073 LED_D_OFF();
1074 } else if (reader->posCount == 8 * 256) {
1075 reader->posCount = 0;
1076 reader->output[reader->byteCount++] = 0x00;
1077 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
1080 break;
1082 default:
1083 LED_B_OFF();
1084 DecodeReaderReset(reader);
1085 break;
1088 return false;
1091 //-----------------------------------------------------------------------------
1092 // Receive a command (from the reader to us, where we are the simulated tag),
1093 // and store it in the given buffer, up to the given maximum length. Keeps
1094 // spinning, waiting for a well-framed command, until either we get one
1095 // (returns len) or someone presses the pushbutton on the board (returns -1).
1097 // Assume that we're called with the SSC (to the FPGA) and ADC path set
1098 // correctly.
1099 //-----------------------------------------------------------------------------
1101 int GetIso15693CommandFromReader(uint8_t *received, size_t max_len, uint32_t *eof_time) {
1102 int samples = 0;
1103 bool gotFrame = false;
1105 // the decoder data structure
1106 DecodeReader_t *dr = (DecodeReader_t *)BigBuf_malloc(sizeof(DecodeReader_t));
1107 DecodeReaderInit(dr, received, max_len, 0, NULL);
1109 // wait for last transfer to complete
1110 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
1112 LED_D_OFF();
1113 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
1115 // clear receive register and wait for next transfer
1116 uint32_t temp = AT91C_BASE_SSC->SSC_RHR;
1117 (void) temp;
1118 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) ;
1120 // Setup and start DMA.
1121 dmabuf8_t *dma = get_dma8();
1122 if (FpgaSetupSscDma(dma->buf, DMA_BUFFER_SIZE) == false) {
1123 if (DBGLEVEL > DBG_ERROR) Dbprintf("FpgaSetupSscDma failed. Exiting");
1124 return -4;
1126 uint8_t *upTo = dma->buf;
1128 uint32_t dma_start_time = GetCountSspClk() & 0xfffffff8;
1130 for (;;) {
1131 volatile uint16_t behindBy = ((uint8_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
1132 if (behindBy == 0) continue;
1134 if (samples == 0) {
1135 // DMA has transferred the very first data
1136 dma_start_time = GetCountSspClk() & 0xfffffff0;
1139 volatile uint8_t b = *upTo++;
1140 if (upTo >= dma->buf + DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
1141 upTo = dma->buf; // start reading the circular buffer from the beginning
1142 if (behindBy > (9 * DMA_BUFFER_SIZE / 10)) {
1143 Dbprintf("About to blow circular buffer - aborted! behindBy %d", behindBy);
1144 break;
1147 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
1148 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf; // refresh the DMA Next Buffer and
1149 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; // DMA Next Counter registers
1152 for (int i = 7; i >= 0; i--) {
1153 if (Handle15693SampleFromReader((b >> i) & 0x01, dr)) {
1154 *eof_time = dma_start_time + samples - DELAY_READER_TO_ARM; // end of EOF
1155 gotFrame = true;
1156 break;
1158 samples++;
1161 if (gotFrame) {
1162 break;
1165 if (BUTTON_PRESS()) {
1166 dr->byteCount = -1;
1167 break;
1170 WDT_HIT();
1173 FpgaDisableSscDma();
1175 if (DBGLEVEL >= DBG_EXTENDED) {
1176 Dbprintf("samples = %d, gotFrame = %d, Decoder: state = %d, len = %d, bitCount = %d, posCount = %d",
1177 samples, gotFrame, dr->state, dr->byteCount,
1178 dr->bitCount, dr->posCount);
1181 if (dr->byteCount >= 0) {
1182 uint32_t sof_time = *eof_time
1183 - dr->byteCount * (dr->Coding == CODING_1_OUT_OF_4 ? 128 : 2048) // time for byte transfers
1184 - 32 // time for SOF transfer
1185 - 16; // time for EOF transfer
1186 LogTrace_ISO15693(dr->output, dr->byteCount, (sof_time * 32), (*eof_time * 32), NULL, true);
1189 return dr->byteCount;
1192 //-----------------------------------------------------------------------------
1193 // Start to read an ISO 15693 tag. We send an identify request, then wait
1194 // for the response. The response is not demodulated, just left in the buffer
1195 // so that it can be downloaded to a PC and processed there.
1196 //-----------------------------------------------------------------------------
1197 void AcquireRawAdcSamplesIso15693(void) {
1198 LED_A_ON();
1199 uint8_t *dest = BigBuf_malloc(4000);
1201 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1202 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1203 LED_D_ON();
1204 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1205 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1207 uint8_t cmd[5];
1208 BuildIdentifyRequest(cmd);
1209 CodeIso15693AsReader(cmd, sizeof(cmd));
1211 // Give the tags time to energize
1212 SpinDelay(100);
1214 // Now send the command
1215 tosend_t *ts = get_tosend();
1217 uint32_t start_time = 0;
1218 TransmitTo15693Tag(ts->buf, ts->max, &start_time);
1220 // wait for last transfer to complete
1221 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY)) ;
1223 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_424_KHZ | FPGA_HF_READER_MODE_RECEIVE_AMPLITUDE);
1225 for (int c = 0; c < 4000;) {
1226 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1227 uint16_t r = AT91C_BASE_SSC->SSC_RHR;
1228 dest[c++] = r >> 5;
1232 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1233 LEDsoff();
1236 void SniffIso15693(uint8_t jam_search_len, uint8_t *jam_search_string) {
1238 LEDsoff();
1239 LED_A_ON();
1241 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1243 DbpString("Starting to sniff. Press PM3 Button to stop.");
1245 BigBuf_free();
1246 clear_trace();
1247 set_tracing(true);
1249 DecodeTag_t dtag = {0};
1250 uint8_t response[ISO15693_MAX_RESPONSE_LENGTH] = {0};
1251 DecodeTagInit(&dtag, response, sizeof(response));
1253 DecodeReader_t dreader = {0};
1254 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH] = {0};
1255 DecodeReaderInit(&dreader, cmd, sizeof(cmd), jam_search_len, jam_search_string);
1257 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE);
1258 LED_D_OFF();
1260 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1261 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1263 StartCountSspClk();
1265 // The DMA buffer, used to stream samples from the FPGA
1266 dmabuf16_t *dma = get_dma16();
1268 // Setup and start DMA.
1269 if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) {
1270 if (DBGLEVEL > DBG_ERROR) DbpString("FpgaSetupSscDma failed. Exiting");
1271 switch_off();
1272 return;
1275 bool tag_is_active = false;
1276 bool reader_is_active = false;
1277 bool expect_tag_answer = false;
1278 int dma_start_time = 0;
1280 // Count of samples received so far, so that we can include timing
1281 int samples = 0;
1283 uint16_t *upTo = dma->buf;
1285 for (;;) {
1287 volatile int behind_by = ((uint16_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
1288 if (behind_by < 1) continue;
1290 samples++;
1291 if (samples == 1) {
1292 // DMA has transferred the very first data
1293 dma_start_time = GetCountSspClk() & 0xfffffff0;
1296 volatile uint16_t sniffdata = *upTo++;
1298 // we have read all of the DMA buffer content
1299 if (upTo >= dma->buf + DMA_BUFFER_SIZE) {
1301 // start reading the circular buffer from the beginning
1302 upTo = dma->buf;
1304 // DMA Counter Register had reached 0, already rotated.
1305 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) {
1307 // primary buffer was stopped
1308 if (AT91C_BASE_PDC_SSC->PDC_RCR == false) {
1309 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf;
1310 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
1312 // secondary buffer sets as primary, secondary buffer was stopped
1313 if (AT91C_BASE_PDC_SSC->PDC_RNCR == false) {
1314 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf;
1315 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1318 WDT_HIT();
1319 if (BUTTON_PRESS()) {
1320 DbpString("Sniff stopped");
1321 break;
1326 // no need to try decoding reader data if the tag is sending
1327 if (tag_is_active == false) {
1329 if (Handle15693SampleFromReader((sniffdata & 0x02) >> 1, &dreader)) {
1331 uint32_t eof_time = dma_start_time + (samples * 16) + 8 - DELAY_READER_TO_ARM_SNIFF; // end of EOF
1332 if (dreader.byteCount > 0) {
1333 uint32_t sof_time = eof_time
1334 - dreader.byteCount * (dreader.Coding == CODING_1_OUT_OF_4 ? 128 * 16 : 2048 * 16) // time for byte transfers
1335 - 32 * 16 // time for SOF transfer
1336 - 16 * 16; // time for EOF transfer
1337 LogTrace_ISO15693(dreader.output, dreader.byteCount, (sof_time * 4), (eof_time * 4), NULL, true);
1339 // And ready to receive another command.
1340 DecodeReaderReset(&dreader);
1341 DecodeTagReset(&dtag);
1342 reader_is_active = false;
1343 expect_tag_answer = true;
1345 } else if (Handle15693SampleFromReader(sniffdata & 0x01, &dreader)) {
1347 uint32_t eof_time = dma_start_time + (samples * 16) + 16 - DELAY_READER_TO_ARM_SNIFF; // end of EOF
1348 if (dreader.byteCount > 0) {
1349 uint32_t sof_time = eof_time
1350 - dreader.byteCount * (dreader.Coding == CODING_1_OUT_OF_4 ? 128 * 16 : 2048 * 16) // time for byte transfers
1351 - 32 * 16 // time for SOF transfer
1352 - 16 * 16; // time for EOF transfer
1353 LogTrace_ISO15693(dreader.output, dreader.byteCount, (sof_time * 4), (eof_time * 4), NULL, true);
1355 // And ready to receive another command
1356 DecodeReaderReset(&dreader);
1357 DecodeTagReset(&dtag);
1358 reader_is_active = false;
1359 expect_tag_answer = true;
1361 } else {
1362 reader_is_active = (dreader.state >= STATE_READER_RECEIVE_DATA_1_OUT_OF_4);
1366 if (reader_is_active == false && expect_tag_answer) { // no need to try decoding tag data if the reader is currently sending or no answer expected yet
1368 if (Handle15693SamplesFromTag(sniffdata >> 2, &dtag)) {
1370 uint32_t eof_time = dma_start_time + (samples * 16) - DELAY_TAG_TO_ARM_SNIFF; // end of EOF
1371 if (dtag.lastBit == SOF_PART2) {
1372 eof_time -= (8 * 16); // needed 8 additional samples to confirm single SOF (iCLASS)
1374 uint32_t sof_time = eof_time
1375 - dtag.len * 8 * 8 * 16 // time for byte transfers
1376 - (32 * 16) // time for SOF transfer
1377 - (dtag.lastBit != SOF_PART2 ? (32 * 16) : 0); // time for EOF transfer
1379 LogTrace_ISO15693(dtag.output, dtag.len, (sof_time * 4), (eof_time * 4), NULL, false);
1380 // And ready to receive another response.
1381 DecodeTagReset(&dtag);
1382 DecodeReaderReset(&dreader);
1383 expect_tag_answer = false;
1384 tag_is_active = false;
1385 } else {
1386 tag_is_active = (dtag.state >= STATE_TAG_RECEIVING_DATA);
1392 FpgaDisableTracing();
1393 switch_off();
1395 DbpString("");
1396 DbpString(_CYAN_("Sniff statistics"));
1397 DbpString("=================================");
1398 Dbprintf(" DecodeTag State........%d", dtag.state);
1399 Dbprintf(" DecodeTag byteCnt......%d", dtag.len);
1400 Dbprintf(" DecodeTag posCount.....%d", dtag.posCount);
1401 Dbprintf(" DecodeReader State.....%d", dreader.state);
1402 Dbprintf(" DecodeReader byteCnt...%d", dreader.byteCount);
1403 Dbprintf(" DecodeReader posCount..%d", dreader.posCount);
1404 Dbprintf(" Trace length..........." _YELLOW_("%d"), BigBuf_get_traceLen());
1405 DbpString("");
1409 // Initialize Proxmark3 as ISO15693 reader
1410 void Iso15693InitReader(void) {
1412 LEDsoff();
1413 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1415 // Start from off (no field generated)
1416 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1417 SpinDelay(10);
1419 // switch field on
1420 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1421 LED_D_ON();
1423 // initialize SSC and select proper AD input
1424 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1425 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1427 set_tracing(true);
1429 // give tags some time to energize
1430 SpinDelay(250);
1432 StartCountSspClk();
1435 ///////////////////////////////////////////////////////////////////////
1436 // ISO 15693 Part 3 - Air Interface
1437 // This section basicly contains transmission and receiving of bits
1438 ///////////////////////////////////////////////////////////////////////
1440 // Encode an identify request, which is the first
1441 // thing that you must send to a tag to get a response.
1442 // It expects "cmdout" to be at least CMD_ID_RESP large
1443 // When READER:
1444 static void BuildIdentifyRequest(uint8_t *cmd) {
1445 // flags
1446 cmd[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1;
1447 // inventory command code
1448 cmd[1] = ISO15693_INVENTORY;
1449 // no mask
1450 cmd[2] = 0x00;
1451 // CRC
1452 AddCrc15(cmd, 3);
1455 // Universal Method for sending to and recv bytes from a tag
1456 // init ... should we initialize the reader?
1457 // speed ... 0 low speed, 1 hi speed
1458 // **recv will return you a pointer to the received data
1459 // If you do not need the answer use NULL for *recv[]
1460 // return: length of received data
1461 // logging enabled
1462 int SendDataTag(uint8_t *send, int sendlen, bool init, bool speed_fast, uint8_t *recv,
1463 uint16_t max_recv_len, uint32_t start_time, uint16_t timeout, uint32_t *eof_time) {
1465 if (init) {
1466 Iso15693InitReader();
1467 start_time = GetCountSspClk();
1470 if (speed_fast) {
1471 // high speed (1 out of 4)
1472 CodeIso15693AsReader(send, sendlen);
1473 } else {
1474 // low speed (1 out of 256)
1475 CodeIso15693AsReader256(send, sendlen);
1477 int res = 0;
1478 tosend_t *ts = get_tosend();
1479 TransmitTo15693Tag(ts->buf, ts->max, &start_time);
1481 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
1483 res = PM3_ETEAROFF;
1485 } else {
1487 *eof_time = start_time + 32 * ((8 * ts->max) - 4); // substract the 4 padding bits after EOF
1488 LogTrace_ISO15693(send, sendlen, (start_time * 4), (*eof_time * 4), NULL, true);
1489 if (recv != NULL) {
1490 res = GetIso15693AnswerFromTag(recv, max_recv_len, timeout, eof_time);
1493 return res;
1496 int SendDataTagEOF(uint8_t *recv, uint16_t max_recv_len, uint32_t start_time, uint16_t timeout, uint32_t *eof_time) {
1498 CodeIso15693AsReaderEOF();
1499 tosend_t *ts = get_tosend();
1500 TransmitTo15693Tag(ts->buf, ts->max, &start_time);
1501 uint32_t end_time = start_time + 32 * (8 * ts->max - 4); // substract the 4 padding bits after EOF
1502 LogTrace_ISO15693(NULL, 0, (start_time * 4), (end_time * 4), NULL, true);
1504 int res = 0;
1505 if (recv != NULL) {
1506 res = GetIso15693AnswerFromTag(recv, max_recv_len, timeout, eof_time);
1508 return res;
1511 // --------------------------------------------------------------------
1512 // Debug Functions
1513 // --------------------------------------------------------------------
1515 // Decodes a message from a tag and displays its metadata and content
1516 #define DBD15STATLEN 48
1517 static void DbdecodeIso15693Answer(int len, uint8_t *d) {
1519 if (len > 3) {
1521 char status[DBD15STATLEN + 1] = {0};
1523 if (d[0] & ISO15_RES_EXT)
1524 strncat(status, "ProtExt ", DBD15STATLEN - strlen(status));
1526 if (d[0] & ISO15_RES_ERROR) {
1527 // error
1528 strncat(status, "Error ", DBD15STATLEN - strlen(status));
1529 switch (d[1]) {
1530 case 0x01:
1531 strncat(status, "01: not supported", DBD15STATLEN - strlen(status));
1532 break;
1533 case 0x02:
1534 strncat(status, "02: not recognized", DBD15STATLEN - strlen(status));
1535 break;
1536 case 0x03:
1537 strncat(status, "03: opt not supported", DBD15STATLEN - strlen(status));
1538 break;
1539 case 0x0f:
1540 strncat(status, "0F: no info", DBD15STATLEN - strlen(status));
1541 break;
1542 case 0x10:
1543 strncat(status, "10: don't exist", DBD15STATLEN - strlen(status));
1544 break;
1545 case 0x11:
1546 strncat(status, "11: lock again", DBD15STATLEN - strlen(status));
1547 break;
1548 case 0x12:
1549 strncat(status, "12: locked", DBD15STATLEN - strlen(status));
1550 break;
1551 case 0x13:
1552 strncat(status, "13: program error", DBD15STATLEN - strlen(status));
1553 break;
1554 case 0x14:
1555 strncat(status, "14: lock error", DBD15STATLEN - strlen(status));
1556 break;
1557 default:
1558 strncat(status, "unknown error", DBD15STATLEN - strlen(status));
1560 strncat(status, " ", DBD15STATLEN - strlen(status));
1561 } else {
1562 strncat(status, "No error ", DBD15STATLEN - strlen(status));
1565 if (CheckCrc15(d, len))
1566 strncat(status, "[+] crc (" _GREEN_("OK") ")", DBD15STATLEN - strlen(status));
1567 else
1568 strncat(status, "[!] crc (" _RED_("fail") ")", DBD15STATLEN - strlen(status));
1570 if (DBGLEVEL >= DBG_ERROR) Dbprintf("%s", status);
1574 ///////////////////////////////////////////////////////////////////////
1575 // Functions called via USB/Client
1576 ///////////////////////////////////////////////////////////////////////
1578 //-----------------------------------------------------------------------------
1579 // Act as ISO15693 reader, perform anti-collision and then attempt to read a sector
1580 // all demodulation performed in arm rather than host. - greg
1581 //-----------------------------------------------------------------------------
1582 // ok
1583 // parameter is unused !?!
1584 void ReaderIso15693(uint32_t parameter, iso15_card_select_t *p_card) {
1586 LED_A_ON();
1587 set_tracing(true);
1589 uint8_t *answer = BigBuf_malloc(ISO15693_MAX_RESPONSE_LENGTH);
1590 memset(answer, 0x00, ISO15693_MAX_RESPONSE_LENGTH);
1592 // FIRST WE RUN AN INVENTORY TO GET THE TAG UID
1593 // THIS MEANS WE CAN PRE-BUILD REQUESTS TO SAVE CPU TIME
1595 // Send the IDENTIFY command
1596 uint8_t cmd[5] = {0};
1597 BuildIdentifyRequest(cmd);
1598 uint32_t start_time = 0;
1599 uint32_t eof_time;
1600 int recvlen = SendDataTag(cmd, sizeof(cmd), true, true, answer, ISO15693_MAX_RESPONSE_LENGTH, start_time, ISO15693_READER_TIMEOUT, &eof_time);
1602 if (recvlen == PM3_ETEAROFF) { // tearoff occurred
1603 reply_mix(CMD_ACK, recvlen, 0, 0, NULL, 0);
1604 } else {
1606 //start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
1608 // we should do a better check than this
1609 if (recvlen >= 12) {
1610 uint8_t uid[8];
1611 uid[0] = answer[9]; // always E0
1612 uid[1] = answer[8]; // IC Manufacturer code
1613 uid[2] = answer[7];
1614 uid[3] = answer[6];
1615 uid[4] = answer[5];
1616 uid[5] = answer[4];
1617 uid[6] = answer[3];
1618 uid[7] = answer[2];
1620 if (p_card != NULL) {
1621 memcpy(p_card->uid, uid, 8);
1622 p_card->uidlen = 8;
1625 if (DBGLEVEL >= DBG_EXTENDED) {
1626 Dbprintf("[+] UID = %02X%02X%02X%02X%02X%02X%02X%02X",
1627 uid[0], uid[1], uid[2], uid[3],
1628 uid[4], uid[5], uid[5], uid[6]
1631 // send UID back to client.
1632 // arg0 = 1 = OK
1633 // arg1 = len of response (12 bytes)
1634 // arg2 = rtf
1635 // asbytes = uid.
1636 reply_mix(CMD_ACK, 1, sizeof(uid), 0, uid, sizeof(uid));
1638 if (DBGLEVEL >= DBG_EXTENDED) {
1639 Dbprintf("[+] %d octets read from IDENTIFY request:", recvlen);
1640 DbdecodeIso15693Answer(recvlen, answer);
1641 Dbhexdump(recvlen, answer, true);
1643 } else {
1644 p_card->uidlen = 0;
1645 DbpString("Failed to select card");
1646 reply_mix(CMD_ACK, 0, 0, 0, NULL, 0);
1649 switch_off();
1650 BigBuf_free();
1653 // When SIM: initialize the Proxmark3 as ISO15693 tag
1654 void Iso15693InitTag(void) {
1656 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1658 // Start from off (no field generated)
1659 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1660 LEDsoff();
1661 SpinDelay(10);
1663 // switch simulation FPGA
1664 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
1666 // initialize SSC and select proper AD input
1667 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
1668 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1670 clear_trace();
1671 set_tracing(true);
1673 StartCountSspClk();
1676 // Simulate an ISO15693 TAG, perform anti-collision and then print any reader commands
1677 // all demodulation performed in arm rather than host. - greg
1678 void SimTagIso15693(uint8_t *uid) {
1680 // free eventually allocated BigBuf memory
1681 BigBuf_free_keep_EM();
1683 Iso15693InitTag();
1685 LED_A_ON();
1687 Dbprintf("ISO-15963 Simulating uid: %02X%02X%02X%02X%02X%02X%02X%02X", uid[0], uid[1], uid[2], uid[3], uid[4], uid[5], uid[6], uid[7]);
1689 LED_C_ON();
1693 enum { NO_FIELD, IDLE, ACTIVATED, SELECTED, HALTED } chip_state = NO_FIELD;
1695 bool button_pressed = false;
1696 int vHf; // in mV
1698 bool exit_loop = false;
1699 while (exit_loop == false) {
1701 button_pressed = BUTTON_PRESS();
1702 if (button_pressed || data_available())
1703 break;
1705 WDT_HIT();
1707 // find reader field
1708 if (chip_state == NO_FIELD) {
1710 #if defined RDV4
1711 vHf = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
1712 #else
1713 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
1714 #endif
1715 if (vHf > MF_MINFIELDV) {
1716 chip_state = IDLE;
1717 LED_A_ON();
1718 } else {
1719 continue;
1723 // Listen to reader
1724 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
1725 uint32_t reader_eof_time = 0;
1726 int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &reader_eof_time);
1727 if (cmd_len < 0) {
1728 button_pressed = true;
1729 break;
1732 // TODO: check more flags
1733 if ((cmd_len >= 5) && (cmd[0] & ISO15_REQ_INVENTORY) && (cmd[1] == ISO15693_INVENTORY)) {
1734 bool slow = !(cmd[0] & ISO15_REQ_DATARATE_HIGH);
1735 uint32_t response_time = reader_eof_time + DELAY_ISO15693_VCD_TO_VICC_SIM;
1737 // Build INVENTORY command
1738 uint8_t resp_inv[CMD_INV_RESP] = {0};
1740 resp_inv[0] = 0; // No error, no protocol format extension
1741 resp_inv[1] = 0; // DSFID (data storage format identifier). 0x00 = not supported
1743 // 64-bit UID
1744 resp_inv[2] = uid[7];
1745 resp_inv[3] = uid[6];
1746 resp_inv[4] = uid[5];
1747 resp_inv[5] = uid[4];
1748 resp_inv[6] = uid[3];
1749 resp_inv[7] = uid[2];
1750 resp_inv[8] = uid[1];
1751 resp_inv[9] = uid[0];
1753 // CRC
1754 AddCrc15(resp_inv, 10);
1755 CodeIso15693AsTag(resp_inv, CMD_INV_RESP);
1757 tosend_t *ts = get_tosend();
1759 TransmitTo15693Reader(ts->buf, ts->max, &response_time, 0, slow);
1760 LogTrace_ISO15693(resp_inv, CMD_INV_RESP, response_time * 32, (response_time * 32) + (ts->max * 32 * 64), NULL, false);
1762 chip_state = SELECTED;
1765 // GET_SYSTEM_INFO
1766 if ((cmd[1] == ISO15693_GET_SYSTEM_INFO)) {
1767 bool slow = !(cmd[0] & ISO15_REQ_DATARATE_HIGH);
1768 uint32_t response_time = reader_eof_time + DELAY_ISO15693_VCD_TO_VICC_SIM;
1770 // Build GET_SYSTEM_INFO command
1771 uint8_t resp_sysinfo[CMD_SYSINFO_RESP] = {0};
1773 resp_sysinfo[0] = 0; // Response flags.
1774 resp_sysinfo[1] = 0x0F; // Information flags (0x0F - DSFID, AFI, Mem size, IC)
1776 // 64-bit UID
1777 resp_sysinfo[2] = uid[7];
1778 resp_sysinfo[3] = uid[6];
1779 resp_sysinfo[4] = uid[5];
1780 resp_sysinfo[5] = uid[4];
1781 resp_sysinfo[6] = uid[3];
1782 resp_sysinfo[7] = uid[2];
1783 resp_sysinfo[8] = uid[1];
1784 resp_sysinfo[9] = uid[0];
1786 resp_sysinfo[10] = 0; // DSFID
1787 resp_sysinfo[11] = 0; // AFI
1789 resp_sysinfo[12] = 0x1B; // Memory size.
1790 resp_sysinfo[13] = 0x03; // Memory size.
1791 resp_sysinfo[14] = 0x01; // IC reference.
1793 // CRC
1794 AddCrc15(resp_sysinfo, 15);
1795 CodeIso15693AsTag(resp_sysinfo, CMD_SYSINFO_RESP);
1797 tosend_t *ts = get_tosend();
1799 TransmitTo15693Reader(ts->buf, ts->max, &response_time, 0, slow);
1800 LogTrace_ISO15693(resp_sysinfo, CMD_SYSINFO_RESP, response_time * 32, (response_time * 32) + (ts->max * 32 * 64), NULL, false);
1803 // READ_BLOCK
1804 if ((cmd[1] == ISO15693_READBLOCK)) {
1805 bool slow = !(cmd[0] & ISO15_REQ_DATARATE_HIGH);
1806 uint32_t response_time = reader_eof_time + DELAY_ISO15693_VCD_TO_VICC_SIM;
1808 // Build GET_SYSTEM_INFO command
1809 uint8_t resp_readblock[CMD_READBLOCK_RESP] = {0};
1811 resp_readblock[0] = 0; // Response flags.
1812 resp_readblock[1] = 0; // Block data.
1813 resp_readblock[2] = 0; // Block data.
1814 resp_readblock[3] = 0; // Block data.
1815 resp_readblock[4] = 0; // Block data.
1817 // CRC
1818 AddCrc15(resp_readblock, 5);
1819 CodeIso15693AsTag(resp_readblock, CMD_READBLOCK_RESP);
1821 tosend_t *ts = get_tosend();
1823 TransmitTo15693Reader(ts->buf, ts->max, &response_time, 0, slow);
1824 LogTrace_ISO15693(resp_readblock, CMD_READBLOCK_RESP, response_time * 32, (response_time * 32) + (ts->max * 32 * 64), NULL, false);
1828 switch_off();
1830 if (button_pressed)
1831 DbpString("button pressed");
1833 reply_ng(CMD_HF_ISO15693_SIMULATE, PM3_SUCCESS, NULL, 0);
1836 // Since there is no standardized way of reading the AFI out of a tag, we will brute force it
1837 // (some manufactures offer a way to read the AFI, though)
1838 void BruteforceIso15693Afi(uint32_t speed) {
1840 uint8_t data[7] = {0};
1841 uint8_t recv[ISO15693_MAX_RESPONSE_LENGTH];
1842 Iso15693InitReader();
1844 // first without AFI
1845 // Tags should respond wihtout AFI and with AFI=0 even when AFI is active
1847 data[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1;
1848 data[1] = ISO15693_INVENTORY;
1849 data[2] = 0; // AFI
1850 AddCrc15(data, 3);
1852 int datalen = 5;
1853 uint32_t eof_time = 0;
1854 int recvlen = SendDataTag(data, datalen, true, speed, recv, sizeof(recv), 0, ISO15693_READER_TIMEOUT, &eof_time);
1855 uint32_t start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
1857 WDT_HIT();
1859 if (recvlen >= 12) {
1860 Dbprintf("NoAFI UID = %s", iso15693_sprintUID(NULL, recv + 2));
1861 } else {
1862 DbpString("Failed to select card");
1863 reply_ng(CMD_HF_ISO15693_FINDAFI, PM3_ESOFT, NULL, 0);
1864 switch_off();
1865 return;
1868 // now with AFI
1869 data[0] |= ISO15_REQINV_AFI;
1870 data[2] = 0; // AFI
1871 data[3] = 0; // mask length
1873 // 4 + 2crc
1874 datalen = 6;
1876 bool aborted = false;
1877 for (uint16_t i = 0; i < 256; i++) {
1879 data[2] = i & 0xFF;
1880 AddCrc15(data, 4);
1882 recvlen = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), start_time, ISO15693_READER_TIMEOUT, &eof_time);
1883 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
1885 WDT_HIT();
1887 if (recvlen >= 12) {
1888 Dbprintf("AFI = %i UID = %s", i, iso15693_sprintUID(NULL, recv + 2));
1891 aborted = BUTTON_PRESS() && data_available();
1892 if (aborted) {
1893 break;
1897 DbpString("AFI Bruteforcing done.");
1898 switch_off();
1900 if (aborted) {
1901 reply_ng(CMD_HF_ISO15693_FINDAFI, PM3_EOPABORTED, NULL, 0);
1902 } else {
1903 reply_ng(CMD_HF_ISO15693_FINDAFI, PM3_SUCCESS, NULL, 0);
1907 // Allows to directly send commands to the tag via the client
1908 // OBS: doesn't turn off rf field afterwards.
1909 void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint8_t *data) {
1911 LED_A_ON();
1913 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
1914 uint16_t timeout;
1915 uint32_t eof_time = 0;
1916 bool request_answer = false;
1918 switch (data[1]) {
1919 case ISO15693_WRITEBLOCK:
1920 case ISO15693_LOCKBLOCK:
1921 case ISO15693_WRITE_MULTI_BLOCK:
1922 case ISO15693_WRITE_AFI:
1923 case ISO15693_LOCK_AFI:
1924 case ISO15693_WRITE_DSFID:
1925 case ISO15693_LOCK_DSFID:
1926 timeout = ISO15693_READER_TIMEOUT_WRITE;
1927 request_answer = data[0] & ISO15_REQ_OPTION;
1928 break;
1929 default:
1930 timeout = ISO15693_READER_TIMEOUT;
1933 uint32_t start_time = 0;
1934 int recvlen = SendDataTag(data, datalen, true, speed, (recv ? recvbuf : NULL), sizeof(recvbuf), start_time, timeout, &eof_time);
1936 if (recvlen == PM3_ETEAROFF) { // tearoff occurred
1937 reply_mix(CMD_ACK, recvlen, 0, 0, NULL, 0);
1938 } else {
1940 // send a single EOF to get the tag response
1941 if (request_answer) {
1942 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
1943 recvlen = SendDataTagEOF((recv ? recvbuf : NULL), sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT, &eof_time);
1946 if (recv) {
1947 recvlen = MIN(recvlen, ISO15693_MAX_RESPONSE_LENGTH);
1948 reply_mix(CMD_ACK, recvlen, 0, 0, recvbuf, recvlen);
1949 } else {
1950 reply_mix(CMD_ACK, 1, 0, 0, NULL, 0);
1953 // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
1954 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1955 LED_D_OFF();
1959 SLIx functions from official master forks.
1961 void LockPassSlixIso15693(uint32_t pass_id, uint32_t password) {
1963 LED_A_ON();
1965 uint8_t cmd_inventory[] = {ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_INVENTORY | ISO15693_REQINV_SLOT1, 0x01, 0x00, 0x00, 0x00 };
1966 uint8_t cmd_get_rnd[] = {ISO15693_REQ_DATARATE_HIGH, 0xB2, 0x04, 0x00, 0x00 };
1967 uint8_t cmd_set_pass[] = {ISO15693_REQ_DATARATE_HIGH, 0xB3, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1968 //uint8_t cmd_write_pass[] = {ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_ADDRESS, 0xB4, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1969 uint8_t cmd_lock_pass[] = {ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_ADDRESS, 0xB5, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00 };
1970 uint16_t crc;
1971 int recvlen = 0;
1972 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
1973 uint32_t start_time = 0;
1974 bool done = false;
1976 // setup 'get random number' command
1977 crc = Iso15693Crc(cmd_get_rnd, 3);
1978 cmd_get_rnd[3] = crc & 0xff;
1979 cmd_get_rnd[4] = crc >> 8;
1981 Dbprintf("LockPass: Press button lock password, long-press to terminate.");
1983 while (!done) {
1985 LED_D_ON();
1986 switch(BUTTON_HELD(1000)) {
1987 case BUTTON_SINGLE_CLICK:
1988 Dbprintf("LockPass: Reset 'DONE'-LED (A)");
1989 LED_A_OFF();
1990 LED_B_OFF();
1991 LED_C_OFF();
1992 break;
1993 case BUTTON_HOLD:
1994 Dbprintf("LockPass: Terminating");
1995 done = true;
1996 break;
1997 default:
1998 SpinDelay(50);
1999 continue;
2002 if (done) [
2003 break;
2006 recvlen = SendDataTag(cmd_get_rnd, sizeof(cmd_get_rnd), true, true, recvbuf, sizeof(recvbuf), start_time);
2007 if (recvlen != 5) {
2008 LED_C_ON();
2009 } else {
2010 Dbprintf("LockPass: Received random 0x%02X%02X (%d)", recvbuf[1], recvbuf[2], recvlen);
2012 // setup 'set password' command
2013 cmd_set_pass[4] = ((password>>0) &0xFF) ^ recvbuf[1];
2014 cmd_set_pass[5] = ((password>>8) &0xFF) ^ recvbuf[2];
2015 cmd_set_pass[6] = ((password>>16) &0xFF) ^ recvbuf[1];
2016 cmd_set_pass[7] = ((password>>24) &0xFF) ^ recvbuf[2];
2018 crc = Iso15693Crc(cmd_set_pass, 8);
2019 cmd_set_pass[8] = crc & 0xff;
2020 cmd_set_pass[9] = crc >> 8;
2022 Dbprintf("LockPass: Sending old password to end privacy mode", cmd_set_pass[4], cmd_set_pass[5], cmd_set_pass[6], cmd_set_pass[7]);
2023 recvlen = SendDataTag(cmd_set_pass, sizeof(cmd_set_pass), false, true, recvbuf, sizeof(recvbuf), start_time);
2024 if (recvlen != 3) {
2025 Dbprintf("LockPass: Failed to set password (%d)", recvlen);
2026 LED_B_ON();
2027 } else {
2028 crc = Iso15693Crc(cmd_inventory, 3);
2029 cmd_inventory[3] = crc & 0xff;
2030 cmd_inventory[4] = crc >> 8;
2032 Dbprintf("LockPass: Searching for tag...");
2033 recvlen = SendDataTag(cmd_inventory, sizeof(cmd_inventory), false, true, recvbuf, sizeof(recvbuf), start_time);
2034 if (recvlen != 12) {
2035 Dbprintf("LockPass: Failed to read inventory (%d)", recvlen);
2036 LED_B_ON();
2037 LED_C_ON();
2038 } else {
2040 Dbprintf("LockPass: Answer from %02X%02X%02X%02X%02X%02X%02X%02X", recvbuf[9], recvbuf[8], recvbuf[7], recvbuf[6], recvbuf[5], recvbuf[4], recvbuf[3], recvbuf[2]);
2042 memcpy(&cmd_lock_pass[3], &recvbuf[2], 8);
2044 cmd_lock_pass[8+3] = pass_id;
2046 crc = Iso15693Crc(cmd_lock_pass, 8+4);
2047 cmd_lock_pass[8+4] = crc & 0xff;
2048 cmd_lock_pass[8+5] = crc >> 8;
2050 Dbprintf("LockPass: locking to password 0x%02X%02X%02X%02X for ID %02X", cmd_set_pass[4], cmd_set_pass[5], cmd_set_pass[6], cmd_set_pass[7], pass_id);
2052 recvlen = SendDataTag(cmd_lock_pass, sizeof(cmd_lock_pass), false, true, recvbuf, sizeof(recvbuf), start_time);
2053 if (recvlen != 3) {
2054 Dbprintf("LockPass: Failed to lock password (%d)", recvlen);
2055 } else {
2056 Dbprintf("LockPass: Successful (%d)", recvlen);
2058 LED_A_ON();
2063 Dbprintf("LockPass: Finishing");
2064 cmd_send(CMD_ACK, recvlen, 0, 0, recvbuf, recvlen);
2068 //-----------------------------------------------------------------------------
2069 // Work with "magic Chinese" card.
2071 //-----------------------------------------------------------------------------
2073 // Set the UID on Magic ISO15693 tag (based on Iceman's LUA-script).
2074 void SetTag15693Uid(uint8_t *uid) {
2076 LED_A_ON();
2078 uint8_t cmd[4][9] = {
2079 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3e, 0x00, 0x00, 0x00, 0x00},
2080 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3f, 0x69, 0x96, 0x00, 0x00},
2081 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x38},
2082 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x39}
2085 // Command 3 : 02 21 38 u8u7u6u5 (where uX = uid byte X)
2086 cmd[2][3] = uid[7];
2087 cmd[2][4] = uid[6];
2088 cmd[2][5] = uid[5];
2089 cmd[2][6] = uid[4];
2091 // Command 4 : 02 21 39 u4u3u2u1 (where uX = uid byte X)
2092 cmd[3][3] = uid[3];
2093 cmd[3][4] = uid[2];
2094 cmd[3][5] = uid[1];
2095 cmd[3][6] = uid[0];
2097 AddCrc15(cmd[0], 7);
2098 AddCrc15(cmd[1], 7);
2099 AddCrc15(cmd[2], 7);
2100 AddCrc15(cmd[3], 7);
2102 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2104 uint32_t start_time = 0;
2105 uint32_t eof_time = 0;
2106 for (int i = 0; i < 4; i++) {
2107 SendDataTag(cmd[i], sizeof(cmd[i]), i == 0 ? true : false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, &eof_time);
2108 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2111 reply_ng(CMD_HF_ISO15693_CSETUID, PM3_SUCCESS, NULL, 0);
2112 switch_off();
2115 static void init_password_15693_slixl(uint8_t *buffer, uint8_t *pwd, uint8_t *rnd) {
2116 memcpy(buffer, pwd, 4);
2117 if (rnd) {
2118 buffer[0] ^= rnd[0];
2119 buffer[1] ^= rnd[1];
2120 buffer[2] ^= rnd[0];
2121 buffer[3] ^= rnd[1];
2125 static bool get_rnd_15693_slixl(uint32_t start_time, uint32_t *eof_time, uint8_t *rnd) {
2126 // 0x04, == NXP from manufacture id list.
2127 uint8_t c[] = {ISO15_REQ_DATARATE_HIGH, ISO15693_GET_RANDOM_NUMBER, 0x04, 0x00, 0x00 };
2128 AddCrc15(c, 3);
2130 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2131 int recvlen = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time);
2132 if (recvlen != 5) {
2133 return false;
2136 if (rnd) {
2137 memcpy(rnd, &recvbuf[1], 2);
2139 return true;
2142 static uint32_t set_pass_15693_slixl(uint32_t start_time, uint32_t *eof_time, uint8_t pass_id, uint8_t *password) {
2143 uint8_t rnd[2];
2144 if (get_rnd_15693_slixl(start_time, eof_time, rnd) == false) {
2145 return PM3_ETIMEOUT;
2148 // 0x04, == NXP from manufacture id list.
2149 uint8_t c[] = {ISO15_REQ_DATARATE_HIGH, ISO15693_SET_PASSWORD, 0x04, pass_id, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2150 init_password_15693_slixl(&c[4], password, rnd);
2151 AddCrc15(c, 8);
2153 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2154 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2155 int recvlen = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time);
2156 if (recvlen != 3) {
2157 return PM3_EWRONGANSWER;
2160 return PM3_SUCCESS;
2164 static uint32_t enable_privacy_15693_slixl(uint32_t start_time, uint32_t *eof_time, uint8_t *uid, uint8_t pass_id, uint8_t *password) {
2165 uint8_t rnd[2];
2166 if (get_rnd_15693_slixl(start_time, eof_time, rnd) == false) {
2167 return PM3_ETIMEOUT;
2170 uint8_t c[] = {ISO15_REQ_DATARATE_HIGH | ISO15_REQ_ADDRESS, ISO15693_ENABLE_PRIVACY, pass_id, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2171 memcpy(&c[3], uid, 8);
2172 init_password_15693_slixl(&c[11], password, rnd);
2173 AddCrc15(c, 15);
2175 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2176 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2177 int recvlen = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time);
2178 if (recvlen != 3) {
2179 return PM3_EWRONGANSWER;
2181 return PM3_SUCCESS;
2184 static uint32_t write_password_15693_slixl(uint32_t start_time, uint32_t *eof_time, uint8_t *uid, uint8_t pass_id, uint8_t *password) {
2185 uint8_t rnd[2];
2186 if (get_rnd_15693_slixl(start_time, eof_time, rnd) == false) {
2187 return PM3_ETIMEOUT;
2190 uint8_t c[] = {ISO15_REQ_DATARATE_HIGH | ISO15_REQ_ADDRESS, ISO15693_WRITE_PASSWORD, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2191 memcpy(&c[3], uid, 8);
2192 c[11] = pass_id;
2193 init_password_15693_slixl(&c[12], password, NULL);
2194 AddCrc15(c, 16);
2196 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2198 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2199 int recvlen = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time);
2200 if (recvlen != 3) {
2201 return PM3_EWRONGANSWER;
2203 return PM3_SUCCESS;
2206 static uint32_t destroy_15693_slixl(uint32_t start_time, uint32_t *eof_time, uint8_t *uid, uint8_t *password) {
2208 uint8_t rnd[2];
2209 if (get_rnd_15693_slixl(start_time, eof_time, rnd) == false) {
2210 return PM3_ETIMEOUT;
2213 uint8_t c[] = {ISO15_REQ_DATARATE_HIGH | ISO15_REQ_ADDRESS, ISO15693_DESTROY, ISO15693_ENABLE_PRIVACY, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2214 memcpy(&c[3], uid, 8);
2215 init_password_15693_slixl(&c[11], password, rnd);
2216 AddCrc15(c, 15);
2218 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2219 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2220 int recvlen = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time);
2221 if (recvlen != 3) {
2222 return PM3_EWRONGANSWER;
2224 return PM3_SUCCESS;
2228 void DisablePrivacySlixLIso15693(uint8_t *password) {
2229 LED_D_ON();
2230 Iso15693InitReader();
2231 StartCountSspClk();
2232 uint32_t start_time = 0, eof_time = 0;
2233 // 4 == pass id.
2234 int res = set_pass_15693_slixl(start_time, &eof_time, 0x10, password);
2235 reply_ng(CMD_HF_ISO15693_SLIX_L_DISABLE_PRIVACY, res, NULL, 0);
2236 switch_off();