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