Merge pull request #2654 from Antiklesys/master
[RRG-proxmark3.git] / armsrc / iso15693.c
blob6387672ea2cd9bc74b2d70261158a47e693a5c70
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Jonathan Westhues, Nov 2006
3 // Copyright (C) Greg Jones, Jan 2009
4 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
5 //
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // See LICENSE.txt for the text of the license.
17 //-----------------------------------------------------------------------------
18 // Routines to support ISO 15693. This includes both the reader software and
19 // the `fake tag' modes.
20 //-----------------------------------------------------------------------------
22 // The ISO 15693 describes two transmission modes from reader to tag, and four
23 // transmission modes from tag to reader. As of Oct 2018 this code supports
24 // both reader modes and the high speed variant with one subcarrier from card to reader.
25 // As long as the card fully support ISO 15693 this is no problem, since the
26 // reader chooses both data rates, but some non-standard tags do not.
27 // For card simulation, the code supports both high and low speed modes with one subcarrier.
29 // VCD (reader) -> VICC (tag)
30 // 1 out of 256:
31 // data rate: 1,66 kbit/s (fc/8192)
32 // used for long range
33 // 1 out of 4:
34 // data rate: 26,48 kbit/s (fc/512)
35 // used for short range, high speed
37 // VICC (tag) -> VCD (reader)
38 // Modulation:
39 // ASK / one subcarrier (423,75 kHz)
40 // FSK / two subcarriers (423,75 kHz && 484,28 kHz)
41 // Data Rates / Modes:
42 // low ASK: 6,62 kbit/s
43 // low FSK: 6.67 kbit/s
44 // high ASK: 26,48 kbit/s
45 // high FSK: 26,69 kbit/s
46 //-----------------------------------------------------------------------------
47 // added "1 out of 256" mode (for VCD->PICC) - atrox 20100911
50 // Random Remarks:
51 // *) UID is always used "transmission order" (LSB), which is reverse to display order
53 // TODO / BUGS / ISSUES:
54 // *) signal decoding is unable to detect collisions.
55 // *) add anti-collision support for inventory-commands
56 // *) read security status of a block
57 // *) simulation do not support two subcarrier modes.
58 // *) remove or refactor code under "deprecated"
59 // *) document all the functions
61 #include "iso15693.h"
63 #include "proxmark3_arm.h"
64 #include "util.h"
65 #include "string.h"
66 #include "iso15693tools.h"
67 #include "protocols.h"
68 #include "cmd.h"
69 #include "appmain.h"
70 #include "dbprint.h"
71 #include "fpgaloader.h"
72 #include "commonutil.h"
73 #include "ticks.h"
74 #include "BigBuf.h"
75 #include "crc16.h"
77 // Delays in SSP_CLK ticks.
78 // SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
79 #define DELAY_READER_TO_ARM 8
80 #define DELAY_ARM_TO_READER 0
82 //SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader. All values should be multiples of 16
83 #define DELAY_ARM_TO_TAG 16
84 #define DELAY_TAG_TO_ARM 32
86 //SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when sniffing. All values should be multiples of 16
87 #define DELAY_TAG_TO_ARM_SNIFF 32
88 #define DELAY_READER_TO_ARM_SNIFF 32
90 // times in samples @ 212kHz when acting as reader
91 #define ISO15693_READER_TIMEOUT 330 // 330/212kHz = 1558us
92 #define ISO15693_READER_TIMEOUT_WRITE 4700 // 4700/212kHz = 22ms, nominal 20ms
94 // iceman: This defines below exists in the header file, just here for my easy reading
95 // Delays in SSP_CLK ticks.
96 // SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
97 //#define DELAY_ISO15693_VCD_TO_VICC_SIM 132 // 132/423.75kHz = 311.5us from end of command EOF to start of tag response
99 //SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader. All values should be multiples of 16
100 //#define DELAY_ISO15693_VCD_TO_VICC_READER 1056 // 1056/3,39MHz = 311.5us from end of command EOF to start of tag response
101 //#define DELAY_ISO15693_VICC_TO_VCD_READER 1024 // 1024/3.39MHz = 302.1us between end of tag response and next reader command
104 ///////////////////////////////////////////////////////////////////////
105 // ISO 15693 Part 2 - Air Interface
106 // This section basically contains transmission and receiving of bits
107 ///////////////////////////////////////////////////////////////////////
109 // buffers
110 #define ISO15693_MAX_RESPONSE_LENGTH 2116 // allows read multiple block with the maximum block size of 256bits and a maximum block number of 64 with REQ_OPTION (lock status for each block).
111 #define ISO15693_MAX_COMMAND_LENGTH 45 // allows write single block with the maximum block size of 256bits. Write multiple blocks not supported yet
113 // 32 + 2 crc + 1
114 #define ISO15_MAX_FRAME 35
115 #define CMD_ID_RESP 5
116 #define CMD_READ_RESP 13
117 #define CMD_INV_RESP 12
118 #define CMD_SYSINFO_RESP 17
120 //#define Crc(data, len) Crc(CRC_15693, (data), (len))
121 #define CheckCrc15(data, len) check_crc(CRC_15693, (data), (len))
122 #define AddCrc15(data, len) compute_crc(CRC_15693, (data), (len), (data)+(len), (data)+(len)+1)
123 #define CalculateCrc15(data, len) Crc16ex(CRC_15693, (data), (len))
125 static void BuildIdentifyRequest(uint8_t *cmd);
127 // ---------------------------
129 // Signal Processing
130 // ---------------------------
132 // prepare data using "1 out of 4" code for later transmission
133 // resulting data rate is 26.48 kbit/s (fc/512)
134 // cmd ... data
135 // n ... length of data
136 static uint8_t encode15_lut[] = {
137 0x40, // 01000000
138 0x10, // 00010000
139 0x04, // 00000100
140 0x01 // 00000001
143 void CodeIso15693AsReader(const uint8_t *cmd, int n) {
145 tosend_reset();
146 tosend_t *ts = get_tosend();
148 // SOF for 1of4
149 ts->buf[++ts->max] = 0x84; //10000100
151 // data
152 for (int i = 0; i < n; i++) {
154 volatile uint8_t b = (cmd[i] >> 0) & 0x03;
155 ts->buf[++ts->max] = encode15_lut[b];
157 b = (cmd[i] >> 2) & 0x03;
158 ts->buf[++ts->max] = encode15_lut[b];
160 b = (cmd[i] >> 4) & 0x03;
161 ts->buf[++ts->max] = encode15_lut[b];
163 b = (cmd[i] >> 6) & 0x03;
164 ts->buf[++ts->max] = encode15_lut[b];
167 // EOF
168 ts->buf[++ts->max] = 0x20; //0010 + 0000 padding
169 ts->max++;
172 // Encode EOF only
173 static void CodeIso15693AsReaderEOF(void) {
174 tosend_reset();
175 tosend_t *ts = get_tosend();
176 ts->buf[++ts->max] = 0x20;
177 ts->max++;
181 static int get_uid_slix(uint32_t start_time, uint32_t *eof_time, uint8_t *uid) {
183 uint8_t *answer = BigBuf_malloc(ISO15693_MAX_RESPONSE_LENGTH);
184 memset(answer, 0x00, ISO15693_MAX_RESPONSE_LENGTH);
186 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
188 uint8_t cmd[5] = {0};
189 BuildIdentifyRequest(cmd);
190 uint16_t recvlen = 0;
191 SendDataTag(cmd, sizeof(cmd), false, true, answer, ISO15693_MAX_RESPONSE_LENGTH, start_time, ISO15693_READER_TIMEOUT, eof_time, &recvlen);
193 if (recvlen != 12) {
194 return PM3_ETIMEOUT;
197 uid[0] = answer[2];
198 uid[1] = answer[3];
199 uid[2] = answer[4];
200 uid[3] = answer[5];
201 uid[4] = answer[6];
202 uid[5] = answer[7];
203 uid[6] = answer[8];
204 uid[7] = answer[9];
206 BigBuf_free();
207 return PM3_SUCCESS;
211 // encode data using "1 out of 256" scheme
212 // data rate is 1,66 kbit/s (fc/8192)
213 // is designed for more robust communication over longer distances
214 static void CodeIso15693AsReader256(const uint8_t *cmd, int n) {
216 tosend_reset();
217 tosend_t *ts = get_tosend();
219 // SOF for 1of256
220 ts->buf[++ts->max] = 0x81; //10000001
222 // data
223 for (int i = 0; i < n; i++) {
224 for (int j = 0; j <= 255; j++) {
225 if (cmd[i] == j) {
226 tosend_stuffbit(0);
227 tosend_stuffbit(1);
228 } else {
229 tosend_stuffbit(0);
230 tosend_stuffbit(0);
235 // EOF
236 ts->buf[++ts->max] = 0x20; //0010 + 0000 padding
237 ts->max++;
240 static const uint8_t encode_4bits[16] = {
241 // 0 1 2 3
242 0xaa, 0x6a, 0x9a, 0x5a,
243 // 4 5 6 7
244 0xa6, 0x66, 0x96, 0x56,
245 // 8 9 A B
246 0xa9, 0x69, 0x99, 0x59,
247 // C D E F
248 0xa5, 0x65, 0x95, 0x55
251 void CodeIso15693AsTag(const uint8_t *cmd, size_t len) {
253 * SOF comprises 3 parts;
254 * * An unmodulated time of 56.64 us
255 * * 24 pulses of 423.75 kHz (fc/32)
256 * * A logic 1, which starts with an unmodulated time of 18.88us
257 * followed by 8 pulses of 423.75kHz (fc/32)
259 * EOF comprises 3 parts:
260 * - A logic 0 (which starts with 8 pulses of fc/32 followed by an unmodulated
261 * time of 18.88us.
262 * - 24 pulses of fc/32
263 * - An unmodulated time of 56.64 us
265 * A logic 0 starts with 8 pulses of fc/32
266 * followed by an unmodulated time of 256/fc (~18,88us).
268 * A logic 0 starts with unmodulated time of 256/fc (~18,88us) followed by
269 * 8 pulses of fc/32 (also 18.88us)
271 * A bit here becomes 8 pulses of fc/32. Therefore:
272 * The SOF can be written as 00011101 = 0x1D
273 * The EOF can be written as 10111000 = 0xb8
274 * A logic 1 is 01
275 * A logic 0 is 10
277 * */
278 tosend_reset();
279 tosend_t *ts = get_tosend();
281 // SOF
282 ts->buf[++ts->max] = 0x1D; // 00011101
284 // data
285 for (size_t i = 0; i < len; i ++) {
286 ts->buf[++ts->max] = encode_4bits[cmd[i] & 0xF];
287 ts->buf[++ts->max] = encode_4bits[cmd[i] >> 4];
290 // EOF
291 ts->buf[++ts->max] = 0xB8; // 10111000
292 ts->max++;
295 // Transmit the command (to the tag) that was placed in cmd[].
296 void TransmitTo15693Tag(const uint8_t *cmd, int len, uint32_t *start_time, bool shallow_mod) {
298 #ifdef RDV4
299 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | (shallow_mod ? FPGA_HF_READER_MODE_SEND_SHALLOW_MOD_RDV4 : FPGA_HF_READER_MODE_SEND_FULL_MOD));
300 #else
301 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | (shallow_mod ? FPGA_HF_READER_MODE_SEND_SHALLOW_MOD : FPGA_HF_READER_MODE_SEND_FULL_MOD));
302 #endif
305 if (*start_time < DELAY_ARM_TO_TAG) {
306 *start_time = DELAY_ARM_TO_TAG;
309 *start_time = (*start_time - DELAY_ARM_TO_TAG) & 0xfffffff0;
311 if (GetCountSspClk() > *start_time) { // we may miss the intended time
312 *start_time = (GetCountSspClk() + 16) & 0xfffffff0; // next possible time
315 // wait
316 while (GetCountSspClk() < *start_time) ;
318 LED_B_ON();
319 for (int c = 0; c < len; c++) {
320 volatile uint8_t data = cmd[c];
322 for (uint8_t i = 0; i < 8; i++) {
323 uint16_t send_word = (data & 0x80) ? 0xffff : 0x0000;
324 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
325 AT91C_BASE_SSC->SSC_THR = send_word;
326 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
327 AT91C_BASE_SSC->SSC_THR = send_word;
328 data <<= 1;
330 WDT_HIT();
332 LED_B_OFF();
334 *start_time = *start_time + DELAY_ARM_TO_TAG;
335 FpgaDisableTracing();
338 //-----------------------------------------------------------------------------
339 // Transmit the tag response (to the reader) that was placed in cmd[].
340 //-----------------------------------------------------------------------------
341 void TransmitTo15693Reader(const uint8_t *cmd, size_t len, uint32_t *start_time, uint32_t slot_time, bool slow) {
343 // don't use the FPGA_HF_SIMULATOR_MODULATE_424K_8BIT minor mode. It would spoil GetCountSspClk()
344 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K);
346 uint32_t modulation_start_time = *start_time - DELAY_ARM_TO_READER + 3 * 8; // no need to transfer the unmodulated start of SOF
348 while (GetCountSspClk() > (modulation_start_time & 0xfffffff8) + 3) { // we will miss the intended time
349 if (slot_time) {
350 modulation_start_time += slot_time; // use next available slot
351 } else {
352 modulation_start_time = (modulation_start_time & 0xfffffff8) + 8; // next possible time
356 // wait
357 while (GetCountSspClk() < (modulation_start_time & 0xfffffff8)) ;
359 uint8_t shift_delay = modulation_start_time & 0x00000007;
361 *start_time = modulation_start_time + DELAY_ARM_TO_READER - 3 * 8;
363 LED_C_ON();
364 uint8_t bits_to_shift = 0x00;
365 uint8_t bits_to_send = 0x00;
367 for (size_t c = 0; c < len; c++) {
368 for (int i = (c == 0 ? 4 : 7); i >= 0; i--) {
370 uint8_t cmd_bits = ((cmd[c] >> i) & 0x01) ? 0xff : 0x00;
372 for (int j = 0; j < (slow ? 4 : 1);) {
373 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
374 bits_to_send = bits_to_shift << (8 - shift_delay) | cmd_bits >> shift_delay;
375 AT91C_BASE_SSC->SSC_THR = bits_to_send;
376 bits_to_shift = cmd_bits;
377 j++;
381 WDT_HIT();
384 // send the remaining bits, padded with 0:
385 bits_to_send = bits_to_shift << (8 - shift_delay);
386 if (bits_to_send) {
387 for (; ;) {
388 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
389 AT91C_BASE_SSC->SSC_THR = bits_to_send;
390 break;
394 LED_C_OFF();
397 //=============================================================================
398 // An ISO 15693 decoder for tag responses (one subcarrier only).
399 // Uses cross correlation to identify each bit and EOF.
400 // This function is called 8 times per bit (every 2 subcarrier cycles).
401 // Subcarrier frequency fs is 424kHz, 1/fs = 2,36us,
402 // i.e. function is called every 4,72us
403 // LED handling:
404 // LED C -> ON once we have received the SOF and are expecting the rest.
405 // LED C -> OFF once we have received EOF or are unsynced
407 // Returns: true if we received a EOF
408 // false if we are still waiting for some more
409 //=============================================================================
411 #define NOISE_THRESHOLD 80 // don't try to correlate noise
412 #define MAX_PREVIOUS_AMPLITUDE (-1 - NOISE_THRESHOLD)
414 typedef struct {
415 enum {
416 STATE_TAG_SOF_LOW,
417 STATE_TAG_SOF_RISING_EDGE,
418 STATE_TAG_SOF_HIGH,
419 STATE_TAG_SOF_HIGH_END,
420 STATE_TAG_RECEIVING_DATA,
421 STATE_TAG_EOF,
422 STATE_TAG_EOF_TAIL
423 } state;
424 int bitCount;
425 int posCount;
426 enum {
427 LOGIC0,
428 LOGIC1,
429 SOF_PART1,
430 SOF_PART2
431 } lastBit;
432 uint16_t shiftReg;
433 uint16_t max_len;
434 uint16_t len;
435 int sum1;
436 int sum2;
437 int threshold_sof;
438 int threshold_half;
439 uint16_t previous_amplitude;
440 uint8_t *output;
441 } DecodeTag_t;
443 //-----------------------------------------------------------------------------
444 // DEMODULATE tag answer
445 //-----------------------------------------------------------------------------
446 static RAMFUNC int Handle15693SamplesFromTag(uint16_t amplitude, DecodeTag_t *tag, bool recv_speed) {
448 switch (tag->state) {
450 case STATE_TAG_SOF_LOW: {
451 // waiting for a rising edge
452 if (amplitude > NOISE_THRESHOLD + tag->previous_amplitude) {
453 if (tag->posCount > 10) {
454 tag->threshold_sof = amplitude - tag->previous_amplitude; // to be divided by 2
455 tag->threshold_half = 0;
456 tag->state = STATE_TAG_SOF_RISING_EDGE;
457 } else {
458 tag->posCount = 0;
460 } else {
461 tag->posCount++;
462 tag->previous_amplitude = amplitude;
464 break;
467 case STATE_TAG_SOF_RISING_EDGE: {
468 if (amplitude > tag->threshold_sof + tag->previous_amplitude) { // edge still rising
469 if (amplitude > tag->threshold_sof + tag->threshold_sof) { // steeper edge, take this as time reference
470 tag->posCount = 1;
471 } else {
472 tag->posCount = 2;
474 tag->threshold_sof = (amplitude - tag->previous_amplitude) / 2;
475 } else {
476 tag->posCount = 2;
477 tag->threshold_sof = tag->threshold_sof / 2;
479 tag->state = STATE_TAG_SOF_HIGH;
480 break;
483 case STATE_TAG_SOF_HIGH: {
484 // waiting for 10 times high. Take average over the last 8
485 if (amplitude > tag->threshold_sof) {
486 tag->posCount++;
487 if (tag->posCount > 2) {
488 tag->threshold_half += amplitude; // keep track of average high value
490 if (tag->posCount == (recv_speed ? 10 : 40)) {
491 tag->threshold_half >>= 2; // (4 times 1/2 average)
492 tag->state = STATE_TAG_SOF_HIGH_END;
494 } else { // high phase was too short
495 tag->posCount = 1;
496 tag->previous_amplitude = amplitude;
497 tag->state = STATE_TAG_SOF_LOW;
499 break;
502 case STATE_TAG_SOF_HIGH_END: {
503 // check for falling edge
504 if (tag->posCount == (recv_speed ? 13 : 52) && amplitude < tag->threshold_sof) {
505 tag->lastBit = SOF_PART1; // detected 1st part of SOF (12 samples low and 12 samples high)
506 tag->shiftReg = 0;
507 tag->bitCount = 0;
508 tag->len = 0;
509 tag->sum1 = amplitude;
510 tag->sum2 = 0;
511 tag->posCount = 2;
512 tag->state = STATE_TAG_RECEIVING_DATA;
513 LED_C_ON();
514 } else {
515 tag->posCount++;
516 if (tag->posCount > (recv_speed ? 13 : 52)) { // high phase too long
517 tag->posCount = 0;
518 tag->previous_amplitude = amplitude;
519 tag->state = STATE_TAG_SOF_LOW;
520 LED_C_OFF();
523 break;
526 case STATE_TAG_RECEIVING_DATA: {
527 if (tag->posCount == 1) {
528 tag->sum1 = 0;
529 tag->sum2 = 0;
532 if (tag->posCount <= (recv_speed ? 4 : 16)) {
533 tag->sum1 += amplitude;
534 } else {
535 tag->sum2 += amplitude;
538 if (tag->posCount == (recv_speed ? 8 : 32)) {
539 if (tag->sum1 > tag->threshold_half && tag->sum2 > tag->threshold_half) { // modulation in both halves
540 if (tag->lastBit == LOGIC0) { // this was already part of EOF
541 tag->state = STATE_TAG_EOF;
542 } else {
543 tag->posCount = 0;
544 tag->previous_amplitude = amplitude;
545 tag->state = STATE_TAG_SOF_LOW;
546 LED_C_OFF();
548 } else if (tag->sum1 < tag->threshold_half && tag->sum2 > tag->threshold_half) { // modulation in second half
549 // logic 1
550 if (tag->lastBit == SOF_PART1) { // still part of SOF
551 tag->lastBit = SOF_PART2; // SOF completed
552 } else {
553 tag->lastBit = LOGIC1;
554 tag->shiftReg >>= 1;
555 tag->shiftReg |= 0x80;
556 tag->bitCount++;
557 if (tag->bitCount == 8) {
558 tag->output[tag->len] = tag->shiftReg & 0xFF;
559 tag->len++;
561 if (tag->len > tag->max_len) {
562 // buffer overflow, give up
563 LED_C_OFF();
564 return true;
566 tag->bitCount = 0;
567 tag->shiftReg = 0;
570 } else if (tag->sum1 > tag->threshold_half && tag->sum2 < tag->threshold_half) { // modulation in first half
571 // logic 0
572 if (tag->lastBit == SOF_PART1) { // incomplete SOF
573 tag->posCount = 0;
574 tag->previous_amplitude = amplitude;
575 tag->state = STATE_TAG_SOF_LOW;
576 LED_C_OFF();
577 } else {
578 tag->lastBit = LOGIC0;
579 tag->shiftReg >>= 1;
580 tag->bitCount++;
582 if (tag->bitCount == 8) {
583 tag->output[tag->len] = (tag->shiftReg & 0xFF);
584 tag->len++;
586 if (tag->len > tag->max_len) {
587 // buffer overflow, give up
588 tag->posCount = 0;
589 tag->previous_amplitude = amplitude;
590 tag->state = STATE_TAG_SOF_LOW;
591 LED_C_OFF();
593 tag->bitCount = 0;
594 tag->shiftReg = 0;
597 } else { // no modulation
598 if (tag->lastBit == SOF_PART2) { // only SOF (this is OK for iClass)
599 LED_C_OFF();
600 return true;
601 } else {
602 tag->posCount = 0;
603 tag->state = STATE_TAG_SOF_LOW;
604 LED_C_OFF();
607 tag->posCount = 0;
609 tag->posCount++;
610 break;
613 case STATE_TAG_EOF: {
614 if (tag->posCount == 1) {
615 tag->sum1 = 0;
616 tag->sum2 = 0;
619 if (tag->posCount <= (recv_speed ? 4 : 16)) {
620 tag->sum1 += amplitude;
621 } else {
622 tag->sum2 += amplitude;
625 if (tag->posCount == (recv_speed ? 8 : 32)) {
626 if (tag->sum1 > tag->threshold_half && tag->sum2 < tag->threshold_half) { // modulation in first half
627 tag->posCount = 0;
628 tag->state = STATE_TAG_EOF_TAIL;
629 } else {
630 tag->posCount = 0;
631 tag->previous_amplitude = amplitude;
632 tag->state = STATE_TAG_SOF_LOW;
633 LED_C_OFF();
636 tag->posCount++;
637 break;
640 case STATE_TAG_EOF_TAIL: {
641 if (tag->posCount == 1) {
642 tag->sum1 = 0;
643 tag->sum2 = 0;
646 if (tag->posCount <= (recv_speed ? 4 : 16)) {
647 tag->sum1 += amplitude;
648 } else {
649 tag->sum2 += amplitude;
652 if (tag->posCount == (recv_speed ? 8 : 32)) {
653 if (tag->sum1 < tag->threshold_half && tag->sum2 < tag->threshold_half) { // no modulation in both halves
654 LED_C_OFF();
655 return true;
656 } else {
657 tag->posCount = 0;
658 tag->previous_amplitude = amplitude;
659 tag->state = STATE_TAG_SOF_LOW;
660 LED_C_OFF();
663 tag->posCount++;
664 break;
668 return false;
671 static void DecodeTagReset(DecodeTag_t *tag) {
672 tag->posCount = 0;
673 tag->state = STATE_TAG_SOF_LOW;
674 tag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
677 static void DecodeTagInit(DecodeTag_t *tag, uint8_t *data, uint16_t max_len) {
678 tag->output = data;
679 tag->max_len = max_len;
680 DecodeTagReset(tag);
683 //=============================================================================
684 // An ISO 15693 decoder for tag responses in FSK (two subcarriers) mode.
685 // Subcarriers frequencies are 424kHz and 484kHz (fc/32 and fc/28),
686 // LED handling:
687 // LED C -> ON once we have received the SOF and are expecting the rest.
688 // LED C -> OFF once we have received EOF or are unsynced
690 // Returns: true if we received a EOF
691 // false if we are still waiting for some more
692 //=============================================================================
693 //#define DEBUG 1
694 #define FREQ_IS_484(f) ((f & 1) == 1) //(f >= 26 && f <= 30)
695 #define FREQ_IS_424(f) ((f & 2) == 2) //(f >= 30 && f <= 34)
696 #define FREQ_IS_0(f) ((f & 3) == 0) // (f <= 24 || f >= 36)
697 #define SEOF_COUNT(c, s) ((s) ? (c >= 11 && c <= 13) : (c >= 45 && c <= 51))
698 #define LOGIC_COUNT(c, s) ((s) ? (c >= 3 && c <= 6) : (c >= 14 && c <= 20))
699 #define MAX_COUNT(c, s) ((s) ? (c >= 13) : (c >= 52))
701 typedef struct DecodeTagFSK {
702 enum {
703 STATE_FSK_ERROR,
704 STATE_FSK_BEFORE_SOF,
705 STATE_FSK_SOF_484,
706 STATE_FSK_SOF_424,
707 STATE_FSK_SOF_END_484,
708 STATE_FSK_SOF_END_424,
709 STATE_FSK_RECEIVING_DATA_484,
710 STATE_FSK_RECEIVING_DATA_424,
711 STATE_FSK_EOF
712 } state;
713 enum {
714 LOGIC0_PART1,
715 LOGIC1_PART1,
716 LOGIC0_PART2,
717 LOGIC1_PART2,
719 } lastBit;
720 uint8_t count;
721 uint8_t bitCount;
722 uint8_t shiftReg;
723 uint16_t len;
724 uint16_t max_len;
725 uint8_t *output;
726 } DecodeTagFSK_t;
728 static void DecodeTagFSKReset(DecodeTagFSK_t *DecodeTag) {
729 DecodeTag->state = STATE_FSK_BEFORE_SOF;
730 DecodeTag->bitCount = 0;
731 DecodeTag->len = 0;
732 DecodeTag->shiftReg = 0;
735 static void DecodeTagFSKInit(DecodeTagFSK_t *DecodeTag, uint8_t *data, uint16_t max_len) {
736 DecodeTag->output = data;
737 DecodeTag->max_len = max_len;
738 DecodeTagFSKReset(DecodeTag);
741 // Performances of this function are crutial for stability
742 // as it is called in real time for every samples
743 static int RAMFUNC Handle15693FSKSamplesFromTag(uint8_t freq, DecodeTagFSK_t *DecodeTag, bool recv_speed) {
744 switch (DecodeTag->state) {
745 case STATE_FSK_BEFORE_SOF:
746 if (FREQ_IS_484(freq)) {
747 // possible SOF starting
748 DecodeTag->state = STATE_FSK_SOF_484;
749 DecodeTag->lastBit = LOGIC0_PART1;
750 DecodeTag->count = 1;
752 break;
754 case STATE_FSK_SOF_484:
755 //DbpString("STATE_FSK_SOF_484");
756 if (FREQ_IS_424(freq) && SEOF_COUNT(DecodeTag->count, recv_speed)) {
757 // SOF part1 continue at 424
758 DecodeTag->state = STATE_FSK_SOF_424;
759 DecodeTag->count = 1;
760 } else if (FREQ_IS_484(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) { // still in SOF at 484
761 DecodeTag->count++;
762 } else { // SOF failed, roll back
763 DecodeTag->state = STATE_FSK_BEFORE_SOF;
765 break;
767 case STATE_FSK_SOF_424:
768 //DbpString("STATE_FSK_SOF_424");
769 if (FREQ_IS_484(freq) && SEOF_COUNT(DecodeTag->count, recv_speed)) {
770 // SOF part 1 finished
771 DecodeTag->state = STATE_FSK_SOF_END_484;
772 DecodeTag->count = 1;
773 } else if (FREQ_IS_424(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) // still in SOF at 424
774 DecodeTag->count++;
775 else { // SOF failed, roll back
776 #ifdef DEBUG
777 if (DEBUG)
778 Dbprintf("SOF_424 failed: freq=%d, count=%d, recv_speed=%d", freq, DecodeTag->count, recv_speed);
779 #endif
780 DecodeTag->state = STATE_FSK_BEFORE_SOF;
782 break;
784 case STATE_FSK_SOF_END_484:
785 if (FREQ_IS_424(freq) && LOGIC_COUNT(DecodeTag->count, recv_speed)) {
786 DecodeTag->state = STATE_FSK_SOF_END_424;
787 DecodeTag->count = 1;
788 } else if (FREQ_IS_484(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) // still in SOF_END_484
789 DecodeTag->count++;
790 else { // SOF failed, roll back
791 #ifdef DEBUG
792 if (DEBUG)
793 Dbprintf("SOF_END_484 failed: freq=%d, count=%d, recv_speed=%d", freq, DecodeTag->count, recv_speed);
794 #endif
795 DecodeTag->state = STATE_FSK_BEFORE_SOF;
797 break;
798 case STATE_FSK_SOF_END_424:
799 if (FREQ_IS_484(freq) && LOGIC_COUNT(DecodeTag->count, recv_speed)) {
800 // SOF finished at 484
801 DecodeTag->count = 1;
802 DecodeTag->lastBit = SOF;
803 DecodeTag->state = STATE_FSK_RECEIVING_DATA_484;
804 LED_C_ON();
805 } else if (FREQ_IS_424(freq) && LOGIC_COUNT(DecodeTag->count - 2, recv_speed)) {
806 // SOF finished at 424 (wait count+2 to be sure that next freq is 424)
807 DecodeTag->count = 2;
808 DecodeTag->lastBit = SOF;
809 DecodeTag->state = STATE_FSK_RECEIVING_DATA_424;
810 LED_C_ON();
811 } else if (FREQ_IS_424(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) // still in SOF_END_424
812 DecodeTag->count++;
813 else { // SOF failed, roll back
814 #ifdef DEBUG
815 if (DEBUG)
816 Dbprintf("SOF_END_424 failed: freq=%d, count=%d, recv_speed=%d", freq, DecodeTag->count, recv_speed);
817 #endif
818 DecodeTag->state = STATE_FSK_BEFORE_SOF;
820 break;
823 case STATE_FSK_RECEIVING_DATA_424:
824 if (FREQ_IS_484(freq) && LOGIC_COUNT(DecodeTag->count, recv_speed)) {
825 if (DecodeTag->lastBit == LOGIC1_PART1) {
826 // logic 1 finished, goto 484
827 DecodeTag->lastBit = LOGIC1_PART2;
829 DecodeTag->shiftReg >>= 1;
830 DecodeTag->shiftReg |= 0x80;
831 DecodeTag->bitCount++;
832 if (DecodeTag->bitCount == 8) {
833 DecodeTag->output[DecodeTag->len++] = DecodeTag->shiftReg;
834 if (DecodeTag->len > DecodeTag->max_len) {
835 // buffer overflow, give up
836 LED_C_OFF();
837 return true;
839 DecodeTag->bitCount = 0;
840 DecodeTag->shiftReg = 0;
842 } else {
843 // end of LOGIC0_PART1
844 DecodeTag->lastBit = LOGIC0_PART1;
846 DecodeTag->count = 1;
847 DecodeTag->state = STATE_FSK_RECEIVING_DATA_484;
848 } else if (FREQ_IS_424(freq) && LOGIC_COUNT(DecodeTag->count - 2, recv_speed) &&
849 DecodeTag->lastBit == LOGIC1_PART1) {
850 // logic 1 finished, stay in 484
851 DecodeTag->lastBit = LOGIC1_PART2;
853 DecodeTag->shiftReg >>= 1;
854 DecodeTag->shiftReg |= 0x80;
855 DecodeTag->bitCount++;
856 if (DecodeTag->bitCount == 8) {
857 DecodeTag->output[DecodeTag->len++] = DecodeTag->shiftReg;
858 if (DecodeTag->len > DecodeTag->max_len) {
859 // buffer overflow, give up
860 LED_C_OFF();
861 return true;
863 DecodeTag->bitCount = 0;
864 DecodeTag->shiftReg = 0;
866 DecodeTag->count = 2;
867 } else if (FREQ_IS_424(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) // still at 424
868 DecodeTag->count++;
870 else if (FREQ_IS_484(freq) && DecodeTag->lastBit == LOGIC0_PART2 &&
871 SEOF_COUNT(DecodeTag->count, recv_speed)) {
872 // EOF has started
873 #ifdef DEBUG
874 if (DEBUG)
875 Dbprintf("RECEIVING_DATA_424->EOF: freq=%d, count=%d, recv_speed=%d, lastbit=%d, state=%d", freq, DecodeTag->count, recv_speed, DecodeTag->lastBit, DecodeTag->state);
876 #endif
877 DecodeTag->count = 1;
878 DecodeTag->state = STATE_FSK_EOF;
879 LED_C_OFF();
880 } else { // error
881 #ifdef DEBUG
882 if (DEBUG)
883 Dbprintf("RECEIVING_DATA_424 error: freq=%d, count=%d, recv_speed=%d, lastbit=%d, state=%d", freq, DecodeTag->count, recv_speed, DecodeTag->lastBit, DecodeTag->state);
884 #endif
885 DecodeTag->state = STATE_FSK_ERROR;
886 LED_C_OFF();
887 return true;
889 break;
891 case STATE_FSK_RECEIVING_DATA_484:
892 if (FREQ_IS_424(freq) && LOGIC_COUNT(DecodeTag->count, recv_speed)) {
893 if (DecodeTag->lastBit == LOGIC0_PART1) {
894 // logic 0 finished, goto 424
895 DecodeTag->lastBit = LOGIC0_PART2;
897 DecodeTag->shiftReg >>= 1;
898 DecodeTag->bitCount++;
899 if (DecodeTag->bitCount == 8) {
900 DecodeTag->output[DecodeTag->len++] = DecodeTag->shiftReg;
901 if (DecodeTag->len > DecodeTag->max_len) {
902 // buffer overflow, give up
903 LED_C_OFF();
904 return true;
906 DecodeTag->bitCount = 0;
907 DecodeTag->shiftReg = 0;
909 } else {
910 // end of LOGIC1_PART1
911 DecodeTag->lastBit = LOGIC1_PART1;
913 DecodeTag->count = 1;
914 DecodeTag->state = STATE_FSK_RECEIVING_DATA_424;
915 } else if (FREQ_IS_484(freq) && LOGIC_COUNT(DecodeTag->count - 2, recv_speed) &&
916 DecodeTag->lastBit == LOGIC0_PART1) {
917 // logic 0 finished, stay in 424
918 DecodeTag->lastBit = LOGIC0_PART2;
920 DecodeTag->shiftReg >>= 1;
921 DecodeTag->bitCount++;
922 if (DecodeTag->bitCount == 8) {
923 DecodeTag->output[DecodeTag->len++] = DecodeTag->shiftReg;
924 if (DecodeTag->len > DecodeTag->max_len) {
925 // buffer overflow, give up
926 LED_C_OFF();
927 return true;
929 DecodeTag->bitCount = 0;
930 DecodeTag->shiftReg = 0;
932 DecodeTag->count = 2;
933 } else if (FREQ_IS_484(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) // still at 484
934 DecodeTag->count++;
935 else { // error
936 #ifdef DEBUG
937 if (DEBUG)
938 Dbprintf("RECEIVING_DATA_484 error: freq=%d, count=%d, recv_speed=%d, lastbit=%d, state=%d", freq, DecodeTag->count, recv_speed, DecodeTag->lastBit, DecodeTag->state);
939 #endif
940 LED_C_OFF();
941 DecodeTag->state = STATE_FSK_ERROR;
942 return true;
944 break;
946 case STATE_FSK_EOF:
947 if (FREQ_IS_484(freq) && !MAX_COUNT(DecodeTag->count, recv_speed)) { // still at 484
948 DecodeTag->count++;
949 if (SEOF_COUNT(DecodeTag->count, recv_speed))
950 return true; // end of the transmission
951 } else { // error
952 #ifdef DEBUG
953 if (DEBUG)
954 Dbprintf("EOF error: freq=%d, count=%d, recv_speed=%d", freq, DecodeTag->count, recv_speed);
955 #endif
956 DecodeTag->state = STATE_FSK_ERROR;
957 return true;
959 break;
960 case STATE_FSK_ERROR:
961 LED_C_OFF();
962 #ifdef DEBUG
963 if (DEBUG)
964 Dbprintf("FSK error: freq=%d, count=%d, recv_speed=%d", freq, DecodeTag->count, recv_speed);
965 #endif
966 return true; // error
967 break;
969 return false;
973 * Receive and decode the tag response, also log to tracebuffer
975 int GetIso15693AnswerFromTag(uint8_t *response, uint16_t max_len, uint16_t timeout, uint32_t *eof_time, bool fsk, bool recv_speed, uint16_t *resp_len) {
977 int samples = 0, ret = PM3_SUCCESS;
978 if (resp_len) {
979 *resp_len = 0;
981 // the Decoder data structure
982 DecodeTag_t dtm = { 0 };
983 DecodeTag_t *dt = &dtm;
985 DecodeTagFSK_t dtfm = { 0 };
986 DecodeTagFSK_t *dtf = &dtfm;
988 if (fsk)
989 DecodeTagFSKInit(dtf, response, max_len);
990 else
991 DecodeTagInit(dt, response, max_len);
993 // wait for last transfer to complete
994 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
996 // And put the FPGA in the appropriate mode
997 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_2SUBCARRIERS_424_484_KHZ | FPGA_HF_READER_MODE_RECEIVE_AMPLITUDE);
999 // Setup and start DMA.
1000 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1002 // The DMA buffer, used to stream samples from the FPGA
1003 dmabuf16_t *dma = get_dma16();
1005 // Setup and start DMA.
1006 if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) {
1007 if (g_dbglevel > DBG_ERROR) Dbprintf("FpgaSetupSscDma failed. Exiting");
1008 return PM3_EINIT;
1011 uint32_t dma_start_time = 0;
1012 const uint16_t *upTo = dma->buf;
1014 for (;;) {
1016 volatile uint16_t behindBy = ((uint16_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
1017 if (behindBy == 0)
1018 continue;
1020 samples++;
1021 if (samples == 1) {
1022 // DMA has transferred the very first data
1023 dma_start_time = GetCountSspClk() & 0xfffffff0;
1026 volatile uint16_t tagdata = *upTo++;
1028 if (upTo >= dma->buf + DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
1029 upTo = dma->buf; // start reading the circular buffer from the beginning
1031 // DMA Counter Register had reached 0, already rotated.
1032 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) {
1034 // primary buffer was stopped
1035 if (AT91C_BASE_PDC_SSC->PDC_RCR == false) {
1036 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf;
1037 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
1039 // secondary buffer sets as primary, secondary buffer was stopped
1040 if (AT91C_BASE_PDC_SSC->PDC_RNCR == false) {
1041 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf;
1042 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1045 WDT_HIT();
1046 if (BUTTON_PRESS()) {
1047 break;
1052 if (fsk) {
1054 if (Handle15693FSKSamplesFromTag(tagdata >> 14, dtf, recv_speed)) {
1056 *eof_time = dma_start_time + (samples * 16) - DELAY_TAG_TO_ARM; // end of EOF
1058 if (dtf->lastBit == SOF) {
1059 *eof_time -= (8 * 16); // needed 8 additional samples to confirm single SOF (iCLASS)
1062 if (dtf->len > dtf->max_len) {
1063 ret = PM3_EOVFLOW;
1064 Dbprintf("overflow (%d > %d)", dtf->len, dtf->max_len);
1066 break;
1069 // timeout
1070 if (samples > timeout && dtf->state < STATE_FSK_RECEIVING_DATA_484) {
1071 ret = PM3_ETIMEOUT;
1072 break;
1075 } else {
1077 if (Handle15693SamplesFromTag(tagdata & 0x3FFF, dt, recv_speed)) {
1079 *eof_time = dma_start_time + (samples * 16) - DELAY_TAG_TO_ARM; // end of EOF
1081 if (dt->lastBit == SOF_PART2) {
1082 *eof_time -= (8 * 16); // needed 8 additional samples to confirm single SOF (iCLASS)
1085 if (dt->len > dt->max_len) {
1086 ret = PM3_EOVFLOW;
1087 Dbprintf("overflow (%d > %d)", dt->len, dt->max_len);
1089 break;
1092 // timeout
1093 if (samples > timeout && dt->state < STATE_TAG_RECEIVING_DATA) {
1094 ret = PM3_ETIMEOUT;
1095 break;
1100 FpgaDisableSscDma();
1101 FpgaDisableTracing();
1103 uint32_t sof_time = *eof_time - (32 * 16); // time for SOF transfer
1105 if (fsk) {
1106 sof_time -= (dtf->len * 8 * 8 * 16) // time for byte transfers
1107 + (dtf->lastBit != SOF ? (32 * 16) : 0); // time for EOF transfer
1108 } else {
1109 sof_time -= (dt->len * 8 * 8 * 16) // time for byte transfers
1110 + (dt->lastBit != SOF_PART2 ? (32 * 16) : 0); // time for EOF transfer
1113 if (ret != PM3_SUCCESS) {
1114 *resp_len = 0;
1115 return ret;
1118 if (fsk) {
1119 LogTrace_ISO15693(dtf->output, dtf->len, (sof_time * 4), (*eof_time * 4), NULL, false);
1120 *resp_len = dtf->len;
1121 } else {
1122 LogTrace_ISO15693(dt->output, dt->len, (sof_time * 4), (*eof_time * 4), NULL, false);
1123 *resp_len = dt->len;
1125 return PM3_SUCCESS;
1129 //=============================================================================
1130 // An ISO15693 decoder for reader commands.
1132 // This function is called 4 times per bit (every 2 subcarrier cycles).
1133 // Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
1134 // LED handling:
1135 // LED B -> ON once we have received the SOF and are expecting the rest.
1136 // LED B -> OFF once we have received EOF or are in error state or unsynced
1138 // Returns: true if we received a EOF
1139 // false if we are still waiting for some more
1140 //=============================================================================
1142 typedef struct {
1143 enum {
1144 STATE_READER_UNSYNCD,
1145 STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF,
1146 STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF,
1147 STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF,
1148 STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF,
1149 STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4,
1150 STATE_READER_RECEIVE_DATA_1_OUT_OF_4,
1151 STATE_READER_RECEIVE_DATA_1_OUT_OF_256,
1152 STATE_READER_RECEIVE_JAMMING
1153 } state;
1154 enum {
1155 CODING_1_OUT_OF_4,
1156 CODING_1_OUT_OF_256
1157 } Coding;
1158 uint8_t shiftReg;
1159 uint8_t bitCount;
1160 int byteCount;
1161 int byteCountMax;
1162 int posCount;
1163 int sum1, sum2;
1164 uint8_t *output;
1165 uint8_t jam_search_len;
1166 uint8_t *jam_search_string;
1167 } DecodeReader_t;
1169 static void DecodeReaderInit(DecodeReader_t *reader, uint8_t *data, uint16_t max_len, uint8_t jam_search_len, uint8_t *jam_search_string) {
1170 reader->output = data;
1171 reader->byteCountMax = max_len;
1172 reader->state = STATE_READER_UNSYNCD;
1173 reader->byteCount = 0;
1174 reader->bitCount = 0;
1175 reader->posCount = 1;
1176 reader->shiftReg = 0;
1177 reader->jam_search_len = jam_search_len;
1178 reader->jam_search_string = jam_search_string;
1181 static void DecodeReaderReset(DecodeReader_t *reader) {
1182 reader->state = STATE_READER_UNSYNCD;
1185 //static inline __attribute__((always_inline))
1186 static int RAMFUNC Handle15693SampleFromReader(bool bit, DecodeReader_t *reader) {
1187 switch (reader->state) {
1188 case STATE_READER_UNSYNCD:
1189 // wait for unmodulated carrier
1190 if (bit) {
1191 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
1193 break;
1195 case STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF:
1196 if (!bit) {
1197 // we went low, so this could be the beginning of a SOF
1198 reader->posCount = 1;
1199 reader->state = STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF;
1201 break;
1203 case STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF:
1204 if (bit) { // detected rising edge
1205 if (reader->posCount < 2) { // rising edge too early (nominally expected at 4)
1206 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
1207 } else { // SOF
1208 reader->state = STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF;
1209 reader->posCount = 1;
1211 } else {
1212 reader->posCount++;
1213 if (reader->posCount > 6) { // stayed low for too long
1214 DecodeReaderReset(reader);
1217 break;
1219 case STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF:
1220 if (!bit) { // detected a falling edge
1221 if (reader->posCount < 14) { // falling edge too early (nominally expected at 16 earliest)
1222 DecodeReaderReset(reader);
1223 } else if (reader->posCount <= 18) { // SOF for 1 out of 4 coding
1224 reader->Coding = CODING_1_OUT_OF_4;
1225 reader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
1226 reader->posCount = 1;
1227 } else if (reader->posCount < 22) { // falling edge too early (nominally expected at 24 latest)
1228 DecodeReaderReset(reader);
1229 } else { // SOF for 1 out of 256 coding
1230 reader->Coding = CODING_1_OUT_OF_256;
1231 reader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
1232 reader->posCount = 1;
1234 } else {
1235 reader->posCount++;
1236 if (reader->posCount > 26) { // stayed high for too long
1237 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
1238 } else {
1239 // do nothing, keep waiting
1242 break;
1244 case STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF:
1245 if (bit) { // detected rising edge
1246 if (reader->posCount < 2) { // rising edge too early (nominally expected at 8)
1247 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
1248 } else {
1249 reader->posCount = 1;
1250 if (reader->Coding == CODING_1_OUT_OF_256) {
1251 reader->bitCount = 1;
1252 reader->byteCount = 0;
1253 reader->sum1 = 1;
1254 LED_B_ON();
1255 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
1256 } else { // CODING_1_OUT_OF_4
1257 reader->state = STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4;
1260 } else {
1261 reader->posCount++;
1262 if (reader->posCount > 6) { // signal stayed low for too long
1263 DecodeReaderReset(reader);
1264 } else {
1265 // do nothing, keep waiting
1268 break;
1270 case STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4:
1271 if (bit) {
1272 reader->posCount++;
1274 if (reader->posCount == 8) {
1275 reader->posCount = 0;
1276 reader->bitCount = 0;
1277 reader->byteCount = 0;
1278 reader->sum1 = 0;
1279 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
1280 LED_B_ON();
1282 } else { // unexpected falling edge
1283 DecodeReaderReset(reader);
1285 break;
1287 case STATE_READER_RECEIVE_DATA_1_OUT_OF_4:
1288 if (!bit) {
1289 reader->sum1++;
1290 if (reader->sum1 == 1) { // first low bit
1291 if (reader->posCount <= 6) { // bits : 00
1292 reader->shiftReg >>= 2;
1293 //reader->shiftReg |= (0 << 6);
1294 reader->bitCount += 2;
1295 reader->posCount = -28;
1296 } else if (reader->posCount <= 9) { // EOF
1297 LED_B_OFF(); // Finished receiving
1298 DecodeReaderReset(reader);
1299 if (reader->byteCount > 0) {
1300 return true;
1302 } else if (reader->posCount <= 14) { // bits : 01
1303 reader->shiftReg >>= 2;
1304 reader->shiftReg |= (1 << 6);
1305 reader->bitCount += 2;
1306 reader->posCount = -20;
1307 } else if (reader->posCount < 18) { // unexpected falling edge
1308 DecodeReaderReset(reader);
1309 if (reader->byteCount >= 0) {
1310 reader->output[reader->byteCount++] = reader->posCount;
1311 reader->output[reader->byteCount++] = reader->bitCount;
1312 reader->output[reader->byteCount++] = 0x42;
1313 return true;
1315 } else if (reader->posCount <= 22) { // bits : 10
1316 reader->shiftReg >>= 2;
1317 reader->shiftReg |= (2 << 6);
1318 reader->bitCount += 2;
1319 reader->posCount = -12;
1320 } else if (reader->posCount < 26) { // unexpected falling edge
1321 DecodeReaderReset(reader);
1322 if (reader->byteCount >= 0) {
1323 reader->output[reader->byteCount++] = reader->posCount;
1324 reader->output[reader->byteCount++] = reader->bitCount;
1325 reader->output[reader->byteCount++] = 0x43;
1326 return true;
1328 } else { // bits : 11
1329 reader->shiftReg >>= 2;
1330 reader->shiftReg |= (3 << 6);
1331 reader->bitCount += 2;
1332 reader->posCount = -4;
1335 if (reader->bitCount == 8) {
1336 reader->output[reader->byteCount++] = reader->shiftReg;
1337 if (reader->byteCount > reader->byteCountMax) {
1338 // buffer overflow, give up
1339 LED_B_OFF();
1340 DecodeReaderReset(reader);
1343 reader->bitCount = 0;
1344 reader->shiftReg = 0;
1345 if (reader->byteCount == reader->jam_search_len) {
1346 if (!memcmp(reader->output, reader->jam_search_string, reader->jam_search_len)) {
1347 LED_D_ON();
1348 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_JAM);
1349 reader->state = STATE_READER_RECEIVE_JAMMING;
1353 } else if (reader->sum1 > 6) { // too long low bit
1354 DecodeReaderReset(reader);
1355 if (reader->byteCount >= 0) {
1356 reader->output[reader->byteCount++] = reader->posCount;
1357 reader->output[reader->byteCount++] = reader->bitCount;
1358 reader->output[reader->byteCount++] = 0x44;
1359 return true;
1362 } else {
1363 reader->posCount++;
1364 if (reader->posCount > 30) {
1365 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
1366 if (reader->byteCount >= 0) {
1367 reader->output[reader->byteCount++] = reader->posCount;
1368 reader->output[reader->byteCount++] = reader->bitCount;
1369 reader->output[reader->byteCount++] = 0x45;
1370 return true;
1373 if (reader->sum1 == 1) {
1374 reader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
1375 if (reader->byteCount >= 0) {
1376 reader->output[reader->byteCount++] = reader->posCount;
1377 reader->output[reader->byteCount++] = reader->bitCount;
1378 reader->output[reader->byteCount++] = 0x46;
1379 return true;
1381 } else if (reader->sum1 > 1) {
1382 reader->posCount += reader->sum1;
1383 reader->sum1 = 0;
1386 break;
1388 case STATE_READER_RECEIVE_DATA_1_OUT_OF_256:
1390 reader->posCount++;
1392 if (reader->posCount == 1) {
1393 reader->sum1 = bit ? 1 : 0;
1394 } else if (reader->posCount <= 4) {
1395 if (bit) reader->sum1++;
1396 } else if (reader->posCount == 5) {
1397 reader->sum2 = bit ? 1 : 0;
1398 } else if (bit) {
1399 reader->sum2++;
1402 if (reader->posCount == 8) {
1403 reader->posCount = 0;
1404 if (reader->sum1 <= 1 && reader->sum2 >= 3) { // EOF
1405 LED_B_OFF(); // Finished receiving
1406 DecodeReaderReset(reader);
1407 if (reader->byteCount != 0) {
1408 return true;
1411 } else if (reader->sum1 >= 3 && reader->sum2 <= 1) { // detected the bit position
1412 reader->shiftReg = reader->bitCount;
1415 if (reader->bitCount == 255) { // we have a full byte
1416 reader->output[reader->byteCount++] = reader->shiftReg;
1417 if (reader->byteCount > reader->byteCountMax) {
1418 // buffer overflow, give up
1419 LED_B_OFF();
1420 DecodeReaderReset(reader);
1423 if (reader->byteCount == reader->jam_search_len) {
1424 if (!memcmp(reader->output, reader->jam_search_string, reader->jam_search_len)) {
1425 LED_D_ON();
1426 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_JAM);
1427 reader->state = STATE_READER_RECEIVE_JAMMING;
1431 reader->bitCount++;
1433 break;
1435 case STATE_READER_RECEIVE_JAMMING:
1437 reader->posCount++;
1439 if (reader->Coding == CODING_1_OUT_OF_4) {
1440 if (reader->posCount == 7 * 16) { // 7 bits jammed
1441 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE); // stop jamming
1442 // FpgaDisableTracing();
1443 LED_D_OFF();
1444 } else if (reader->posCount == 8 * 16) {
1445 reader->posCount = 0;
1446 reader->output[reader->byteCount++] = 0x00;
1447 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
1449 } else {
1450 if (reader->posCount == 7 * 256) { // 7 bits jammend
1451 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE); // stop jamming
1452 LED_D_OFF();
1453 } else if (reader->posCount == 8 * 256) {
1454 reader->posCount = 0;
1455 reader->output[reader->byteCount++] = 0x00;
1456 reader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
1459 break;
1461 default:
1462 LED_B_OFF();
1463 DecodeReaderReset(reader);
1464 break;
1467 return false;
1470 //-----------------------------------------------------------------------------
1471 // Receive a command (from the reader to us, where we are the simulated tag),
1472 // and store it in the given buffer, up to the given maximum length. Keeps
1473 // spinning, waiting for a well-framed command, until either we get one
1474 // (returns len) or someone presses the pushbutton on the board (returns -1).
1476 // Assume that we're called with the SSC (to the FPGA) and ADC path set
1477 // correctly.
1478 //-----------------------------------------------------------------------------
1480 int GetIso15693CommandFromReader(uint8_t *received, size_t max_len, uint32_t *eof_time) {
1481 int samples = 0;
1482 bool gotFrame = false;
1484 // the decoder data structure
1485 DecodeReader_t *dr = (DecodeReader_t *)BigBuf_malloc(sizeof(DecodeReader_t));
1486 DecodeReaderInit(dr, received, max_len, 0, NULL);
1488 // wait for last transfer to complete
1489 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
1491 LED_D_OFF();
1492 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
1494 // clear receive register and wait for next transfer
1495 uint32_t temp = AT91C_BASE_SSC->SSC_RHR;
1496 (void) temp;
1497 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) ;
1499 // Setup and start DMA.
1500 dmabuf8_t *dma = get_dma8();
1501 if (FpgaSetupSscDma(dma->buf, DMA_BUFFER_SIZE) == false) {
1502 if (g_dbglevel > DBG_ERROR) Dbprintf("FpgaSetupSscDma failed. Exiting");
1503 return -4;
1505 const uint8_t *upTo = dma->buf;
1507 uint32_t dma_start_time = GetCountSspClk() & 0xfffffff8;
1509 for (;;) {
1510 volatile uint16_t behindBy = ((uint8_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
1511 if (behindBy == 0) continue;
1513 if (samples == 0) {
1514 // DMA has transferred the very first data
1515 dma_start_time = GetCountSspClk() & 0xfffffff0;
1518 volatile uint8_t b = *upTo++;
1519 if (upTo >= dma->buf + DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
1520 upTo = dma->buf; // start reading the circular buffer from the beginning
1521 if (behindBy > (9 * DMA_BUFFER_SIZE / 10)) {
1522 Dbprintf("About to blow circular buffer - aborted! behindBy %d", behindBy);
1523 break;
1526 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
1527 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf; // refresh the DMA Next Buffer and
1528 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; // DMA Next Counter registers
1531 for (int i = 7; i >= 0; i--) {
1532 if (Handle15693SampleFromReader((b >> i) & 0x01, dr)) {
1533 *eof_time = dma_start_time + samples - DELAY_READER_TO_ARM; // end of EOF
1534 gotFrame = true;
1535 break;
1537 samples++;
1540 if (gotFrame) {
1541 break;
1544 if (BUTTON_PRESS()) {
1545 dr->byteCount = -1;
1546 break;
1549 WDT_HIT();
1552 FpgaDisableSscDma();
1554 if (dr->byteCount >= 0) {
1555 uint32_t sof_time = *eof_time
1556 - dr->byteCount * (dr->Coding == CODING_1_OUT_OF_4 ? 128 : 2048) // time for byte transfers
1557 - 32 // time for SOF transfer
1558 - 16; // time for EOF transfer
1559 LogTrace_ISO15693(dr->output, dr->byteCount, (sof_time * 32), (*eof_time * 32), NULL, true);
1562 return dr->byteCount;
1565 //-----------------------------------------------------------------------------
1566 // Start to read an ISO 15693 tag. We send an identify request, then wait
1567 // for the response. The response is not demodulated, just left in the buffer
1568 // so that it can be downloaded to a PC and processed there.
1569 //-----------------------------------------------------------------------------
1570 void AcquireRawAdcSamplesIso15693(void) {
1572 LEDsoff();
1573 DbpString("Starting to acquire data...");
1574 FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15);
1576 BigBuf_free();
1577 clear_trace();
1579 // Start from off (no field generated)
1580 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1581 SpinDelay(10);
1584 uint8_t cmd[5];
1585 BuildIdentifyRequest(cmd);
1586 CodeIso15693AsReader(cmd, sizeof(cmd));
1588 LED_A_ON();
1590 uint8_t *dest = BigBuf_malloc(4000);
1592 // switch field on
1593 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1594 LED_D_ON();
1596 // initialize SSC and select proper AD input
1597 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1598 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1600 StartCountSspClk();
1602 // Give the tags time to energize
1603 SpinDelay(250);
1605 // Now send the command
1606 const tosend_t *ts = get_tosend();
1608 uint32_t start_time = 0;
1609 TransmitTo15693Tag(ts->buf, ts->max, &start_time, false);
1611 // wait for last transfer to complete
1612 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY)) ;
1614 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_424_KHZ | FPGA_HF_READER_MODE_RECEIVE_AMPLITUDE);
1616 for (int c = 0; c < 4000;) {
1617 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1618 uint16_t r = AT91C_BASE_SSC->SSC_RHR;
1619 dest[c++] = r >> 5;
1624 FpgaDisableSscDma();
1625 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1626 LEDsoff();
1629 void SniffIso15693(uint8_t jam_search_len, uint8_t *jam_search_string, bool iclass) {
1631 LEDsoff();
1632 LED_A_ON();
1634 FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15);
1636 if (g_dbglevel >= DBG_INFO) {
1637 DbpString("Press " _GREEN_("pm3 button") " to abort sniffing");
1639 BigBuf_free();
1640 clear_trace();
1641 set_tracing(true);
1643 DecodeTag_t dtag = {0};
1644 uint8_t response[ISO15693_MAX_RESPONSE_LENGTH] = {0};
1645 DecodeTagInit(&dtag, response, sizeof(response));
1647 DecodeTagFSK_t dtagfsk = {0};
1648 uint8_t response2[ISO15693_MAX_RESPONSE_LENGTH] = {0};
1649 DecodeTagFSKInit(&dtagfsk, response2, sizeof(response2));
1651 DecodeReader_t dreader = {0};
1652 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH] = {0};
1653 DecodeReaderInit(&dreader, cmd, sizeof(cmd), jam_search_len, jam_search_string);
1655 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE | FPGA_HF_READER_2SUBCARRIERS_424_484_KHZ);
1657 LED_D_OFF();
1659 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1660 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1662 StartCountSspClk();
1664 // The DMA buffer, used to stream samples from the FPGA
1665 dmabuf16_t *dma = get_dma16();
1667 // Setup and start DMA.
1668 if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) {
1669 if (g_dbglevel > DBG_ERROR) DbpString("FpgaSetupSscDma failed. Exiting");
1670 switch_off();
1671 return;
1674 bool tag_is_active = false;
1675 bool reader_is_active = false;
1676 bool expect_tag_answer = false;
1677 bool expect_fsk_answer = false;
1678 bool expect_fast_answer = true; // default to true is required for iClass
1679 int dma_start_time = 0;
1681 // Count of samples received so far, so that we can include timing
1682 int samples = 0;
1684 const uint16_t *upTo = dma->buf;
1686 for (;;) {
1688 volatile int behind_by = ((uint16_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
1689 if (behind_by < 1) continue;
1691 samples++;
1692 if (samples == 1) {
1693 // DMA has transferred the very first data
1694 dma_start_time = GetCountSspClk() & 0xfffffff0;
1697 volatile uint16_t sniffdata = 0;
1698 volatile uint16_t sniffdata_prev = sniffdata;
1699 sniffdata = *upTo++;
1701 // we have read all of the DMA buffer content
1702 if (upTo >= dma->buf + DMA_BUFFER_SIZE) {
1704 // start reading the circular buffer from the beginning
1705 upTo = dma->buf;
1707 // DMA Counter Register had reached 0, already rotated.
1708 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) {
1710 // primary buffer was stopped
1711 if (AT91C_BASE_PDC_SSC->PDC_RCR == false) {
1712 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf;
1713 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
1715 // secondary buffer sets as primary, secondary buffer was stopped
1716 if (AT91C_BASE_PDC_SSC->PDC_RNCR == false) {
1717 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf;
1718 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1721 WDT_HIT();
1722 if (BUTTON_PRESS()) {
1723 break;
1728 // no need to try decoding reader data if the tag is sending
1729 if (tag_is_active == false) {
1731 int extra_8s = 1;
1732 if (Handle15693SampleFromReader((sniffdata & 0x02) >> 1, &dreader) ||
1733 (++extra_8s && Handle15693SampleFromReader(sniffdata & 0x01, &dreader))) {
1735 if (dreader.byteCount > 0) {
1736 // sof/eof_times are in ssp_clk, which is 13.56MHz / 4
1737 // not sure where the extra +8's on the EOF time comes from though, if someone knows update this comment
1738 uint32_t eof_time = dma_start_time + (samples * 16) + (extra_8s * 8) - DELAY_READER_TO_ARM_SNIFF; // end of EOF
1739 uint32_t sof_time = eof_time
1740 - dreader.byteCount * (dreader.Coding == CODING_1_OUT_OF_4 ? 1024 : 16384) // time for byte transfers
1741 - 256 // time for SOF transfer (1024/fc / 4)
1742 - 128; // time for EOF transfer (512/fc / 4)
1743 // sof/eof_times * 4 here to bring from ssp_clk freq to RF carrier freq
1744 LogTrace_ISO15693(dreader.output, dreader.byteCount, (sof_time * 4), (eof_time * 4), NULL, true);
1746 if (iclass == false) { // Those flags don't exist in iClass
1747 expect_fsk_answer = dreader.output[0] & ISO15_REQ_SUBCARRIER_TWO;
1748 expect_fast_answer = dreader.output[0] & ISO15_REQ_DATARATE_HIGH;
1752 // And ready to receive another command.
1753 //DecodeReaderReset(&dreader); // already reseted
1754 DecodeTagReset(&dtag);
1755 DecodeTagFSKReset(&dtagfsk);
1756 reader_is_active = false;
1757 expect_tag_answer = true;
1758 } else {
1759 reader_is_active = (dreader.state >= STATE_READER_RECEIVE_DATA_1_OUT_OF_4);
1763 // no need to try decoding tag data if the reader is currently sending or no answer expected yet
1764 if ((reader_is_active == false) && expect_tag_answer) {
1766 if (expect_fsk_answer == false) {
1767 // single subcarrier tag response
1768 if (Handle15693SamplesFromTag((sniffdata >> 4) << 2, &dtag, expect_fast_answer)) {
1770 // sof/eof_times are in ssp_clk, which is 13.56MHz / 4
1771 uint32_t eof_time = dma_start_time + (samples * 16) - DELAY_TAG_TO_ARM_SNIFF; // end of EOF
1773 if (dtag.lastBit == SOF_PART2) {
1774 eof_time -= (8 * 16); // needed 8 additional samples to confirm single SOF (iCLASS)
1777 uint32_t sof_time = eof_time
1778 - dtag.len * 1024 // time for byte transfers (4096/fc / 4)
1779 - 512 // time for SOF transfer (2048/fc / 4)
1780 - (dtag.lastBit != SOF_PART2 ? 512 : 0); // time for EOF transfer (2048/fc / 4)
1782 // sof/eof_times * 4 here to bring from ssp_clk freq to RF carrier freq
1783 LogTrace_ISO15693(dtag.output, dtag.len, (sof_time * 4), (eof_time * 4), NULL, false);
1785 // And ready to receive another response.
1786 DecodeTagReset(&dtag);
1787 DecodeTagFSKReset(&dtagfsk);
1788 DecodeReaderReset(&dreader);
1789 expect_tag_answer = false;
1790 tag_is_active = false;
1791 } else {
1792 tag_is_active = (dtag.state >= STATE_TAG_RECEIVING_DATA);
1795 } else {
1796 // dual subcarrier tag response
1797 if (FREQ_IS_0((sniffdata >> 2) & 0x3)) { // tolerate 1 00
1798 sniffdata = sniffdata_prev;
1801 if (Handle15693FSKSamplesFromTag((sniffdata >> 2) & 0x3, &dtagfsk, expect_fast_answer)) {
1802 if (dtagfsk.len > 0) {
1803 // sof/eof_times are in ssp_clk, which is 13.56MHz / 4
1804 uint32_t eof_time = dma_start_time + (samples * 16) - DELAY_TAG_TO_ARM_SNIFF; // end of EOF
1806 if (dtagfsk.lastBit == SOF) {
1807 eof_time -= (8 * 16); // needed 8 additional samples to confirm single SOF (iCLASS)
1810 uint32_t sof_time = eof_time
1811 - dtagfsk.len * 1016 // time for byte transfers (4064/fc / 4) - FSK is slightly different
1812 - 512 // time for SOF transfer (2048/fc / 4)
1813 - (dtagfsk.lastBit != SOF ? 512 : 0); // time for EOF transfer (2048/fc / 4)
1815 // sof/eof_times * 4 here to bring from ssp_clk freq to RF carrier freq
1816 LogTrace_ISO15693(dtagfsk.output, dtagfsk.len, (sof_time * 4), (eof_time * 4), NULL, false);
1819 DecodeTagFSKReset(&dtagfsk);
1820 DecodeReaderReset(&dreader);
1821 expect_tag_answer = false;
1822 tag_is_active = false;
1823 // FSK answer no more expected: switch back to ASK
1824 expect_fsk_answer = false;
1825 } else {
1826 tag_is_active = (dtagfsk.state >= STATE_FSK_RECEIVING_DATA_484);
1832 FpgaDisableTracing();
1833 switch_off();
1835 DbpString("");
1836 if (g_dbglevel > DBG_ERROR) {
1837 DbpString(_CYAN_("Sniff statistics"));
1838 DbpString("=================================");
1839 Dbprintf("DecodeTag State........ %d", dtag.state);
1840 Dbprintf("DecodeTag byteCnt...... %d", dtag.len);
1841 Dbprintf("DecodeTag posCount..... %d", dtag.posCount);
1842 Dbprintf("DecodeTagFSK State..... %d", dtagfsk.state);
1843 Dbprintf("DecodeTagFSK byteCnt... %d", dtagfsk.len);
1844 Dbprintf("DecodeTagFSK count..... %d", dtagfsk.count);
1845 Dbprintf("DecodeReader State..... %d", dreader.state);
1846 Dbprintf("DecodeReader byteCnt... %d", dreader.byteCount);
1847 Dbprintf("DecodeReader posCount.. %d", dreader.posCount);
1849 Dbprintf("Trace length........... " _YELLOW_("%d"), BigBuf_get_traceLen());
1852 // Initialize Proxmark3 as ISO15693 reader
1853 void Iso15693InitReader(void) {
1855 LEDsoff();
1856 FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15);
1858 // Start from off (no field generated)
1859 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1860 SpinDelay(10);
1862 // switch field on
1863 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1864 LED_D_ON();
1866 // initialize SSC and select proper AD input
1867 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1868 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1870 set_tracing(true);
1872 // give tags some time to energize
1873 SpinDelay(250);
1875 StartCountSspClk();
1878 ///////////////////////////////////////////////////////////////////////
1879 // ISO 15693 Part 3 - Air Interface
1880 // This section basically contains transmission and receiving of bits
1881 ///////////////////////////////////////////////////////////////////////
1883 // Encode an identify request, which is the first
1884 // thing that you must send to a tag to get a response.
1885 // It expects "cmdout" to be at least CMD_ID_RESP large
1886 // When READER:
1887 static void BuildIdentifyRequest(uint8_t *cmd) {
1888 // flags
1889 cmd[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1;
1890 // inventory command code
1891 cmd[1] = ISO15693_INVENTORY;
1892 // no mask
1893 cmd[2] = 0x00;
1894 // CRC
1895 AddCrc15(cmd, 3);
1898 // Universal Method for sending to and recv bytes from a tag
1899 // init ... should we initialize the reader?
1900 // speed ... 0 low speed, 1 hi speed
1901 // **recv will return you a pointer to the received data
1902 // If you do not need the answer use NULL for *recv[]
1903 // return: length of received data
1904 // logging enabled
1905 int SendDataTag(const uint8_t *send, int sendlen, bool init, bool speed_fast, uint8_t *recv,
1906 uint16_t max_recv_len, uint32_t start_time, uint16_t timeout, uint32_t *eof_time, uint16_t *resp_len) {
1908 if (init) {
1909 Iso15693InitReader();
1910 start_time = GetCountSspClk();
1913 if (speed_fast) {
1914 // high speed (1 out of 4)
1915 CodeIso15693AsReader(send, sendlen);
1916 } else {
1917 // low speed (1 out of 256)
1918 CodeIso15693AsReader256(send, sendlen);
1921 const tosend_t *ts = get_tosend();
1922 TransmitTo15693Tag(ts->buf, ts->max, &start_time, false);
1924 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
1925 *resp_len = 0;
1926 return PM3_ETEAROFF;
1927 } else {
1929 int res = PM3_SUCCESS;
1930 *eof_time = start_time + 32 * ((8 * ts->max) - 4); // subtract the 4 padding bits after EOF
1931 LogTrace_ISO15693(send, sendlen, (start_time * 4), (*eof_time * 4), NULL, true);
1932 if (recv != NULL) {
1933 bool fsk = ((send[0] & ISO15_REQ_SUBCARRIER_TWO) == ISO15_REQ_SUBCARRIER_TWO);
1934 bool recv_speed = ((send[0] & ISO15_REQ_DATARATE_HIGH) == ISO15_REQ_DATARATE_HIGH);
1935 res = GetIso15693AnswerFromTag(recv, max_recv_len, timeout, eof_time, fsk, recv_speed, resp_len);
1937 return res;
1941 int SendDataTagEOF(uint8_t *recv, uint16_t max_recv_len, uint32_t start_time, uint16_t timeout, uint32_t *eof_time, bool fsk, bool recv_speed, uint16_t *resp_len) {
1943 CodeIso15693AsReaderEOF();
1944 const tosend_t *ts = get_tosend();
1945 TransmitTo15693Tag(ts->buf, ts->max, &start_time, false);
1946 uint32_t end_time = start_time + 32 * (8 * ts->max - 4); // subtract the 4 padding bits after EOF
1947 LogTrace_ISO15693(NULL, 0, (start_time * 4), (end_time * 4), NULL, true);
1949 int res = PM3_SUCCESS;
1950 if (recv) {
1951 res = GetIso15693AnswerFromTag(recv, max_recv_len, timeout, eof_time, fsk, recv_speed, resp_len);
1953 return res;
1956 // --------------------------------------------------------------------
1957 // Debug Functions
1958 // --------------------------------------------------------------------
1960 // Decodes a message from a tag and displays its metadata and content
1961 #define DBD15STATLEN 48
1962 static void DbdecodeIso15693Answer(int n, const uint8_t *d) {
1964 if (n > 3) {
1966 char status[DBD15STATLEN + 1] = {0};
1968 if (d[0] & ISO15_RES_EXT)
1969 strncat(status, "ProtExt ", DBD15STATLEN - strlen(status));
1971 if (d[0] & ISO15_RES_ERROR) {
1972 // error
1973 strncat(status, "Error ", DBD15STATLEN - strlen(status));
1974 switch (d[1]) {
1975 case 0x01:
1976 strncat(status, "01: not supported", DBD15STATLEN - strlen(status));
1977 break;
1978 case 0x02:
1979 strncat(status, "02: not recognized", DBD15STATLEN - strlen(status));
1980 break;
1981 case 0x03:
1982 strncat(status, "03: opt not supported", DBD15STATLEN - strlen(status));
1983 break;
1984 case 0x0f:
1985 strncat(status, "0F: no info", DBD15STATLEN - strlen(status));
1986 break;
1987 case 0x10:
1988 strncat(status, "10: don't exist", DBD15STATLEN - strlen(status));
1989 break;
1990 case 0x11:
1991 strncat(status, "11: lock again", DBD15STATLEN - strlen(status));
1992 break;
1993 case 0x12:
1994 strncat(status, "12: locked", DBD15STATLEN - strlen(status));
1995 break;
1996 case 0x13:
1997 strncat(status, "13: program error", DBD15STATLEN - strlen(status));
1998 break;
1999 case 0x14:
2000 strncat(status, "14: lock error", DBD15STATLEN - strlen(status));
2001 break;
2002 default:
2003 strncat(status, "unknown error", DBD15STATLEN - strlen(status));
2005 strncat(status, " ", DBD15STATLEN - strlen(status));
2006 } else {
2007 strncat(status, "No error ", DBD15STATLEN - strlen(status));
2010 if (CheckCrc15(d, n))
2011 strncat(status, "[+] crc ( " _GREEN_("ok") " )", DBD15STATLEN - strlen(status));
2012 else
2013 strncat(status, "[!] crc ( " _RED_("fail") " )", DBD15STATLEN - strlen(status));
2015 if (g_dbglevel >= DBG_ERROR) Dbprintf("%s", status);
2019 ///////////////////////////////////////////////////////////////////////
2020 // Functions called via USB/Client
2021 ///////////////////////////////////////////////////////////////////////
2023 //-----------------------------------------------------------------------------
2024 // Act as ISO15693 reader, perform anti-collision and then attempt to read a sector
2025 // all demodulation performed in arm rather than host. - greg
2026 //-----------------------------------------------------------------------------
2027 void ReaderIso15693(iso15_card_select_t *p_card) {
2029 LED_A_ON();
2030 set_tracing(true);
2032 uint8_t *answer = BigBuf_malloc(ISO15693_MAX_RESPONSE_LENGTH);
2033 memset(answer, 0x00, ISO15693_MAX_RESPONSE_LENGTH);
2035 // FIRST WE RUN AN INVENTORY TO GET THE TAG UID
2036 // THIS MEANS WE CAN PRE-BUILD REQUESTS TO SAVE CPU TIME
2038 // Send the IDENTIFY command
2039 uint8_t cmd[5] = {0};
2040 BuildIdentifyRequest(cmd);
2041 uint32_t start_time = 0;
2042 uint32_t eof_time;
2043 uint16_t recvlen = 0;
2044 int res = SendDataTag(cmd, sizeof(cmd), true, true, answer, ISO15693_MAX_RESPONSE_LENGTH, start_time, ISO15693_READER_TIMEOUT, &eof_time, &recvlen);
2046 if (res == PM3_ETEAROFF) { // tearoff occurred
2047 reply_ng(CMD_HF_ISO15693_READER, res, NULL, 0);
2048 } else {
2050 //start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2052 // we should do a better check than this
2053 if (recvlen >= 12) {
2054 uint8_t uid[8];
2055 uid[0] = answer[9]; // always E0
2056 uid[1] = answer[8]; // IC Manufacturer code
2057 uid[2] = answer[7];
2058 uid[3] = answer[6];
2059 uid[4] = answer[5];
2060 uid[5] = answer[4];
2061 uid[6] = answer[3];
2062 uid[7] = answer[2];
2064 if (p_card != NULL) {
2065 memcpy(p_card->uid, uid, 8);
2066 p_card->uidlen = 8;
2069 if (g_dbglevel >= DBG_EXTENDED) {
2070 Dbprintf("[+] UID = %02X%02X%02X%02X%02X%02X%02X%02X",
2071 uid[0], uid[1], uid[2], uid[3],
2072 uid[4], uid[5], uid[5], uid[6]
2075 // send UID back to client.
2076 // arg0 = 1 = OK
2077 // arg1 = len of response (12 bytes)
2078 // arg2 = rtf
2079 // asbytes = uid.
2080 reply_ng(CMD_HF_ISO15693_READER, PM3_SUCCESS, uid, sizeof(uid));
2082 if (g_dbglevel >= DBG_EXTENDED) {
2083 Dbprintf("[+] %d bytes read from IDENTIFY request:", recvlen);
2084 DbdecodeIso15693Answer(recvlen, answer);
2085 Dbhexdump(recvlen, answer, true);
2087 } else {
2088 p_card->uidlen = 0;
2089 DbpString("Failed to select card");
2090 reply_ng(CMD_HF_ISO15693_READER, PM3_EFAILED, NULL, 0);
2093 switch_off();
2094 BigBuf_free();
2097 // When SIM: initialize the Proxmark3 as ISO15693 tag
2098 void Iso15693InitTag(void) {
2100 FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15);
2102 // Start from off (no field generated)
2103 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2104 LEDsoff();
2105 SpinDelay(10);
2107 // switch simulation FPGA
2108 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
2110 // initialize SSC and select proper AD input
2111 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
2112 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2114 clear_trace();
2115 set_tracing(true);
2117 StartCountSspClk();
2120 void EmlClearIso15693(void) {
2121 // Resetting the bitstream also frees the BigBuf memory, so we do this here to prevent
2122 // an inconvenient reset in the future by Iso15693InitTag
2123 FpgaDownloadAndGo(FPGA_BITSTREAM_HF_15);
2124 BigBuf_Clear_EM();
2125 reply_ng(CMD_HF_ISO15693_EML_CLEAR, PM3_SUCCESS, NULL, 0);
2128 // Simulate an ISO15693 TAG, perform anti-collision and then print any reader commands
2129 // all demodulation performed in arm rather than host. - greg
2130 void SimTagIso15693(const uint8_t *uid, uint8_t block_size) {
2132 // free eventually allocated BigBuf memory
2133 BigBuf_free_keep_EM();
2134 // Init early to be sure FPGA is loaded before any EML operation
2135 // usefull when eml memory is empty (UID supplied)
2136 Iso15693InitTag(); // to be sure FPGA is loaded before any EML operation
2138 iso15_tag_t *tag = (iso15_tag_t *) BigBuf_get_EM_addr();
2139 if (tag == NULL) {
2140 Dbprintf("Can't allocate emulator memory");
2141 reply_ng(CMD_HF_ISO15693_SIMULATE, PM3_EFAILED, NULL, 0);
2142 return;
2145 if (uid != NULL) {
2147 uint8_t empty[8] = { 0 };
2149 // User supplied not empty?
2150 if (memcmp(uid, empty, 8)) {
2151 // Set default values if user supplied a UID.
2152 // Assume emulator memory is empty
2153 tag->uid[0] = uid[7]; // always E0
2154 tag->uid[1] = uid[6]; // IC Manufacturer code
2155 tag->uid[2] = uid[5];
2156 tag->uid[3] = uid[4];
2157 tag->uid[4] = uid[3];
2158 tag->uid[5] = uid[2];
2159 tag->uid[6] = uid[1];
2160 tag->uid[7] = uid[0];
2162 tag->dsfid = 0;
2163 tag->dsfidLock = false;
2164 tag->afi = 0;
2165 tag->afiLock = false;
2166 tag->bytesPerPage = (block_size > 0) ? block_size : 4;
2167 tag->pagesCount = 64;
2168 tag->ic = 0;
2169 memset(tag->locks, 0, sizeof(tag->locks));
2170 memset(tag->data, 0, sizeof(tag->data));
2174 if ((tag->pagesCount > ISO15693_TAG_MAX_PAGES) ||
2175 ((tag->pagesCount * tag->bytesPerPage) > ISO15693_TAG_MAX_SIZE) ||
2176 (tag->pagesCount == 0) ||
2177 (tag->bytesPerPage == 0)) {
2178 Dbprintf("Tag size error: pagesCount = %d, bytesPerPage=%d", tag->pagesCount, tag->bytesPerPage);
2179 reply_ng(CMD_HF_ISO15693_SIMULATE, PM3_EOPABORTED, NULL, 0);
2180 return;
2183 LED_A_ON();
2185 if (g_dbglevel >= DBG_DEBUG) {
2186 Dbprintf("ISO-15963 Simulating uid: %02X%02X%02X%02X%02X%02X%02X%02X, %u bytes/blocks x %u blocks"
2187 , tag->uid[7]
2188 , tag->uid[6]
2189 , tag->uid[5]
2190 , tag->uid[4]
2191 , tag->uid[3]
2192 , tag->uid[2]
2193 , tag->uid[1]
2194 , tag->uid[0]
2195 , tag->bytesPerPage
2196 , tag->pagesCount
2200 LED_C_ON();
2202 bool button_pressed = false;
2203 int vHf; // in mV
2205 bool exit_loop = false;
2206 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH] = {0};
2207 uint8_t recv[ISO15693_MAX_RESPONSE_LENGTH] = {0};
2208 uint8_t mask_len = 0;
2209 uint8_t maskCpt = 0;
2210 uint8_t cmdCpt = 0;
2211 uint16_t recvLen = 0;
2212 uint8_t error = 0;
2213 uint8_t pageNum = 0;
2214 uint8_t nbPages = 0;
2215 uint8_t pwdId = 0;
2217 while (exit_loop == false) {
2219 button_pressed = BUTTON_PRESS();
2220 if (button_pressed || data_available())
2221 break;
2223 WDT_HIT();
2225 // find reader field
2226 if (tag->state == TAG_STATE_NO_FIELD) {
2228 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
2229 if (vHf > MF_MINFIELDV) {
2230 tag->state = TAG_STATE_READY;
2231 LED_A_ON();
2232 } else {
2233 continue;
2237 // Listen to reader
2238 uint32_t reader_eof_time = 0;
2239 int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &reader_eof_time);
2240 if (cmd_len < 0) {
2241 button_pressed = true;
2242 break;
2245 if (cmd_len <= 3)
2246 continue;
2248 // Shorten 0 terminated msgs
2249 // (Some times received commands are prolonged with a random number of 0 bytes...)
2250 while (cmd[cmd_len - 1] == 0) {
2251 cmd_len--;
2252 if (cmd_len <= 3)
2253 break;
2256 if (g_dbglevel >= DBG_DEBUG) {
2257 Dbprintf("%d bytes read from reader:", cmd_len);
2258 Dbhexdump(cmd_len, cmd, false);
2261 if (cmd_len < 3)
2262 continue;
2264 // Check CRC and drop received cmd with bad CRC
2265 uint16_t crc = CalculateCrc15(cmd, cmd_len - 2);
2266 if (((crc & 0xff) != cmd[cmd_len - 2]) || ((crc >> 8) != cmd[cmd_len - 1])) {
2267 crc = CalculateCrc15(cmd, ++cmd_len - 2); // if crc end with 00
2268 if (((crc & 0xff) != cmd[cmd_len - 2]) || ((crc >> 8) != cmd[cmd_len - 1])) {
2269 crc = CalculateCrc15(cmd, ++cmd_len - 2); // if crc end with 00 00
2270 if (((crc & 0xff) != cmd[cmd_len - 2]) || ((crc >> 8) != cmd[cmd_len - 1])) {
2271 if (g_dbglevel >= DBG_DEBUG) Dbprintf("CrcFail!, expected CRC=%02X%02X", crc & 0xff, crc >> 8);
2272 continue;
2273 } else if (g_dbglevel >= DBG_DEBUG)
2274 Dbprintf("CrcOK");
2275 } else if (g_dbglevel >= DBG_DEBUG)
2276 Dbprintf("CrcOK");
2277 } else if (g_dbglevel >= DBG_DEBUG)
2278 Dbprintf("CrcOK");
2280 cmd_len -= 2; // remove the CRC from the cmd
2281 recvLen = 0;
2283 tag->expectFast = ((cmd[0] & ISO15_REQ_DATARATE_HIGH) == ISO15_REQ_DATARATE_HIGH);
2284 tag->expectFsk = ((cmd[0] & ISO15_REQ_SUBCARRIER_TWO) == ISO15_REQ_SUBCARRIER_TWO);
2286 if (g_dbglevel >= DBG_DEBUG) {
2287 if (tag->expectFsk)
2288 Dbprintf("ISO15_REQ_SUBCARRIER_TWO support is currently experimental!");
2289 if ((cmd[0] & ISO15_REQ_PROTOCOL_EXT) == ISO15_REQ_PROTOCOL_EXT)
2290 Dbprintf("ISO15_REQ_PROTOCOL_EXT not supported!");
2291 if ((cmd[0] & ISO15_REQ_OPTION) == ISO15_REQ_OPTION)
2292 Dbprintf("ISO15_REQ_OPTION not supported!");
2295 if (((cmd[0] & ISO15_REQ_INVENTORY) == ISO15_REQ_INVENTORY) && tag->state != TAG_STATE_SILENCED) {
2296 // REQ_INVENTORY flaged requests are interpreted as a INVENTORY no matter
2297 // what is the CMD (as observed from various actual tags)
2299 // TODO: support colision avoidances
2301 if (g_dbglevel >= DBG_DEBUG) {
2302 Dbprintf("Inventory req");
2303 if ((cmd[0] & ISO15_REQINV_SLOT1) == ISO15_REQINV_SLOT1)
2304 Dbprintf("ISO15_REQINV_SLOT1/SLOT16 not supported!");
2307 cmdCpt = 2;
2309 // Check AFI
2310 if ((cmd[0] & ISO15_REQINV_AFI) == ISO15_REQINV_AFI) {
2311 if (cmd[cmdCpt] != tag->afi && cmd[cmdCpt] != 0)
2312 continue; // bad AFI : drop request
2313 cmdCpt++;
2316 // Check mask
2317 if (cmdCpt >= cmd_len)
2318 continue; // mask is not present : drop request
2319 mask_len = cmd[cmdCpt++];
2321 maskCpt = 0;
2323 while (mask_len >= 8 && cmdCpt < (uint8_t)cmd_len && maskCpt < 8) { // Byte comparison
2324 if (cmd[cmdCpt++] != tag->uid[maskCpt++]) {
2325 error++; // mask don't match : drop request
2326 break;
2328 mask_len -= 8;
2331 if (mask_len > 0 && cmdCpt >= cmd_len)
2332 continue; // mask is shorter than declared mask lenght: drop request
2334 while (mask_len > 0) { // Bit comparison
2335 mask_len--;
2336 if (((cmd[cmdCpt] >> mask_len) & 1) != ((tag->uid[maskCpt] >> mask_len) & 1)) {
2337 error++; // mask don't match : drop request
2338 break;
2342 if (error > 0)
2343 continue;
2345 // No error: Answer
2346 recv[0] = ISO15_NOERROR;
2347 recv[1] = tag->dsfid;
2348 memcpy(&recv[2], tag->uid, 8);
2349 recvLen = 10;
2350 } else {
2351 if ((cmd[0] & ISO15_REQ_SELECT) == ISO15_REQ_SELECT) {
2352 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Selected Request");
2353 if (tag->state != TAG_STATE_SELECTED)
2354 continue; // drop selected request if not selected
2355 tag->state = TAG_STATE_READY; // Select flag set if already selected : unselect
2358 cmdCpt = 2;
2359 if ((cmd[0] & ISO15_REQ_ADDRESS) == ISO15_REQ_ADDRESS) {
2360 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Addressed Request");
2361 if (cmd_len < cmdCpt + 8)
2362 continue;
2363 if (memcmp(&cmd[cmdCpt], tag->uid, 8) != 0) {
2364 if (cmd_len < cmdCpt + 9 || memcmp(&cmd[cmdCpt + 1], tag->uid, 8) != 0) {
2365 // check uid even if manifacturer byte is present
2366 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Address don't match tag uid");
2367 if (cmd[1] == ISO15693_SELECT)
2368 tag->state = TAG_STATE_READY; // we are not anymore the selected TAG
2369 continue; // drop addressed request with other uid
2371 cmdCpt++;
2373 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Address match tag uid");
2374 cmdCpt += 8;
2375 } else if (tag->state == TAG_STATE_SILENCED) {
2376 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Unaddressed request in quiet state: drop");
2377 continue; // drop unadressed request in quiet state
2380 switch (cmd[1]) {
2381 case ISO15693_INVENTORY:
2382 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Inventory cmd");
2383 recv[0] = ISO15_NOERROR;
2384 recv[1] = tag->dsfid;
2385 memcpy(&recv[2], tag->uid, 8);
2386 recvLen = 10;
2387 break;
2388 case ISO15693_STAYQUIET:
2389 if (g_dbglevel >= DBG_DEBUG) Dbprintf("StayQuiet cmd");
2390 tag->state = TAG_STATE_SILENCED;
2391 break;
2392 case ISO15693_READBLOCK:
2393 if (g_dbglevel >= DBG_DEBUG) Dbprintf("ReadBlock cmd");
2394 pageNum = cmd[cmdCpt++];
2395 if (pageNum >= tag->pagesCount)
2396 error = ISO15_ERROR_BLOCK_UNAVAILABLE;
2397 else {
2398 recv[0] = ISO15_NOERROR;
2399 recvLen = 1;
2400 if ((cmd[0] & ISO15_REQ_OPTION) == ISO15_REQ_OPTION) { // ask for lock status
2401 recv[1] = tag->locks[pageNum];
2402 recvLen++;
2404 for (uint8_t i = 0 ; i < tag->bytesPerPage ; i++)
2405 recv[recvLen + i] = tag->data[(pageNum * tag->bytesPerPage) + i];
2406 recvLen += tag->bytesPerPage;
2408 break;
2409 case ISO15693_WRITEBLOCK:
2410 if (g_dbglevel >= DBG_DEBUG) Dbprintf("WriteBlock cmd");
2411 pageNum = cmd[cmdCpt++];
2412 if (pageNum >= tag->pagesCount)
2413 error = ISO15_ERROR_BLOCK_UNAVAILABLE;
2414 else {
2415 for (uint8_t i = 0 ; i < tag->bytesPerPage ; i++)
2416 tag->data[(pageNum * tag->bytesPerPage) + i] = cmd[i + cmdCpt];
2417 recv[0] = ISO15_NOERROR;
2418 recvLen = 1;
2420 break;
2421 case ISO15693_LOCKBLOCK:
2422 if (g_dbglevel >= DBG_DEBUG) Dbprintf("LockBlock cmd");
2423 pageNum = cmd[cmdCpt++];
2424 if (pageNum >= tag->pagesCount)
2425 error = ISO15_ERROR_BLOCK_UNAVAILABLE;
2426 else if (tag->locks[pageNum])
2427 error = ISO15_ERROR_BLOCK_LOCKED_ALREADY;
2428 else {
2429 tag->locks[pageNum] = 1;
2430 recv[0] = ISO15_NOERROR;
2431 recvLen = 1;
2433 break;
2434 case ISO15693_READ_MULTI_BLOCK:
2435 if (g_dbglevel >= DBG_DEBUG) Dbprintf("ReadMultiBlock cmd");
2436 pageNum = cmd[cmdCpt++];
2437 nbPages = cmd[cmdCpt++];
2438 if (pageNum + nbPages >= tag->pagesCount)
2439 error = ISO15_ERROR_BLOCK_UNAVAILABLE;
2440 else {
2441 recv[0] = ISO15_NOERROR;
2442 recvLen = 1;
2443 for (int i = 0 ; i < (nbPages + 1) * tag->bytesPerPage && \
2444 recvLen + 3 < ISO15693_MAX_RESPONSE_LENGTH ; i++) {
2445 if ((i % tag->bytesPerPage) == 0 && (cmd[0] & ISO15_REQ_OPTION))
2446 recv[recvLen++] = tag->locks[pageNum + (i / tag->bytesPerPage)];
2447 recv[recvLen++] = tag->data[(pageNum * tag->bytesPerPage) + i];
2449 if (recvLen + 3 > ISO15693_MAX_RESPONSE_LENGTH) // limit response size
2450 recvLen = ISO15693_MAX_RESPONSE_LENGTH - 3; // to avoid overflow
2452 break;
2453 case ISO15693_WRITE_AFI:
2454 if (g_dbglevel >= DBG_DEBUG) Dbprintf("WriteAFI cmd");
2455 if (tag->afiLock)
2456 error = ISO15_ERROR_BLOCK_LOCKED;
2457 else {
2458 tag->afi = cmd[cmdCpt++];
2459 recv[0] = ISO15_NOERROR;
2460 recvLen = 1;
2462 break;
2463 case ISO15693_LOCK_AFI:
2464 if (g_dbglevel >= DBG_DEBUG) Dbprintf("LockAFI cmd");
2465 if (tag->afiLock)
2466 error = ISO15_ERROR_BLOCK_LOCKED_ALREADY;
2467 else {
2468 tag->afiLock = true;
2469 recv[0] = ISO15_NOERROR;
2470 recvLen = 1;
2472 break;
2473 case ISO15693_WRITE_DSFID:
2474 if (g_dbglevel >= DBG_DEBUG) Dbprintf("WriteDSFID cmd");
2475 if (tag->dsfidLock)
2476 error = ISO15_ERROR_BLOCK_LOCKED;
2477 else {
2478 tag->dsfid = cmd[cmdCpt++];
2479 recv[0] = ISO15_NOERROR;
2480 recvLen = 1;
2482 break;
2483 case ISO15693_LOCK_DSFID:
2484 if (g_dbglevel >= DBG_DEBUG) Dbprintf("LockDSFID cmd");
2485 if (tag->dsfidLock)
2486 error = ISO15_ERROR_BLOCK_LOCKED_ALREADY;
2487 else {
2488 tag->dsfidLock = true;
2489 recv[0] = ISO15_NOERROR;
2490 recvLen = 1;
2492 break;
2493 case ISO15693_SELECT:
2494 if (g_dbglevel >= DBG_DEBUG) Dbprintf("Select cmd");
2495 tag->state = TAG_STATE_SELECTED;
2496 recv[0] = ISO15_NOERROR;
2497 recvLen = 1;
2498 break;
2499 case ISO15693_RESET_TO_READY:
2500 if (g_dbglevel >= DBG_DEBUG) Dbprintf("ResetToReady cmd");
2501 tag->state = TAG_STATE_READY;
2502 recv[0] = ISO15_NOERROR;
2503 recvLen = 1;
2504 break;
2505 case ISO15693_GET_SYSTEM_INFO:
2506 if (g_dbglevel >= DBG_DEBUG) Dbprintf("GetSystemInfo cmd");
2507 recv[0] = ISO15_NOERROR;
2508 recv[1] = 0x0f; // sysinfo contain all info
2509 memcpy(&recv[2], tag->uid, 8);
2510 recv[10] = tag->dsfid;
2511 recv[11] = tag->afi;
2512 recv[12] = tag->pagesCount - 1;
2513 recv[13] = tag->bytesPerPage - 1;
2514 recv[14] = tag->ic;
2515 recvLen = 15;
2516 break;
2517 case ISO15693_READ_MULTI_SECSTATUS:
2518 if (g_dbglevel >= DBG_DEBUG) Dbprintf("ReadMultiSecStatus cmd");
2519 pageNum = cmd[cmdCpt++];
2520 nbPages = cmd[cmdCpt++];
2521 if (pageNum + nbPages >= tag->pagesCount)
2522 error = ISO15_ERROR_BLOCK_UNAVAILABLE;
2523 else {
2524 recv[0] = ISO15_NOERROR;
2525 recvLen = 1;
2526 for (uint8_t i = 0 ; i < nbPages + 1 ; i++)
2527 recv[recvLen++] = tag->locks[pageNum + i];
2529 break;
2530 case ISO15693_GET_RANDOM_NUMBER:
2531 if (g_dbglevel >= DBG_DEBUG) Dbprintf("GetRandomNumber cmd");
2532 tag->random[0] = (uint8_t)(reader_eof_time) ^ 0xFF; // poor random number
2533 tag->random[1] = (uint8_t)(reader_eof_time >> 8) ^ 0xFF;
2534 recv[0] = ISO15_NOERROR;
2535 recv[1] = tag->random[0]; // poor random number
2536 recv[2] = tag->random[1];
2537 recvLen = 3;
2538 break;
2539 case ISO15693_SET_PASSWORD:
2540 if (g_dbglevel >= DBG_DEBUG) Dbprintf("SetPassword cmd");
2541 if (cmd_len > cmdCpt + 5)
2542 cmdCpt++; // skip manifacturer code
2543 if (cmd_len > cmdCpt + 4) {
2544 pwdId = cmd[cmdCpt++];
2545 if (pwdId == 4) { // Privacy password
2546 tag->privacyPasswd[0] = cmd[cmdCpt] ^ tag->random[0];
2547 tag->privacyPasswd[1] = cmd[cmdCpt + 1] ^ tag->random[1];
2548 tag->privacyPasswd[2] = cmd[cmdCpt + 2] ^ tag->random[0];
2549 tag->privacyPasswd[3] = cmd[cmdCpt + 3] ^ tag->random[1];
2552 recv[0] = ISO15_NOERROR;
2553 recvLen = 1;
2554 break;
2555 case ISO15693_ENABLE_PRIVACY:
2556 if (g_dbglevel >= DBG_DEBUG) Dbprintf("EnablePrivacy cmd");
2557 // not realy entering privacy mode
2558 // just return NOERROR
2559 recv[0] = ISO15_NOERROR;
2560 recvLen = 1;
2561 break;
2562 default:
2563 if (g_dbglevel >= DBG_DEBUG)
2564 Dbprintf("ISO15693 CMD 0x%2X not supported", cmd[1]);
2566 error = ISO15_ERROR_CMD_NOT_SUP;
2567 break;
2570 if (error != 0) { // Error happened
2571 recv[0] = ISO15_RES_ERROR;
2572 recv[1] = error;
2573 recvLen = 2;
2574 error = 0;
2575 if (g_dbglevel >= DBG_DEBUG)
2576 Dbprintf("ERROR 0x%2X in received request", error);
2580 if (recvLen > 0) { // We need to answer
2581 AddCrc15(recv, recvLen);
2582 recvLen += 2;
2583 CodeIso15693AsTag(recv, recvLen);
2584 const tosend_t *ts = get_tosend();
2585 uint32_t response_time = reader_eof_time + DELAY_ISO15693_VCD_TO_VICC_SIM;
2587 if (tag->expectFsk) { // Not suppoted yet
2588 if (g_dbglevel >= DBG_DEBUG) Dbprintf("%ERROR: FSK answers are not supported yet");
2589 //TransmitTo15693ReaderFSK(ts->buf,ts->max, &response_time, 0, !tag->expectFast);
2590 } else
2591 TransmitTo15693Reader(ts->buf, ts->max, &response_time, 0, !tag->expectFast);
2593 LogTrace_ISO15693(recv, recvLen, response_time * 32, (response_time * 32) + (ts->max * 32 * 64), NULL, false);
2597 switch_off();
2599 if (button_pressed) {
2600 DbpString("button pressed");
2603 reply_ng(CMD_HF_ISO15693_SIMULATE, PM3_SUCCESS, NULL, 0);
2606 // Since there is no standardized way of reading the AFI out of a tag, we will brute force it
2607 // (some manufactures offer a way to read the AFI, though)
2608 void BruteforceIso15693Afi(uint32_t flags) {
2610 clear_trace();
2612 Iso15693InitReader();
2614 bool speed = ((flags & ISO15_HIGH_SPEED) == ISO15_HIGH_SPEED);
2616 // first without AFI
2617 // Tags should respond without AFI and with AFI=0 even when AFI is active
2618 uint8_t data[7] = {0};
2619 uint8_t recv[ISO15693_MAX_RESPONSE_LENGTH] = {0};
2621 data[0] = (ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1);
2622 data[1] = ISO15693_INVENTORY;
2623 data[2] = 0; // AFI
2624 AddCrc15(data, 3);
2626 int datalen = 5;
2627 uint32_t eof_time = 0;
2628 uint16_t recvlen = 0;
2629 int res = SendDataTag(data, datalen, true, speed, recv, sizeof(recv), 0, ISO15693_READER_TIMEOUT, &eof_time, &recvlen);
2630 if (res != PM3_SUCCESS) {
2631 DbpString("Failed to select card");
2632 reply_ng(CMD_HF_ISO15693_FINDAFI, res, NULL, 0);
2633 switch_off();
2634 return;
2637 uint32_t start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2638 WDT_HIT();
2640 if (recvlen >= 12) {
2641 Dbprintf("NoAFI UID = %s", iso15693_sprintUID(NULL, recv + 2));
2644 // now with AFI
2645 data[0] |= ISO15_REQINV_AFI;
2646 data[2] = 0; // AFI
2647 data[3] = 0; // mask length
2649 // 4 + 2crc
2650 datalen = 6;
2652 bool aborted = false;
2653 for (uint16_t i = 0; i < 256; i++) {
2655 data[2] = i & 0xFF;
2656 AddCrc15(data, 4);
2658 recvlen = 0;
2659 res = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), start_time, ISO15693_READER_TIMEOUT, &eof_time, &recvlen);
2660 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2662 WDT_HIT();
2664 if (recvlen >= 12) {
2665 Dbprintf("AFI = %i UID = %s", i, iso15693_sprintUID(NULL, recv + 2));
2668 aborted = (BUTTON_PRESS() && data_available());
2669 if (aborted) {
2670 break;
2674 DbpString("AFI Bruteforcing done.");
2675 switch_off();
2677 if (aborted) {
2678 reply_ng(CMD_HF_ISO15693_FINDAFI, PM3_EOPABORTED, NULL, 0);
2679 } else {
2680 reply_ng(CMD_HF_ISO15693_FINDAFI, PM3_SUCCESS, NULL, 0);
2684 // Allows to directly send commands to the tag via the client
2685 // OBS: doesn't turn off rf field afterwards.
2686 void SendRawCommand15693(iso15_raw_cmd_t *packet) {
2688 LED_A_ON();
2690 uint16_t timeout = ISO15693_READER_TIMEOUT;
2691 if ((packet->flags & ISO15_LONG_WAIT) == ISO15_LONG_WAIT) {
2692 timeout = ISO15693_READER_TIMEOUT_WRITE;
2695 bool speed = ((packet->flags & ISO15_HIGH_SPEED) == ISO15_HIGH_SPEED);
2696 bool keep_field_on = ((packet->flags & ISO15_NO_DISCONNECT) == ISO15_NO_DISCONNECT);
2697 bool read_respone = ((packet->flags & ISO15_READ_RESPONSE) == ISO15_READ_RESPONSE);
2698 bool init = ((packet->flags & ISO15_CONNECT) == ISO15_CONNECT);
2700 // This is part of ISO15693 protocol definitions where the following commands needs to request option.
2701 // note:
2702 // it seem like previous we just guessed and never followed the fISO145_REQ_OPTION flag if it was set / not set from client side.
2703 // this is a problem. Since without this the response from the tag is one byte shorter. And a lot of client side functions has been
2704 // hardcoded to assume for the extra byte in the response.
2706 bool request_answer = false;
2708 switch (packet->raw[1]) {
2709 case ISO15693_SET_PASSWORD:
2710 case ISO15693_ENABLE_PRIVACY:
2711 case ISO15693_WRITEBLOCK:
2712 case ISO15693_LOCKBLOCK:
2713 case ISO15693_WRITE_MULTI_BLOCK:
2714 case ISO15693_WRITE_AFI:
2715 case ISO15693_LOCK_AFI:
2716 case ISO15693_WRITE_DSFID:
2717 case ISO15693_WRITE_PASSWORD:
2718 case ISO15693_PASSWORD_PROTECT_EAS:
2719 case ISO15693_LOCK_DSFID:
2720 request_answer = ((packet->raw[0] & ISO15_REQ_OPTION) == ISO15_REQ_OPTION);
2721 break;
2722 default:
2723 break;
2726 uint32_t eof_time = 0;
2727 uint32_t start_time = 0;
2728 uint16_t recvlen = 0;
2730 uint8_t buf[ISO15693_MAX_RESPONSE_LENGTH] = {0x00};
2732 int res = SendDataTag(packet->raw, packet->rawlen, init, speed, (read_respone ? buf : NULL), sizeof(buf), start_time, timeout, &eof_time, &recvlen);
2734 if (res == PM3_ETEAROFF) { // tearoff occurred
2735 reply_ng(CMD_HF_ISO15693_COMMAND, res, NULL, 0);
2736 } else {
2738 // if tag answers with an error code, it don't care about EOF packet
2739 if (recvlen) {
2740 recvlen = MIN(recvlen, ISO15693_MAX_RESPONSE_LENGTH);
2741 reply_ng(CMD_HF_ISO15693_COMMAND, res, buf, recvlen);
2744 // looking at the first byte of the RAW bytes to determine Subcarrier, datarate, request option
2745 bool fsk = ((packet->raw[0] & ISO15_REQ_SUBCARRIER_TWO) == ISO15_REQ_SUBCARRIER_TWO);
2746 bool recv_speed = ((packet->raw[0] & ISO15_REQ_DATARATE_HIGH) == ISO15_REQ_DATARATE_HIGH);
2748 // send a single EOF to get the tag response
2749 if (request_answer) {
2750 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2751 res = SendDataTagEOF((read_respone ? buf : NULL), sizeof(buf), start_time, ISO15693_READER_TIMEOUT, &eof_time, fsk, recv_speed, &recvlen);
2754 if (read_respone) {
2755 recvlen = MIN(recvlen, ISO15693_MAX_RESPONSE_LENGTH);
2756 reply_ng(CMD_HF_ISO15693_COMMAND, res, buf, recvlen);
2757 } else {
2758 reply_ng(CMD_HF_ISO15693_COMMAND, PM3_SUCCESS, NULL, 0);
2762 if (keep_field_on == false) {
2763 switch_off(); // disconnect raw
2764 SpinDelay(20);
2767 LED_A_OFF();
2771 SLIx functions from official master forks.
2773 void LockPassSlixIso15693(uint32_t pass_id, uint32_t password) {
2775 LED_A_ON();
2777 uint8_t cmd_inventory[] = {ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_INVENTORY | ISO15693_REQINV_SLOT1, 0x01, 0x00, 0x00, 0x00 };
2778 uint8_t cmd_get_rnd[] = {ISO15693_REQ_DATARATE_HIGH, 0xB2, 0x04, 0x00, 0x00 };
2779 uint8_t cmd_set_pass[] = {ISO15693_REQ_DATARATE_HIGH, 0xB3, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2780 //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 };
2781 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 };
2782 uint16_t crc;
2783 uint16_t recvlen = 0;
2784 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2785 uint32_t start_time = 0;
2786 bool done = false;
2787 int res;
2789 // setup 'get random number' command
2790 crc = Iso15693Crc(cmd_get_rnd, 3);
2791 cmd_get_rnd[3] = crc & 0xff;
2792 cmd_get_rnd[4] = crc >> 8;
2794 Dbprintf("LockPass: Press button lock password, long-press to terminate.");
2796 while (!done) {
2798 LED_D_ON();
2799 switch(BUTTON_HELD(1000)) {
2800 case BUTTON_SINGLE_CLICK:
2801 Dbprintf("LockPass: Reset 'DONE'-LED (A)");
2802 LED_A_OFF();
2803 LED_B_OFF();
2804 LED_C_OFF();
2805 break;
2806 case BUTTON_HOLD:
2807 Dbprintf("LockPass: Terminating");
2808 done = true;
2809 break;
2810 default:
2811 SpinDelay(50);
2812 continue;
2815 if (done) [
2816 break;
2819 res = SendDataTag(cmd_get_rnd, sizeof(cmd_get_rnd), true, true, recvbuf, sizeof(recvbuf), start_time, &recvlen);
2820 if (res != PM3_SUCCESS && recvlen != 5) {
2821 LED_C_ON();
2822 } else {
2823 Dbprintf("LockPass: Received random 0x%02X%02X (%d)", recvbuf[1], recvbuf[2], recvlen);
2825 // setup 'set password' command
2826 cmd_set_pass[4] = ((password>>0) &0xFF) ^ recvbuf[1];
2827 cmd_set_pass[5] = ((password>>8) &0xFF) ^ recvbuf[2];
2828 cmd_set_pass[6] = ((password>>16) &0xFF) ^ recvbuf[1];
2829 cmd_set_pass[7] = ((password>>24) &0xFF) ^ recvbuf[2];
2831 crc = Iso15693Crc(cmd_set_pass, 8);
2832 cmd_set_pass[8] = crc & 0xff;
2833 cmd_set_pass[9] = crc >> 8;
2835 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]);
2836 res = SendDataTag(cmd_set_pass, sizeof(cmd_set_pass), false, true, recvbuf, sizeof(recvbuf), start_time, &recvlen);
2837 if (res != PM3_SUCCESS && recvlen != 3) {
2838 Dbprintf("LockPass: Failed to set password (%d)", recvlen);
2839 LED_B_ON();
2840 } else {
2841 crc = Iso15693Crc(cmd_inventory, 3);
2842 cmd_inventory[3] = crc & 0xff;
2843 cmd_inventory[4] = crc >> 8;
2845 Dbprintf("LockPass: Searching for tag...");
2846 res = SendDataTag(cmd_inventory, sizeof(cmd_inventory), false, true, recvbuf, sizeof(recvbuf), start_time, &recvlen);
2847 if (res != PM3_SUCCESS && recvlen != 12) {
2848 Dbprintf("LockPass: Failed to read inventory (%d)", recvlen);
2849 LED_B_ON();
2850 LED_C_ON();
2851 } else {
2853 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]);
2855 memcpy(&cmd_lock_pass[3], &recvbuf[2], 8);
2857 cmd_lock_pass[8+3] = pass_id;
2859 crc = Iso15693Crc(cmd_lock_pass, 8+4);
2860 cmd_lock_pass[8+4] = crc & 0xff;
2861 cmd_lock_pass[8+5] = crc >> 8;
2863 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);
2865 res = SendDataTag(cmd_lock_pass, sizeof(cmd_lock_pass), false, true, recvbuf, sizeof(recvbuf), start_time, &recvlen);
2866 if (res != PM3_SUCCESS && recvlen != 3) {
2867 Dbprintf("LockPass: Failed to lock password (%d)", recvlen);
2868 } else {
2869 Dbprintf("LockPass: Successful (%d)", recvlen);
2871 LED_A_ON();
2876 Dbprintf("LockPass: Finishing");
2877 cmd_send(CMD_ACK, recvlen, 0, 0, recvbuf, recvlen);
2881 //-----------------------------------------------------------------------------
2882 // Work with "magic Chinese" card.
2884 //-----------------------------------------------------------------------------
2886 // Set the UID on Magic ISO15693 tag (based on Iceman's LUA-script).
2887 void SetTag15693Uid(const uint8_t *uid) {
2889 LED_A_ON();
2890 uint8_t cmd[4][9] = {
2891 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3e, 0x00, 0x00, 0x00, 0x00, 0xE9, 0x8F},
2892 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3f, 0x69, 0x96, 0x00, 0x00, 0x8A, 0xBB},
2894 // Command 3 : 02 21 38 u8u7u6u5 (where uX = uid byte X)
2895 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x38, uid[7], uid[6], uid[5], uid[4]},
2897 // Command 4 : 02 21 39 u4u3u2u1 (where uX = uid byte X)
2898 {ISO15_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x39, uid[3], uid[2], uid[1], uid[0]}
2902 AddCrc15(cmd[2], 7);
2903 AddCrc15(cmd[3], 7);
2905 uint8_t buf[ISO15693_MAX_RESPONSE_LENGTH] = {0x00};
2907 uint32_t start_time = 0;
2908 uint32_t eof_time = 0;
2909 uint16_t recvlen = 0;
2911 int res = PM3_SUCCESS;
2913 for (int i = 0; i < 4; i++) {
2914 res = SendDataTag(
2915 cmd[i],
2916 sizeof(cmd[i]),
2917 (i == 0) ? true : false,
2918 true,
2919 buf,
2920 sizeof(buf),
2921 start_time,
2922 ISO15693_READER_TIMEOUT_WRITE,
2923 &eof_time,
2924 &recvlen
2927 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2930 reply_ng(CMD_HF_ISO15693_CSETUID, res, NULL, 0);
2931 switch_off();
2934 // Set the UID on Magic ISO15693 tag ( Gen2 ?)
2935 // E0 00 09 - seem to be command
2936 // 0x41, 0x40 - seem to be block referens
2937 void SetTag15693Uid_v2(const uint8_t *uid) {
2939 LED_A_ON();
2940 uint8_t cmd[4][10] = {
2941 { ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x47, 0x3f, 0x03, 0x8b, 0x00, 0x00, 0x00 },
2942 { ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
2943 // hf 15 raw -wac -d 02 e0 09 41 + uid first four bytes
2944 {ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x40, uid[7], uid[6], uid[5], uid[4], 0x00, 0x00},
2945 // hf 15 raw -wac -d 02 e0 09 40 + uid last four bytes
2946 {ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x41, uid[3], uid[2], uid[1], uid[0], 0x00, 0x00}
2949 uint8_t buf[ISO15693_MAX_RESPONSE_LENGTH] = {0x00};
2951 uint32_t start_time = 0;
2952 uint32_t eof_time = 0;
2953 uint16_t recvlen = 0;
2955 int res = PM3_SUCCESS;
2957 for (int i = 0; i < 4; i++) {
2959 AddCrc15(cmd[i], 8);
2960 res = SendDataTag(
2961 cmd[i],
2962 sizeof(cmd[i]),
2963 (i == 0) ? true : false,
2964 true,
2965 buf,
2966 sizeof(buf),
2967 start_time,
2968 ISO15693_READER_TIMEOUT_WRITE,
2969 &eof_time,
2970 &recvlen
2973 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
2976 reply_ng(CMD_HF_ISO15693_CSETUID_V2, res, NULL, 0);
2977 switch_off();
2981 static void init_password_15693_Slix(uint8_t *buffer, const uint8_t *pwd, const uint8_t *rnd) {
2982 memcpy(buffer, pwd, 4);
2983 if (rnd) {
2984 buffer[0] ^= rnd[0];
2985 buffer[1] ^= rnd[1];
2986 buffer[2] ^= rnd[0];
2987 buffer[3] ^= rnd[1];
2991 static bool get_rnd_15693_Slix(uint32_t start_time, uint32_t *eof_time, uint8_t *rnd) {
2992 // 0x04, == NXP from manufacture id list.
2993 uint8_t c[] = {ISO15_REQ_DATARATE_HIGH, ISO15693_GET_RANDOM_NUMBER, 0x04, 0x00, 0x00 };
2994 AddCrc15(c, 3);
2996 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
2997 uint16_t recvlen = 0;
2998 int res = SendDataTag(c, sizeof(c), true, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
2999 if (res != PM3_SUCCESS && recvlen != 5) {
3000 return false;
3003 if (rnd) {
3004 memcpy(rnd, &recvbuf[1], 2);
3006 return true;
3009 static uint32_t disable_privacy_15693_Slix(uint32_t start_time, uint32_t *eof_time, uint8_t pass_id, const uint8_t *password) {
3011 uint8_t rnd[2];
3012 if (get_rnd_15693_Slix(start_time, eof_time, rnd) == false) {
3013 return PM3_ETIMEOUT;
3016 // 0x04, == NXP from manufacture id list.
3017 uint8_t c[] = { ISO15_REQ_DATARATE_HIGH, ISO15693_SET_PASSWORD, 0x04, pass_id, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3018 init_password_15693_Slix(&c[4], password, rnd);
3019 AddCrc15(c, 8);
3021 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3022 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3023 uint16_t recvlen = 0;
3024 int res = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3025 if (res != PM3_SUCCESS && recvlen != 3) {
3026 return PM3_EWRONGANSWER;
3028 return PM3_SUCCESS;
3031 static uint32_t set_pass_15693_Slix(uint32_t start_time, uint32_t *eof_time, uint8_t pass_id, const uint8_t *password, const uint8_t *uid) {
3034 uint8_t rnd[2];
3035 if (get_rnd_15693_Slix(start_time, eof_time, rnd) == false) {
3036 return PM3_ETIMEOUT;
3039 // 0x04, == NXP from manufacture id list.
3040 uint8_t c[] = { (ISO15_REQ_DATARATE_HIGH | ISO15_REQ_ADDRESS), ISO15693_SET_PASSWORD, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, pass_id, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3042 init_password_15693_Slix(&c[12], password, rnd);
3044 memcpy(&c[3], uid, 8);
3045 AddCrc15(c, 16);
3047 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3048 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3049 uint16_t recvlen = 0;
3051 int res = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3052 if (res != PM3_SUCCESS && recvlen != 3) {
3053 return PM3_EWRONGANSWER;
3055 return PM3_SUCCESS;
3058 static uint32_t set_privacy_15693_Slix(uint32_t start_time, uint32_t *eof_time, const uint8_t *password) {
3059 uint8_t rnd[2];
3060 if (get_rnd_15693_Slix(start_time, eof_time, rnd) == false) {
3061 return PM3_ETIMEOUT;
3064 // 0x04, == NXP from manufacture id list.
3065 uint8_t c[] = { ISO15_REQ_DATARATE_HIGH, 0xBA, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
3066 init_password_15693_Slix(&c[3], password, rnd);
3067 AddCrc15(c, 7);
3069 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3070 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3071 uint16_t recvlen = 0;
3072 int res = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3073 if (res != PM3_SUCCESS && recvlen != 3) {
3074 return PM3_EWRONGANSWER;
3076 return PM3_SUCCESS;
3079 static uint32_t disable_eas_15693_Slix(uint32_t start_time, uint32_t *eof_time, const uint8_t *password, bool usepwd) {
3081 uint8_t uid[8];
3082 get_uid_slix(start_time, eof_time, uid);
3084 uint8_t rnd[2];
3085 if (get_rnd_15693_Slix(start_time, eof_time, rnd) == false) {
3086 return PM3_ETIMEOUT;
3089 if (usepwd) {
3091 int res_setpass = set_pass_15693_Slix(start_time, eof_time, 0x10, password, uid);
3093 if (res_setpass != PM3_SUCCESS) {
3094 return PM3_EWRONGANSWER;
3098 // 0x04, == NXP from manufacture id list.
3099 uint8_t c[] = { ISO15_REQ_DATARATE_HIGH, 0xA3, 0x04, 0x00, 0x00};
3100 AddCrc15(c, 3);
3102 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3103 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3104 uint16_t recvlen = 0;
3105 int res = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3106 if (res != PM3_SUCCESS && recvlen != 3) {
3107 return PM3_EWRONGANSWER;
3109 return PM3_SUCCESS;
3112 static uint32_t enable_eas_15693_Slix(uint32_t start_time, uint32_t *eof_time, const uint8_t *password, bool usepwd) {
3114 uint8_t uid[8];
3115 get_uid_slix(start_time, eof_time, uid);
3117 uint8_t rnd[2];
3118 if (get_rnd_15693_Slix(start_time, eof_time, rnd) == false) {
3119 return PM3_ETIMEOUT;
3122 if (usepwd) {
3123 int res_setpass = set_pass_15693_Slix(start_time, eof_time, 0x10, password, uid);
3125 if (res_setpass != PM3_SUCCESS) {
3126 return PM3_EWRONGANSWER;
3129 // 0x04, == NXP from manufacture id list.
3130 uint8_t c[] = { ISO15_REQ_DATARATE_HIGH, 0xA2, 0x04, 0x00, 0x00};
3131 //init_password_15693_Slix(&c[3], password, rnd);
3132 AddCrc15(c, 3);
3134 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3135 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3136 uint16_t recvlen = 0;
3137 int res = SendDataTag(c, sizeof(c), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3138 if (res != PM3_SUCCESS && recvlen != 3) {
3139 return PM3_EWRONGANSWER;
3141 return PM3_SUCCESS;
3144 static uint32_t write_password_15693_Slix(uint32_t start_time, uint32_t *eof_time, uint8_t pwd_id, const uint8_t *password, const uint8_t *uid) {
3146 uint8_t new_pwd_cmd[] = { (ISO15_REQ_DATARATE_HIGH | ISO15_REQ_ADDRESS), ISO15693_WRITE_PASSWORD, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, pwd_id, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
3148 memcpy(&new_pwd_cmd[3], uid, 8);
3149 memcpy(&new_pwd_cmd[12], password, 4);
3151 AddCrc15(new_pwd_cmd, 16);
3153 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3154 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3155 uint16_t recvlen = 0;
3157 int res_wrp = SendDataTag(new_pwd_cmd, sizeof(new_pwd_cmd), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3158 if (res_wrp != PM3_SUCCESS && recvlen != 3) {
3159 return PM3_EWRONGANSWER;
3162 return PM3_SUCCESS;
3165 static uint32_t pass_protect_EASAFI_15693_Slix(uint32_t start_time, uint32_t *eof_time, bool set_option_flag, const uint8_t *password) {
3167 uint8_t flags;
3169 if (set_option_flag)
3170 flags = ISO15_REQ_DATARATE_HIGH | ISO15_REQ_OPTION;
3171 else
3172 flags = ISO15_REQ_DATARATE_HIGH;
3175 uint8_t uid[8];
3176 get_uid_slix(start_time, eof_time, uid);
3178 uint8_t rnd[2];
3179 if (get_rnd_15693_Slix(start_time, eof_time, rnd) == false) {
3180 return PM3_ETIMEOUT;
3183 int res_setpass = set_pass_15693_Slix(start_time, eof_time, 0x10, password, uid);
3185 if (res_setpass != PM3_SUCCESS) {
3186 return PM3_EWRONGANSWER;
3189 uint8_t new_pass_protect_cmd[] = { flags, ISO15693_PASSWORD_PROTECT_EAS, 0x04, 0x00, 0x00};
3190 AddCrc15(new_pass_protect_cmd, 3);
3192 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3193 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3194 uint16_t recvlen = 0;
3196 int res = SendDataTag(new_pass_protect_cmd, sizeof(new_pass_protect_cmd), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3197 if (res != PM3_SUCCESS && recvlen != 3) {
3198 return PM3_EWRONGANSWER;
3201 return PM3_SUCCESS;
3204 static uint32_t write_afi_15693(uint32_t start_time, uint32_t *eof_time, const uint8_t *password, bool usepwd, uint8_t *uid, bool use_uid, uint8_t afi) {
3206 if (!use_uid) {
3207 int res_getuid = get_uid_slix(start_time, eof_time, uid);
3209 if (res_getuid != PM3_SUCCESS) {
3210 return res_getuid;
3214 if (usepwd) {
3215 int res_setpass = set_pass_15693_Slix(start_time, eof_time, 0x10, password, uid);
3217 if (res_setpass != PM3_SUCCESS) {
3218 return PM3_EWRONGANSWER;
3222 uint8_t cmd[] = { ISO15_REQ_DATARATE_HIGH | ISO15_REQ_ADDRESS, ISO15693_WRITE_AFI, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
3224 memcpy(&cmd[2], uid, 8);
3225 cmd[10] = afi;
3226 AddCrc15(cmd, 11);
3228 start_time = *eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
3229 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
3230 uint16_t recvlen = 0;
3232 int res = SendDataTag(cmd, sizeof(cmd), false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, eof_time, &recvlen);
3233 if (res != PM3_SUCCESS || recvlen != 3) {
3234 return PM3_EWRONGANSWER;
3237 return PM3_SUCCESS;
3240 void WritePasswordSlixIso15693(const uint8_t *old_password, const uint8_t *new_password, uint8_t pwd_id) {
3241 LED_D_ON();
3242 Iso15693InitReader();
3243 StartCountSspClk();
3244 uint32_t start_time = 0, eof_time = 0;
3245 int res = PM3_EFAILED;
3247 uint8_t uid[8];
3248 get_uid_slix(start_time, &eof_time, uid);
3250 res = set_pass_15693_Slix(start_time, &eof_time, pwd_id, old_password, uid);
3251 if (res != PM3_SUCCESS) {
3252 reply_ng(CMD_HF_ISO15693_SLIX_WRITE_PWD, res, NULL, 0);
3253 switch_off();
3254 return;
3257 res = write_password_15693_Slix(start_time, &eof_time, pwd_id, new_password, uid);
3259 reply_ng(CMD_HF_ISO15693_SLIX_WRITE_PWD, res, NULL, 0);
3261 switch_off();
3265 void DisablePrivacySlixIso15693(const uint8_t *password) {
3266 LED_D_ON();
3267 Iso15693InitReader();
3268 StartCountSspClk();
3269 uint32_t start_time = 0, eof_time = 0;
3271 // Password identifier Password byte
3272 // 0x04 Privacy
3273 // 0x08 Destroy SLIX-L
3274 // 0x10 EAS/AFI
3275 int res = disable_privacy_15693_Slix(start_time, &eof_time, 0x04, password);
3276 reply_ng(CMD_HF_ISO15693_SLIX_DISABLE_PRIVACY, res, NULL, 0);
3277 switch_off();
3280 void EnablePrivacySlixIso15693(const uint8_t *password) {
3281 LED_D_ON();
3282 Iso15693InitReader();
3283 StartCountSspClk();
3284 uint32_t start_time = 0, eof_time = 0;
3286 // Password identifier Password byte
3287 // 0x04 Privacy
3288 // 0x08 Destroy SLIX-L
3289 // 0x10 EAS/AFI
3290 int res = set_privacy_15693_Slix(start_time, &eof_time, password);
3291 reply_ng(CMD_HF_ISO15693_SLIX_ENABLE_PRIVACY, res, NULL, 0);
3292 switch_off();
3296 void DisableEAS_AFISlixIso15693(const uint8_t *password, bool usepwd) {
3297 LED_D_ON();
3298 Iso15693InitReader();
3299 StartCountSspClk();
3300 uint32_t start_time = 0, eof_time = 0;
3302 // Password identifier Password byte
3303 // 0x04 Privacy
3304 // 0x08 Destroy SLIX-L
3305 // 0x10 EAS/AFI
3306 int res = disable_eas_15693_Slix(start_time, &eof_time, password, usepwd);
3310 reply_ng(CMD_HF_ISO15693_SLIX_DISABLE_EAS, res, NULL, 0);
3311 switch_off();
3314 void EnableEAS_AFISlixIso15693(const uint8_t *password, bool usepwd) {
3315 LED_D_ON();
3316 Iso15693InitReader();
3317 StartCountSspClk();
3318 uint32_t start_time = 0, eof_time = 0;
3320 // Password identifier Password byte
3321 // 0x04 Privacy
3322 // 0x08 Destroy SLIX-L
3323 // 0x10 EAS/AFI
3324 int res = enable_eas_15693_Slix(start_time, &eof_time, password, usepwd);
3325 reply_ng(CMD_HF_ISO15693_SLIX_ENABLE_EAS, res, NULL, 0);
3326 switch_off();
3329 void PassProtextEASSlixIso15693(const uint8_t *password) {
3330 LED_D_ON();
3331 Iso15693InitReader();
3332 StartCountSspClk();
3333 uint32_t start_time = 0, eof_time = 0;
3334 int res = pass_protect_EASAFI_15693_Slix(start_time, &eof_time, false, password);
3335 reply_ng(CMD_HF_ISO15693_SLIX_PASS_PROTECT_EAS, res, NULL, 0);
3336 switch_off();
3338 void PassProtectAFISlixIso15693(const uint8_t *password) {
3339 LED_D_ON();
3340 Iso15693InitReader();
3341 StartCountSspClk();
3342 uint32_t start_time = 0, eof_time = 0;
3343 int res = pass_protect_EASAFI_15693_Slix(start_time, &eof_time, true, password);
3344 reply_ng(CMD_HF_ISO15693_SLIX_PASS_PROTECT_AFI, res, NULL, 0);
3345 switch_off();
3348 void WriteAFIIso15693(const uint8_t *password, bool use_pwd, uint8_t *uid, bool use_uid, uint8_t afi) {
3349 LED_D_ON();
3350 Iso15693InitReader();
3351 StartCountSspClk();
3352 uint32_t start_time = 0, eof_time = 0;
3353 int res = write_afi_15693(start_time, &eof_time, password, use_pwd, uid, use_uid, afi);
3354 reply_ng(CMD_HF_ISO15693_WRITE_AFI, res, NULL, 0);
3355 switch_off();