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