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