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