]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443b.c
REM: removed a tab character that Travis CI dislikes
[proxmark3-svn] / armsrc / iso14443b.c
CommitLineData
489ef36c 1//-----------------------------------------------------------------------------
2// Jonathan Westhues, split Nov 2006
3//
4// This code is licensed to you under the terms of the GNU GPL, version 2 or,
5// at your option, any later version. See the LICENSE.txt file for the text of
6// the license.
7//-----------------------------------------------------------------------------
abb21530 8// Routines to support ISO 14443B. This includes both the reader software and
9// the `fake tag' modes.
489ef36c 10//-----------------------------------------------------------------------------
6fc68747 11#include "iso14443b.h"
489ef36c 12
b8622518 13#ifndef FWT_TIMEOUT_14B
29f8c2cc 14// defaults to 2000ms
15# define FWT_TIMEOUT_14B 35312
b8622518 16#endif
17#ifndef ISO14443B_DMA_BUFFER_SIZE
18# define ISO14443B_DMA_BUFFER_SIZE 256
19#endif
20#ifndef RECEIVE_MASK
21# define RECEIVE_MASK (ISO14443B_DMA_BUFFER_SIZE-1)
22#endif
489ef36c 23
11c2df83 24// Guard Time (per 14443-2)
b8622518 25#ifndef TR0
26# define TR0 0
27#endif
28
11c2df83 29// Synchronization time (per 14443-2)
b8622518 30#ifndef TR1
31# define TR1 0
32#endif
11c2df83 33// Frame Delay Time PICC to PCD (per 14443-3 Amendment 1)
b8622518 34#ifndef TR2
35# define TR2 0
36#endif
d51717ff 37
38// 4sample
c3e8413c 39#define SEND4STUFFBIT(x) ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);
40//#define SEND4STUFFBIT(x) ToSendStuffBit(x);
29f8c2cc 41 // iceman, this threshold value, what makes 8 a good amplituted for this IQ values?
42#ifndef SUBCARRIER_DETECT_THRESHOLD
86db8973 43# define SUBCARRIER_DETECT_THRESHOLD 8
29f8c2cc 44#endif
d51717ff 45
29f8c2cc 46static void iso14b_set_timeout(uint32_t timeout);
47static void iso14b_set_maxframesize(uint16_t size);
11c2df83 48static void switch_off(void);
49
6fc68747 50// the block number for the ISO14443-4 PCB (used with APDUs)
a62bf3af 51static uint8_t pcb_blocknum = 0;
b8622518 52static uint32_t iso14b_timeout = FWT_TIMEOUT_14B;
11c2df83 53
11c2df83 54
489ef36c 55//=============================================================================
56// An ISO 14443 Type B tag. We listen for commands from the reader, using
57// a UART kind of thing that's implemented in software. When we get a
58// frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
59// If it's good, then we can do something appropriate with it, and send
60// a response.
61//=============================================================================
62
cef590d9 63
64//-----------------------------------------------------------------------------
11c2df83 65// The software UART that receives commands from the reader, and its state variables.
cef590d9 66//-----------------------------------------------------------------------------
67static struct {
68 enum {
69 STATE_UNSYNCD,
70 STATE_GOT_FALLING_EDGE_OF_SOF,
71 STATE_AWAITING_START_BIT,
72 STATE_RECEIVING_DATA
73 } state;
11c2df83 74 uint16_t shiftReg;
75 int bitCnt;
76 int byteCnt;
77 int byteCntMax;
78 int posCnt;
79 uint8_t *output;
cef590d9 80} Uart;
81
11c2df83 82static void UartReset() {
cef590d9 83 Uart.state = STATE_UNSYNCD;
11c2df83 84 Uart.shiftReg = 0;
cef590d9 85 Uart.bitCnt = 0;
11c2df83 86 Uart.byteCnt = 0;
87 Uart.byteCntMax = MAX_FRAME_SIZE;
cef590d9 88 Uart.posCnt = 0;
cef590d9 89}
90
11c2df83 91static void UartInit(uint8_t *data) {
cef590d9 92 Uart.output = data;
93 UartReset();
11c2df83 94// memset(Uart.output, 0x00, MAX_FRAME_SIZE);
cef590d9 95}
96
11c2df83 97//-----------------------------------------------------------------------------
98// The software Demod that receives commands from the tag, and its state variables.
99//-----------------------------------------------------------------------------
cef590d9 100static struct {
101 enum {
102 DEMOD_UNSYNCD,
103 DEMOD_PHASE_REF_TRAINING,
104 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
105 DEMOD_GOT_FALLING_EDGE_OF_SOF,
106 DEMOD_AWAITING_START_BIT,
107 DEMOD_RECEIVING_DATA
108 } state;
11c2df83 109 uint16_t bitCount;
110 int posCount;
111 int thisBit;
cef590d9 112/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
113 int metric;
114 int metricN;
115*/
11c2df83 116 uint16_t shiftReg;
117 uint8_t *output;
118 uint16_t len;
119 int sumI;
120 int sumQ;
121 uint32_t startTime, endTime;
cef590d9 122} Demod;
123
11c2df83 124// Clear out the state of the "UART" that receives from the tag.
125static void DemodReset() {
cef590d9 126 Demod.state = DEMOD_UNSYNCD;
cef590d9 127 Demod.bitCount = 0;
11c2df83 128 Demod.posCount = 0;
cef590d9 129 Demod.thisBit = 0;
130 Demod.shiftReg = 0;
11c2df83 131 Demod.len = 0;
132 Demod.sumI = 0;
133 Demod.sumQ = 0;
134 Demod.startTime = 0;
135 Demod.endTime = 0;
cef590d9 136}
137
11c2df83 138static void DemodInit(uint8_t *data) {
cef590d9 139 Demod.output = data;
140 DemodReset();
11c2df83 141 // memset(Demod.output, 0x00, MAX_FRAME_SIZE);
cef590d9 142}
143
29f8c2cc 144
145/*
146* 9.4395 us = 1 ETU and clock is about 1.5 us
147* 13560000Hz
148* 1000ms/s
149* timeout in ETUs (time to transfer 1 bit, 9.4395 us)
150*
151* Formula to calculate FWT (in ETUs) by timeout (in ms):
152* fwt = 13560000 * 1000 / (8*16) * timeout;
153* Sample: 3sec == 3000ms
154* 13560000 * 1000 / (8*16) * 3000 ==
155* 13560000000 / 384000 = 35312 FWT
156* @param timeout is in frame wait time, fwt, measured in ETUs
157*/
158static void iso14b_set_timeout(uint32_t timeout) {
159 #define MAX_TIMEOUT 40542464 // 13560000Hz * 1000ms / (2^32-1) * (8*16)
160 if(timeout > MAX_TIMEOUT)
161 timeout = MAX_TIMEOUT;
162
163 iso14b_timeout = timeout;
164 if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443B Timeout set to %ld fwt", iso14b_timeout);
165}
166static void iso14b_set_maxframesize(uint16_t size) {
167 if (size > 256)
168 size = MAX_FRAME_SIZE;
169
170 Uart.byteCntMax = size;
171 if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443B Max frame size set to %d bytes", Uart.byteCntMax);
172}
173static void switch_off(void){
174 if (MF_DBGLEVEL > 3) Dbprintf("switch_off");
175 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
176 SpinDelay(100);
177 FpgaDisableSscDma();
178 set_tracing(FALSE);
179 LEDsoff();
180}
181
11c2df83 182void AppendCrc14443b(uint8_t* data, int len) {
dccddaef 183 ComputeCrc14443(CRC_14443_B, data, len, data+len, data+len+1);
6fc68747 184}
185
489ef36c 186//-----------------------------------------------------------------------------
187// Code up a string of octets at layer 2 (including CRC, we don't generate
188// that here) so that they can be transmitted to the reader. Doesn't transmit
189// them yet, just leaves them ready to send in ToSend[].
190//-----------------------------------------------------------------------------
11c2df83 191static void CodeIso14443bAsTag(const uint8_t *cmd, int len) {
192 /* ISO 14443 B
193 *
194 * Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
195 * Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
196 *
197 * fc - carrier frequency 13.56mHz
198 * TR0 - Guard Time per 14443-2
199 * TR1 - Synchronization Time per 14443-2
200 * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
201 *
202 * Elementary Time Unit (ETU) is
203 * - 128 Carrier Cycles (9.4395 µS) = 8 Subcarrier Units
204 * - 1 ETU = 1 bit
205 * - 10 ETU = 1 startbit, 8 databits, 1 stopbit (10bits length)
206 * - startbit is a 0
207 * - stopbit is a 1
208 *
209 * Start of frame (SOF) is
210 * - [10-11] ETU of ZEROS, unmodulated time
211 * - [2-3] ETU of ONES,
212 *
213 * End of frame (EOF) is
214 * - [10-11] ETU of ZEROS, unmodulated time
215 *
216 * -TO VERIFY THIS BELOW-
217 * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
218 * works like this:
219 * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (9.44µS)
220 * - A 0-bit input to the FPGA becomes an unmodulated time of 9.44µS
221 *
222 *
223 *
224 * Card sends data ub 847.e kHz subcarrier
225 * 848k = 9.44µS = 128 fc
226 * 424k = 18.88µS = 256 fc
227 * 212k = 37.76µS = 512 fc
228 * 106k = 75.52µS = 1024 fc
229 *
230 * Reader data transmission:
231 * - no modulation ONES
232 * - SOF
233 * - Command, data and CRC_B
234 * - EOF
235 * - no modulation ONES
236 *
237 * Card data transmission
238 * - TR1
239 * - SOF
86db8973 240 * - data (each bytes is: 1startbit, 8bits, 1stopbit)
11c2df83 241 * - CRC_B
242 * - EOF
243 *
244 * FPGA implementation :
245 * At this point only Type A is implemented. This means that we are using a
246 * bit rate of 106 kbit/s, or fc/128. Oversample by 4, which ought to make
247 * things practical for the ARM (fc/32, 423.8 kbits/s, ~50 kbytes/s)
248 *
249 */
250
11c2df83 251 int i,j;
252 uint8_t b;
253
489ef36c 254 ToSendReset();
255
256 // Transmit a burst of ones, as the initial thing that lets the
11c2df83 257 // reader get phase sync.
258 // This loop is TR1, per specification
259 // TR1 minimum must be > 80/fs
260 // TR1 maximum 200/fs
261 // 80/fs < TR1 < 200/fs
262 // 10 ETU < TR1 < 24 ETU
489ef36c 263
264 // Send SOF.
11c2df83 265 // 10-11 ETU * 4times samples ZEROS
d51717ff 266 for(i = 0; i < 10; i++) { SEND4STUFFBIT(0); }
c3e8413c 267 //for(i = 0; i < 10; i++) { ToSendStuffBit(0); }
11c2df83 268
269 // 2-3 ETU * 4times samples ONES
d51717ff 270 for(i = 0; i < 3; i++) { SEND4STUFFBIT(1); }
c3e8413c 271 //for(i = 0; i < 3; i++) { ToSendStuffBit(1); }
11c2df83 272
273 // data
274 for(i = 0; i < len; ++i) {
275
489ef36c 276 // Start bit
d51717ff 277 SEND4STUFFBIT(0);
c3e8413c 278 //ToSendStuffBit(0);
489ef36c 279
280 // Data bits
11c2df83 281 b = cmd[i];
282 for(j = 0; j < 8; ++j) {
86db8973 283 // if(b & 1) {
284 // SEND4STUFFBIT(1);
285 // //ToSendStuffBit(1);
286 // } else {
287 // SEND4STUFFBIT(0);
288 // //ToSendStuffBit(0);
289 // }
290 SEND4STUFFBIT( b & 1 );
489ef36c 291 b >>= 1;
292 }
293
294 // Stop bit
d51717ff 295 SEND4STUFFBIT(1);
c3e8413c 296 //ToSendStuffBit(1);
11c2df83 297
298 // Extra Guard bit
299 // For PICC it ranges 0-18us (1etu = 9us)
d51717ff 300 SEND4STUFFBIT(1);
c3e8413c 301 //ToSendStuffBit(1);
489ef36c 302 }
303
abb21530 304 // Send EOF.
11c2df83 305 // 10-11 ETU * 4 sample rate = ZEROS
d51717ff 306 for(i = 0; i < 10; i++) { SEND4STUFFBIT(0); }
c3e8413c 307 //for(i = 0; i < 10; i++) { ToSendStuffBit(0); }
11c2df83 308
309 // why this?
d51717ff 310 for(i = 0; i < 40; i++) { SEND4STUFFBIT(1); }
c3e8413c 311 //for(i = 0; i < 40; i++) { ToSendStuffBit(1); }
11c2df83 312
489ef36c 313 // Convert from last byte pos to length
6fc68747 314 ++ToSendMax;
489ef36c 315}
316
cef590d9 317
489ef36c 318/* Receive & handle a bit coming from the reader.
abb21530 319 *
320 * This function is called 4 times per bit (every 2 subcarrier cycles).
321 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
489ef36c 322 *
323 * LED handling:
324 * LED A -> ON once we have received the SOF and are expecting the rest.
325 * LED A -> OFF once we have received EOF or are in error state or unsynced
326 *
327 * Returns: true if we received a EOF
328 * false if we are still waiting for some more
329 */
11c2df83 330static RAMFUNC int Handle14443bReaderUartBit(uint8_t bit) {
29f8c2cc 331 switch (Uart.state) {
489ef36c 332 case STATE_UNSYNCD:
29f8c2cc 333 if (!bit) {
dccddaef 334 // we went low, so this could be the beginning of an SOF
489ef36c 335 Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
336 Uart.posCnt = 0;
337 Uart.bitCnt = 0;
338 }
339 break;
340
341 case STATE_GOT_FALLING_EDGE_OF_SOF:
342 Uart.posCnt++;
29f8c2cc 343 if (Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
344 if (bit) {
345 if (Uart.bitCnt > 9) {
489ef36c 346 // we've seen enough consecutive
347 // zeros that it's a valid SOF
348 Uart.posCnt = 0;
349 Uart.byteCnt = 0;
350 Uart.state = STATE_AWAITING_START_BIT;
351 LED_A_ON(); // Indicate we got a valid SOF
352 } else {
29f8c2cc 353 // didn't stay down long enough before going high, error
36f84d47 354 Uart.state = STATE_UNSYNCD;
489ef36c 355 }
356 } else {
357 // do nothing, keep waiting
358 }
359 Uart.bitCnt++;
360 }
29f8c2cc 361 if (Uart.posCnt >= 4) Uart.posCnt = 0;
362 if (Uart.bitCnt > 12) {
363 // Give up if we see too many zeros without a one, too.
36f84d47 364 LED_A_OFF();
365 Uart.state = STATE_UNSYNCD;
489ef36c 366 }
367 break;
368
369 case STATE_AWAITING_START_BIT:
370 Uart.posCnt++;
29f8c2cc 371 if (bit) {
372 if (Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
373 // stayed high for too long between characters, error
36f84d47 374 Uart.state = STATE_UNSYNCD;
489ef36c 375 }
376 } else {
377 // falling edge, this starts the data byte
378 Uart.posCnt = 0;
379 Uart.bitCnt = 0;
380 Uart.shiftReg = 0;
381 Uart.state = STATE_RECEIVING_DATA;
489ef36c 382 }
383 break;
384
385 case STATE_RECEIVING_DATA:
386 Uart.posCnt++;
29f8c2cc 387 if (Uart.posCnt == 2) {
489ef36c 388 // time to sample a bit
389 Uart.shiftReg >>= 1;
29f8c2cc 390 if (bit) {
489ef36c 391 Uart.shiftReg |= 0x200;
392 }
393 Uart.bitCnt++;
394 }
29f8c2cc 395 if (Uart.posCnt >= 4) {
489ef36c 396 Uart.posCnt = 0;
397 }
29f8c2cc 398 if (Uart.bitCnt == 10) {
399 if ((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
489ef36c 400 {
401 // this is a data byte, with correct
402 // start and stop bits
403 Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
404 Uart.byteCnt++;
405
29f8c2cc 406 if (Uart.byteCnt >= Uart.byteCntMax) {
489ef36c 407 // Buffer overflowed, give up
36f84d47 408 LED_A_OFF();
409 Uart.state = STATE_UNSYNCD;
489ef36c 410 } else {
411 // so get the next byte now
412 Uart.posCnt = 0;
413 Uart.state = STATE_AWAITING_START_BIT;
414 }
46734099 415 } else if (Uart.shiftReg == 0x000) {
489ef36c 416 // this is an EOF byte
417 LED_A_OFF(); // Finished receiving
36f84d47 418 Uart.state = STATE_UNSYNCD;
29f8c2cc 419 if (Uart.byteCnt != 0)
420 return TRUE;
421
489ef36c 422 } else {
423 // this is an error
36f84d47 424 LED_A_OFF();
46734099 425 Uart.state = STATE_UNSYNCD;
36f84d47 426 }
489ef36c 427 }
428 break;
429
430 default:
36f84d47 431 LED_A_OFF();
489ef36c 432 Uart.state = STATE_UNSYNCD;
433 break;
434 }
489ef36c 435 return FALSE;
436}
437
438//-----------------------------------------------------------------------------
439// Receive a command (from the reader to us, where we are the simulated tag),
440// and store it in the given buffer, up to the given maximum length. Keeps
441// spinning, waiting for a well-framed command, until either we get one
442// (returns TRUE) or someone presses the pushbutton on the board (FALSE).
443//
444// Assume that we're called with the SSC (to the FPGA) and ADC path set
445// correctly.
446//-----------------------------------------------------------------------------
11c2df83 447static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) {
abb21530 448 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
489ef36c 449 // only, since we are receiving, not transmitting).
450 // Signal field is off with the appropriate LED
451 LED_D_OFF();
452 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
ffeb77fd 453
11c2df83 454 StartCountSspClk();
455
c7b4bcc4 456 volatile uint8_t b = 0;
ffeb77fd 457
458 // clear receiving shift register and holding register
459 // What does this loop do? Is it TR1?
460 for(uint8_t c = 0; c < 10;) {
461 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
462 AT91C_BASE_SSC->SSC_THR = 0xFF;
463 ++c;
464 }
465 }
466
489ef36c 467 // Now run a `software UART' on the stream of incoming samples.
36f84d47 468 UartInit(received);
ffeb77fd 469
ffeb77fd 470 uint8_t mask;
dccddaef 471 while( !BUTTON_PRESS() ) {
489ef36c 472 WDT_HIT();
473
dccddaef 474 if ( AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY ) {
475 b = (uint8_t) AT91C_BASE_SSC->SSC_RHR;
476 for ( mask = 0x80; mask != 0; mask >>= 1) {
477 if ( Handle14443bReaderUartBit(b & mask)) {
489ef36c 478 *len = Uart.byteCnt;
479 return TRUE;
480 }
481 }
482 }
11c2df83 483 }
36f84d47 484 return FALSE;
489ef36c 485}
486
ffeb77fd 487void ClearFpgaShiftingRegisters(void){
488
489 volatile uint8_t b;
490
491 // clear receiving shift register and holding register
c7b4bcc4 492 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) {};
c3e8413c 493
ffeb77fd 494 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
495
c7b4bcc4 496 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) {};
c3e8413c 497
ffeb77fd 498 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
499
500
501 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
502 for (uint8_t j = 0; j < 5; j++) { // allow timeout - better late than never
503 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
504 if (AT91C_BASE_SSC->SSC_RHR) break;
505 }
506
507 // Clear TXRDY:
c3e8413c 508 //AT91C_BASE_SSC->SSC_THR = 0xFF;
ffeb77fd 509}
510
511void WaitForFpgaDelayQueueIsEmpty( uint16_t delay ){
512 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
513 uint8_t fpga_queued_bits = delay >> 3; // twich /8 ?? >>3,
514 for (uint8_t i = 0; i <= fpga_queued_bits/8 + 1; ) {
515 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
516 AT91C_BASE_SSC->SSC_THR = 0xFF;
517 i++;
518 }
519 }
520}
dccddaef 521
522static void TransmitFor14443b_AsTag( uint8_t *response, uint16_t len) {
523
b8622518 524 volatile uint32_t b;
525
526 // Signal field is off with the appropriate LED
527 LED_D_OFF();
528 //uint16_t fpgasendQueueDelay = 0;
529
530 // Modulate BPSK
531 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
532 SpinDelay(40);
533
534 ClearFpgaShiftingRegisters();
535
536 FpgaSetupSsc();
dccddaef 537
b8622518 538 // Transmit the response.
539 for(uint16_t i = 0; i < len;) {
540 if(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
541 AT91C_BASE_SSC->SSC_THR = response[++i];
dccddaef 542 }
b8622518 543 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
544 b = AT91C_BASE_SSC->SSC_RHR;
545 (void)b;
546 }
547 }
548
549 //WaitForFpgaDelayQueueIsEmpty(fpgasendQueueDelay);
550 AT91C_BASE_SSC->SSC_THR = 0xFF;
dccddaef 551}
489ef36c 552//-----------------------------------------------------------------------------
553// Main loop of simulated tag: receive commands from reader, decide what
554// response to send, and send it.
555//-----------------------------------------------------------------------------
dccddaef 556void SimulateIso14443bTag(uint32_t pupi) {
dccddaef 557
0923c43c 558 ///////////// setup device.
99cf19d9 559 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
560
11c2df83 561 // allocate command receive buffer
562 BigBuf_free();
563 BigBuf_Clear_ext(false);
564 clear_trace(); //sim
36f84d47 565 set_tracing(TRUE);
11c2df83 566
dccddaef 567 // connect Demodulated Signal to ADC:
568 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
569
570 // Set up the synchronous serial port
571 FpgaSetupSsc();
0923c43c 572 /////////////
dccddaef 573
0923c43c 574 uint16_t len, cmdsReceived = 0;
575 int cardSTATE = SIM_NOFIELD;
576 int vHf = 0; // in mV
577 // uint32_t time_0 = 0;
578 // uint32_t t2r_time = 0;
579 // uint32_t r2t_time = 0;
580 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
dccddaef 581
0923c43c 582 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
583// static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
584 // ... and REQB, AFI=0, Normal Request, N=1:
585// static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
586 // ... and ATTRIB
587// static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
588
589 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
590 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
591 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
592 uint8_t respATQB[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19,
593 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 };
594
595 // response to HLTB and ATTRIB
596 static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
597
598 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
599 if ( pupi > 0 ) {
c23d2618 600 uint8_t len = sizeof(respATQB);
0923c43c 601 num_to_bytes(pupi, 4, respATQB+1);
c3e8413c 602 ComputeCrc14443(CRC_14443_B, respATQB, 12, &respATQB[len-2], &respATQB[len-1]);
0923c43c 603 }
604
605 // prepare "ATQB" tag answer (encoded):
606 CodeIso14443bAsTag(respATQB, sizeof(respATQB));
607 uint8_t *encodedATQB = BigBuf_malloc(ToSendMax);
608 uint16_t encodedATQBLen = ToSendMax;
609 memcpy(encodedATQB, ToSend, ToSendMax);
610
11c2df83 611
0923c43c 612 // prepare "OK" tag answer (encoded):
613 CodeIso14443bAsTag(respOK, sizeof(respOK));
614 uint8_t *encodedOK = BigBuf_malloc(ToSendMax);
615 uint16_t encodedOKLen = ToSendMax;
616 memcpy(encodedOK, ToSend, ToSendMax);
11c2df83 617
0923c43c 618 // Simulation loop
dccddaef 619 while (!BUTTON_PRESS() && !usb_poll_validate_length()) {
620 WDT_HIT();
489ef36c 621
dccddaef 622 // find reader field
0923c43c 623 if (cardSTATE == SIM_NOFIELD) {
dccddaef 624 vHf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10;
0923c43c 625 if ( vHf > MF_MINFIELDV ) {
626 cardSTATE = SIM_IDLE;
627 LED_A_ON();
628 }
dccddaef 629 }
0923c43c 630 if (cardSTATE == SIM_NOFIELD) continue;
489ef36c 631
0923c43c 632 // Get reader command
810f5379 633 if (!GetIso14443bCommandFromReader(receivedCmd, &len)) {
0923c43c 634 Dbprintf("button pressed, received %d commands", cmdsReceived);
810f5379 635 break;
489ef36c 636 }
637
0923c43c 638 // ISO14443-B protocol states:
639 // REQ or WUP request in ANY state
640 // WUP in HALTED state
641 if (len == 5 ) {
ffeb77fd 642 if ( (receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8)== 0x8 && cardSTATE == SIM_HALTED) ||
643 receivedCmd[0] == ISO14443B_REQB ){
644 LogTrace(receivedCmd, len, 0, 0, NULL, TRUE);
0923c43c 645 cardSTATE = SIM_SELECTING;
0923c43c 646 }
647 }
648
649 /*
650 * How should this flow go?
651 * REQB or WUPB
652 * send response ( waiting for Attrib)
653 * ATTRIB
654 * send response ( waiting for commands 7816)
655 * HALT
656 send halt response ( waiting for wupb )
657 */
d51717ff 658
b8622518 659 switch (cardSTATE) {
0923c43c 660 case SIM_NOFIELD:
661 case SIM_HALTED:
b8622518 662 case SIM_IDLE: {
dccddaef 663 LogTrace(receivedCmd, len, 0, 0, NULL, TRUE);
664 break;
665 }
0923c43c 666 case SIM_SELECTING: {
667 TransmitFor14443b_AsTag( encodedATQB, encodedATQBLen );
668 LogTrace(respATQB, sizeof(respATQB), 0, 0, NULL, FALSE);
ffeb77fd 669 cardSTATE = SIM_WORK;
dccddaef 670 break;
0923c43c 671 }
672 case SIM_HALTING: {
673 TransmitFor14443b_AsTag( encodedOK, encodedOKLen );
674 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, FALSE);
675 cardSTATE = SIM_HALTED;
dccddaef 676 break;
0923c43c 677 }
b8622518 678 case SIM_ACKNOWLEDGE: {
0923c43c 679 TransmitFor14443b_AsTag( encodedOK, encodedOKLen );
680 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, FALSE);
681 cardSTATE = SIM_IDLE;
682 break;
683 }
b8622518 684 case SIM_WORK: {
d51717ff 685 if ( len == 7 && receivedCmd[0] == ISO14443B_HALT ) {
686 cardSTATE = SIM_HALTED;
687 } else if ( len == 11 && receivedCmd[0] == ISO14443B_ATTRIB ) {
688 cardSTATE = SIM_ACKNOWLEDGE;
689 } else {
690 // Todo:
691 // - SLOT MARKER
692 // - ISO7816
693 // - emulate with a memory dump
694 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsReceived);
695
696 // CRC Check
697 uint8_t b1, b2;
698 if (len >= 3){ // if crc exists
699 ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2);
700 if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1])
701 DbpString("+++CRC fail");
702 else
703 DbpString("CRC passes");
704 }
705 cardSTATE = SIM_IDLE;
706 }
dccddaef 707 break;
d51717ff 708 }
709 default: break;
dccddaef 710 }
711
0923c43c 712 ++cmdsReceived;
b8622518 713 // iceman, could add a switch to turn this on/off (if off, no logging?)
0923c43c 714 if(cmdsReceived > 1000) {
dccddaef 715 DbpString("14B Simulate, 1000 commands later...");
489ef36c 716 break;
717 }
489ef36c 718 }
dccddaef 719 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, BigBuf_get_traceLen());
11c2df83 720 switch_off(); //simulate
489ef36c 721}
722
723//=============================================================================
724// An ISO 14443 Type B reader. We take layer two commands, code them
725// appropriately, and then send them to the tag. We then listen for the
726// tag's response, which we leave in the buffer to be demodulated on the
727// PC side.
728//=============================================================================
729
489ef36c 730/*
731 * Handles reception of a bit from the tag
732 *
abb21530 733 * This function is called 2 times per bit (every 4 subcarrier cycles).
734 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
735 *
489ef36c 736 * LED handling:
737 * LED C -> ON once we have received the SOF and are expecting the rest.
738 * LED C -> OFF once we have received EOF or are unsynced
739 *
740 * Returns: true if we received a EOF
741 * false if we are still waiting for some more
742 *
743 */
11c2df83 744static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) {
29f8c2cc 745 int v = 0, myI = ABS(ci), myQ = ABS(cq);
746
51d4f6f1 747// The soft decision on the bit uses an estimate of just the
748// quadrant of the reference angle, not the exact angle.
489ef36c 749#define MAKE_SOFT_DECISION() { \
5b59bf20 750 if(Demod.sumI > 0) { \
751 v = ci; \
752 } else { \
753 v = -ci; \
754 } \
489ef36c 755 if(Demod.sumQ > 0) { \
756 v += cq; \
757 } else { \
758 v -= cq; \
759 } \
760 }
761
cef590d9 762// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq)
abb21530 763// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
b8622518 764#define CHECK_FOR_SUBCARRIER_old() { \
cef590d9 765 if(ci < 0) { \
766 if(cq < 0) { /* ci < 0, cq < 0 */ \
767 if (cq < ci) { \
768 v = -cq - (ci >> 1); \
769 } else { \
770 v = -ci - (cq >> 1); \
771 } \
772 } else { /* ci < 0, cq >= 0 */ \
773 if (cq < -ci) { \
774 v = -ci + (cq >> 1); \
775 } else { \
776 v = cq - (ci >> 1); \
777 } \
778 } \
779 } else { \
780 if(cq < 0) { /* ci >= 0, cq < 0 */ \
781 if (-cq < ci) { \
782 v = ci - (cq >> 1); \
783 } else { \
784 v = -cq + (ci >> 1); \
785 } \
786 } else { /* ci >= 0, cq >= 0 */ \
787 if (cq < ci) { \
788 v = ci + (cq >> 1); \
789 } else { \
790 v = cq + (ci >> 1); \
791 } \
792 } \
793 } \
794 }
db25599d 795
6fc68747 796//note: couldn't we just use MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2) from common.h - marshmellow
b8622518 797#define CHECK_FOR_SUBCARRIER() { \
b8622518 798 v = MAX(myI, myQ) + (MIN(myI, myQ) >> 1); \
6fc68747 799 }
db25599d 800
489ef36c 801 switch(Demod.state) {
802 case DEMOD_UNSYNCD:
cef590d9 803
abb21530 804 CHECK_FOR_SUBCARRIER();
c2df2883 805
cef590d9 806 // subcarrier detected
86db8973 807 if (v > SUBCARRIER_DETECT_THRESHOLD) {
489ef36c 808 Demod.state = DEMOD_PHASE_REF_TRAINING;
abb21530 809 Demod.sumI = ci;
810 Demod.sumQ = cq;
811 Demod.posCount = 1;
489ef36c 812 }
813 break;
814
815 case DEMOD_PHASE_REF_TRAINING:
86db8973 816 if (Demod.posCount < 8) {
cef590d9 817
abb21530 818 CHECK_FOR_SUBCARRIER();
cef590d9 819
abb21530 820 if (v > SUBCARRIER_DETECT_THRESHOLD) {
821 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
822 // note: synchronization time > 80 1/fs
b10a759f 823 Demod.sumI += ci;
824 Demod.sumQ += cq;
cef590d9 825 ++Demod.posCount;
826 } else {
827 // subcarrier lost
b10a759f 828 Demod.state = DEMOD_UNSYNCD;
abb21530 829 }
489ef36c 830 } else {
b10a759f 831 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
489ef36c 832 }
489ef36c 833 break;
834
835 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
cef590d9 836
489ef36c 837 MAKE_SOFT_DECISION();
cef590d9 838
86db8973 839 if (v < 0) { // logic '0' detected
489ef36c 840 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
abb21530 841 Demod.posCount = 0; // start of SOF sequence
489ef36c 842 } else {
cef590d9 843 // maximum length of TR1 = 200 1/fs
c3e8413c 844 if(Demod.posCount > 26*2) Demod.state = DEMOD_UNSYNCD;
489ef36c 845 }
cef590d9 846 ++Demod.posCount;
489ef36c 847 break;
848
849 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
cef590d9 850 ++Demod.posCount;
851
489ef36c 852 MAKE_SOFT_DECISION();
cef590d9 853
86db8973 854 if (v > 0) {
cef590d9 855 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
86db8973 856 if (Demod.posCount < 8*2) {
489ef36c 857 Demod.state = DEMOD_UNSYNCD;
858 } else {
a62bf3af 859 LED_C_ON(); // Got SOF
86db8973 860 //Demod.startTime = GetCountSspClk();
489ef36c 861 Demod.state = DEMOD_AWAITING_START_BIT;
862 Demod.posCount = 0;
863 Demod.len = 0;
489ef36c 864 }
865 } else {
cef590d9 866 // low phase of SOF too long (> 12 etu)
c3e8413c 867 if (Demod.posCount > 14*2) {
489ef36c 868 Demod.state = DEMOD_UNSYNCD;
47286d89 869 LED_C_OFF();
489ef36c 870 }
871 }
489ef36c 872 break;
873
874 case DEMOD_AWAITING_START_BIT:
cef590d9 875 ++Demod.posCount;
876
489ef36c 877 MAKE_SOFT_DECISION();
cef590d9 878
879 if (v > 0) {
c3e8413c 880 if(Demod.posCount > 2*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
489ef36c 881 Demod.state = DEMOD_UNSYNCD;
47286d89 882 LED_C_OFF();
489ef36c 883 }
abb21530 884 } else { // start bit detected
489ef36c 885 Demod.bitCount = 0;
abb21530 886 Demod.posCount = 1; // this was the first half
489ef36c 887 Demod.thisBit = v;
888 Demod.shiftReg = 0;
889 Demod.state = DEMOD_RECEIVING_DATA;
890 }
891 break;
892
893 case DEMOD_RECEIVING_DATA:
cef590d9 894
489ef36c 895 MAKE_SOFT_DECISION();
cef590d9 896
897 if (Demod.posCount == 0) {
898 // first half of bit
489ef36c 899 Demod.thisBit = v;
900 Demod.posCount = 1;
cef590d9 901 } else {
902 // second half of bit
489ef36c 903 Demod.thisBit += v;
489ef36c 904 Demod.shiftReg >>= 1;
489ef36c 905
86db8973 906 // OR in a logic '1'
b8622518 907 if (Demod.thisBit > 0) Demod.shiftReg |= 0x200;
cef590d9 908
909 ++Demod.bitCount;
910
b8622518 911 // 1 start 8 data 1 stop = 10
912 if (Demod.bitCount == 10) {
cef590d9 913
489ef36c 914 uint16_t s = Demod.shiftReg;
cef590d9 915
916 // stop bit == '1', start bit == '0'
29f8c2cc 917 if ((s & 0x200) && (s & 0x001) == 0 ) {
918 // left shift to drop the startbit
919 Demod.output[Demod.len] = (s >> 1) & 0xFF;
cef590d9 920 ++Demod.len;
489ef36c 921 Demod.state = DEMOD_AWAITING_START_BIT;
489ef36c 922 } else {
29f8c2cc 923 // this one is a bit hard, either its a correc byte or its unsynced.
489ef36c 924 Demod.state = DEMOD_UNSYNCD;
86db8973 925 //Demod.endTime = GetCountSspClk();
47286d89 926 LED_C_OFF();
cef590d9 927
928 // This is EOF (start, stop and all data bits == '0'
29f8c2cc 929 if (s == 0) return TRUE;
489ef36c 930 }
931 }
932 Demod.posCount = 0;
933 }
934 break;
935
936 default:
937 Demod.state = DEMOD_UNSYNCD;
47286d89 938 LED_C_OFF();
489ef36c 939 break;
940 }
489ef36c 941 return FALSE;
942}
943
944
489ef36c 945/*
946 * Demodulate the samples we received from the tag, also log to tracebuffer
489ef36c 947 * quiet: set to 'TRUE' to disable debug output
948 */
dccddaef 949static void GetTagSamplesFor14443bDemod() {
b8622518 950 bool gotFrame = FALSE, finished = FALSE;
11c2df83 951 int lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
29f8c2cc 952 int ci = 0, cq = 0;
11c2df83 953 uint32_t time_0 = 0, time_stop = 0;
489ef36c 954
11c2df83 955 BigBuf_free();
956
489ef36c 957 // Set up the demodulator for tag -> reader responses.
db25599d 958 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
b10a759f 959
960 // The DMA buffer, used to stream samples from the FPGA
961 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE);
11c2df83 962 int8_t *upTo = dmaBuf;
cef590d9 963
db25599d 964 // Setup and start DMA.
11c2df83 965 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE) ){
966 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
967 return;
968 }
b8622518 969
11c2df83 970 // And put the FPGA in the appropriate mode
971 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
489ef36c 972
b8622518 973 // get current clock
974 time_0 = GetCountSspClk();
975
976 // rx counter - dma counter? (how much?) & (mod) mask > 2. (since 2bytes at the time is read)
977 while ( !finished ) {
489ef36c 978
b8622518 979 LED_A_INV();
980 WDT_HIT();
11c2df83 981
b8622518 982 // LSB is a fpga signal bit.
983 ci = upTo[0] >> 1;
984 cq = upTo[1] >> 1;
985 upTo += 2;
b8622518 986 lastRxCounter -= 2;
987
988 // restart DMA buffer to receive again.
989 if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) {
990 upTo = dmaBuf;
991 lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
992 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
993 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE;
489ef36c 994 }
995
b8622518 996 // https://github.com/Proxmark/proxmark3/issues/103
b8622518 997 gotFrame = Handle14443bTagSamplesDemod(ci, cq);
11c2df83 998 time_stop = GetCountSspClk() - time_0;
b8622518 999
1000 finished = (time_stop > iso14b_timeout || gotFrame);
489ef36c 1001 }
11c2df83 1002
1003 FpgaDisableSscDma();
d8b7a5f2 1004
1005 if ( upTo ) upTo = NULL;
1006
dccddaef 1007 if (MF_DBGLEVEL >= 3) {
d8b7a5f2 1008 Dbprintf("Demod.state = %d, Demod.len = %u, PDC_RCR = %u",
cef590d9 1009 Demod.state,
d8b7a5f2 1010 Demod.len,
1011 AT91C_BASE_PDC_SSC->PDC_RCR
b10a759f 1012 );
1013 }
b8622518 1014
d8b7a5f2 1015 // print the last batch of IQ values from FPGA
b8622518 1016 if (MF_DBGLEVEL == 4)
1017 Dbhexdump(ISO14443B_DMA_BUFFER_SIZE, (uint8_t *)dmaBuf, FALSE);
1018
11c2df83 1019 if ( Demod.len > 0 )
86db8973 1020 LogTrace(Demod.output, Demod.len, time_0, time_stop, NULL, FALSE);
489ef36c 1021}
1022
1023
489ef36c 1024//-----------------------------------------------------------------------------
1025// Transmit the command (to the tag) that was placed in ToSend[].
1026//-----------------------------------------------------------------------------
11c2df83 1027static void TransmitFor14443b_AsReader(void) {
489ef36c 1028
11c2df83 1029 // we could been in following mode:
1030 // FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ
1031 // if its second call or more
c3e8413c 1032
1033 // while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1034 // AT91C_BASE_SSC->SSC_THR = 0XFF;
1035 // }
1036
1037 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1038 SpinDelay(40);
11c2df83 1039
c3e8413c 1040 int c;
1041 volatile uint32_t b;
1042
11c2df83 1043 // What does this loop do? Is it TR1?
c3e8413c 1044 // 0xFF = 8 bits of 1. 1 bit == 1Etu,..
1045 // loop 10 * 8 = 80 ETU of delay, with a non modulated signal. why?
1046 // 80*9 = 720us.
1047 for(c = 0; c < 50;) {
489ef36c 1048 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
11c2df83 1049 AT91C_BASE_SSC->SSC_THR = 0xFF;
cef590d9 1050 ++c;
489ef36c 1051 }
c3e8413c 1052 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1053 b = AT91C_BASE_SSC->SSC_RHR;
1054 (void)b;
1055 }
489ef36c 1056 }
c3e8413c 1057
11c2df83 1058 // Send frame loop
1059 for(c = 0; c < ToSendMax;) {
489ef36c 1060 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
c3e8413c 1061 AT91C_BASE_SSC->SSC_THR = ToSend[c++];
489ef36c 1062 }
c3e8413c 1063 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1064 b = AT91C_BASE_SSC->SSC_RHR;
1065 (void)b;
1066 }
489ef36c 1067 }
c3e8413c 1068 //WaitForFpgaDelayQueueIsEmpty(delay);
1069 // We should wait here for the FPGA to send all bits.
11c2df83 1070 WDT_HIT();
489ef36c 1071}
1072
489ef36c 1073//-----------------------------------------------------------------------------
1074// Code a layer 2 command (string of octets, including CRC) into ToSend[],
abb21530 1075// so that it is ready to transmit to the tag using TransmitFor14443b().
489ef36c 1076//-----------------------------------------------------------------------------
86db8973 1077static void CodeIso14443bAsReader(const uint8_t *cmd, int len) {
11c2df83 1078 /*
1079 * Reader data transmission:
1080 * - no modulation ONES
1081 * - SOF
1082 * - Command, data and CRC_B
1083 * - EOF
1084 * - no modulation ONES
1085 *
1086 * 1 ETU == 1 BIT!
1087 * TR0 - 8 ETUS minimum.
c3e8413c 1088 *
1089 * QUESTION: how long is a 1 or 0 in pulses in the xcorr_848 mode?
1090 * 1 "stuffbit" = 1ETU (9us)
11c2df83 1091 */
1092 int i;
489ef36c 1093 uint8_t b;
11c2df83 1094
489ef36c 1095 ToSendReset();
1096
489ef36c 1097 // Send SOF
11c2df83 1098 // 10-11 ETUs of ZERO
1099 for(i = 0; i < 10; ++i) ToSendStuffBit(0);
1100
1101 // 2-3 ETUs of ONE
1102 ToSendStuffBit(1);
1103 ToSendStuffBit(1);
1104 ToSendStuffBit(1);
1105
1106 // Sending cmd, LSB
1107 // from here we add BITS
6fc68747 1108 for(i = 0; i < len; ++i) {
11c2df83 1109 // Start bit
489ef36c 1110 ToSendStuffBit(0);
1111 // Data bits
11c2df83 1112 b = cmd[i];
86db8973 1113 // if ( b & 1 ) ToSendStuffBit(1); else ToSendStuffBit(0);
1114 // if ( (b>>1) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1115 // if ( (b>>2) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1116 // if ( (b>>3) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1117 // if ( (b>>4) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1118 // if ( (b>>5) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1119 // if ( (b>>6) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1120 // if ( (b>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1121
1122 ToSendStuffBit( b & 1);
1123 ToSendStuffBit( (b>>1) & 1);
1124 ToSendStuffBit( (b>>2) & 1);
1125 ToSendStuffBit( (b>>3) & 1);
1126 ToSendStuffBit( (b>>4) & 1);
1127 ToSendStuffBit( (b>>5) & 1);
1128 ToSendStuffBit( (b>>6) & 1);
1129 ToSendStuffBit( (b>>7) & 1);
1130
11c2df83 1131 // Stop bit
489ef36c 1132 ToSendStuffBit(1);
11c2df83 1133 // EGT extra guard time
1134 // For PCD it ranges 0-57us (1etu = 9us)
489ef36c 1135 ToSendStuffBit(1);
11c2df83 1136 ToSendStuffBit(1);
1137 ToSendStuffBit(1);
1138 }
1139
1140 // Send EOF
1141 // 10-11 ETUs of ZERO
1142 for(i = 0; i < 10; ++i) ToSendStuffBit(0);
489ef36c 1143
11c2df83 1144 // Transition time. TR0 - guard time
1145 // 8ETUS minum?
1146 // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF.
c3e8413c 1147 // I'm guessing this is for the FPGA to be able to send all bits before we switch to listening mode
1148 for(i = 0; i < 32 ; ++i) ToSendStuffBit(1);
11c2df83 1149
1150 // TR1 - Synchronization time
489ef36c 1151 // Convert from last character reference to length
cef590d9 1152 ++ToSendMax;
489ef36c 1153}
1154
1155
86db8973 1156/*
1157* Convenience function to encode, transmit and trace iso 14443b comms
1158*/
11c2df83 1159static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) {
86db8973 1160
1161 uint32_t time_start = GetCountSspClk();
11c2df83 1162
489ef36c 1163 CodeIso14443bAsReader(cmd, len);
6fc68747 1164
11c2df83 1165 TransmitFor14443b_AsReader();
86db8973 1166
6fc68747 1167 if(trigger) LED_A_ON();
86db8973 1168
dccddaef 1169 LogTrace(cmd, len, time_start, GetCountSspClk()-time_start, NULL, TRUE);
489ef36c 1170}
1171
a62bf3af 1172/* Sends an APDU to the tag
1173 * TODO: check CRC and preamble
1174 */
6fc68747 1175uint8_t iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response)
a62bf3af 1176{
6fc68747 1177 uint8_t crc[2] = {0x00, 0x00};
a62bf3af 1178 uint8_t message_frame[message_length + 4];
1179 // PCB
1180 message_frame[0] = 0x0A | pcb_blocknum;
1181 pcb_blocknum ^= 1;
1182 // CID
1183 message_frame[1] = 0;
1184 // INF
1185 memcpy(message_frame + 2, message, message_length);
1186 // EDC (CRC)
1187 ComputeCrc14443(CRC_14443_B, message_frame, message_length + 2, &message_frame[message_length + 2], &message_frame[message_length + 3]);
1188 // send
11c2df83 1189 CodeAndTransmit14443bAsReader(message_frame, message_length + 4); //no
a62bf3af 1190 // get response
dccddaef 1191 GetTagSamplesFor14443bDemod(); //no
a62bf3af 1192 if(Demod.len < 3)
a62bf3af 1193 return 0;
cef590d9 1194
6fc68747 1195 // VALIDATE CRC
1196 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1197 if ( crc[0] != Demod.output[Demod.len-2] || crc[1] != Demod.output[Demod.len-1] )
1198 return 0;
1199
a62bf3af 1200 // copy response contents
1201 if(response != NULL)
a62bf3af 1202 memcpy(response, Demod.output, Demod.len);
cef590d9 1203
a62bf3af 1204 return Demod.len;
1205}
1206
6fc68747 1207/**
1208* SRx Initialise.
1209*/
1210uint8_t iso14443b_select_srx_card(iso14b_card_select_t *card )
1211{
1212 // INITIATE command: wake up the tag using the INITIATE
1213 static const uint8_t init_srx[] = { ISO14443B_INITIATE, 0x00, 0x97, 0x5b };
1214 // SELECT command (with space for CRC)
1215 uint8_t select_srx[] = { ISO14443B_SELECT, 0x00, 0x00, 0x00};
1216 // temp to calc crc.
1217 uint8_t crc[2] = {0x00, 0x00};
1218
1219 CodeAndTransmit14443bAsReader(init_srx, sizeof(init_srx));
dccddaef 1220 GetTagSamplesFor14443bDemod(); //no
6fc68747 1221
1222 if (Demod.len == 0) return 2;
1223
1224 // Randomly generated Chip ID
1225 if (card) card->chipid = Demod.output[0];
1226
1227 select_srx[1] = Demod.output[0];
1228
1229 ComputeCrc14443(CRC_14443_B, select_srx, 2, &select_srx[2], &select_srx[3]);
1230 CodeAndTransmit14443bAsReader(select_srx, sizeof(select_srx));
dccddaef 1231 GetTagSamplesFor14443bDemod(); //no
6fc68747 1232
1233 if (Demod.len != 3) return 2;
1234
1235 // Check the CRC of the answer:
1236 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2 , &crc[0], &crc[1]);
1237 if(crc[0] != Demod.output[1] || crc[1] != Demod.output[2]) return 3;
1238
1239 // Check response from the tag: should be the same UID as the command we just sent:
1240 if (select_srx[1] != Demod.output[0]) return 1;
1241
1242 // First get the tag's UID:
1243 select_srx[0] = ISO14443B_GET_UID;
1244
1245 ComputeCrc14443(CRC_14443_B, select_srx, 1 , &select_srx[1], &select_srx[2]);
1246 CodeAndTransmit14443bAsReader(select_srx, 3); // Only first three bytes for this one
dccddaef 1247 GetTagSamplesFor14443bDemod(); //no
6fc68747 1248
1249 if (Demod.len != 10) return 2;
1250
1251 // The check the CRC of the answer
1252 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1253 if(crc[0] != Demod.output[8] || crc[1] != Demod.output[9]) return 3;
1254
1255 if (card) {
1256 card->uidlen = 8;
1257 memcpy(card->uid, Demod.output, 8);
1258 }
1259
1260 return 0;
1261}
a62bf3af 1262/* Perform the ISO 14443 B Card Selection procedure
1263 * Currently does NOT do any collision handling.
1264 * It expects 0-1 cards in the device's range.
1265 * TODO: Support multiple cards (perform anticollision)
1266 * TODO: Verify CRC checksums
1267 */
6fc68747 1268uint8_t iso14443b_select_card(iso14b_card_select_t *card )
a62bf3af 1269{
1270 // WUPB command (including CRC)
1271 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
6fc68747 1272 static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 };
a62bf3af 1273 // ATTRIB command (with space for CRC)
6fc68747 1274 uint8_t attrib[] = { ISO14443B_ATTRIB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
a62bf3af 1275
6fc68747 1276 // temp to calc crc.
1277 uint8_t crc[2] = {0x00, 0x00};
1278
a62bf3af 1279 // first, wake up the tag
1280 CodeAndTransmit14443bAsReader(wupb, sizeof(wupb));
dccddaef 1281 GetTagSamplesFor14443bDemod(); //select_card
6fc68747 1282
a62bf3af 1283 // ATQB too short?
6fc68747 1284 if (Demod.len < 14) return 2;
1285
1286 // VALIDATE CRC
1287 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1288 if ( crc[0] != Demod.output[12] || crc[1] != Demod.output[13] )
1289 return 3;
1290
1291 if (card) {
1292 card->uidlen = 4;
1293 memcpy(card->uid, Demod.output+1, 4);
1294 memcpy(card->atqb, Demod.output+5, 7);
1295 }
a62bf3af 1296
11c2df83 1297 // copy the PUPI to ATTRIB ( PUPI == UID )
a62bf3af 1298 memcpy(attrib + 1, Demod.output + 1, 4);
6fc68747 1299
1300 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
a62bf3af 1301 attrib[7] = Demod.output[10] & 0x0F;
1302 ComputeCrc14443(CRC_14443_B, attrib, 9, attrib + 9, attrib + 10);
6fc68747 1303
a62bf3af 1304 CodeAndTransmit14443bAsReader(attrib, sizeof(attrib));
dccddaef 1305 GetTagSamplesFor14443bDemod();//select_card
6fc68747 1306
a62bf3af 1307 // Answer to ATTRIB too short?
6fc68747 1308 if(Demod.len < 3) return 2;
1309
1310 // VALIDATE CRC
1311 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1312 if ( crc[0] != Demod.output[1] || crc[1] != Demod.output[2] )
1313 return 3;
29f8c2cc 1314
65cdf0e3 1315 if (card) {
29f8c2cc 1316
1317 // CID
65cdf0e3 1318 card->cid = Demod.output[0];
29f8c2cc 1319
1320 // MAX FRAME
1321 uint16_t maxFrame = card->atqb[5] >> 4;
1322 if (maxFrame < 5) maxFrame = 8 * maxFrame + 16;
1323 else if (maxFrame == 5) maxFrame = 64;
1324 else if (maxFrame == 6) maxFrame = 96;
1325 else if (maxFrame == 7) maxFrame = 128;
1326 else if (maxFrame == 8) maxFrame = 256;
1327 else maxFrame = 257;
1328 iso14b_set_maxframesize(maxFrame);
1329
1330 // FWT
65cdf0e3 1331 uint8_t fwt = card->atqb[6] >> 4;
1332 if ( fwt < 16 ){
1333 uint32_t fwt_time = (302 << fwt);
1334 iso14b_set_timeout( fwt_time);
1335 }
11c2df83 1336 }
a62bf3af 1337 // reset PCB block number
1338 pcb_blocknum = 0;
6fc68747 1339 return 0;
a62bf3af 1340}
1341
1342// Set up ISO 14443 Type B communication (similar to iso14443a_setup)
11c2df83 1343// field is setup for "Sending as Reader"
a62bf3af 1344void iso14443b_setup() {
11c2df83 1345 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup Enter");
1346 LEDsoff();
a62bf3af 1347 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
11c2df83 1348 //BigBuf_free();
1349 //BigBuf_Clear_ext(false);
ff3e0744 1350
11c2df83 1351 // Initialize Demod and Uart structs
1352 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1353 UartInit(BigBuf_malloc(MAX_FRAME_SIZE));
cef590d9 1354
a62bf3af 1355 // connect Demodulated Signal to ADC:
1356 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1357
11c2df83 1358 // Set up the synchronous serial port
1359 FpgaSetupSsc();
1360
a62bf3af 1361 // Signal field is on with the appropriate LED
a62bf3af 1362 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
11c2df83 1363 SpinDelay(100);
a62bf3af 1364
1365 // Start the timer
ff3e0744 1366 StartCountSspClk();
11c2df83 1367
1368 LED_D_ON();
1369 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup Exit");
a62bf3af 1370}
489ef36c 1371
1372//-----------------------------------------------------------------------------
abb21530 1373// Read a SRI512 ISO 14443B tag.
489ef36c 1374//
1375// SRI512 tags are just simple memory tags, here we're looking at making a dump
1376// of the contents of the memory. No anticollision algorithm is done, we assume
1377// we have a single tag in the field.
1378//
1379// I tried to be systematic and check every answer of the tag, every CRC, etc...
1380//-----------------------------------------------------------------------------
6fc68747 1381void ReadSTMemoryIso14443b(uint8_t numofblocks)
489ef36c 1382{
17ad0e09 1383 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
489ef36c 1384
489ef36c 1385 // Make sure that we start from off, since the tags are stateful;
1386 // confusing things will happen if we don't reset them between reads.
11c2df83 1387 switch_off(); // before ReadStMemory
1388
1389 set_tracing(TRUE);
1390
1391 uint8_t i = 0x00;
99cf19d9 1392
489ef36c 1393 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1394 FpgaSetupSsc();
1395
1396 // Now give it time to spin up.
1397 // Signal field is on with the appropriate LED
1398 LED_D_ON();
22e24700 1399 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
11c2df83 1400 SpinDelay(20);
489ef36c 1401
1402 // First command: wake up the tag using the INITIATE command
6fc68747 1403 uint8_t cmd1[] = {ISO14443B_INITIATE, 0x00, 0x97, 0x5b};
11c2df83 1404 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); //no
dccddaef 1405 GetTagSamplesFor14443bDemod(); // no
489ef36c 1406
1407 if (Demod.len == 0) {
22e24700 1408 DbpString("No response from tag");
5ee53a0e 1409 set_tracing(FALSE);
22e24700 1410 return;
489ef36c 1411 } else {
705bfa10 1412 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1413 Demod.output[0], Demod.output[1], Demod.output[2]);
489ef36c 1414 }
705bfa10 1415
489ef36c 1416 // There is a response, SELECT the uid
1417 DbpString("Now SELECT tag:");
6fc68747 1418 cmd1[0] = ISO14443B_SELECT; // 0x0E is SELECT
489ef36c 1419 cmd1[1] = Demod.output[0];
1420 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
11c2df83 1421 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); //no
dccddaef 1422 GetTagSamplesFor14443bDemod(); //no
489ef36c 1423 if (Demod.len != 3) {
22e24700 1424 Dbprintf("Expected 3 bytes from tag, got %d", Demod.len);
5ee53a0e 1425 set_tracing(FALSE);
22e24700 1426 return;
489ef36c 1427 }
1428 // Check the CRC of the answer:
1429 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
1430 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
22e24700 1431 DbpString("CRC Error reading select response.");
5ee53a0e 1432 set_tracing(FALSE);
22e24700 1433 return;
489ef36c 1434 }
1435 // Check response from the tag: should be the same UID as the command we just sent:
1436 if (cmd1[1] != Demod.output[0]) {
22e24700 1437 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1[1], Demod.output[0]);
5ee53a0e 1438 set_tracing(FALSE);
22e24700 1439 return;
489ef36c 1440 }
705bfa10 1441
489ef36c 1442 // Tag is now selected,
1443 // First get the tag's UID:
6fc68747 1444 cmd1[0] = ISO14443B_GET_UID;
489ef36c 1445 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
11c2df83 1446 CodeAndTransmit14443bAsReader(cmd1, 3); // no -- Only first three bytes for this one
dccddaef 1447 GetTagSamplesFor14443bDemod(); //no
489ef36c 1448 if (Demod.len != 10) {
22e24700 1449 Dbprintf("Expected 10 bytes from tag, got %d", Demod.len);
5ee53a0e 1450 set_tracing(FALSE);
22e24700 1451 return;
489ef36c 1452 }
1453 // The check the CRC of the answer (use cmd1 as temporary variable):
1454 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
51d4f6f1 1455 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
22e24700 1456 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
705bfa10 1457 (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]);
489ef36c 1458 // Do not return;, let's go on... (we should retry, maybe ?)
1459 }
1460 Dbprintf("Tag UID (64 bits): %08x %08x",
705bfa10 1461 (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4],
1462 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]);
489ef36c 1463
1464 // Now loop to read all 16 blocks, address from 0 to last block
6fc68747 1465 Dbprintf("Tag memory dump, block 0 to %d", numofblocks);
489ef36c 1466 cmd1[0] = 0x08;
1467 i = 0x00;
6fc68747 1468 ++numofblocks;
1469
489ef36c 1470 for (;;) {
6fc68747 1471 if (i == numofblocks) {
489ef36c 1472 DbpString("System area block (0xff):");
1473 i = 0xff;
1474 }
1475 cmd1[1] = i;
1476 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
11c2df83 1477 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); //no
dccddaef 1478 GetTagSamplesFor14443bDemod(); //no
6fc68747 1479
489ef36c 1480 if (Demod.len != 6) { // Check if we got an answer from the tag
6fc68747 1481 DbpString("Expected 6 bytes from tag, got less...");
1482 return;
489ef36c 1483 }
1484 // The check the CRC of the answer (use cmd1 as temporary variable):
1485 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
1486 if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
132a0217 1487 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
705bfa10 1488 (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]);
489ef36c 1489 // Do not return;, let's go on... (we should retry, maybe ?)
1490 }
1491 // Now print out the memory location:
22e24700 1492 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i,
705bfa10 1493 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0],
17ad0e09 1494 (Demod.output[4]<<8)+Demod.output[5]);
6fc68747 1495
1496 if (i == 0xff) break;
1497 ++i;
489ef36c 1498 }
5ee53a0e 1499
1500 set_tracing(FALSE);
489ef36c 1501}
1502
11c2df83 1503
1504static void iso1444b_setup_snoop(void){
1505 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup_snoop Enter");
1506 LEDsoff();
1507 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1508 BigBuf_free();
1509 BigBuf_Clear_ext(false);
1510 clear_trace();//setup snoop
1511 set_tracing(TRUE);
1512
1513 // Initialize Demod and Uart structs
1514 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1515 UartInit(BigBuf_malloc(MAX_FRAME_SIZE));
1516
1517 if (MF_DBGLEVEL > 1) {
1518 // Print debug information about the buffer sizes
1519 Dbprintf("Snooping buffers initialized:");
1520 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1521 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE);
1522 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE);
1523 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE);
1524 }
1525
1526 // connect Demodulated Signal to ADC:
1527 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1528
1529 // Setup for the DMA.
1530 FpgaSetupSsc();
1531
1532 // Set FPGA in the appropriate mode
1533 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP);
1534 SpinDelay(20);
1535
1536 // Start the SSP timer
1537 StartCountSspClk();
1538 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup_snoop Exit");
1539}
1540
489ef36c 1541//=============================================================================
1542// Finally, the `sniffer' combines elements from both the reader and
1543// simulated tag, to show both sides of the conversation.
1544//=============================================================================
1545
1546//-----------------------------------------------------------------------------
1547// Record the sequence of commands sent by the reader to the tag, with
1548// triggering so that we start recording at the point that the tag is moved
1549// near the reader.
1550//-----------------------------------------------------------------------------
1551/*
1552 * Memory usage for this function, (within BigBuf)
47286d89 1553 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1554 * Last Received command (tag->reader) - MAX_FRAME_SIZE
705bfa10 1555 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
47286d89 1556 * Demodulated samples received - all the rest
489ef36c 1557 */
11c2df83 1558void RAMFUNC SnoopIso14443b(void) {
1559
1560 uint32_t time_0 = 0, time_start = 0, time_stop = 0;
d8b7a5f2 1561 int ci = 0, cq = 0;
1562 int lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
1563
489ef36c 1564 // We won't start recording the frames that we acquire until we trigger;
1565 // a good trigger condition to get started is probably when we see a
1566 // response from the tag.
d8b7a5f2 1567 bool triggered = TRUE; // TODO: set and evaluate trigger condition
f53020e7 1568 bool TagIsActive = FALSE;
1569 bool ReaderIsActive = FALSE;
11c2df83 1570
1571 iso1444b_setup_snoop();
1572
1573 // The DMA buffer, used to stream samples from the FPGA
1574 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE);
1575 int8_t *upTo = dmaBuf;
1576
1577 // Setup and start DMA.
1578 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE) ){
1579 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1580 BigBuf_free();
1581 return;
1582 }
1583
1584 time_0 = GetCountSspClk();
489ef36c 1585
1586 // And now we loop, receiving samples.
1587 for(;;) {
abb21530 1588
11c2df83 1589 WDT_HIT();
489ef36c 1590
1591 ci = upTo[0];
1592 cq = upTo[1];
d8b7a5f2 1593 upTo += 2;
489ef36c 1594 lastRxCounter -= 2;
11c2df83 1595
1596 if (upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) {
489ef36c 1597 upTo = dmaBuf;
b8622518 1598 lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
489ef36c 1599 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
705bfa10 1600 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE;
d8b7a5f2 1601
1602 if (!tracing) {
1603 if (MF_DBGLEVEL >= 2) DbpString("Trace full");
abb21530 1604 break;
1605 }
11c2df83 1606
d8b7a5f2 1607 if (BUTTON_PRESS()) {
1608 if (MF_DBGLEVEL >= 2) DbpString("cancelled");
abb21530 1609 break;
1610 }
489ef36c 1611 }
11c2df83 1612
1613 if (!TagIsActive) {
1614
1615 LED_A_ON();
1616
1617 // no need to try decoding reader data if the tag is sending
1618 if (Handle14443bReaderUartBit(ci & 0x01)) {
489ef36c 1619
b8622518 1620 time_stop = GetCountSspClk() - time_0;
11c2df83 1621
1622 if (triggered)
1623 LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, NULL, TRUE);
6fc68747 1624
810f5379 1625 /* And ready to receive another command. */
1626 UartReset();
1627 /* And also reset the demod code, which might have been */
1628 /* false-triggered by the commands from the reader. */
1629 DemodReset();
11c2df83 1630 } else {
b8622518 1631 time_start = GetCountSspClk() - time_0;
489ef36c 1632 }
6fc68747 1633
11c2df83 1634 if (Handle14443bReaderUartBit(cq & 0x01)) {
1635
b8622518 1636 time_stop = GetCountSspClk() - time_0;
11c2df83 1637
1638 if (triggered)
1639 LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, NULL, TRUE);
6fc68747 1640
1cb9b2a3
RW
1641 /* And ready to receive another command. */
1642 UartReset();
1643 /* And also reset the demod code, which might have been */
1644 /* false-triggered by the commands from the reader. */
1645 DemodReset();
11c2df83 1646 } else {
b8622518 1647 time_start = GetCountSspClk() - time_0;
6fc68747 1648 }
36f84d47 1649 ReaderIsActive = (Uart.state > STATE_GOT_FALLING_EDGE_OF_SOF);
11c2df83 1650 LED_A_OFF();
47286d89 1651 }
11c2df83 1652
d8b7a5f2 1653 if (!ReaderIsActive) {
11c2df83 1654 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
d8af608f 1655 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
d8b7a5f2 1656 // LSB is a fpga signal bit.
1657 if (Handle14443bTagSamplesDemod(ci >> 1, cq >> 1)) {
11c2df83 1658
b8622518 1659 time_stop = GetCountSspClk() - time_0;
11c2df83 1660
1661 LogTrace(Demod.output, Demod.len, time_start, time_stop, NULL, FALSE);
489ef36c 1662
810f5379 1663 triggered = TRUE;
1664
1665 // And ready to receive another response.
1666 DemodReset();
11c2df83 1667 } else {
b8622518 1668 time_start = GetCountSspClk() - time_0;
810f5379 1669 }
22e24700 1670 TagIsActive = (Demod.state > DEMOD_GOT_FALLING_EDGE_OF_SOF);
47286d89 1671 }
489ef36c 1672 }
abb21530 1673
11c2df83 1674 switch_off(); // Snoop
810f5379 1675
489ef36c 1676 DbpString("Snoop statistics:");
11c2df83 1677 Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart.state, Uart.byteCnt, Uart.byteCntMax);
489ef36c 1678 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
11c2df83 1679
1680 // free mem refs.
d8b7a5f2 1681 if ( upTo ) upTo = NULL;
c3e8413c 1682
11c2df83 1683 // Uart.byteCntMax should be set with ATQB value..
489ef36c 1684}
1685
6fc68747 1686void iso14b_set_trigger(bool enable) {
1687 trigger = enable;
1688}
489ef36c 1689
1690/*
1691 * Send raw command to tag ISO14443B
1692 * @Input
6fc68747 1693 * param flags enum ISO14B_COMMAND. (mifare.h)
1694 * len len of buffer data
1695 * data buffer with bytes to send
489ef36c 1696 *
1697 * @Output
1698 * none
1699 *
1700 */
6fc68747 1701void SendRawCommand14443B_Ex(UsbCommand *c)
489ef36c 1702{
6fc68747 1703 iso14b_command_t param = c->arg[0];
1704 size_t len = c->arg[1] & 0xffff;
1705 uint8_t *cmd = c->d.asBytes;
1706 uint8_t status = 0;
1707 uint32_t sendlen = sizeof(iso14b_card_select_t);
1708 uint8_t buf[USB_CMD_DATA_SIZE] = {0x00};
1709
11c2df83 1710 if (MF_DBGLEVEL > 3) Dbprintf("14b raw: param, %04x", param );
b10a759f 1711
6fc68747 1712 // turn on trigger (LED_A)
11c2df83 1713 if ((param & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER)
6fc68747 1714 iso14b_set_trigger(TRUE);
1715
11c2df83 1716 if ((param & ISO14B_CONNECT) == ISO14B_CONNECT) {
6fc68747 1717 // Make sure that we start from off, since the tags are stateful;
1718 // confusing things will happen if we don't reset them between reads.
11c2df83 1719 //switch_off(); // before connect in raw
6fc68747 1720 iso14443b_setup();
99cf19d9 1721 }
6fc68747 1722
1723 set_tracing(TRUE);
489ef36c 1724
11c2df83 1725 if ((param & ISO14B_SELECT_STD) == ISO14B_SELECT_STD) {
6fc68747 1726 iso14b_card_select_t *card = (iso14b_card_select_t*)buf;
1727 status = iso14443b_select_card(card);
1728 cmd_send(CMD_ACK, status, sendlen, 0, buf, sendlen);
1729 // 0: OK 2: attrib fail, 3:crc fail,
1730 if ( status > 0 ) return;
1731 }
1732
11c2df83 1733 if ((param & ISO14B_SELECT_SR) == ISO14B_SELECT_SR) {
6fc68747 1734 iso14b_card_select_t *card = (iso14b_card_select_t*)buf;
1735 status = iso14443b_select_srx_card(card);
1736 cmd_send(CMD_ACK, status, sendlen, 0, buf, sendlen);
1737 // 0: OK 2: attrib fail, 3:crc fail,
1738 if ( status > 0 ) return;
1739 }
1740
11c2df83 1741 if ((param & ISO14B_APDU) == ISO14B_APDU) {
6fc68747 1742 status = iso14443b_apdu(cmd, len, buf);
1743 cmd_send(CMD_ACK, status, status, 0, buf, status);
489ef36c 1744 }
abb21530 1745
11c2df83 1746 if ((param & ISO14B_RAW) == ISO14B_RAW) {
1747 if((param & ISO14B_APPEND_CRC) == ISO14B_APPEND_CRC) {
6fc68747 1748 AppendCrc14443b(cmd, len);
1749 len += 2;
1750 }
1751
11c2df83 1752 CodeAndTransmit14443bAsReader(cmd, len); // raw
dccddaef 1753 GetTagSamplesFor14443bDemod(); // raw
6fc68747 1754
1755 sendlen = MIN(Demod.len, USB_CMD_DATA_SIZE);
1756 status = (Demod.len > 0) ? 0 : 1;
1757 cmd_send(CMD_ACK, status, sendlen, 0, Demod.output, sendlen);
1758 }
1759
1760 // turn off trigger (LED_A)
11c2df83 1761 if ((param & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER)
1762 iso14b_set_trigger(FALSE);
6fc68747 1763
1764 // turn off antenna et al
1765 // we don't send a HALT command.
11c2df83 1766 if ((param & ISO14B_DISCONNECT) == ISO14B_DISCONNECT) {
6fc68747 1767 if (MF_DBGLEVEL > 3) Dbprintf("disconnect");
11c2df83 1768 switch_off(); // disconnect raw
1769 } else {
1770 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
489ef36c 1771 }
11c2df83 1772
1cb9b2a3 1773}
Impressum, Datenschutz