]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443b.c
CHG: change the number of calls to prng_successor was done. Fewer should mean faster :)
[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
ffeb77fd 456 volatile uint8_t b;
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
470 b = 0;
471 uint8_t mask;
dccddaef 472 while( !BUTTON_PRESS() ) {
489ef36c 473 WDT_HIT();
474
dccddaef 475 if ( AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY ) {
476 b = (uint8_t) AT91C_BASE_SSC->SSC_RHR;
477 for ( mask = 0x80; mask != 0; mask >>= 1) {
478 if ( Handle14443bReaderUartBit(b & mask)) {
489ef36c 479 *len = Uart.byteCnt;
480 return TRUE;
481 }
482 }
483 }
11c2df83 484 }
36f84d47 485 return FALSE;
489ef36c 486}
487
ffeb77fd 488void ClearFpgaShiftingRegisters(void){
489
490 volatile uint8_t b;
491
492 // clear receiving shift register and holding register
493 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
c3e8413c 494
ffeb77fd 495 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
496
497 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
c3e8413c 498
ffeb77fd 499 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
500
501
502 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
503 for (uint8_t j = 0; j < 5; j++) { // allow timeout - better late than never
504 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
505 if (AT91C_BASE_SSC->SSC_RHR) break;
506 }
507
508 // Clear TXRDY:
c3e8413c 509 //AT91C_BASE_SSC->SSC_THR = 0xFF;
ffeb77fd 510}
511
512void WaitForFpgaDelayQueueIsEmpty( uint16_t delay ){
513 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
514 uint8_t fpga_queued_bits = delay >> 3; // twich /8 ?? >>3,
515 for (uint8_t i = 0; i <= fpga_queued_bits/8 + 1; ) {
516 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
517 AT91C_BASE_SSC->SSC_THR = 0xFF;
518 i++;
519 }
520 }
521}
dccddaef 522
523static void TransmitFor14443b_AsTag( uint8_t *response, uint16_t len) {
524
b8622518 525 volatile uint32_t b;
526
527 // Signal field is off with the appropriate LED
528 LED_D_OFF();
529 //uint16_t fpgasendQueueDelay = 0;
530
531 // Modulate BPSK
532 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
533 SpinDelay(40);
534
535 ClearFpgaShiftingRegisters();
536
537 FpgaSetupSsc();
dccddaef 538
b8622518 539 // Transmit the response.
540 for(uint16_t i = 0; i < len;) {
541 if(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
542 AT91C_BASE_SSC->SSC_THR = response[++i];
dccddaef 543 }
b8622518 544 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
545 b = AT91C_BASE_SSC->SSC_RHR;
546 (void)b;
547 }
548 }
549
550 //WaitForFpgaDelayQueueIsEmpty(fpgasendQueueDelay);
551 AT91C_BASE_SSC->SSC_THR = 0xFF;
dccddaef 552}
489ef36c 553//-----------------------------------------------------------------------------
554// Main loop of simulated tag: receive commands from reader, decide what
555// response to send, and send it.
556//-----------------------------------------------------------------------------
dccddaef 557void SimulateIso14443bTag(uint32_t pupi) {
dccddaef 558
0923c43c 559 ///////////// setup device.
99cf19d9 560 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
561
11c2df83 562 // allocate command receive buffer
563 BigBuf_free();
564 BigBuf_Clear_ext(false);
565 clear_trace(); //sim
36f84d47 566 set_tracing(TRUE);
11c2df83 567
dccddaef 568 // connect Demodulated Signal to ADC:
569 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
570
571 // Set up the synchronous serial port
572 FpgaSetupSsc();
0923c43c 573 /////////////
dccddaef 574
0923c43c 575 uint16_t len, cmdsReceived = 0;
576 int cardSTATE = SIM_NOFIELD;
577 int vHf = 0; // in mV
578 // uint32_t time_0 = 0;
579 // uint32_t t2r_time = 0;
580 // uint32_t r2t_time = 0;
581 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
dccddaef 582
0923c43c 583 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
584// static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
585 // ... and REQB, AFI=0, Normal Request, N=1:
586// static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
587 // ... and ATTRIB
588// static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
589
590 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
591 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
592 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
593 uint8_t respATQB[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19,
594 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 };
595
596 // response to HLTB and ATTRIB
597 static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
598
599 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
600 if ( pupi > 0 ) {
c23d2618 601 uint8_t len = sizeof(respATQB);
0923c43c 602 num_to_bytes(pupi, 4, respATQB+1);
c3e8413c 603 ComputeCrc14443(CRC_14443_B, respATQB, 12, &respATQB[len-2], &respATQB[len-1]);
0923c43c 604 }
605
606 // prepare "ATQB" tag answer (encoded):
607 CodeIso14443bAsTag(respATQB, sizeof(respATQB));
608 uint8_t *encodedATQB = BigBuf_malloc(ToSendMax);
609 uint16_t encodedATQBLen = ToSendMax;
610 memcpy(encodedATQB, ToSend, ToSendMax);
611
11c2df83 612
0923c43c 613 // prepare "OK" tag answer (encoded):
614 CodeIso14443bAsTag(respOK, sizeof(respOK));
615 uint8_t *encodedOK = BigBuf_malloc(ToSendMax);
616 uint16_t encodedOKLen = ToSendMax;
617 memcpy(encodedOK, ToSend, ToSendMax);
11c2df83 618
0923c43c 619 // Simulation loop
dccddaef 620 while (!BUTTON_PRESS() && !usb_poll_validate_length()) {
621 WDT_HIT();
489ef36c 622
dccddaef 623 // find reader field
0923c43c 624 if (cardSTATE == SIM_NOFIELD) {
dccddaef 625 vHf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10;
0923c43c 626 if ( vHf > MF_MINFIELDV ) {
627 cardSTATE = SIM_IDLE;
628 LED_A_ON();
629 }
dccddaef 630 }
0923c43c 631 if (cardSTATE == SIM_NOFIELD) continue;
489ef36c 632
0923c43c 633 // Get reader command
810f5379 634 if (!GetIso14443bCommandFromReader(receivedCmd, &len)) {
0923c43c 635 Dbprintf("button pressed, received %d commands", cmdsReceived);
810f5379 636 break;
489ef36c 637 }
638
0923c43c 639 // ISO14443-B protocol states:
640 // REQ or WUP request in ANY state
641 // WUP in HALTED state
642 if (len == 5 ) {
ffeb77fd 643 if ( (receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8)== 0x8 && cardSTATE == SIM_HALTED) ||
644 receivedCmd[0] == ISO14443B_REQB ){
645 LogTrace(receivedCmd, len, 0, 0, NULL, TRUE);
0923c43c 646 cardSTATE = SIM_SELECTING;
0923c43c 647 }
648 }
649
650 /*
651 * How should this flow go?
652 * REQB or WUPB
653 * send response ( waiting for Attrib)
654 * ATTRIB
655 * send response ( waiting for commands 7816)
656 * HALT
657 send halt response ( waiting for wupb )
658 */
d51717ff 659
b8622518 660 switch (cardSTATE) {
0923c43c 661 case SIM_NOFIELD:
662 case SIM_HALTED:
b8622518 663 case SIM_IDLE: {
dccddaef 664 LogTrace(receivedCmd, len, 0, 0, NULL, TRUE);
665 break;
666 }
0923c43c 667 case SIM_SELECTING: {
668 TransmitFor14443b_AsTag( encodedATQB, encodedATQBLen );
669 LogTrace(respATQB, sizeof(respATQB), 0, 0, NULL, FALSE);
ffeb77fd 670 cardSTATE = SIM_WORK;
dccddaef 671 break;
0923c43c 672 }
673 case SIM_HALTING: {
674 TransmitFor14443b_AsTag( encodedOK, encodedOKLen );
675 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, FALSE);
676 cardSTATE = SIM_HALTED;
dccddaef 677 break;
0923c43c 678 }
b8622518 679 case SIM_ACKNOWLEDGE: {
0923c43c 680 TransmitFor14443b_AsTag( encodedOK, encodedOKLen );
681 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, FALSE);
682 cardSTATE = SIM_IDLE;
683 break;
684 }
b8622518 685 case SIM_WORK: {
d51717ff 686 if ( len == 7 && receivedCmd[0] == ISO14443B_HALT ) {
687 cardSTATE = SIM_HALTED;
688 } else if ( len == 11 && receivedCmd[0] == ISO14443B_ATTRIB ) {
689 cardSTATE = SIM_ACKNOWLEDGE;
690 } else {
691 // Todo:
692 // - SLOT MARKER
693 // - ISO7816
694 // - emulate with a memory dump
695 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsReceived);
696
697 // CRC Check
698 uint8_t b1, b2;
699 if (len >= 3){ // if crc exists
700 ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2);
701 if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1])
702 DbpString("+++CRC fail");
703 else
704 DbpString("CRC passes");
705 }
706 cardSTATE = SIM_IDLE;
707 }
dccddaef 708 break;
d51717ff 709 }
710 default: break;
dccddaef 711 }
712
0923c43c 713 ++cmdsReceived;
b8622518 714 // iceman, could add a switch to turn this on/off (if off, no logging?)
0923c43c 715 if(cmdsReceived > 1000) {
dccddaef 716 DbpString("14B Simulate, 1000 commands later...");
489ef36c 717 break;
718 }
489ef36c 719 }
dccddaef 720 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, BigBuf_get_traceLen());
11c2df83 721 switch_off(); //simulate
489ef36c 722}
723
724//=============================================================================
725// An ISO 14443 Type B reader. We take layer two commands, code them
726// appropriately, and then send them to the tag. We then listen for the
727// tag's response, which we leave in the buffer to be demodulated on the
728// PC side.
729//=============================================================================
730
489ef36c 731/*
732 * Handles reception of a bit from the tag
733 *
abb21530 734 * This function is called 2 times per bit (every 4 subcarrier cycles).
735 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
736 *
489ef36c 737 * LED handling:
738 * LED C -> ON once we have received the SOF and are expecting the rest.
739 * LED C -> OFF once we have received EOF or are unsynced
740 *
741 * Returns: true if we received a EOF
742 * false if we are still waiting for some more
743 *
744 */
11c2df83 745static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) {
29f8c2cc 746 int v = 0, myI = ABS(ci), myQ = ABS(cq);
747
51d4f6f1 748// The soft decision on the bit uses an estimate of just the
749// quadrant of the reference angle, not the exact angle.
489ef36c 750#define MAKE_SOFT_DECISION() { \
5b59bf20 751 if(Demod.sumI > 0) { \
752 v = ci; \
753 } else { \
754 v = -ci; \
755 } \
489ef36c 756 if(Demod.sumQ > 0) { \
757 v += cq; \
758 } else { \
759 v -= cq; \
760 } \
761 }
762
cef590d9 763// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq)
abb21530 764// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
b8622518 765#define CHECK_FOR_SUBCARRIER_old() { \
cef590d9 766 if(ci < 0) { \
767 if(cq < 0) { /* ci < 0, cq < 0 */ \
768 if (cq < ci) { \
769 v = -cq - (ci >> 1); \
770 } else { \
771 v = -ci - (cq >> 1); \
772 } \
773 } else { /* ci < 0, cq >= 0 */ \
774 if (cq < -ci) { \
775 v = -ci + (cq >> 1); \
776 } else { \
777 v = cq - (ci >> 1); \
778 } \
779 } \
780 } else { \
781 if(cq < 0) { /* ci >= 0, cq < 0 */ \
782 if (-cq < ci) { \
783 v = ci - (cq >> 1); \
784 } else { \
785 v = -cq + (ci >> 1); \
786 } \
787 } else { /* ci >= 0, cq >= 0 */ \
788 if (cq < ci) { \
789 v = ci + (cq >> 1); \
790 } else { \
791 v = cq + (ci >> 1); \
792 } \
793 } \
794 } \
795 }
db25599d 796
6fc68747 797//note: couldn't we just use MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2) from common.h - marshmellow
b8622518 798#define CHECK_FOR_SUBCARRIER() { \
b8622518 799 v = MAX(myI, myQ) + (MIN(myI, myQ) >> 1); \
6fc68747 800 }
db25599d 801
489ef36c 802 switch(Demod.state) {
803 case DEMOD_UNSYNCD:
cef590d9 804
abb21530 805 CHECK_FOR_SUBCARRIER();
c2df2883 806
cef590d9 807 // subcarrier detected
86db8973 808 if (v > SUBCARRIER_DETECT_THRESHOLD) {
489ef36c 809 Demod.state = DEMOD_PHASE_REF_TRAINING;
abb21530 810 Demod.sumI = ci;
811 Demod.sumQ = cq;
812 Demod.posCount = 1;
489ef36c 813 }
814 break;
815
816 case DEMOD_PHASE_REF_TRAINING:
86db8973 817 if (Demod.posCount < 8) {
cef590d9 818
abb21530 819 CHECK_FOR_SUBCARRIER();
cef590d9 820
abb21530 821 if (v > SUBCARRIER_DETECT_THRESHOLD) {
822 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
823 // note: synchronization time > 80 1/fs
b10a759f 824 Demod.sumI += ci;
825 Demod.sumQ += cq;
cef590d9 826 ++Demod.posCount;
827 } else {
828 // subcarrier lost
b10a759f 829 Demod.state = DEMOD_UNSYNCD;
abb21530 830 }
489ef36c 831 } else {
b10a759f 832 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
489ef36c 833 }
489ef36c 834 break;
835
836 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
cef590d9 837
489ef36c 838 MAKE_SOFT_DECISION();
cef590d9 839
86db8973 840 if (v < 0) { // logic '0' detected
489ef36c 841 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
abb21530 842 Demod.posCount = 0; // start of SOF sequence
489ef36c 843 } else {
cef590d9 844 // maximum length of TR1 = 200 1/fs
c3e8413c 845 if(Demod.posCount > 26*2) Demod.state = DEMOD_UNSYNCD;
489ef36c 846 }
cef590d9 847 ++Demod.posCount;
489ef36c 848 break;
849
850 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
cef590d9 851 ++Demod.posCount;
852
489ef36c 853 MAKE_SOFT_DECISION();
cef590d9 854
86db8973 855 if (v > 0) {
cef590d9 856 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
86db8973 857 if (Demod.posCount < 8*2) {
489ef36c 858 Demod.state = DEMOD_UNSYNCD;
859 } else {
a62bf3af 860 LED_C_ON(); // Got SOF
86db8973 861 //Demod.startTime = GetCountSspClk();
489ef36c 862 Demod.state = DEMOD_AWAITING_START_BIT;
863 Demod.posCount = 0;
864 Demod.len = 0;
489ef36c 865 }
866 } else {
cef590d9 867 // low phase of SOF too long (> 12 etu)
c3e8413c 868 if (Demod.posCount > 14*2) {
489ef36c 869 Demod.state = DEMOD_UNSYNCD;
47286d89 870 LED_C_OFF();
489ef36c 871 }
872 }
489ef36c 873 break;
874
875 case DEMOD_AWAITING_START_BIT:
cef590d9 876 ++Demod.posCount;
877
489ef36c 878 MAKE_SOFT_DECISION();
cef590d9 879
880 if (v > 0) {
c3e8413c 881 if(Demod.posCount > 2*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
489ef36c 882 Demod.state = DEMOD_UNSYNCD;
47286d89 883 LED_C_OFF();
489ef36c 884 }
abb21530 885 } else { // start bit detected
489ef36c 886 Demod.bitCount = 0;
abb21530 887 Demod.posCount = 1; // this was the first half
489ef36c 888 Demod.thisBit = v;
889 Demod.shiftReg = 0;
890 Demod.state = DEMOD_RECEIVING_DATA;
891 }
892 break;
893
894 case DEMOD_RECEIVING_DATA:
cef590d9 895
489ef36c 896 MAKE_SOFT_DECISION();
cef590d9 897
898 if (Demod.posCount == 0) {
899 // first half of bit
489ef36c 900 Demod.thisBit = v;
901 Demod.posCount = 1;
cef590d9 902 } else {
903 // second half of bit
489ef36c 904 Demod.thisBit += v;
489ef36c 905 Demod.shiftReg >>= 1;
489ef36c 906
86db8973 907 // OR in a logic '1'
b8622518 908 if (Demod.thisBit > 0) Demod.shiftReg |= 0x200;
cef590d9 909
910 ++Demod.bitCount;
911
b8622518 912 // 1 start 8 data 1 stop = 10
913 if (Demod.bitCount == 10) {
cef590d9 914
489ef36c 915 uint16_t s = Demod.shiftReg;
cef590d9 916
917 // stop bit == '1', start bit == '0'
29f8c2cc 918 if ((s & 0x200) && (s & 0x001) == 0 ) {
919 // left shift to drop the startbit
920 Demod.output[Demod.len] = (s >> 1) & 0xFF;
cef590d9 921 ++Demod.len;
489ef36c 922 Demod.state = DEMOD_AWAITING_START_BIT;
489ef36c 923 } else {
29f8c2cc 924 // this one is a bit hard, either its a correc byte or its unsynced.
489ef36c 925 Demod.state = DEMOD_UNSYNCD;
86db8973 926 //Demod.endTime = GetCountSspClk();
47286d89 927 LED_C_OFF();
cef590d9 928
929 // This is EOF (start, stop and all data bits == '0'
29f8c2cc 930 if (s == 0) return TRUE;
489ef36c 931 }
932 }
933 Demod.posCount = 0;
934 }
935 break;
936
937 default:
938 Demod.state = DEMOD_UNSYNCD;
47286d89 939 LED_C_OFF();
489ef36c 940 break;
941 }
489ef36c 942 return FALSE;
943}
944
945
489ef36c 946/*
947 * Demodulate the samples we received from the tag, also log to tracebuffer
489ef36c 948 * quiet: set to 'TRUE' to disable debug output
949 */
dccddaef 950static void GetTagSamplesFor14443bDemod() {
b8622518 951 bool gotFrame = FALSE, finished = FALSE;
11c2df83 952 int lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
29f8c2cc 953 int ci = 0, cq = 0;
11c2df83 954 uint32_t time_0 = 0, time_stop = 0;
489ef36c 955
11c2df83 956 BigBuf_free();
957
489ef36c 958 // Set up the demodulator for tag -> reader responses.
db25599d 959 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
b10a759f 960
961 // The DMA buffer, used to stream samples from the FPGA
962 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE);
11c2df83 963 int8_t *upTo = dmaBuf;
cef590d9 964
db25599d 965 // Setup and start DMA.
11c2df83 966 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE) ){
967 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
968 return;
969 }
b8622518 970
11c2df83 971 // And put the FPGA in the appropriate mode
972 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
489ef36c 973
b8622518 974 // get current clock
975 time_0 = GetCountSspClk();
976
977 // rx counter - dma counter? (how much?) & (mod) mask > 2. (since 2bytes at the time is read)
978 while ( !finished ) {
489ef36c 979
b8622518 980 LED_A_INV();
981 WDT_HIT();
11c2df83 982
b8622518 983 // LSB is a fpga signal bit.
984 ci = upTo[0] >> 1;
985 cq = upTo[1] >> 1;
986 upTo += 2;
b8622518 987 lastRxCounter -= 2;
988
989 // restart DMA buffer to receive again.
990 if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) {
991 upTo = dmaBuf;
992 lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
993 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
994 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE;
489ef36c 995 }
996
b8622518 997 // https://github.com/Proxmark/proxmark3/issues/103
b8622518 998 gotFrame = Handle14443bTagSamplesDemod(ci, cq);
11c2df83 999 time_stop = GetCountSspClk() - time_0;
b8622518 1000
1001 finished = (time_stop > iso14b_timeout || gotFrame);
489ef36c 1002 }
11c2df83 1003
1004 FpgaDisableSscDma();
d8b7a5f2 1005
1006 if ( upTo ) upTo = NULL;
1007
dccddaef 1008 if (MF_DBGLEVEL >= 3) {
d8b7a5f2 1009 Dbprintf("Demod.state = %d, Demod.len = %u, PDC_RCR = %u",
cef590d9 1010 Demod.state,
d8b7a5f2 1011 Demod.len,
1012 AT91C_BASE_PDC_SSC->PDC_RCR
b10a759f 1013 );
1014 }
b8622518 1015
d8b7a5f2 1016 // print the last batch of IQ values from FPGA
b8622518 1017 if (MF_DBGLEVEL == 4)
1018 Dbhexdump(ISO14443B_DMA_BUFFER_SIZE, (uint8_t *)dmaBuf, FALSE);
1019
11c2df83 1020 if ( Demod.len > 0 )
86db8973 1021 LogTrace(Demod.output, Demod.len, time_0, time_stop, NULL, FALSE);
489ef36c 1022}
1023
1024
489ef36c 1025//-----------------------------------------------------------------------------
1026// Transmit the command (to the tag) that was placed in ToSend[].
1027//-----------------------------------------------------------------------------
11c2df83 1028static void TransmitFor14443b_AsReader(void) {
489ef36c 1029
11c2df83 1030 // we could been in following mode:
1031 // FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ
1032 // if its second call or more
c3e8413c 1033
1034 // while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1035 // AT91C_BASE_SSC->SSC_THR = 0XFF;
1036 // }
1037
1038 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1039 SpinDelay(40);
11c2df83 1040
c3e8413c 1041 int c;
1042 volatile uint32_t b;
1043
11c2df83 1044 // What does this loop do? Is it TR1?
c3e8413c 1045 // 0xFF = 8 bits of 1. 1 bit == 1Etu,..
1046 // loop 10 * 8 = 80 ETU of delay, with a non modulated signal. why?
1047 // 80*9 = 720us.
1048 for(c = 0; c < 50;) {
489ef36c 1049 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
11c2df83 1050 AT91C_BASE_SSC->SSC_THR = 0xFF;
cef590d9 1051 ++c;
489ef36c 1052 }
c3e8413c 1053 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1054 b = AT91C_BASE_SSC->SSC_RHR;
1055 (void)b;
1056 }
489ef36c 1057 }
c3e8413c 1058
11c2df83 1059 // Send frame loop
1060 for(c = 0; c < ToSendMax;) {
489ef36c 1061 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
c3e8413c 1062 AT91C_BASE_SSC->SSC_THR = ToSend[c++];
489ef36c 1063 }
c3e8413c 1064 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1065 b = AT91C_BASE_SSC->SSC_RHR;
1066 (void)b;
1067 }
489ef36c 1068 }
c3e8413c 1069 //WaitForFpgaDelayQueueIsEmpty(delay);
1070 // We should wait here for the FPGA to send all bits.
11c2df83 1071 WDT_HIT();
489ef36c 1072}
1073
489ef36c 1074//-----------------------------------------------------------------------------
1075// Code a layer 2 command (string of octets, including CRC) into ToSend[],
abb21530 1076// so that it is ready to transmit to the tag using TransmitFor14443b().
489ef36c 1077//-----------------------------------------------------------------------------
86db8973 1078static void CodeIso14443bAsReader(const uint8_t *cmd, int len) {
11c2df83 1079 /*
1080 * Reader data transmission:
1081 * - no modulation ONES
1082 * - SOF
1083 * - Command, data and CRC_B
1084 * - EOF
1085 * - no modulation ONES
1086 *
1087 * 1 ETU == 1 BIT!
1088 * TR0 - 8 ETUS minimum.
c3e8413c 1089 *
1090 * QUESTION: how long is a 1 or 0 in pulses in the xcorr_848 mode?
1091 * 1 "stuffbit" = 1ETU (9us)
11c2df83 1092 */
1093 int i;
489ef36c 1094 uint8_t b;
11c2df83 1095
489ef36c 1096 ToSendReset();
1097
489ef36c 1098 // Send SOF
11c2df83 1099 // 10-11 ETUs of ZERO
1100 for(i = 0; i < 10; ++i) ToSendStuffBit(0);
1101
1102 // 2-3 ETUs of ONE
1103 ToSendStuffBit(1);
1104 ToSendStuffBit(1);
1105 ToSendStuffBit(1);
1106
1107 // Sending cmd, LSB
1108 // from here we add BITS
6fc68747 1109 for(i = 0; i < len; ++i) {
11c2df83 1110 // Start bit
489ef36c 1111 ToSendStuffBit(0);
1112 // Data bits
11c2df83 1113 b = cmd[i];
86db8973 1114 // if ( b & 1 ) ToSendStuffBit(1); else ToSendStuffBit(0);
1115 // if ( (b>>1) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1116 // if ( (b>>2) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1117 // if ( (b>>3) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1118 // if ( (b>>4) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1119 // if ( (b>>5) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1120 // if ( (b>>6) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1121 // if ( (b>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1122
1123 ToSendStuffBit( b & 1);
1124 ToSendStuffBit( (b>>1) & 1);
1125 ToSendStuffBit( (b>>2) & 1);
1126 ToSendStuffBit( (b>>3) & 1);
1127 ToSendStuffBit( (b>>4) & 1);
1128 ToSendStuffBit( (b>>5) & 1);
1129 ToSendStuffBit( (b>>6) & 1);
1130 ToSendStuffBit( (b>>7) & 1);
1131
11c2df83 1132 // Stop bit
489ef36c 1133 ToSendStuffBit(1);
11c2df83 1134 // EGT extra guard time
1135 // For PCD it ranges 0-57us (1etu = 9us)
489ef36c 1136 ToSendStuffBit(1);
11c2df83 1137 ToSendStuffBit(1);
1138 ToSendStuffBit(1);
1139 }
1140
1141 // Send EOF
1142 // 10-11 ETUs of ZERO
1143 for(i = 0; i < 10; ++i) ToSendStuffBit(0);
489ef36c 1144
11c2df83 1145 // Transition time. TR0 - guard time
1146 // 8ETUS minum?
1147 // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF.
c3e8413c 1148 // I'm guessing this is for the FPGA to be able to send all bits before we switch to listening mode
1149 for(i = 0; i < 32 ; ++i) ToSendStuffBit(1);
11c2df83 1150
1151 // TR1 - Synchronization time
489ef36c 1152 // Convert from last character reference to length
cef590d9 1153 ++ToSendMax;
489ef36c 1154}
1155
1156
86db8973 1157/*
1158* Convenience function to encode, transmit and trace iso 14443b comms
1159*/
11c2df83 1160static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) {
86db8973 1161
1162 uint32_t time_start = GetCountSspClk();
11c2df83 1163
489ef36c 1164 CodeIso14443bAsReader(cmd, len);
6fc68747 1165
11c2df83 1166 TransmitFor14443b_AsReader();
86db8973 1167
6fc68747 1168 if(trigger) LED_A_ON();
86db8973 1169
dccddaef 1170 LogTrace(cmd, len, time_start, GetCountSspClk()-time_start, NULL, TRUE);
489ef36c 1171}
1172
a62bf3af 1173/* Sends an APDU to the tag
1174 * TODO: check CRC and preamble
1175 */
6fc68747 1176uint8_t iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response)
a62bf3af 1177{
6fc68747 1178 uint8_t crc[2] = {0x00, 0x00};
a62bf3af 1179 uint8_t message_frame[message_length + 4];
1180 // PCB
1181 message_frame[0] = 0x0A | pcb_blocknum;
1182 pcb_blocknum ^= 1;
1183 // CID
1184 message_frame[1] = 0;
1185 // INF
1186 memcpy(message_frame + 2, message, message_length);
1187 // EDC (CRC)
1188 ComputeCrc14443(CRC_14443_B, message_frame, message_length + 2, &message_frame[message_length + 2], &message_frame[message_length + 3]);
1189 // send
11c2df83 1190 CodeAndTransmit14443bAsReader(message_frame, message_length + 4); //no
a62bf3af 1191 // get response
dccddaef 1192 GetTagSamplesFor14443bDemod(); //no
a62bf3af 1193 if(Demod.len < 3)
a62bf3af 1194 return 0;
cef590d9 1195
6fc68747 1196 // VALIDATE CRC
1197 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1198 if ( crc[0] != Demod.output[Demod.len-2] || crc[1] != Demod.output[Demod.len-1] )
1199 return 0;
1200
a62bf3af 1201 // copy response contents
1202 if(response != NULL)
a62bf3af 1203 memcpy(response, Demod.output, Demod.len);
cef590d9 1204
a62bf3af 1205 return Demod.len;
1206}
1207
6fc68747 1208/**
1209* SRx Initialise.
1210*/
1211uint8_t iso14443b_select_srx_card(iso14b_card_select_t *card )
1212{
1213 // INITIATE command: wake up the tag using the INITIATE
1214 static const uint8_t init_srx[] = { ISO14443B_INITIATE, 0x00, 0x97, 0x5b };
1215 // SELECT command (with space for CRC)
1216 uint8_t select_srx[] = { ISO14443B_SELECT, 0x00, 0x00, 0x00};
1217 // temp to calc crc.
1218 uint8_t crc[2] = {0x00, 0x00};
1219
1220 CodeAndTransmit14443bAsReader(init_srx, sizeof(init_srx));
dccddaef 1221 GetTagSamplesFor14443bDemod(); //no
6fc68747 1222
1223 if (Demod.len == 0) return 2;
1224
1225 // Randomly generated Chip ID
1226 if (card) card->chipid = Demod.output[0];
1227
1228 select_srx[1] = Demod.output[0];
1229
1230 ComputeCrc14443(CRC_14443_B, select_srx, 2, &select_srx[2], &select_srx[3]);
1231 CodeAndTransmit14443bAsReader(select_srx, sizeof(select_srx));
dccddaef 1232 GetTagSamplesFor14443bDemod(); //no
6fc68747 1233
1234 if (Demod.len != 3) return 2;
1235
1236 // Check the CRC of the answer:
1237 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2 , &crc[0], &crc[1]);
1238 if(crc[0] != Demod.output[1] || crc[1] != Demod.output[2]) return 3;
1239
1240 // Check response from the tag: should be the same UID as the command we just sent:
1241 if (select_srx[1] != Demod.output[0]) return 1;
1242
1243 // First get the tag's UID:
1244 select_srx[0] = ISO14443B_GET_UID;
1245
1246 ComputeCrc14443(CRC_14443_B, select_srx, 1 , &select_srx[1], &select_srx[2]);
1247 CodeAndTransmit14443bAsReader(select_srx, 3); // Only first three bytes for this one
dccddaef 1248 GetTagSamplesFor14443bDemod(); //no
6fc68747 1249
1250 if (Demod.len != 10) return 2;
1251
1252 // The check the CRC of the answer
1253 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1254 if(crc[0] != Demod.output[8] || crc[1] != Demod.output[9]) return 3;
1255
1256 if (card) {
1257 card->uidlen = 8;
1258 memcpy(card->uid, Demod.output, 8);
1259 }
1260
1261 return 0;
1262}
a62bf3af 1263/* Perform the ISO 14443 B Card Selection procedure
1264 * Currently does NOT do any collision handling.
1265 * It expects 0-1 cards in the device's range.
1266 * TODO: Support multiple cards (perform anticollision)
1267 * TODO: Verify CRC checksums
1268 */
6fc68747 1269uint8_t iso14443b_select_card(iso14b_card_select_t *card )
a62bf3af 1270{
1271 // WUPB command (including CRC)
1272 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
6fc68747 1273 static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 };
a62bf3af 1274 // ATTRIB command (with space for CRC)
6fc68747 1275 uint8_t attrib[] = { ISO14443B_ATTRIB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
a62bf3af 1276
6fc68747 1277 // temp to calc crc.
1278 uint8_t crc[2] = {0x00, 0x00};
1279
a62bf3af 1280 // first, wake up the tag
1281 CodeAndTransmit14443bAsReader(wupb, sizeof(wupb));
dccddaef 1282 GetTagSamplesFor14443bDemod(); //select_card
6fc68747 1283
a62bf3af 1284 // ATQB too short?
6fc68747 1285 if (Demod.len < 14) return 2;
1286
1287 // VALIDATE CRC
1288 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1289 if ( crc[0] != Demod.output[12] || crc[1] != Demod.output[13] )
1290 return 3;
1291
1292 if (card) {
1293 card->uidlen = 4;
1294 memcpy(card->uid, Demod.output+1, 4);
1295 memcpy(card->atqb, Demod.output+5, 7);
1296 }
a62bf3af 1297
11c2df83 1298 // copy the PUPI to ATTRIB ( PUPI == UID )
a62bf3af 1299 memcpy(attrib + 1, Demod.output + 1, 4);
6fc68747 1300
1301 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
a62bf3af 1302 attrib[7] = Demod.output[10] & 0x0F;
1303 ComputeCrc14443(CRC_14443_B, attrib, 9, attrib + 9, attrib + 10);
6fc68747 1304
a62bf3af 1305 CodeAndTransmit14443bAsReader(attrib, sizeof(attrib));
dccddaef 1306 GetTagSamplesFor14443bDemod();//select_card
6fc68747 1307
a62bf3af 1308 // Answer to ATTRIB too short?
6fc68747 1309 if(Demod.len < 3) return 2;
1310
1311 // VALIDATE CRC
1312 ComputeCrc14443(CRC_14443_B, Demod.output, Demod.len-2, &crc[0], &crc[1]);
1313 if ( crc[0] != Demod.output[1] || crc[1] != Demod.output[2] )
1314 return 3;
29f8c2cc 1315
65cdf0e3 1316 if (card) {
29f8c2cc 1317
1318 // CID
65cdf0e3 1319 card->cid = Demod.output[0];
29f8c2cc 1320
1321 // MAX FRAME
1322 uint16_t maxFrame = card->atqb[5] >> 4;
1323 if (maxFrame < 5) maxFrame = 8 * maxFrame + 16;
1324 else if (maxFrame == 5) maxFrame = 64;
1325 else if (maxFrame == 6) maxFrame = 96;
1326 else if (maxFrame == 7) maxFrame = 128;
1327 else if (maxFrame == 8) maxFrame = 256;
1328 else maxFrame = 257;
1329 iso14b_set_maxframesize(maxFrame);
1330
1331 // FWT
65cdf0e3 1332 uint8_t fwt = card->atqb[6] >> 4;
1333 if ( fwt < 16 ){
1334 uint32_t fwt_time = (302 << fwt);
1335 iso14b_set_timeout( fwt_time);
1336 }
11c2df83 1337 }
a62bf3af 1338 // reset PCB block number
1339 pcb_blocknum = 0;
6fc68747 1340 return 0;
a62bf3af 1341}
1342
1343// Set up ISO 14443 Type B communication (similar to iso14443a_setup)
11c2df83 1344// field is setup for "Sending as Reader"
a62bf3af 1345void iso14443b_setup() {
11c2df83 1346 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup Enter");
1347 LEDsoff();
a62bf3af 1348 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
11c2df83 1349 //BigBuf_free();
1350 //BigBuf_Clear_ext(false);
ff3e0744 1351
11c2df83 1352 // Initialize Demod and Uart structs
1353 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1354 UartInit(BigBuf_malloc(MAX_FRAME_SIZE));
cef590d9 1355
a62bf3af 1356 // connect Demodulated Signal to ADC:
1357 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1358
11c2df83 1359 // Set up the synchronous serial port
1360 FpgaSetupSsc();
1361
a62bf3af 1362 // Signal field is on with the appropriate LED
a62bf3af 1363 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
11c2df83 1364 SpinDelay(100);
a62bf3af 1365
1366 // Start the timer
ff3e0744 1367 StartCountSspClk();
11c2df83 1368
1369 LED_D_ON();
1370 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup Exit");
a62bf3af 1371}
489ef36c 1372
1373//-----------------------------------------------------------------------------
abb21530 1374// Read a SRI512 ISO 14443B tag.
489ef36c 1375//
1376// SRI512 tags are just simple memory tags, here we're looking at making a dump
1377// of the contents of the memory. No anticollision algorithm is done, we assume
1378// we have a single tag in the field.
1379//
1380// I tried to be systematic and check every answer of the tag, every CRC, etc...
1381//-----------------------------------------------------------------------------
6fc68747 1382void ReadSTMemoryIso14443b(uint8_t numofblocks)
489ef36c 1383{
17ad0e09 1384 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
489ef36c 1385
489ef36c 1386 // Make sure that we start from off, since the tags are stateful;
1387 // confusing things will happen if we don't reset them between reads.
11c2df83 1388 switch_off(); // before ReadStMemory
1389
1390 set_tracing(TRUE);
1391
1392 uint8_t i = 0x00;
99cf19d9 1393
489ef36c 1394 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1395 FpgaSetupSsc();
1396
1397 // Now give it time to spin up.
1398 // Signal field is on with the appropriate LED
1399 LED_D_ON();
22e24700 1400 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
11c2df83 1401 SpinDelay(20);
489ef36c 1402
1403 // First command: wake up the tag using the INITIATE command
6fc68747 1404 uint8_t cmd1[] = {ISO14443B_INITIATE, 0x00, 0x97, 0x5b};
11c2df83 1405 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); //no
dccddaef 1406 GetTagSamplesFor14443bDemod(); // no
489ef36c 1407
1408 if (Demod.len == 0) {
22e24700 1409 DbpString("No response from tag");
5ee53a0e 1410 set_tracing(FALSE);
22e24700 1411 return;
489ef36c 1412 } else {
705bfa10 1413 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1414 Demod.output[0], Demod.output[1], Demod.output[2]);
489ef36c 1415 }
705bfa10 1416
489ef36c 1417 // There is a response, SELECT the uid
1418 DbpString("Now SELECT tag:");
6fc68747 1419 cmd1[0] = ISO14443B_SELECT; // 0x0E is SELECT
489ef36c 1420 cmd1[1] = Demod.output[0];
1421 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
11c2df83 1422 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); //no
dccddaef 1423 GetTagSamplesFor14443bDemod(); //no
489ef36c 1424 if (Demod.len != 3) {
22e24700 1425 Dbprintf("Expected 3 bytes from tag, got %d", Demod.len);
5ee53a0e 1426 set_tracing(FALSE);
22e24700 1427 return;
489ef36c 1428 }
1429 // Check the CRC of the answer:
1430 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
1431 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
22e24700 1432 DbpString("CRC Error reading select response.");
5ee53a0e 1433 set_tracing(FALSE);
22e24700 1434 return;
489ef36c 1435 }
1436 // Check response from the tag: should be the same UID as the command we just sent:
1437 if (cmd1[1] != Demod.output[0]) {
22e24700 1438 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1[1], Demod.output[0]);
5ee53a0e 1439 set_tracing(FALSE);
22e24700 1440 return;
489ef36c 1441 }
705bfa10 1442
489ef36c 1443 // Tag is now selected,
1444 // First get the tag's UID:
6fc68747 1445 cmd1[0] = ISO14443B_GET_UID;
489ef36c 1446 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
11c2df83 1447 CodeAndTransmit14443bAsReader(cmd1, 3); // no -- Only first three bytes for this one
dccddaef 1448 GetTagSamplesFor14443bDemod(); //no
489ef36c 1449 if (Demod.len != 10) {
22e24700 1450 Dbprintf("Expected 10 bytes from tag, got %d", Demod.len);
5ee53a0e 1451 set_tracing(FALSE);
22e24700 1452 return;
489ef36c 1453 }
1454 // The check the CRC of the answer (use cmd1 as temporary variable):
1455 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
51d4f6f1 1456 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
22e24700 1457 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
705bfa10 1458 (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]);
489ef36c 1459 // Do not return;, let's go on... (we should retry, maybe ?)
1460 }
1461 Dbprintf("Tag UID (64 bits): %08x %08x",
705bfa10 1462 (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4],
1463 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]);
489ef36c 1464
1465 // Now loop to read all 16 blocks, address from 0 to last block
6fc68747 1466 Dbprintf("Tag memory dump, block 0 to %d", numofblocks);
489ef36c 1467 cmd1[0] = 0x08;
1468 i = 0x00;
6fc68747 1469 ++numofblocks;
1470
489ef36c 1471 for (;;) {
6fc68747 1472 if (i == numofblocks) {
489ef36c 1473 DbpString("System area block (0xff):");
1474 i = 0xff;
1475 }
1476 cmd1[1] = i;
1477 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
11c2df83 1478 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); //no
dccddaef 1479 GetTagSamplesFor14443bDemod(); //no
6fc68747 1480
489ef36c 1481 if (Demod.len != 6) { // Check if we got an answer from the tag
6fc68747 1482 DbpString("Expected 6 bytes from tag, got less...");
1483 return;
489ef36c 1484 }
1485 // The check the CRC of the answer (use cmd1 as temporary variable):
1486 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
1487 if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
132a0217 1488 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
705bfa10 1489 (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]);
489ef36c 1490 // Do not return;, let's go on... (we should retry, maybe ?)
1491 }
1492 // Now print out the memory location:
22e24700 1493 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i,
705bfa10 1494 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0],
17ad0e09 1495 (Demod.output[4]<<8)+Demod.output[5]);
6fc68747 1496
1497 if (i == 0xff) break;
1498 ++i;
489ef36c 1499 }
5ee53a0e 1500
1501 set_tracing(FALSE);
489ef36c 1502}
1503
11c2df83 1504
1505static void iso1444b_setup_snoop(void){
1506 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup_snoop Enter");
1507 LEDsoff();
1508 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1509 BigBuf_free();
1510 BigBuf_Clear_ext(false);
1511 clear_trace();//setup snoop
1512 set_tracing(TRUE);
1513
1514 // Initialize Demod and Uart structs
1515 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1516 UartInit(BigBuf_malloc(MAX_FRAME_SIZE));
1517
1518 if (MF_DBGLEVEL > 1) {
1519 // Print debug information about the buffer sizes
1520 Dbprintf("Snooping buffers initialized:");
1521 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1522 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE);
1523 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE);
1524 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE);
1525 }
1526
1527 // connect Demodulated Signal to ADC:
1528 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1529
1530 // Setup for the DMA.
1531 FpgaSetupSsc();
1532
1533 // Set FPGA in the appropriate mode
1534 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP);
1535 SpinDelay(20);
1536
1537 // Start the SSP timer
1538 StartCountSspClk();
1539 if (MF_DBGLEVEL > 3) Dbprintf("iso1443b_setup_snoop Exit");
1540}
1541
489ef36c 1542//=============================================================================
1543// Finally, the `sniffer' combines elements from both the reader and
1544// simulated tag, to show both sides of the conversation.
1545//=============================================================================
1546
1547//-----------------------------------------------------------------------------
1548// Record the sequence of commands sent by the reader to the tag, with
1549// triggering so that we start recording at the point that the tag is moved
1550// near the reader.
1551//-----------------------------------------------------------------------------
1552/*
1553 * Memory usage for this function, (within BigBuf)
47286d89 1554 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1555 * Last Received command (tag->reader) - MAX_FRAME_SIZE
705bfa10 1556 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
47286d89 1557 * Demodulated samples received - all the rest
489ef36c 1558 */
11c2df83 1559void RAMFUNC SnoopIso14443b(void) {
1560
1561 uint32_t time_0 = 0, time_start = 0, time_stop = 0;
d8b7a5f2 1562 int ci = 0, cq = 0;
1563 int lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
1564
489ef36c 1565 // We won't start recording the frames that we acquire until we trigger;
1566 // a good trigger condition to get started is probably when we see a
1567 // response from the tag.
d8b7a5f2 1568 bool triggered = TRUE; // TODO: set and evaluate trigger condition
f53020e7 1569 bool TagIsActive = FALSE;
1570 bool ReaderIsActive = FALSE;
11c2df83 1571
1572 iso1444b_setup_snoop();
1573
1574 // The DMA buffer, used to stream samples from the FPGA
1575 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE);
1576 int8_t *upTo = dmaBuf;
1577
1578 // Setup and start DMA.
1579 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE) ){
1580 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1581 BigBuf_free();
1582 return;
1583 }
1584
1585 time_0 = GetCountSspClk();
489ef36c 1586
1587 // And now we loop, receiving samples.
1588 for(;;) {
abb21530 1589
11c2df83 1590 WDT_HIT();
489ef36c 1591
1592 ci = upTo[0];
1593 cq = upTo[1];
d8b7a5f2 1594 upTo += 2;
489ef36c 1595 lastRxCounter -= 2;
11c2df83 1596
1597 if (upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) {
489ef36c 1598 upTo = dmaBuf;
b8622518 1599 lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
489ef36c 1600 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
705bfa10 1601 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE;
d8b7a5f2 1602
1603 if (!tracing) {
1604 if (MF_DBGLEVEL >= 2) DbpString("Trace full");
abb21530 1605 break;
1606 }
11c2df83 1607
d8b7a5f2 1608 if (BUTTON_PRESS()) {
1609 if (MF_DBGLEVEL >= 2) DbpString("cancelled");
abb21530 1610 break;
1611 }
489ef36c 1612 }
11c2df83 1613
1614 if (!TagIsActive) {
1615
1616 LED_A_ON();
1617
1618 // no need to try decoding reader data if the tag is sending
1619 if (Handle14443bReaderUartBit(ci & 0x01)) {
489ef36c 1620
b8622518 1621 time_stop = GetCountSspClk() - time_0;
11c2df83 1622
1623 if (triggered)
1624 LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, NULL, TRUE);
6fc68747 1625
810f5379 1626 /* And ready to receive another command. */
1627 UartReset();
1628 /* And also reset the demod code, which might have been */
1629 /* false-triggered by the commands from the reader. */
1630 DemodReset();
11c2df83 1631 } else {
b8622518 1632 time_start = GetCountSspClk() - time_0;
489ef36c 1633 }
6fc68747 1634
11c2df83 1635 if (Handle14443bReaderUartBit(cq & 0x01)) {
1636
b8622518 1637 time_stop = GetCountSspClk() - time_0;
11c2df83 1638
1639 if (triggered)
1640 LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, NULL, TRUE);
6fc68747 1641
810f5379 1642 /* And ready to receive another command. */
1643 UartReset();
1644 /* And also reset the demod code, which might have been */
1645 /* false-triggered by the commands from the reader. */
1646 DemodReset();
11c2df83 1647 } else {
b8622518 1648 time_start = GetCountSspClk() - time_0;
6fc68747 1649 }
36f84d47 1650 ReaderIsActive = (Uart.state > STATE_GOT_FALLING_EDGE_OF_SOF);
11c2df83 1651 LED_A_OFF();
47286d89 1652 }
11c2df83 1653
d8b7a5f2 1654 if (!ReaderIsActive) {
11c2df83 1655 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
d8af608f 1656 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
d8b7a5f2 1657 // LSB is a fpga signal bit.
1658 if (Handle14443bTagSamplesDemod(ci >> 1, cq >> 1)) {
11c2df83 1659
b8622518 1660 time_stop = GetCountSspClk() - time_0;
11c2df83 1661
1662 LogTrace(Demod.output, Demod.len, time_start, time_stop, NULL, FALSE);
489ef36c 1663
810f5379 1664 triggered = TRUE;
1665
1666 // And ready to receive another response.
1667 DemodReset();
11c2df83 1668 } else {
b8622518 1669 time_start = GetCountSspClk() - time_0;
810f5379 1670 }
22e24700 1671 TagIsActive = (Demod.state > DEMOD_GOT_FALLING_EDGE_OF_SOF);
47286d89 1672 }
489ef36c 1673 }
abb21530 1674
11c2df83 1675 switch_off(); // Snoop
810f5379 1676
489ef36c 1677 DbpString("Snoop statistics:");
11c2df83 1678 Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart.state, Uart.byteCnt, Uart.byteCntMax);
489ef36c 1679 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
11c2df83 1680
1681 // free mem refs.
d8b7a5f2 1682 if ( upTo ) upTo = NULL;
c3e8413c 1683
11c2df83 1684 // Uart.byteCntMax should be set with ATQB value..
489ef36c 1685}
1686
6fc68747 1687void iso14b_set_trigger(bool enable) {
1688 trigger = enable;
1689}
489ef36c 1690
1691/*
1692 * Send raw command to tag ISO14443B
1693 * @Input
6fc68747 1694 * param flags enum ISO14B_COMMAND. (mifare.h)
1695 * len len of buffer data
1696 * data buffer with bytes to send
489ef36c 1697 *
1698 * @Output
1699 * none
1700 *
1701 */
6fc68747 1702void SendRawCommand14443B_Ex(UsbCommand *c)
489ef36c 1703{
6fc68747 1704 iso14b_command_t param = c->arg[0];
1705 size_t len = c->arg[1] & 0xffff;
1706 uint8_t *cmd = c->d.asBytes;
1707 uint8_t status = 0;
1708 uint32_t sendlen = sizeof(iso14b_card_select_t);
1709 uint8_t buf[USB_CMD_DATA_SIZE] = {0x00};
1710
11c2df83 1711 if (MF_DBGLEVEL > 3) Dbprintf("14b raw: param, %04x", param );
b10a759f 1712
6fc68747 1713 // turn on trigger (LED_A)
11c2df83 1714 if ((param & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER)
6fc68747 1715 iso14b_set_trigger(TRUE);
1716
11c2df83 1717 if ((param & ISO14B_CONNECT) == ISO14B_CONNECT) {
6fc68747 1718 // Make sure that we start from off, since the tags are stateful;
1719 // confusing things will happen if we don't reset them between reads.
11c2df83 1720 //switch_off(); // before connect in raw
6fc68747 1721 iso14443b_setup();
99cf19d9 1722 }
6fc68747 1723
1724 set_tracing(TRUE);
489ef36c 1725
11c2df83 1726 if ((param & ISO14B_SELECT_STD) == ISO14B_SELECT_STD) {
6fc68747 1727 iso14b_card_select_t *card = (iso14b_card_select_t*)buf;
1728 status = iso14443b_select_card(card);
1729 cmd_send(CMD_ACK, status, sendlen, 0, buf, sendlen);
1730 // 0: OK 2: attrib fail, 3:crc fail,
1731 if ( status > 0 ) return;
1732 }
1733
11c2df83 1734 if ((param & ISO14B_SELECT_SR) == ISO14B_SELECT_SR) {
6fc68747 1735 iso14b_card_select_t *card = (iso14b_card_select_t*)buf;
1736 status = iso14443b_select_srx_card(card);
1737 cmd_send(CMD_ACK, status, sendlen, 0, buf, sendlen);
1738 // 0: OK 2: attrib fail, 3:crc fail,
1739 if ( status > 0 ) return;
1740 }
1741
11c2df83 1742 if ((param & ISO14B_APDU) == ISO14B_APDU) {
6fc68747 1743 status = iso14443b_apdu(cmd, len, buf);
1744 cmd_send(CMD_ACK, status, status, 0, buf, status);
489ef36c 1745 }
abb21530 1746
11c2df83 1747 if ((param & ISO14B_RAW) == ISO14B_RAW) {
1748 if((param & ISO14B_APPEND_CRC) == ISO14B_APPEND_CRC) {
6fc68747 1749 AppendCrc14443b(cmd, len);
1750 len += 2;
1751 }
1752
11c2df83 1753 CodeAndTransmit14443bAsReader(cmd, len); // raw
dccddaef 1754 GetTagSamplesFor14443bDemod(); // raw
6fc68747 1755
1756 sendlen = MIN(Demod.len, USB_CMD_DATA_SIZE);
1757 status = (Demod.len > 0) ? 0 : 1;
1758 cmd_send(CMD_ACK, status, sendlen, 0, Demod.output, sendlen);
1759 }
1760
1761 // turn off trigger (LED_A)
11c2df83 1762 if ((param & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER)
1763 iso14b_set_trigger(FALSE);
6fc68747 1764
1765 // turn off antenna et al
1766 // we don't send a HALT command.
11c2df83 1767 if ((param & ISO14B_DISCONNECT) == ISO14B_DISCONNECT) {
6fc68747 1768 if (MF_DBGLEVEL > 3) Dbprintf("disconnect");
11c2df83 1769 switch_off(); // disconnect raw
1770 } else {
1771 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
489ef36c 1772 }
11c2df83 1773
6fc68747 1774}
Impressum, Datenschutz