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