]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443b.c
usb communication (device side) refactoring
[proxmark3-svn] / armsrc / iso14443b.c
CommitLineData
15c4dc5a 1//-----------------------------------------------------------------------------
bd20f8f4 2// Jonathan Westhues, split Nov 2006
6a5d4e17 3// piwi 2018
bd20f8f4 4//
5// This code is licensed to you under the terms of the GNU GPL, version 2 or,
6// at your option, any later version. See the LICENSE.txt file for the text of
7// the license.
8//-----------------------------------------------------------------------------
51d4f6f1 9// Routines to support ISO 14443B. This includes both the reader software and
10// the `fake tag' modes.
15c4dc5a 11//-----------------------------------------------------------------------------
bd20f8f4 12
fc52fbd4 13#include "iso14443b.h"
14
e30c654b 15#include "proxmark3.h"
15c4dc5a 16#include "apps.h"
867e10a5 17#include "usb_cdc.h"
f7e3ed82 18#include "util.h"
9ab7a6c7 19#include "string.h"
f7e3ed82 20#include "iso14443crc.h"
fc52fbd4 21#include "fpgaloader.h"
5ea2a248 22#include "BigBuf.h"
15c4dc5a 23
5ea2a248 24#define RECEIVE_SAMPLES_TIMEOUT 64 // TR0 max is 256/fs = 256/(848kHz) = 302us or 64 samples from FPGA
6a5d4e17 25#define ISO14443B_DMA_BUFFER_SIZE 128
0d9a86c7 26
4be27083
FM
27// PCB Block number for APDUs
28static uint8_t pcb_blocknum = 0;
29
15c4dc5a 30//=============================================================================
31// An ISO 14443 Type B tag. We listen for commands from the reader, using
32// a UART kind of thing that's implemented in software. When we get a
33// frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
34// If it's good, then we can do something appropriate with it, and send
35// a response.
36//=============================================================================
37
38//-----------------------------------------------------------------------------
39// Code up a string of octets at layer 2 (including CRC, we don't generate
40// that here) so that they can be transmitted to the reader. Doesn't transmit
41// them yet, just leaves them ready to send in ToSend[].
42//-----------------------------------------------------------------------------
f7e3ed82 43static void CodeIso14443bAsTag(const uint8_t *cmd, int len)
15c4dc5a 44{
7d5ebac9
MHS
45 int i;
46
47 ToSendReset();
48
49 // Transmit a burst of ones, as the initial thing that lets the
50 // reader get phase sync. This (TR1) must be > 80/fs, per spec,
51 // but tag that I've tried (a Paypass) exceeds that by a fair bit,
52 // so I will too.
53 for(i = 0; i < 20; i++) {
54 ToSendStuffBit(1);
55 ToSendStuffBit(1);
56 ToSendStuffBit(1);
57 ToSendStuffBit(1);
58 }
59
60 // Send SOF.
61 for(i = 0; i < 10; i++) {
62 ToSendStuffBit(0);
63 ToSendStuffBit(0);
64 ToSendStuffBit(0);
65 ToSendStuffBit(0);
66 }
67 for(i = 0; i < 2; i++) {
68 ToSendStuffBit(1);
69 ToSendStuffBit(1);
70 ToSendStuffBit(1);
71 ToSendStuffBit(1);
72 }
73
74 for(i = 0; i < len; i++) {
75 int j;
76 uint8_t b = cmd[i];
77
78 // Start bit
79 ToSendStuffBit(0);
80 ToSendStuffBit(0);
81 ToSendStuffBit(0);
82 ToSendStuffBit(0);
83
84 // Data bits
85 for(j = 0; j < 8; j++) {
86 if(b & 1) {
87 ToSendStuffBit(1);
88 ToSendStuffBit(1);
89 ToSendStuffBit(1);
90 ToSendStuffBit(1);
91 } else {
92 ToSendStuffBit(0);
93 ToSendStuffBit(0);
94 ToSendStuffBit(0);
95 ToSendStuffBit(0);
96 }
97 b >>= 1;
98 }
99
100 // Stop bit
101 ToSendStuffBit(1);
102 ToSendStuffBit(1);
103 ToSendStuffBit(1);
104 ToSendStuffBit(1);
105 }
106
51d4f6f1 107 // Send EOF.
7d5ebac9
MHS
108 for(i = 0; i < 10; i++) {
109 ToSendStuffBit(0);
110 ToSendStuffBit(0);
111 ToSendStuffBit(0);
112 ToSendStuffBit(0);
113 }
51d4f6f1 114 for(i = 0; i < 2; i++) {
7d5ebac9
MHS
115 ToSendStuffBit(1);
116 ToSendStuffBit(1);
117 ToSendStuffBit(1);
118 ToSendStuffBit(1);
119 }
120
121 // Convert from last byte pos to length
122 ToSendMax++;
15c4dc5a 123}
124
125//-----------------------------------------------------------------------------
126// The software UART that receives commands from the reader, and its state
127// variables.
128//-----------------------------------------------------------------------------
129static struct {
7d5ebac9
MHS
130 enum {
131 STATE_UNSYNCD,
132 STATE_GOT_FALLING_EDGE_OF_SOF,
133 STATE_AWAITING_START_BIT,
46734099 134 STATE_RECEIVING_DATA
7d5ebac9
MHS
135 } state;
136 uint16_t shiftReg;
137 int bitCnt;
138 int byteCnt;
139 int byteCntMax;
140 int posCnt;
141 uint8_t *output;
15c4dc5a 142} Uart;
143
144/* Receive & handle a bit coming from the reader.
51d4f6f1 145 *
146 * This function is called 4 times per bit (every 2 subcarrier cycles).
147 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
15c4dc5a 148 *
149 * LED handling:
150 * LED A -> ON once we have received the SOF and are expecting the rest.
151 * LED A -> OFF once we have received EOF or are in error state or unsynced
152 *
153 * Returns: true if we received a EOF
154 * false if we are still waiting for some more
155 */
46734099 156static RAMFUNC int Handle14443bUartBit(uint8_t bit)
15c4dc5a 157{
7d5ebac9 158 switch(Uart.state) {
03dc1740 159 case STATE_UNSYNCD:
7d5ebac9
MHS
160 if(!bit) {
161 // we went low, so this could be the beginning
162 // of an SOF
163 Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
164 Uart.posCnt = 0;
165 Uart.bitCnt = 0;
166 }
167 break;
168
169 case STATE_GOT_FALLING_EDGE_OF_SOF:
170 Uart.posCnt++;
51d4f6f1 171 if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
7d5ebac9 172 if(bit) {
51d4f6f1 173 if(Uart.bitCnt > 9) {
7d5ebac9
MHS
174 // we've seen enough consecutive
175 // zeros that it's a valid SOF
176 Uart.posCnt = 0;
177 Uart.byteCnt = 0;
178 Uart.state = STATE_AWAITING_START_BIT;
179 LED_A_ON(); // Indicate we got a valid SOF
180 } else {
181 // didn't stay down long enough
182 // before going high, error
46734099 183 Uart.state = STATE_UNSYNCD;
7d5ebac9
MHS
184 }
185 } else {
186 // do nothing, keep waiting
187 }
188 Uart.bitCnt++;
189 }
190 if(Uart.posCnt >= 4) Uart.posCnt = 0;
51d4f6f1 191 if(Uart.bitCnt > 12) {
7d5ebac9
MHS
192 // Give up if we see too many zeros without
193 // a one, too.
46734099 194 LED_A_OFF();
195 Uart.state = STATE_UNSYNCD;
7d5ebac9
MHS
196 }
197 break;
198
199 case STATE_AWAITING_START_BIT:
200 Uart.posCnt++;
201 if(bit) {
51d4f6f1 202 if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
7d5ebac9
MHS
203 // stayed high for too long between
204 // characters, error
46734099 205 Uart.state = STATE_UNSYNCD;
7d5ebac9
MHS
206 }
207 } else {
208 // falling edge, this starts the data byte
209 Uart.posCnt = 0;
210 Uart.bitCnt = 0;
211 Uart.shiftReg = 0;
212 Uart.state = STATE_RECEIVING_DATA;
7d5ebac9
MHS
213 }
214 break;
215
216 case STATE_RECEIVING_DATA:
217 Uart.posCnt++;
218 if(Uart.posCnt == 2) {
219 // time to sample a bit
220 Uart.shiftReg >>= 1;
221 if(bit) {
222 Uart.shiftReg |= 0x200;
223 }
224 Uart.bitCnt++;
225 }
226 if(Uart.posCnt >= 4) {
227 Uart.posCnt = 0;
228 }
229 if(Uart.bitCnt == 10) {
230 if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
231 {
232 // this is a data byte, with correct
233 // start and stop bits
234 Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
235 Uart.byteCnt++;
236
237 if(Uart.byteCnt >= Uart.byteCntMax) {
238 // Buffer overflowed, give up
46734099 239 LED_A_OFF();
240 Uart.state = STATE_UNSYNCD;
7d5ebac9
MHS
241 } else {
242 // so get the next byte now
243 Uart.posCnt = 0;
244 Uart.state = STATE_AWAITING_START_BIT;
245 }
46734099 246 } else if (Uart.shiftReg == 0x000) {
7d5ebac9
MHS
247 // this is an EOF byte
248 LED_A_OFF(); // Finished receiving
46734099 249 Uart.state = STATE_UNSYNCD;
132a0217 250 if (Uart.byteCnt != 0) {
44964fd1 251 return true;
132a0217 252 }
7d5ebac9
MHS
253 } else {
254 // this is an error
46734099 255 LED_A_OFF();
256 Uart.state = STATE_UNSYNCD;
7d5ebac9
MHS
257 }
258 }
259 break;
260
7d5ebac9 261 default:
46734099 262 LED_A_OFF();
7d5ebac9
MHS
263 Uart.state = STATE_UNSYNCD;
264 break;
265 }
266
44964fd1 267 return false;
15c4dc5a 268}
269
46734099 270
271static void UartReset()
272{
273 Uart.byteCntMax = MAX_FRAME_SIZE;
274 Uart.state = STATE_UNSYNCD;
275 Uart.byteCnt = 0;
276 Uart.bitCnt = 0;
277}
278
279
280static void UartInit(uint8_t *data)
281{
282 Uart.output = data;
283 UartReset();
284}
285
286
15c4dc5a 287//-----------------------------------------------------------------------------
288// Receive a command (from the reader to us, where we are the simulated tag),
289// and store it in the given buffer, up to the given maximum length. Keeps
290// spinning, waiting for a well-framed command, until either we get one
44964fd1 291// (returns true) or someone presses the pushbutton on the board (false).
15c4dc5a 292//
293// Assume that we're called with the SSC (to the FPGA) and ADC path set
294// correctly.
295//-----------------------------------------------------------------------------
46734099 296static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len)
15c4dc5a 297{
51d4f6f1 298 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
7d5ebac9
MHS
299 // only, since we are receiving, not transmitting).
300 // Signal field is off with the appropriate LED
301 LED_D_OFF();
302 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
303
7d5ebac9 304 // Now run a `software UART' on the stream of incoming samples.
46734099 305 UartInit(received);
7d5ebac9
MHS
306
307 for(;;) {
308 WDT_HIT();
309
44964fd1 310 if(BUTTON_PRESS()) return false;
7d5ebac9 311
7d5ebac9
MHS
312 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
313 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
46734099 314 for(uint8_t mask = 0x80; mask != 0x00; mask >>= 1) {
315 if(Handle14443bUartBit(b & mask)) {
7d5ebac9 316 *len = Uart.byteCnt;
44964fd1 317 return true;
7d5ebac9
MHS
318 }
319 }
320 }
321 }
bee99bbf 322
44964fd1 323 return false;
15c4dc5a 324}
325
326//-----------------------------------------------------------------------------
327// Main loop of simulated tag: receive commands from reader, decide what
328// response to send, and send it.
329//-----------------------------------------------------------------------------
51d4f6f1 330void SimulateIso14443bTag(void)
15c4dc5a 331{
ca8a3478 332 LED_A_ON();
14660057 333 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
334 static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // WUPB
335 // ... and REQB, AFI=0, Normal Request, N=1:
f3b83bee 336 static const uint8_t cmd2[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; // REQB
f3b83bee 337 // ... and HLTB
14660057 338 static const uint8_t cmd3[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB
f3b83bee 339 // ... and ATTRIB
14660057 340 static const uint8_t cmd4[] = { 0x1D, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
46734099 341
342 // ... and we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
51d4f6f1 343 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
344 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
7d5ebac9
MHS
345 static const uint8_t response1[] = {
346 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22,
347 0x00, 0x21, 0x85, 0x5e, 0xd7
348 };
f3b83bee 349 // response to HLTB and ATTRIB
350 static const uint8_t response2[] = {0x00, 0x78, 0xF0};
351
15c4dc5a 352
5f605b8f 353 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
354
46734099 355 clear_trace();
44964fd1 356 set_tracing(true);
46734099 357
358 const uint8_t *resp;
359 uint8_t *respCode;
360 uint16_t respLen, respCodeLen;
15c4dc5a 361
51d4f6f1 362 // allocate command receive buffer
363 BigBuf_free();
364 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
15c4dc5a 365
46734099 366 uint16_t len;
367 uint16_t cmdsRecvd = 0;
15c4dc5a 368
51d4f6f1 369 // prepare the (only one) tag answer:
7d5ebac9 370 CodeIso14443bAsTag(response1, sizeof(response1));
46734099 371 uint8_t *resp1Code = BigBuf_malloc(ToSendMax);
dd57061c 372 memcpy(resp1Code, ToSend, ToSendMax);
46734099 373 uint16_t resp1CodeLen = ToSendMax;
15c4dc5a 374
f3b83bee 375 // prepare the (other) tag answer:
376 CodeIso14443bAsTag(response2, sizeof(response2));
377 uint8_t *resp2Code = BigBuf_malloc(ToSendMax);
dd57061c 378 memcpy(resp2Code, ToSend, ToSendMax);
f3b83bee 379 uint16_t resp2CodeLen = ToSendMax;
380
7d5ebac9
MHS
381 // We need to listen to the high-frequency, peak-detected path.
382 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
6a5d4e17 383 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
15c4dc5a 384
7d5ebac9 385 cmdsRecvd = 0;
15c4dc5a 386
7d5ebac9 387 for(;;) {
15c4dc5a 388
46734099 389 if(!GetIso14443bCommandFromReader(receivedCmd, &len)) {
51d4f6f1 390 Dbprintf("button pressed, received %d commands", cmdsRecvd);
391 break;
46734099 392 }
7d5ebac9 393
d9de20fa 394 LogTrace(receivedCmd, len, 0, 0, NULL, true);
7d5ebac9 395
46734099 396 // Good, look at the command now.
397 if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0)
14660057 398 || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) {
dd57061c 399 resp = response1;
46734099 400 respLen = sizeof(response1);
dd57061c 401 respCode = resp1Code;
46734099 402 respCodeLen = resp1CodeLen;
14660057 403 } else if ( (len == sizeof(cmd3) && receivedCmd[0] == cmd3[0])
404 || (len == sizeof(cmd4) && receivedCmd[0] == cmd4[0]) ) {
dd57061c 405 resp = response2;
f3b83bee 406 respLen = sizeof(response2);
dd57061c 407 respCode = resp2Code;
f3b83bee 408 respCodeLen = resp2CodeLen;
7d5ebac9
MHS
409 } else {
410 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd);
411 // And print whether the CRC fails, just for good measure
46734099 412 uint8_t b1, b2;
f3b83bee 413 if (len >= 3){ // if crc exists
414 ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2);
415 if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) {
416 // Not so good, try again.
417 DbpString("+++CRC fail");
14660057 418
f3b83bee 419 } else {
420 DbpString("CRC passes");
421 }
7d5ebac9 422 }
f3b83bee 423 //get rid of compiler warning
424 respCodeLen = 0;
425 resp = response1;
426 respLen = 0;
427 respCode = resp1Code;
428 //don't crash at new command just wait and see if reader will send other new cmds.
429 //break;
7d5ebac9
MHS
430 }
431
7d5ebac9
MHS
432 cmdsRecvd++;
433
434 if(cmdsRecvd > 0x30) {
435 DbpString("many commands later...");
436 break;
437 }
438
46734099 439 if(respCodeLen <= 0) continue;
7d5ebac9
MHS
440
441 // Modulate BPSK
442 // Signal field is off with the appropriate LED
443 LED_D_OFF();
444 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
445 AT91C_BASE_SSC->SSC_THR = 0xff;
6a5d4e17 446 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
7d5ebac9
MHS
447
448 // Transmit the response.
46734099 449 uint16_t i = 0;
7d5ebac9
MHS
450 for(;;) {
451 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
46734099 452 uint8_t b = respCode[i];
7d5ebac9
MHS
453
454 AT91C_BASE_SSC->SSC_THR = b;
455
456 i++;
46734099 457 if(i > respCodeLen) {
7d5ebac9
MHS
458 break;
459 }
460 }
461 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
462 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
463 (void)b;
464 }
465 }
dd57061c 466
46734099 467 // trace the response:
d9de20fa 468 LogTrace(resp, respLen, 0, 0, NULL, false);
dd57061c 469
7d5ebac9 470 }
ca8a3478 471
472 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
473 LED_A_OFF();
15c4dc5a 474}
475
476//=============================================================================
477// An ISO 14443 Type B reader. We take layer two commands, code them
478// appropriately, and then send them to the tag. We then listen for the
479// tag's response, which we leave in the buffer to be demodulated on the
480// PC side.
481//=============================================================================
482
483static struct {
7d5ebac9
MHS
484 enum {
485 DEMOD_UNSYNCD,
486 DEMOD_PHASE_REF_TRAINING,
487 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
488 DEMOD_GOT_FALLING_EDGE_OF_SOF,
489 DEMOD_AWAITING_START_BIT,
46734099 490 DEMOD_RECEIVING_DATA
7d5ebac9
MHS
491 } state;
492 int bitCount;
493 int posCount;
494 int thisBit;
51d4f6f1 495/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
7d5ebac9
MHS
496 int metric;
497 int metricN;
51d4f6f1 498*/
7d5ebac9
MHS
499 uint16_t shiftReg;
500 uint8_t *output;
501 int len;
502 int sumI;
503 int sumQ;
15c4dc5a 504} Demod;
505
506/*
507 * Handles reception of a bit from the tag
508 *
51d4f6f1 509 * This function is called 2 times per bit (every 4 subcarrier cycles).
510 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
511 *
15c4dc5a 512 * LED handling:
513 * LED C -> ON once we have received the SOF and are expecting the rest.
514 * LED C -> OFF once we have received EOF or are unsynced
515 *
516 * Returns: true if we received a EOF
517 * false if we are still waiting for some more
518 *
519 */
51d4f6f1 520static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq)
15c4dc5a 521{
7d5ebac9 522 int v;
15c4dc5a 523
51d4f6f1 524// The soft decision on the bit uses an estimate of just the
525// quadrant of the reference angle, not the exact angle.
15c4dc5a 526#define MAKE_SOFT_DECISION() { \
7d5ebac9
MHS
527 if(Demod.sumI > 0) { \
528 v = ci; \
529 } else { \
530 v = -ci; \
531 } \
532 if(Demod.sumQ > 0) { \
533 v += cq; \
534 } else { \
535 v -= cq; \
536 } \
537 }
15c4dc5a 538
51d4f6f1 539#define SUBCARRIER_DETECT_THRESHOLD 8
540
51d4f6f1 541// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
6a5d4e17 542#define AMPLITUDE(ci,cq) (MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2))
7d5ebac9
MHS
543 switch(Demod.state) {
544 case DEMOD_UNSYNCD:
6a5d4e17 545 if(AMPLITUDE(ci,cq) > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
7d5ebac9 546 Demod.state = DEMOD_PHASE_REF_TRAINING;
51d4f6f1 547 Demod.sumI = ci;
548 Demod.sumQ = cq;
549 Demod.posCount = 1;
550 }
7d5ebac9
MHS
551 break;
552
553 case DEMOD_PHASE_REF_TRAINING:
554 if(Demod.posCount < 8) {
6a5d4e17 555 if (AMPLITUDE(ci,cq) > SUBCARRIER_DETECT_THRESHOLD) {
51d4f6f1 556 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
557 // note: synchronization time > 80 1/fs
558 Demod.sumI += ci;
559 Demod.sumQ += cq;
560 Demod.posCount++;
561 } else { // subcarrier lost
562 Demod.state = DEMOD_UNSYNCD;
7d5ebac9 563 }
51d4f6f1 564 } else {
565 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
7d5ebac9 566 }
7d5ebac9
MHS
567 break;
568
569 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
570 MAKE_SOFT_DECISION();
51d4f6f1 571 if(v < 0) { // logic '0' detected
7d5ebac9 572 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
51d4f6f1 573 Demod.posCount = 0; // start of SOF sequence
7d5ebac9 574 } else {
51d4f6f1 575 if(Demod.posCount > 200/4) { // maximum length of TR1 = 200 1/fs
7d5ebac9
MHS
576 Demod.state = DEMOD_UNSYNCD;
577 }
578 }
579 Demod.posCount++;
580 break;
581
582 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
51d4f6f1 583 Demod.posCount++;
7d5ebac9
MHS
584 MAKE_SOFT_DECISION();
585 if(v > 0) {
51d4f6f1 586 if(Demod.posCount < 9*2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
7d5ebac9
MHS
587 Demod.state = DEMOD_UNSYNCD;
588 } else {
589 LED_C_ON(); // Got SOF
7d5ebac9 590 Demod.posCount = 0;
a3bef986 591 Demod.bitCount = 0;
7d5ebac9 592 Demod.len = 0;
a3bef986 593 Demod.state = DEMOD_AWAITING_START_BIT;
51d4f6f1 594/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
7d5ebac9
MHS
595 Demod.metricN = 0;
596 Demod.metric = 0;
51d4f6f1 597*/
7d5ebac9
MHS
598 }
599 } else {
51d4f6f1 600 if(Demod.posCount > 12*2) { // low phase of SOF too long (> 12 etu)
7d5ebac9 601 Demod.state = DEMOD_UNSYNCD;
09c66f1f 602 LED_C_OFF();
7d5ebac9
MHS
603 }
604 }
7d5ebac9
MHS
605 break;
606
607 case DEMOD_AWAITING_START_BIT:
51d4f6f1 608 Demod.posCount++;
7d5ebac9 609 MAKE_SOFT_DECISION();
a3bef986 610 if (v > 0) {
611 if (Demod.posCount > 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
09c66f1f 612 LED_C_OFF();
a3bef986 613 if (Demod.bitCount == 0 && Demod.len == 0) { // received SOF only, this is valid for iClass/Picopass
614 return true;
615 } else {
616 Demod.state = DEMOD_UNSYNCD;
617 }
7d5ebac9 618 }
51d4f6f1 619 } else { // start bit detected
51d4f6f1 620 Demod.posCount = 1; // this was the first half
7d5ebac9
MHS
621 Demod.thisBit = v;
622 Demod.shiftReg = 0;
623 Demod.state = DEMOD_RECEIVING_DATA;
624 }
625 break;
626
627 case DEMOD_RECEIVING_DATA:
628 MAKE_SOFT_DECISION();
a3bef986 629 if (Demod.posCount == 0) { // first half of bit
7d5ebac9
MHS
630 Demod.thisBit = v;
631 Demod.posCount = 1;
51d4f6f1 632 } else { // second half of bit
7d5ebac9
MHS
633 Demod.thisBit += v;
634
51d4f6f1 635/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
7d5ebac9
MHS
636 if(Demod.thisBit > 0) {
637 Demod.metric += Demod.thisBit;
638 } else {
639 Demod.metric -= Demod.thisBit;
640 }
641 (Demod.metricN)++;
dd57061c 642*/
7d5ebac9
MHS
643
644 Demod.shiftReg >>= 1;
a3bef986 645 if (Demod.thisBit > 0) { // logic '1'
7d5ebac9
MHS
646 Demod.shiftReg |= 0x200;
647 }
648
649 Demod.bitCount++;
a3bef986 650 if (Demod.bitCount == 10) {
7d5ebac9 651 uint16_t s = Demod.shiftReg;
a3bef986 652 if ((s & 0x200) && !(s & 0x001)) { // stop bit == '1', start bit == '0'
7d5ebac9
MHS
653 uint8_t b = (s >> 1);
654 Demod.output[Demod.len] = b;
655 Demod.len++;
a3bef986 656 Demod.bitCount = 0;
7d5ebac9 657 Demod.state = DEMOD_AWAITING_START_BIT;
7d5ebac9
MHS
658 } else {
659 Demod.state = DEMOD_UNSYNCD;
09c66f1f 660 LED_C_OFF();
a3bef986 661 if (s == 0x000) {
51d4f6f1 662 // This is EOF (start, stop and all data bits == '0'
44964fd1 663 return true;
09c66f1f 664 }
7d5ebac9
MHS
665 }
666 }
667 Demod.posCount = 0;
668 }
669 break;
670
671 default:
672 Demod.state = DEMOD_UNSYNCD;
09c66f1f 673 LED_C_OFF();
7d5ebac9
MHS
674 break;
675 }
676
44964fd1 677 return false;
7d5ebac9 678}
67ac4bf7 679
680
aeadbdb2
MHS
681static void DemodReset()
682{
683 // Clear out the state of the "UART" that receives from the tag.
aeadbdb2
MHS
684 Demod.len = 0;
685 Demod.state = DEMOD_UNSYNCD;
51d4f6f1 686 Demod.posCount = 0;
aeadbdb2 687 memset(Demod.output, 0x00, MAX_FRAME_SIZE);
7d5ebac9 688}
67ac4bf7 689
690
7d5ebac9
MHS
691static void DemodInit(uint8_t *data)
692{
693 Demod.output = data;
694 DemodReset();
aeadbdb2
MHS
695}
696
67ac4bf7 697
15c4dc5a 698/*
355c8b4a 699 * Demodulate the samples we received from the tag, also log to tracebuffer
44964fd1 700 * quiet: set to 'true' to disable debug output
15c4dc5a 701 */
a3bef986 702static int GetSamplesFor14443bDemod(int timeout, bool quiet) {
703 int ret = 0;
6a5d4e17 704 int maxBehindBy = 0;
44964fd1 705 bool gotFrame = false;
6a5d4e17 706 int lastRxCounter, samples = 0;
707 int8_t ci, cq;
708
7d5ebac9
MHS
709 // Allocate memory from BigBuf for some buffers
710 // free all previous allocations first
711 BigBuf_free();
dd57061c 712
7d5ebac9
MHS
713 // The response (tag -> reader) that we're receiving.
714 uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE);
dd57061c 715
7d5ebac9 716 // The DMA buffer, used to stream samples from the FPGA
6a5d4e17 717 uint16_t *dmaBuf = (uint16_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE * sizeof(uint16_t));
15c4dc5a 718
7d5ebac9
MHS
719 // Set up the demodulator for tag -> reader responses.
720 DemodInit(receivedResponse);
15c4dc5a 721
6a5d4e17 722 // wait for last transfer to complete
723 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY))
724
7d5ebac9 725 // Setup and start DMA.
5ea2a248 726 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
705bfa10 727 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE);
15c4dc5a 728
6a5d4e17 729 uint16_t *upTo = dmaBuf;
705bfa10 730 lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
15c4dc5a 731
7d5ebac9 732 // Signal field is ON with the appropriate LED:
51d4f6f1 733 LED_D_ON();
7d5ebac9 734 // And put the FPGA in the appropriate mode
5ea2a248 735 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_848_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
15c4dc5a 736
7d5ebac9 737 for(;;) {
6a5d4e17 738 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & (ISO14443B_DMA_BUFFER_SIZE-1);
739 if(behindBy > maxBehindBy) {
740 maxBehindBy = behindBy;
741 }
15c4dc5a 742
6a5d4e17 743 if(behindBy < 1) continue;
15c4dc5a 744
6a5d4e17 745 ci = *upTo >> 8;
746 cq = *upTo;
747 upTo++;
748 lastRxCounter--;
749 if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
750 upTo = dmaBuf; // start reading the circular buffer from the beginning
751 lastRxCounter += ISO14443B_DMA_BUFFER_SIZE;
752 }
753 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
754 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
755 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; // DMA Next Counter registers
756 }
757 samples++;
758
a3bef986 759 if (Handle14443bSamplesDemod(ci, cq)) {
760 ret = Demod.len;
6a5d4e17 761 gotFrame = true;
762 break;
7d5ebac9 763 }
15c4dc5a 764
5ea2a248 765 if(samples > timeout && Demod.state < DEMOD_PHASE_REF_TRAINING) {
a3bef986 766 ret = -1;
5ea2a248 767 LED_C_OFF();
7d5ebac9
MHS
768 break;
769 }
770 }
51d4f6f1 771
6a5d4e17 772 FpgaDisableSscDma();
51d4f6f1 773
6a5d4e17 774 if (!quiet) Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", maxBehindBy, samples, gotFrame, Demod.len, Demod.sumI, Demod.sumQ);
a3bef986 775
776 if (ret < 0) {
777 return ret;
355c8b4a 778 }
a3bef986 779 //Tracing
780 LogTrace(Demod.output, Demod.len, 0, 0, NULL, false);
781
782 return ret;
15c4dc5a 783}
784
67ac4bf7 785
15c4dc5a 786//-----------------------------------------------------------------------------
787// Transmit the command (to the tag) that was placed in ToSend[].
788//-----------------------------------------------------------------------------
51d4f6f1 789static void TransmitFor14443b(void)
15c4dc5a 790{
5ea2a248 791 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_SHALLOW_MOD);
15c4dc5a 792 LED_B_ON();
5ea2a248 793 for(int c = 0; c < ToSendMax; c++) {
794 uint8_t data = ToSend[c];
795 for (int i = 0; i < 8; i++) {
796 uint16_t send_word = (data & 0x80) ? 0x0000 : 0xffff;
797 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
798 AT91C_BASE_SSC->SSC_THR = send_word;
799 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
800 AT91C_BASE_SSC->SSC_THR = send_word;
801 data <<= 1;
7d5ebac9 802 }
7d5ebac9
MHS
803 WDT_HIT();
804 }
5ea2a248 805 LED_B_OFF();
15c4dc5a 806}
807
67ac4bf7 808
15c4dc5a 809//-----------------------------------------------------------------------------
810// Code a layer 2 command (string of octets, including CRC) into ToSend[],
51d4f6f1 811// so that it is ready to transmit to the tag using TransmitFor14443b().
15c4dc5a 812//-----------------------------------------------------------------------------
7cf3ef20 813static void CodeIso14443bAsReader(const uint8_t *cmd, int len)
15c4dc5a 814{
7d5ebac9
MHS
815 int i, j;
816 uint8_t b;
817
818 ToSendReset();
819
7d5ebac9
MHS
820 // Send SOF
821 for(i = 0; i < 10; i++) {
822 ToSendStuffBit(0);
823 }
6a5d4e17 824 ToSendStuffBit(1);
825 ToSendStuffBit(1);
7d5ebac9
MHS
826
827 for(i = 0; i < len; i++) {
7d5ebac9
MHS
828 // Start bit
829 ToSendStuffBit(0);
830 // Data bits
831 b = cmd[i];
832 for(j = 0; j < 8; j++) {
833 if(b & 1) {
834 ToSendStuffBit(1);
835 } else {
836 ToSendStuffBit(0);
837 }
838 b >>= 1;
839 }
6a5d4e17 840 // Stop bit
841 ToSendStuffBit(1);
7d5ebac9 842 }
6a5d4e17 843
7d5ebac9 844 // Send EOF
7d5ebac9
MHS
845 for(i = 0; i < 10; i++) {
846 ToSendStuffBit(0);
847 }
6a5d4e17 848 ToSendStuffBit(1);
7d5ebac9 849
6a5d4e17 850 // ensure that last byte is filled up
851 for(i = 0; i < 8; i++) {
7d5ebac9
MHS
852 ToSendStuffBit(1);
853 }
854
855 // Convert from last character reference to length
856 ToSendMax++;
15c4dc5a 857}
858
67ac4bf7 859
355c8b4a
MHS
860/**
861 Convenience function to encode, transmit and trace iso 14443b comms
862 **/
863static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len)
864{
865 CodeIso14443bAsReader(cmd, len);
51d4f6f1 866 TransmitFor14443b();
d9de20fa 867 LogTrace(cmd,len, 0, 0, NULL, true);
355c8b4a
MHS
868}
869
4be27083
FM
870/* Sends an APDU to the tag
871 * TODO: check CRC and preamble
872 */
a3bef986 873int iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response) {
ca8a3478 874 LED_A_ON();
4be27083
FM
875 uint8_t message_frame[message_length + 4];
876 // PCB
877 message_frame[0] = 0x0A | pcb_blocknum;
878 pcb_blocknum ^= 1;
879 // CID
880 message_frame[1] = 0;
881 // INF
882 memcpy(message_frame + 2, message, message_length);
883 // EDC (CRC)
884 ComputeCrc14443(CRC_14443_B, message_frame, message_length + 2, &message_frame[message_length + 2], &message_frame[message_length + 3]);
885 // send
886 CodeAndTransmit14443bAsReader(message_frame, message_length + 4);
887 // get response
a3bef986 888 int ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
ca8a3478 889 FpgaDisableTracing();
a3bef986 890 if (ret < 3) {
ca8a3478 891 LED_A_OFF();
4be27083
FM
892 return 0;
893 }
894 // TODO: Check CRC
895 // copy response contents
a3bef986 896 if (response != NULL) {
4be27083
FM
897 memcpy(response, Demod.output, Demod.len);
898 }
ca8a3478 899 LED_A_OFF();
a3bef986 900 return ret;
4be27083
FM
901}
902
903/* Perform the ISO 14443 B Card Selection procedure
904 * Currently does NOT do any collision handling.
905 * It expects 0-1 cards in the device's range.
906 * TODO: Support multiple cards (perform anticollision)
907 * TODO: Verify CRC checksums
908 */
909int iso14443b_select_card()
910{
911 // WUPB command (including CRC)
912 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
913 static const uint8_t wupb[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
914 // ATTRIB command (with space for CRC)
915 uint8_t attrib[] = { 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
916
917 // first, wake up the tag
918 CodeAndTransmit14443bAsReader(wupb, sizeof(wupb));
a3bef986 919 int ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
4be27083 920 // ATQB too short?
a3bef986 921 if (ret < 14) {
4be27083
FM
922 return 2;
923 }
924
925 // select the tag
926 // copy the PUPI to ATTRIB
927 memcpy(attrib + 1, Demod.output + 1, 4);
928 /* copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into
929 ATTRIB (Param 3) */
930 attrib[7] = Demod.output[10] & 0x0F;
931 ComputeCrc14443(CRC_14443_B, attrib, 9, attrib + 9, attrib + 10);
932 CodeAndTransmit14443bAsReader(attrib, sizeof(attrib));
a3bef986 933 ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
4be27083 934 // Answer to ATTRIB too short?
a3bef986 935 if (ret < 3) {
4be27083
FM
936 return 2;
937 }
938 // reset PCB block number
939 pcb_blocknum = 0;
940 return 1;
941}
942
943// Set up ISO 14443 Type B communication (similar to iso14443a_setup)
944void iso14443b_setup() {
945 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
946 // Set up the synchronous serial port
5ea2a248 947 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
4be27083
FM
948 // connect Demodulated Signal to ADC:
949 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
950
951 // Signal field is on with the appropriate LED
952 LED_D_ON();
5ea2a248 953 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_SHALLOW_MOD);
4be27083 954
4be27083
FM
955 DemodReset();
956 UartReset();
957}
67ac4bf7 958
15c4dc5a 959//-----------------------------------------------------------------------------
51d4f6f1 960// Read a SRI512 ISO 14443B tag.
15c4dc5a 961//
962// SRI512 tags are just simple memory tags, here we're looking at making a dump
963// of the contents of the memory. No anticollision algorithm is done, we assume
964// we have a single tag in the field.
965//
966// I tried to be systematic and check every answer of the tag, every CRC, etc...
967//-----------------------------------------------------------------------------
51d4f6f1 968void ReadSTMemoryIso14443b(uint32_t dwLast)
15c4dc5a 969{
ca8a3478 970 LED_A_ON();
7d5ebac9 971 uint8_t i = 0x00;
15c4dc5a 972
7d5ebac9
MHS
973 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
974 // Make sure that we start from off, since the tags are stateful;
975 // confusing things will happen if we don't reset them between reads.
976 LED_D_OFF();
977 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
978 SpinDelay(200);
15c4dc5a 979
7d5ebac9 980 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
5ea2a248 981 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
15c4dc5a 982
7d5ebac9
MHS
983 // Now give it time to spin up.
984 // Signal field is on with the appropriate LED
985 LED_D_ON();
5ea2a248 986 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_SHALLOW_MOD);
7d5ebac9 987 SpinDelay(200);
15c4dc5a 988
5f605b8f 989 clear_trace();
44964fd1 990 set_tracing(true);
5f605b8f 991
7d5ebac9 992 // First command: wake up the tag using the INITIATE command
51d4f6f1 993 uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b};
355c8b4a 994 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1));
a3bef986 995 int ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
15c4dc5a 996
a3bef986 997 if (ret < 0) {
6a5d4e17 998 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 999 DbpString("No response from tag");
1000 LEDsoff();
705bfa10 1001 return;
7d5ebac9 1002 } else {
705bfa10 1003 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1004 Demod.output[0], Demod.output[1], Demod.output[2]);
7d5ebac9 1005 }
705bfa10 1006
7d5ebac9
MHS
1007 // There is a response, SELECT the uid
1008 DbpString("Now SELECT tag:");
1009 cmd1[0] = 0x0E; // 0x0E is SELECT
1010 cmd1[1] = Demod.output[0];
1011 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
355c8b4a 1012 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1));
a3bef986 1013 ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
7d5ebac9 1014 if (Demod.len != 3) {
6a5d4e17 1015 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 1016 Dbprintf("Expected 3 bytes from tag, got %d", Demod.len);
1017 LEDsoff();
51d4f6f1 1018 return;
7d5ebac9
MHS
1019 }
1020 // Check the CRC of the answer:
1021 ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]);
1022 if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) {
6a5d4e17 1023 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 1024 DbpString("CRC Error reading select response.");
1025 LEDsoff();
51d4f6f1 1026 return;
7d5ebac9
MHS
1027 }
1028 // Check response from the tag: should be the same UID as the command we just sent:
1029 if (cmd1[1] != Demod.output[0]) {
6a5d4e17 1030 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 1031 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1[1], Demod.output[0]);
1032 LEDsoff();
51d4f6f1 1033 return;
7d5ebac9 1034 }
705bfa10 1035
7d5ebac9
MHS
1036 // Tag is now selected,
1037 // First get the tag's UID:
1038 cmd1[0] = 0x0B;
1039 ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]);
355c8b4a 1040 CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one
a3bef986 1041 ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
1042 if (ret != 10) {
6a5d4e17 1043 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 1044 Dbprintf("Expected 10 bytes from tag, got %d", Demod.len);
1045 LEDsoff();
51d4f6f1 1046 return;
7d5ebac9
MHS
1047 }
1048 // The check the CRC of the answer (use cmd1 as temporary variable):
1049 ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]);
51d4f6f1 1050 if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) {
132a0217 1051 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
705bfa10 1052 (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]);
51d4f6f1 1053 // Do not return;, let's go on... (we should retry, maybe ?)
7d5ebac9
MHS
1054 }
1055 Dbprintf("Tag UID (64 bits): %08x %08x",
705bfa10 1056 (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4],
1057 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]);
15c4dc5a 1058
7d5ebac9 1059 // Now loop to read all 16 blocks, address from 0 to last block
132a0217 1060 Dbprintf("Tag memory dump, block 0 to %d", dwLast);
7d5ebac9
MHS
1061 cmd1[0] = 0x08;
1062 i = 0x00;
1063 dwLast++;
1064 for (;;) {
51d4f6f1 1065 if (i == dwLast) {
7d5ebac9
MHS
1066 DbpString("System area block (0xff):");
1067 i = 0xff;
1068 }
1069 cmd1[1] = i;
1070 ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]);
355c8b4a 1071 CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1));
a3bef986 1072 ret = GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, true);
1073 if (ret != 6) { // Check if we got an answer from the tag
6a5d4e17 1074 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 1075 DbpString("Expected 6 bytes from tag, got less...");
1076 LEDsoff();
51d4f6f1 1077 return;
7d5ebac9
MHS
1078 }
1079 // The check the CRC of the answer (use cmd1 as temporary variable):
1080 ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]);
a3bef986 1081 if (cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) {
132a0217 1082 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
705bfa10 1083 (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]);
51d4f6f1 1084 // Do not return;, let's go on... (we should retry, maybe ?)
7d5ebac9
MHS
1085 }
1086 // Now print out the memory location:
132a0217 1087 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i,
705bfa10 1088 (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0],
1089 (Demod.output[4]<<8)+Demod.output[5]);
7d5ebac9 1090 if (i == 0xff) {
51d4f6f1 1091 break;
7d5ebac9
MHS
1092 }
1093 i++;
1094 }
6a5d4e17 1095
6a5d4e17 1096 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
ca8a3478 1097 LEDsoff();
15c4dc5a 1098}
1099
1100
1101//=============================================================================
1102// Finally, the `sniffer' combines elements from both the reader and
1103// simulated tag, to show both sides of the conversation.
1104//=============================================================================
1105
1106//-----------------------------------------------------------------------------
1107// Record the sequence of commands sent by the reader to the tag, with
1108// triggering so that we start recording at the point that the tag is moved
1109// near the reader.
1110//-----------------------------------------------------------------------------
1111/*
1112 * Memory usage for this function, (within BigBuf)
5b95953d 1113 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1114 * Last Received command (tag->reader) - MAX_FRAME_SIZE
705bfa10 1115 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
5b95953d 1116 * Demodulated samples received - all the rest
15c4dc5a 1117 */
51d4f6f1 1118void RAMFUNC SnoopIso14443b(void)
15c4dc5a 1119{
ca8a3478 1120 LED_A_ON();
7d5ebac9 1121 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
f71f4deb 1122 BigBuf_free();
15c4dc5a 1123
aeadbdb2 1124 clear_trace();
44964fd1 1125 set_tracing(true);
aeadbdb2 1126
7d5ebac9 1127 // The DMA buffer, used to stream samples from the FPGA
6a5d4e17 1128 uint16_t *dmaBuf = (uint16_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE * sizeof(uint16_t));
7d5ebac9 1129 int lastRxCounter;
6a5d4e17 1130 uint16_t *upTo;
1131 int8_t ci, cq;
7d5ebac9
MHS
1132 int maxBehindBy = 0;
1133
1134 // Count of samples received so far, so that we can include timing
1135 // information in the trace buffer.
1136 int samples = 0;
15c4dc5a 1137
7d5ebac9
MHS
1138 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1139 UartInit(BigBuf_malloc(MAX_FRAME_SIZE));
15c4dc5a 1140
7d5ebac9
MHS
1141 // Print some debug information about the buffer sizes
1142 Dbprintf("Snooping buffers initialized:");
1143 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
aeadbdb2
MHS
1144 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE);
1145 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE);
705bfa10 1146 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE);
e30c654b 1147
5ea2a248 1148 // Signal field is off
1149 LED_D_OFF();
aeadbdb2
MHS
1150
1151 // And put the FPGA in the appropriate mode
5ea2a248 1152 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_848_KHZ | FPGA_HF_READER_MODE_SNOOP_IQ);
7d5ebac9
MHS
1153 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1154
1155 // Setup for the DMA.
5ea2a248 1156 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
7d5ebac9 1157 upTo = dmaBuf;
705bfa10 1158 lastRxCounter = ISO14443B_DMA_BUFFER_SIZE;
1159 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE);
5b95953d 1160
44964fd1 1161 bool TagIsActive = false;
1162 bool ReaderIsActive = false;
6a5d4e17 1163 // We won't start recording the frames that we acquire until we trigger.
1164 // A good trigger condition to get started is probably when we see a
1165 // reader command
1166 bool triggered = false;
dd57061c 1167
7d5ebac9
MHS
1168 // And now we loop, receiving samples.
1169 for(;;) {
6a5d4e17 1170 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & (ISO14443B_DMA_BUFFER_SIZE-1);
7d5ebac9
MHS
1171 if(behindBy > maxBehindBy) {
1172 maxBehindBy = behindBy;
7d5ebac9 1173 }
51d4f6f1 1174
6a5d4e17 1175 if(behindBy < 1) continue;
7d5ebac9 1176
6a5d4e17 1177 ci = *upTo>>8;
1178 cq = *upTo;
1179 upTo++;
1180 lastRxCounter--;
1181 if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
1182 upTo = dmaBuf; // start reading the circular buffer from the beginning again
705bfa10 1183 lastRxCounter += ISO14443B_DMA_BUFFER_SIZE;
6a5d4e17 1184 if(behindBy > (9*ISO14443B_DMA_BUFFER_SIZE/10)) {
1185 Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy);
51d4f6f1 1186 break;
1187 }
6a5d4e17 1188 }
1189 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
1190 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
1191 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; // DMA Next Counter registers
1192 WDT_HIT();
51d4f6f1 1193 if(BUTTON_PRESS()) {
1194 DbpString("cancelled");
1195 break;
1196 }
7d5ebac9 1197 }
15c4dc5a 1198
6a5d4e17 1199 samples++;
15c4dc5a 1200
5b95953d 1201 if (!TagIsActive) { // no need to try decoding reader data if the tag is sending
51d4f6f1 1202 if(Handle14443bUartBit(ci & 0x01)) {
6a5d4e17 1203 triggered = true;
d9de20fa 1204 LogTrace(Uart.output, Uart.byteCnt, samples, samples, NULL, true);
5b95953d 1205 /* And ready to receive another command. */
1206 UartReset();
1207 /* And also reset the demod code, which might have been */
1208 /* false-triggered by the commands from the reader. */
1209 DemodReset();
aeadbdb2 1210 }
51d4f6f1 1211 if(Handle14443bUartBit(cq & 0x01)) {
6a5d4e17 1212 triggered = true;
d9de20fa 1213 LogTrace(Uart.output, Uart.byteCnt, samples, samples, NULL, true);
5b95953d 1214 /* And ready to receive another command. */
1215 UartReset();
1216 /* And also reset the demod code, which might have been */
1217 /* false-triggered by the commands from the reader. */
1218 DemodReset();
1219 }
46734099 1220 ReaderIsActive = (Uart.state > STATE_GOT_FALLING_EDGE_OF_SOF);
aeadbdb2 1221 }
15c4dc5a 1222
a3bef986 1223 if (!ReaderIsActive && triggered) { // no need to try decoding tag data if the reader is sending or not yet triggered
1224 if (Handle14443bSamplesDemod(ci/2, cq/2) >= 0) {
5b95953d 1225 //Use samples as a time measurement
d9de20fa 1226 LogTrace(Demod.output, Demod.len, samples, samples, NULL, false);
5b95953d 1227 // And ready to receive another response.
1228 DemodReset();
1229 }
d5875804 1230 TagIsActive = (Demod.state > DEMOD_GOT_FALLING_EDGE_OF_SOF);
aeadbdb2 1231 }
15c4dc5a 1232
7d5ebac9 1233 }
51d4f6f1 1234
aeadbdb2 1235 FpgaDisableSscDma();
15c4dc5a 1236 DbpString("Snoop statistics:");
355c8b4a 1237 Dbprintf(" Max behind by: %i", maxBehindBy);
15c4dc5a 1238 Dbprintf(" Uart State: %x", Uart.state);
1239 Dbprintf(" Uart ByteCnt: %i", Uart.byteCnt);
1240 Dbprintf(" Uart ByteCntMax: %i", Uart.byteCntMax);
3000dc4e 1241 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
ca8a3478 1242 LEDsoff();
15c4dc5a 1243}
7cf3ef20 1244
67ac4bf7 1245
7cf3ef20 1246/*
1247 * Send raw command to tag ISO14443B
1248 * @Input
1249 * datalen len of buffer data
1250 * recv bool when true wait for data from tag and send to client
1251 * powerfield bool leave the field on when true
1252 * data buffer with byte to send
1253 *
1254 * @Output
1255 * none
1256 *
1257 */
67ac4bf7 1258void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, uint8_t data[])
7cf3ef20 1259{
5ea2a248 1260 LED_A_ON();
7d5ebac9 1261 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
51d4f6f1 1262 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
6a5d4e17 1263
1264 // switch field on and give tag some time to power up
1265 LED_D_ON();
5ea2a248 1266 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_SHALLOW_MOD);
1267 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
6a5d4e17 1268 SpinDelay(10);
5f605b8f 1269
9d84e689 1270 if (datalen){
44964fd1 1271 set_tracing(true);
9d84e689 1272
1273 CodeAndTransmit14443bAsReader(data, datalen);
1274
a3bef986 1275 if (recv) {
1276 int ret = GetSamplesFor14443bDemod(5*RECEIVE_SAMPLES_TIMEOUT, true);
ca8a3478 1277 FpgaDisableTracing();
9d84e689 1278 uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE);
a3bef986 1279 cmd_send(CMD_ACK, ret, 0, 0, Demod.output, iLen);
9d84e689 1280 }
ca8a3478 1281
1282 FpgaDisableTracing();
dd57061c 1283 }
355c8b4a 1284
a3bef986 1285 if (!powerfield) {
7d5ebac9
MHS
1286 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1287 LED_D_OFF();
1288 }
5ea2a248 1289
1290 LED_A_OFF();
7cf3ef20 1291}
1292
Impressum, Datenschutz