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