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