]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/legicrf.c
60e5593849e495995058097815e45141d9ae70dd
[proxmark3-svn] / armsrc / legicrf.c
1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // LEGIC RF simulation code
9 //-----------------------------------------------------------------------------
10
11 #include "legicrf.h"
12
13 static struct legic_frame {
14 int bits;
15 uint32_t data;
16 } current_frame;
17
18 static enum {
19 STATE_DISCON,
20 STATE_IV,
21 STATE_CON,
22 } legic_state;
23
24 static crc_t legic_crc;
25 static int legic_read_count;
26 static uint32_t legic_prng_bc;
27 static uint32_t legic_prng_iv;
28
29 static int legic_phase_drift;
30 static int legic_frame_drift;
31 static int legic_reqresp_drift;
32
33 int timestamp;
34
35 AT91PS_TC timer;
36 AT91PS_TC prng_timer;
37
38 /*
39 static void setup_timer(void) {
40 // Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging
41 // this it won't be terribly accurate but should be good enough.
42 //
43 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
44 timer = AT91C_BASE_TC1;
45 timer->TC_CCR = AT91C_TC_CLKDIS;
46 timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
47 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
48
49 //
50 // Set up Timer 2 to use for measuring time between frames in
51 // tag simulation mode. Runs 4x faster as Timer 1
52 //
53 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC2);
54 prng_timer = AT91C_BASE_TC2;
55 prng_timer->TC_CCR = AT91C_TC_CLKDIS;
56 prng_timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV2_CLOCK;
57 prng_timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
58 }
59 */
60
61 // At TIMER_CLOCK3 (MCK/32)
62 //#define RWD_TIME_1 150 /* RWD_TIME_PAUSE off, 80us on = 100us */
63 //#define RWD_TIME_0 90 /* RWD_TIME_PAUSE off, 40us on = 60us */
64 //#define RWD_TIME_PAUSE 30 /* 20us */
65
66 // testing calculating in ticks instead of (us) microseconds.
67 #define RWD_TIME_1 120 // READER_TIME_PAUSE off, 80us on = 100us 80 * 1.5 == 120ticks
68 #define RWD_TIME_0 60 // READER_TIME_PAUSE off, 40us on = 60us 40 * 1.5 == 60ticks
69 #define RWD_TIME_PAUSE 30 // 20us == 20 * 1.5 == 30ticks */
70 #define TAG_BIT_PERIOD 150 // 100us == 100 * 1.5 == 150ticks
71
72 #define RWD_TIME_FUZZ 20 // rather generous 13us, since the peak detector + hysteresis fuzz quite a bit
73 #define TAG_TIME_WAIT 495 // 330us from READER frame end to TAG frame start. 330 * 1.5 == 495
74
75 #define SIM_DIVISOR 586 /* prng_time/SIM_DIVISOR count prng needs to be forwared */
76 #define SIM_SHIFT 900 /* prng_time+SIM_SHIFT shift of delayed start */
77
78 #define OFFSET_LOG 1024
79
80 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz)))
81
82 #ifndef SHORT_COIL
83 //#define LOW(x) AT91C_BASE_PIOA->PIO_CODR = (x)
84 # define SHORT_COIL LOW(GPIO_SSC_DOUT);
85 #endif
86 #ifndef OPEN_COIL
87 //#define HIGH(x) AT91C_BASE_PIOA->PIO_SODR = (x)
88 # define OPEN_COIL HIGH(GPIO_SSC_DOUT);
89 #endif
90
91 uint32_t stop_send_frame_us = 0;
92
93 // ~ 258us + 100us*delay
94 #define WAIT(delay) SpinDelayCountUs((delay));
95 #define COIL_PULSE(x) { \
96 SHORT_COIL; \
97 Wait(RWD_TIME_PAUSE); \
98 OPEN_COIL; \
99 Wait(x); \
100 }
101 #define GET_COUNT_US GetCountUS()
102
103
104 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
105 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
106 #define LEGIC_CARD_MEMSIZE 1024
107 static uint8_t* cardmem;
108
109 static void Wait(uint32_t time){
110 if ( time == 0 ) return;
111 time += AT91C_BASE_TC0->TC_CV;
112 while(AT91C_BASE_TC0->TC_CV < time);
113 }
114 // Starts Clock and waits until its reset
115 static void Reset(AT91PS_TC clock){
116 clock->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
117 while(clock->TC_CV > 1) ;
118 }
119
120 // Starts Clock and waits until its reset
121 static void ResetClock(void){
122 Reset(timer);
123 }
124
125 static void frame_append_bit(struct legic_frame * const f, int bit) {
126 // Overflow, won't happen
127 if (f->bits >= 31) return;
128
129 f->data |= (bit << f->bits);
130 f->bits++;
131 }
132
133 static void frame_clean(struct legic_frame * const f) {
134 f->data = 0;
135 f->bits = 0;
136 }
137
138 // Prng works when waiting in 99.1us cycles.
139 // and while sending/receiving in bit frames (100, 60)
140 /*static void CalibratePrng( uint32_t time){
141 // Calculate Cycles based on timer 100us
142 uint32_t i = (time - stop_send_frame_us) / 100 ;
143
144 // substract cycles of finished frames
145 int k = i - legic_prng_count()+1;
146
147 // substract current frame length, rewind to beginning
148 if ( k > 0 )
149 legic_prng_forward(k);
150 }
151 */
152
153 /* Generate Keystream */
154 static uint32_t get_key_stream(int skip, int count)
155 {
156 uint32_t key = 0;
157 int i;
158
159 // Use int to enlarge timer tc to 32bit
160 legic_prng_bc += prng_timer->TC_CV;
161
162 // reset the prng timer.
163 Reset(prng_timer);
164
165 /* If skip == -1, forward prng time based */
166 if(skip == -1) {
167 i = (legic_prng_bc + SIM_SHIFT)/SIM_DIVISOR; /* Calculate Cycles based on timer */
168 i -= legic_prng_count(); /* substract cycles of finished frames */
169 i -= count; /* substract current frame length, rewind to beginning */
170 legic_prng_forward(i);
171 } else {
172 legic_prng_forward(skip);
173 }
174
175 i = (count == 6) ? -1 : legic_read_count;
176
177 /* Write Time Data into LOG */
178 // uint8_t *BigBuf = BigBuf_get_addr();
179 // BigBuf[OFFSET_LOG+128+i] = legic_prng_count();
180 // BigBuf[OFFSET_LOG+256+i*4] = (legic_prng_bc >> 0) & 0xff;
181 // BigBuf[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
182 // BigBuf[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
183 // BigBuf[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
184 // BigBuf[OFFSET_LOG+384+i] = count;
185
186 /* Generate KeyStream */
187 for(i=0; i<count; i++) {
188 key |= legic_prng_get_bit() << i;
189 legic_prng_forward(1);
190 }
191 return key;
192 }
193
194 /* Send a frame in tag mode, the FPGA must have been set up by
195 * LegicRfSimulate
196 */
197 static void frame_send_tag(uint16_t response, uint8_t bits, uint8_t crypt) {
198 /* Bitbang the response */
199 LOW(GPIO_SSC_DOUT);
200 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
201 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
202
203 /* Use time to crypt frame */
204 if(crypt) {
205 legic_prng_forward(2); /* TAG_TIME_WAIT -> shift by 2 */
206 response ^= legic_prng_get_bits(bits);
207 }
208
209 /* Wait for the frame start */
210 WAIT( TAG_TIME_WAIT )
211
212 uint8_t bit = 0;
213 for(int i = 0; i < bits; i++) {
214
215 bit = response & 1;
216 response >>= 1;
217
218 if (bit)
219 HIGH(GPIO_SSC_DOUT);
220 else
221 LOW(GPIO_SSC_DOUT);
222
223 WAIT(100)
224 }
225 LOW(GPIO_SSC_DOUT);
226 }
227
228 /* Send a frame in reader mode, the FPGA must have been set up by
229 * LegicRfReader
230 */
231 static void frame_sendAsReader(uint32_t data, uint8_t bits){
232
233 uint32_t starttime = AT91C_BASE_TC0->TC_CV;
234 uint32_t send = data;
235 uint8_t prng1 = legic_prng_count() ;
236 uint16_t mask = 1;
237 uint16_t lfsr = legic_prng_get_bits(bits);
238
239 // xor the lsfr onto data.
240 send ^= lfsr;
241
242 for (; mask < BITMASK(bits); mask <<= 1) {
243 if (send & mask) {
244 COIL_PULSE(RWD_TIME_1);
245 } else {
246 COIL_PULSE(RWD_TIME_0);
247 }
248 }
249
250 // Final pause to mark the end of the frame
251 // tempo = AT91C_BASE_TC0->TC_CV + RWD_TIME_PAUSE;
252 // SHORT_COIL;
253 // while(AT91C_BASE_TC0->TC_CV < tempo);
254 // OPEN_COIL;
255 COIL_PULSE(0);
256
257 stop_send_frame_us = AT91C_BASE_TC0->TC_CV;
258 uint8_t cmdbytes[] = {
259 data & 0xFF,
260 (data >> 8) & 0xFF,
261 bits,
262 lfsr & 0xFF,
263 (lfsr >> 8) & 0xFF,
264 prng1,
265 legic_prng_count()
266 };
267 LogTrace(cmdbytes, sizeof(cmdbytes), starttime, stop_send_frame_us, NULL, TRUE);
268 }
269
270 /* Receive a frame from the card in reader emulation mode, the FPGA and
271 * timer must have been set up by LegicRfReader and frame_sendAsReader.
272 *
273 * The LEGIC RF protocol from card to reader does not include explicit
274 * frame start/stop information or length information. The reader must
275 * know beforehand how many bits it wants to receive. (Notably: a card
276 * sending a stream of 0-bits is indistinguishable from no card present.)
277 *
278 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
279 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
280 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
281 * for edges. Count the edges in each bit interval. If they are approximately
282 * 0 this was a 0-bit, if they are approximately equal to the number of edges
283 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
284 * timer that's still running from frame_sendAsReader in order to get a synchronization
285 * with the frame that we just sent.
286 *
287 * FIXME: Because we're relying on the hysteresis to just do the right thing
288 * the range is severely reduced (and you'll probably also need a good antenna).
289 * So this should be fixed some time in the future for a proper receiver.
290 */
291 static void frame_receiveAsReader(struct legic_frame * const f, uint8_t bits, uint8_t crypt) {
292
293 uint32_t starttime = AT91C_BASE_TC0->TC_CV;
294
295 frame_clean(f);
296
297 uint8_t i = 0, edges = 0;
298 uint16_t lsfr = 0;
299 uint32_t the_bit = 1, next_bit_at = 0, data;
300 int old_level = 0, level = 0;
301
302 if(bits > 32) bits = 32;
303
304 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
305 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
306
307 // calibrate the prng.
308 legic_prng_forward(2);
309 //CalibratePrng( starttime );
310
311 // precompute the cipher
312 uint8_t prng_before = legic_prng_count() ;
313
314 if(crypt)
315 lsfr = legic_prng_get_bits(bits);
316
317 data = lsfr;
318
319 //FIXED time between sending frame and now listening frame. 330us
320 uint32_t icetime = TAG_TIME_WAIT - ( AT91C_BASE_TC0->TC_CV - stop_send_frame_us );
321 while ( AT91C_BASE_TC0->TC_CV != icetime );
322
323 next_bit_at = AT91C_BASE_TC0->TC_CV + TAG_BIT_PERIOD;
324
325 for( i = 0; i < bits; i++) {
326 edges = 0;
327 while ( AT91C_BASE_TC0->TC_CV < next_bit_at) {
328
329 level = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
330
331 if (level != old_level)
332 ++edges;
333
334 old_level = level;
335 }
336 next_bit_at += TAG_BIT_PERIOD;
337
338 // We expect 42 edges == ONE
339 if(edges > 20 && edges < 60)
340 data ^= the_bit;
341
342 the_bit <<= 1;
343 }
344
345 // output
346 f->data = data;
347 f->bits = bits;
348
349 // log
350 stop_send_frame_us = AT91C_BASE_TC0->TC_CV;
351
352 uint8_t cmdbytes[] = {
353 (data & 0xFF),
354 (data >> 8) & 0xFF,
355 bits,
356 (lsfr & 0xFF),
357 (lsfr >> 8) & 0xFF,
358 prng_before,
359 legic_prng_count(),
360 icetime & 0xff,
361 (icetime >> 8) & 0xFF
362 };
363 LogTrace(cmdbytes, sizeof(cmdbytes), starttime, stop_send_frame_us, NULL, FALSE);
364
365 }
366
367 // Setup pm3 as a Legic Reader
368 static uint32_t perform_setup_phase_rwd(uint8_t iv) {
369
370 // Switch on carrier and let the tag charge for 1ms
371 HIGH(GPIO_SSC_DOUT);
372 SpinDelay(20);
373
374 ResetUSClock();
375
376 // no keystream yet
377 legic_prng_init(0);
378
379 // send IV handshake
380 frame_sendAsReader(iv, 7);
381
382 // Now both tag and reader has same IV. Prng can start.
383 legic_prng_init(iv);
384
385 frame_receiveAsReader(&current_frame, 6, 1);
386
387 // fixed delay before sending ack.
388 WAIT(TAG_BIT_PERIOD);
389
390 // Send obsfuscated acknowledgment frame.
391 // 0x19 = 0x18 MIM22, 0x01 LSB READCMD
392 // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD
393 switch ( current_frame.data ) {
394 case 0x0D:
395 frame_sendAsReader(0x19, 6);
396 break;
397 case 0x1D:
398 case 0x3D:
399 frame_sendAsReader(0x39, 6);
400 break;
401 default:
402 break;
403 }
404 return current_frame.data;
405
406 // End of Setup Phase.
407 }
408
409 static void LegicCommonInit(void) {
410 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
411 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
412 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
413 FpgaSetupSsc();
414
415 /* Bitbang the transmitter */
416 LOW(GPIO_SSC_DOUT);
417 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
418 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
419
420 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
421 cardmem = BigBuf_malloc(LEGIC_CARD_MEMSIZE);
422 memset(cardmem, 0x00, LEGIC_CARD_MEMSIZE);
423
424 clear_trace();
425 set_tracing(TRUE);
426
427 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
428
429 StartCountUS();
430 }
431
432 /* Switch off carrier, make sure tag is reset */
433 static void switch_off_tag_rwd(void) {
434 LOW(GPIO_SSC_DOUT);
435 SpinDelay(10);
436 WDT_HIT();
437 set_tracing(FALSE);
438 }
439
440 // calculate crc4 for a legic READ command
441 // 5,8,10 address size.
442 static uint32_t LegicCRC(uint16_t byte_index, uint8_t value, uint8_t cmd_sz) {
443 crc_clear(&legic_crc);
444 uint32_t temp = (value << cmd_sz) | (byte_index << 1) | LEGIC_READ;
445 crc_update(&legic_crc, temp, cmd_sz + 8 );
446 // crc_update(&legic_crc, LEGIC_READ, 1);
447 // crc_update(&legic_crc, byte_index, cmd_sz-1);
448 // crc_update(&legic_crc, value, 8);
449 return crc_finish(&legic_crc);
450 }
451
452 int legic_read_byte(int byte_index, int cmd_sz) {
453
454 uint8_t byte = 0, crc = 0;
455 uint32_t calcCrc = 0;
456 uint32_t cmd = (byte_index << 1) | LEGIC_READ;
457
458 legic_prng_forward(3);
459 WAIT(TAG_TIME_WAIT)
460
461 frame_sendAsReader(cmd, cmd_sz);
462
463 frame_receiveAsReader(&current_frame, 12, 1);
464
465 byte = current_frame.data & 0xFF;
466
467 calcCrc = LegicCRC(byte_index, byte, cmd_sz);
468 crc = (current_frame.data >> 8);
469
470 if( calcCrc != crc ) {
471 Dbprintf("!!! crc mismatch: expected %x but got %x !!!", calcCrc, crc);
472 return -1;
473 }
474
475 return byte;
476 }
477
478 /*
479 * - assemble a write_cmd_frame with crc and send it
480 * - wait until the tag sends back an ACK ('1' bit unencrypted)
481 * - forward the prng based on the timing
482 */
483 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) {
484 int legic_write_byte(int byte, int addr, int addr_sz) {
485
486 //do not write UID, CRC at offset 0-4.
487 if(addr <= 0x04) return 0;
488
489 // crc
490 crc_clear(&legic_crc);
491 crc_update(&legic_crc, 0, 1); /* CMD_WRITE */
492 crc_update(&legic_crc, addr, addr_sz);
493 crc_update(&legic_crc, byte, 8);
494 uint32_t crc = crc_finish(&legic_crc);
495
496 // send write command
497 uint32_t cmd = ((crc <<(addr_sz+1+8)) //CRC
498 |(byte <<(addr_sz+1)) //Data
499 |(addr <<1) //Address
500 |(0x00 <<0)); //CMD = W
501 uint32_t cmd_sz = addr_sz+1+8+4; //crc+data+cmd
502
503 legic_prng_forward(2); /* we wait anyways */
504
505 while(timer->TC_CV < 387) ; /* ~ 258us */
506
507 frame_sendAsReader(cmd, cmd_sz);
508
509 // wllm-rbnt doesnt have these
510 // AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
511 // AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
512
513 // wait for ack
514 int t, old_level = 0, edges = 0;
515 int next_bit_at = 0;
516
517 while(timer->TC_CV < 387) ; /* ~ 258us */
518
519 for( t = 0; t < 80; t++) {
520 edges = 0;
521 next_bit_at += TAG_BIT_PERIOD;
522 while(timer->TC_CV < next_bit_at) {
523 int level = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
524 if(level != old_level) {
525 edges++;
526 }
527 old_level = level;
528 }
529 if(edges > 20 && edges < 60) { /* expected are 42 edges */
530 int t = timer->TC_CV;
531 int c = t / TAG_BIT_PERIOD;
532
533 ResetClock();
534 legic_prng_forward(c);
535 return 0;
536 }
537 }
538
539 ResetClock();
540 return -1;
541 }
542
543 int LegicRfReader(int offset, int bytes, int iv) {
544
545 int byte_index = 0, cmd_sz = 0, card_sz = 0;
546
547 if ( MF_DBGLEVEL >= 2) {
548 Dbprintf("setting up legic card, IV = %x", iv);
549 Dbprintf("ONE %d ZERO %d PAUSE %d", RWD_TIME_1 , RWD_TIME_0 , RWD_TIME_PAUSE);
550 Dbprintf("TAG BIT PERIOD %d FUZZ %d TAG WAIT TIME %d", TAG_BIT_PERIOD, RWD_TIME_FUZZ, TAG_TIME_WAIT);
551
552 // StartCountUS();
553 // for ( uint8_t i =0; i<255; ++i){
554 // uint32_t t1 = GET_COUNT_US;
555 // WAIT(i)
556 // t1 = GET_COUNT_US - t1;
557 // Dbprintf("WAIT(%d) == %u | %u | diff %d", i, t1-i );
558 // }
559 }
560
561 LegicCommonInit();
562
563 uint32_t tag_type = perform_setup_phase_rwd(iv);
564
565 //we lose to mutch time with dprintf
566 switch_off_tag_rwd();
567
568 switch(tag_type) {
569 case 0x0d:
570 if ( MF_DBGLEVEL >= 2) DbpString("MIM22 card found, reading card ...");
571 cmd_sz = 6;
572 card_sz = 22;
573 break;
574 case 0x1d:
575 if ( MF_DBGLEVEL >= 2) DbpString("MIM256 card found, reading card ...");
576 cmd_sz = 9;
577 card_sz = 256;
578 break;
579 case 0x3d:
580 if ( MF_DBGLEVEL >= 2) DbpString("MIM1024 card found, reading card ...");
581 cmd_sz = 11;
582 card_sz = 1024;
583 break;
584 default:
585 if ( MF_DBGLEVEL >= 1) Dbprintf("Unknown card format: %x",tag_type);
586 return 1;
587 }
588 if(bytes == -1)
589 bytes = card_sz;
590
591 if(bytes+offset >= card_sz)
592 bytes = card_sz - offset;
593
594 // Start setup and read bytes.
595 perform_setup_phase_rwd(iv);
596
597 LED_B_ON();
598 while (byte_index < bytes) {
599 int r = legic_read_byte(byte_index+offset, cmd_sz);
600
601 if (r == -1 || BUTTON_PRESS()) {
602 switch_off_tag_rwd();
603 LEDsoff();
604 if ( MF_DBGLEVEL >= 2) DbpString("operation aborted");
605 cmd_send(CMD_ACK,0,0,0,0,0);
606 return 1;
607 }
608 cardmem[byte_index] = r;
609 WDT_HIT();
610 byte_index++;
611 }
612
613 switch_off_tag_rwd();
614 LEDsoff();
615 uint8_t len = (bytes & 0x3FF);
616 cmd_send(CMD_ACK,1,len,0,0,0);
617 return 0;
618 }
619
620 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
621 int byte_index=0;
622
623 LED_B_ON();
624 perform_setup_phase_rwd(iv);
625 //legic_prng_forward(2);
626 while(byte_index < bytes) {
627 int r;
628
629 //check if the DCF should be changed
630 if ( (offset == 0x05) && (bytes == 0x02) ) {
631 //write DCF in reverse order (addr 0x06 before 0x05)
632 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
633 //legic_prng_forward(1);
634 if(r == 0) {
635 byte_index++;
636 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
637 }
638 //legic_prng_forward(1);
639 }
640 else {
641 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
642 }
643 if((r != 0) || BUTTON_PRESS()) {
644 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
645 switch_off_tag_rwd();
646 LED_B_OFF();
647 LED_C_OFF();
648 return -1;
649 }
650
651 WDT_HIT();
652 byte_index++;
653 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
654 }
655 LED_B_OFF();
656 LED_C_OFF();
657 DbpString("write successful");
658 return 0;
659 }*/
660
661 void LegicRfWriter(int offset, int bytes, int iv) {
662
663 int byte_index = 0, addr_sz = 0;
664
665 LegicCommonInit();
666
667 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
668
669 uint32_t tag_type = perform_setup_phase_rwd(iv);
670
671 switch_off_tag_rwd();
672
673 switch(tag_type) {
674 case 0x0d:
675 if(offset+bytes > 22) {
676 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset+bytes);
677 return;
678 }
679 addr_sz = 5;
680 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
681 break;
682 case 0x1d:
683 if(offset+bytes > 0x100) {
684 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset+bytes);
685 return;
686 }
687 addr_sz = 8;
688 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
689 break;
690 case 0x3d:
691 if(offset+bytes > 0x400) {
692 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset+bytes);
693 return;
694 }
695 addr_sz = 10;
696 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset, offset+bytes);
697 break;
698 default:
699 Dbprintf("No or unknown card found, aborting");
700 return;
701 }
702
703 LED_B_ON();
704 perform_setup_phase_rwd(iv);
705 while(byte_index < bytes) {
706 int r;
707
708 //check if the DCF should be changed
709 if ( ((byte_index+offset) == 0x05) && (bytes >= 0x02) ) {
710 //write DCF in reverse order (addr 0x06 before 0x05)
711 r = legic_write_byte(cardmem[(0x06-byte_index)], (0x06-byte_index), addr_sz);
712
713 // write second byte on success...
714 if(r == 0) {
715 byte_index++;
716 r = legic_write_byte(cardmem[(0x06-byte_index)], (0x06-byte_index), addr_sz);
717 }
718 }
719 else {
720 r = legic_write_byte(cardmem[byte_index+offset], byte_index+offset, addr_sz);
721 }
722
723 if((r != 0) || BUTTON_PRESS()) {
724 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
725 switch_off_tag_rwd();
726 LEDsoff();
727 return;
728 }
729
730 WDT_HIT();
731 byte_index++;
732 }
733 LEDsoff();
734 if ( MF_DBGLEVEL >= 1) DbpString("write successful");
735 }
736
737 void LegicRfRawWriter(int address, int byte, int iv) {
738
739 int byte_index = 0, addr_sz = 0;
740
741 LegicCommonInit();
742
743 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
744
745 uint32_t tag_type = perform_setup_phase_rwd(iv);
746
747 switch_off_tag_rwd();
748
749 switch(tag_type) {
750 case 0x0d:
751 if(address > 22) {
752 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address);
753 return;
754 }
755 addr_sz = 5;
756 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address, byte);
757 break;
758 case 0x1d:
759 if(address > 0x100) {
760 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address);
761 return;
762 }
763 addr_sz = 8;
764 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address, byte);
765 break;
766 case 0x3d:
767 if(address > 0x400) {
768 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address);
769 return;
770 }
771 addr_sz = 10;
772 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address, byte);
773 break;
774 default:
775 Dbprintf("No or unknown card found, aborting");
776 return;
777 }
778
779 Dbprintf("integer value: %d address: %d addr_sz: %d", byte, address, addr_sz);
780 LED_B_ON();
781
782 perform_setup_phase_rwd(iv);
783 //legic_prng_forward(2);
784
785 int r = legic_write_byte(byte, address, addr_sz);
786
787 if((r != 0) || BUTTON_PRESS()) {
788 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index, r);
789 switch_off_tag_rwd();
790 LEDsoff();
791 return;
792 }
793
794 LEDsoff();
795 if ( MF_DBGLEVEL >= 1) DbpString("write successful");
796 }
797
798 /* Handle (whether to respond) a frame in tag mode
799 * Only called when simulating a tag.
800 */
801 static void frame_handle_tag(struct legic_frame const * const f)
802 {
803 uint8_t *BigBuf = BigBuf_get_addr();
804
805 /* First Part of Handshake (IV) */
806 if(f->bits == 7) {
807
808 LED_C_ON();
809
810 // Reset prng timer
811 Reset(prng_timer);
812
813 legic_prng_init(f->data);
814 frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1B */
815 legic_state = STATE_IV;
816 legic_read_count = 0;
817 legic_prng_bc = 0;
818 legic_prng_iv = f->data;
819
820 /* TIMEOUT */
821 ResetClock();
822
823 //while(timer->TC_CV < 280);
824 WAIT(280)
825 return;
826 }
827
828 /* 0x19==??? */
829 if(legic_state == STATE_IV) {
830 int local_key = get_key_stream(3, 6);
831 int xored = 0x39 ^ local_key;
832 if((f->bits == 6) && (f->data == xored)) {
833 legic_state = STATE_CON;
834
835 /* TIMEOUT */
836 ResetClock();
837
838 //while(timer->TC_CV < 200);
839 WAIT(200)
840
841 return;
842 } else {
843 legic_state = STATE_DISCON;
844 LED_C_OFF();
845 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv, f->data, local_key, xored);
846 return;
847 }
848 }
849
850 /* Read */
851 if(f->bits == 11) {
852 if(legic_state == STATE_CON) {
853 int key = get_key_stream(2, 11); //legic_phase_drift, 11);
854 int addr = f->data ^ key; addr = addr >> 1;
855 int data = BigBuf[addr];
856 int hash = LegicCRC(addr, data, 11) << 8;
857 BigBuf[OFFSET_LOG+legic_read_count] = (uint8_t)addr;
858 legic_read_count++;
859
860 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
861 legic_prng_forward(legic_reqresp_drift);
862
863 frame_send_tag(hash | data, 12, 1);
864
865 /* TIMEOUT */
866 ResetClock();
867
868 legic_prng_forward(2);
869 //while(timer->TC_CV < 180);
870 WAIT(180)
871
872 return;
873 }
874 }
875
876 /* Write */
877 if(f->bits == 23) {
878 int key = get_key_stream(-1, 23); //legic_frame_drift, 23);
879 int addr = f->data ^ key; addr = addr >> 1; addr = addr & 0x3ff;
880 int data = f->data ^ key; data = data >> 11; data = data & 0xff;
881
882 /* write command */
883 legic_state = STATE_DISCON;
884 LED_C_OFF();
885 Dbprintf("write - addr: %x, data: %x", addr, data);
886 return;
887 }
888
889 if(legic_state != STATE_DISCON) {
890 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f->bits, f->data, legic_state, legic_read_count);
891 int i;
892 Dbprintf("IV: %03.3x", legic_prng_iv);
893 for(i = 0; i<legic_read_count; i++) {
894 Dbprintf("Read Nb: %u, Addr: %u", i, BigBuf[OFFSET_LOG+i]);
895 }
896
897 for(i = -1; i<legic_read_count; i++) {
898 uint32_t t;
899 t = BigBuf[OFFSET_LOG+256+i*4];
900 t |= BigBuf[OFFSET_LOG+256+i*4+1] << 8;
901 t |= BigBuf[OFFSET_LOG+256+i*4+2] <<16;
902 t |= BigBuf[OFFSET_LOG+256+i*4+3] <<24;
903
904 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
905 BigBuf[OFFSET_LOG+128+i],
906 BigBuf[OFFSET_LOG+384+i],
907 t);
908 }
909 }
910 legic_state = STATE_DISCON;
911 legic_read_count = 0;
912 SpinDelay(10);
913 LED_C_OFF();
914 return;
915 }
916
917 /* Read bit by bit untill full frame is received
918 * Call to process frame end answer
919 */
920 static void emit(int bit) {
921
922 switch (bit) {
923 case 1:
924 frame_append_bit(&current_frame, 1);
925 break;
926 case 0:
927 frame_append_bit(&current_frame, 0);
928 break;
929 default:
930 if(current_frame.bits <= 4) {
931 frame_clean(&current_frame);
932 } else {
933 frame_handle_tag(&current_frame);
934 frame_clean(&current_frame);
935 }
936 WDT_HIT();
937 break;
938 }
939 }
940
941 void LegicRfSimulate(int phase, int frame, int reqresp)
942 {
943 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
944 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
945 * envelope waveform on DIN and should send our response on DOUT.
946 *
947 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
948 * measure the time between two rising edges on DIN, and no encoding on the
949 * subcarrier from card to reader, so we'll just shift out our verbatim data
950 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
951 * seems to be 300us-ish.
952 */
953
954 legic_phase_drift = phase;
955 legic_frame_drift = frame;
956 legic_reqresp_drift = reqresp;
957
958 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
959 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
960 FpgaSetupSsc();
961 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_212K);
962
963 /* Bitbang the receiver */
964 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
965 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
966
967 //setup_timer();
968 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
969
970 int old_level = 0;
971 int active = 0;
972 legic_state = STATE_DISCON;
973
974 LED_B_ON();
975 DbpString("Starting Legic emulator, press button to end");
976
977 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
978 int level = !!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
979 int time = timer->TC_CV;
980
981 if(level != old_level) {
982 if(level == 1) {
983 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
984
985 if (FUZZ_EQUAL(time, RWD_TIME_1, RWD_TIME_FUZZ)) {
986 /* 1 bit */
987 emit(1);
988 active = 1;
989 LED_A_ON();
990 } else if (FUZZ_EQUAL(time, RWD_TIME_0, RWD_TIME_FUZZ)) {
991 /* 0 bit */
992 emit(0);
993 active = 1;
994 LED_A_ON();
995 } else if (active) {
996 /* invalid */
997 emit(-1);
998 active = 0;
999 LED_A_OFF();
1000 }
1001 }
1002 }
1003
1004 /* Frame end */
1005 if(time >= (RWD_TIME_1+RWD_TIME_FUZZ) && active) {
1006 emit(-1);
1007 active = 0;
1008 LED_A_OFF();
1009 }
1010
1011 if(time >= (20*RWD_TIME_1) && (timer->TC_SR & AT91C_TC_CLKSTA)) {
1012 timer->TC_CCR = AT91C_TC_CLKDIS;
1013 }
1014
1015 old_level = level;
1016 WDT_HIT();
1017 }
1018 if ( MF_DBGLEVEL >= 1) DbpString("Stopped");
1019 LEDsoff();
1020 }
1021
1022 //-----------------------------------------------------------------------------
1023 //-----------------------------------------------------------------------------
1024
1025
1026 //-----------------------------------------------------------------------------
1027 // Code up a string of octets at layer 2 (including CRC, we don't generate
1028 // that here) so that they can be transmitted to the reader. Doesn't transmit
1029 // them yet, just leaves them ready to send in ToSend[].
1030 //-----------------------------------------------------------------------------
1031 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
1032 // {
1033 // int i;
1034
1035 // ToSendReset();
1036
1037 // // Transmit a burst of ones, as the initial thing that lets the
1038 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
1039 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
1040 // // so I will too.
1041 // for(i = 0; i < 20; i++) {
1042 // ToSendStuffBit(1);
1043 // ToSendStuffBit(1);
1044 // ToSendStuffBit(1);
1045 // ToSendStuffBit(1);
1046 // }
1047
1048 // // Send SOF.
1049 // for(i = 0; i < 10; i++) {
1050 // ToSendStuffBit(0);
1051 // ToSendStuffBit(0);
1052 // ToSendStuffBit(0);
1053 // ToSendStuffBit(0);
1054 // }
1055 // for(i = 0; i < 2; i++) {
1056 // ToSendStuffBit(1);
1057 // ToSendStuffBit(1);
1058 // ToSendStuffBit(1);
1059 // ToSendStuffBit(1);
1060 // }
1061
1062 // for(i = 0; i < len; i++) {
1063 // int j;
1064 // uint8_t b = cmd[i];
1065
1066 // // Start bit
1067 // ToSendStuffBit(0);
1068 // ToSendStuffBit(0);
1069 // ToSendStuffBit(0);
1070 // ToSendStuffBit(0);
1071
1072 // // Data bits
1073 // for(j = 0; j < 8; j++) {
1074 // if(b & 1) {
1075 // ToSendStuffBit(1);
1076 // ToSendStuffBit(1);
1077 // ToSendStuffBit(1);
1078 // ToSendStuffBit(1);
1079 // } else {
1080 // ToSendStuffBit(0);
1081 // ToSendStuffBit(0);
1082 // ToSendStuffBit(0);
1083 // ToSendStuffBit(0);
1084 // }
1085 // b >>= 1;
1086 // }
1087
1088 // // Stop bit
1089 // ToSendStuffBit(1);
1090 // ToSendStuffBit(1);
1091 // ToSendStuffBit(1);
1092 // ToSendStuffBit(1);
1093 // }
1094
1095 // // Send EOF.
1096 // for(i = 0; i < 10; i++) {
1097 // ToSendStuffBit(0);
1098 // ToSendStuffBit(0);
1099 // ToSendStuffBit(0);
1100 // ToSendStuffBit(0);
1101 // }
1102 // for(i = 0; i < 2; i++) {
1103 // ToSendStuffBit(1);
1104 // ToSendStuffBit(1);
1105 // ToSendStuffBit(1);
1106 // ToSendStuffBit(1);
1107 // }
1108
1109 // // Convert from last byte pos to length
1110 // ToSendMax++;
1111 // }
1112
1113 //-----------------------------------------------------------------------------
1114 // The software UART that receives commands from the reader, and its state
1115 // variables.
1116 //-----------------------------------------------------------------------------
1117 static struct {
1118 enum {
1119 STATE_UNSYNCD,
1120 STATE_GOT_FALLING_EDGE_OF_SOF,
1121 STATE_AWAITING_START_BIT,
1122 STATE_RECEIVING_DATA
1123 } state;
1124 uint16_t shiftReg;
1125 int bitCnt;
1126 int byteCnt;
1127 int byteCntMax;
1128 int posCnt;
1129 uint8_t *output;
1130 } Uart;
1131
1132 /* Receive & handle a bit coming from the reader.
1133 *
1134 * This function is called 4 times per bit (every 2 subcarrier cycles).
1135 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1136 *
1137 * LED handling:
1138 * LED A -> ON once we have received the SOF and are expecting the rest.
1139 * LED A -> OFF once we have received EOF or are in error state or unsynced
1140 *
1141 * Returns: true if we received a EOF
1142 * false if we are still waiting for some more
1143 */
1144 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1145 // {
1146 // switch(Uart.state) {
1147 // case STATE_UNSYNCD:
1148 // if(!bit) {
1149 // // we went low, so this could be the beginning of an SOF
1150 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1151 // Uart.posCnt = 0;
1152 // Uart.bitCnt = 0;
1153 // }
1154 // break;
1155
1156 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1157 // Uart.posCnt++;
1158 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1159 // if(bit) {
1160 // if(Uart.bitCnt > 9) {
1161 // // we've seen enough consecutive
1162 // // zeros that it's a valid SOF
1163 // Uart.posCnt = 0;
1164 // Uart.byteCnt = 0;
1165 // Uart.state = STATE_AWAITING_START_BIT;
1166 // LED_A_ON(); // Indicate we got a valid SOF
1167 // } else {
1168 // // didn't stay down long enough
1169 // // before going high, error
1170 // Uart.state = STATE_UNSYNCD;
1171 // }
1172 // } else {
1173 // // do nothing, keep waiting
1174 // }
1175 // Uart.bitCnt++;
1176 // }
1177 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1178 // if(Uart.bitCnt > 12) {
1179 // // Give up if we see too many zeros without
1180 // // a one, too.
1181 // LED_A_OFF();
1182 // Uart.state = STATE_UNSYNCD;
1183 // }
1184 // break;
1185
1186 // case STATE_AWAITING_START_BIT:
1187 // Uart.posCnt++;
1188 // if(bit) {
1189 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1190 // // stayed high for too long between
1191 // // characters, error
1192 // Uart.state = STATE_UNSYNCD;
1193 // }
1194 // } else {
1195 // // falling edge, this starts the data byte
1196 // Uart.posCnt = 0;
1197 // Uart.bitCnt = 0;
1198 // Uart.shiftReg = 0;
1199 // Uart.state = STATE_RECEIVING_DATA;
1200 // }
1201 // break;
1202
1203 // case STATE_RECEIVING_DATA:
1204 // Uart.posCnt++;
1205 // if(Uart.posCnt == 2) {
1206 // // time to sample a bit
1207 // Uart.shiftReg >>= 1;
1208 // if(bit) {
1209 // Uart.shiftReg |= 0x200;
1210 // }
1211 // Uart.bitCnt++;
1212 // }
1213 // if(Uart.posCnt >= 4) {
1214 // Uart.posCnt = 0;
1215 // }
1216 // if(Uart.bitCnt == 10) {
1217 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1218 // {
1219 // // this is a data byte, with correct
1220 // // start and stop bits
1221 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1222 // Uart.byteCnt++;
1223
1224 // if(Uart.byteCnt >= Uart.byteCntMax) {
1225 // // Buffer overflowed, give up
1226 // LED_A_OFF();
1227 // Uart.state = STATE_UNSYNCD;
1228 // } else {
1229 // // so get the next byte now
1230 // Uart.posCnt = 0;
1231 // Uart.state = STATE_AWAITING_START_BIT;
1232 // }
1233 // } else if (Uart.shiftReg == 0x000) {
1234 // // this is an EOF byte
1235 // LED_A_OFF(); // Finished receiving
1236 // Uart.state = STATE_UNSYNCD;
1237 // if (Uart.byteCnt != 0) {
1238 // return TRUE;
1239 // }
1240 // } else {
1241 // // this is an error
1242 // LED_A_OFF();
1243 // Uart.state = STATE_UNSYNCD;
1244 // }
1245 // }
1246 // break;
1247
1248 // default:
1249 // LED_A_OFF();
1250 // Uart.state = STATE_UNSYNCD;
1251 // break;
1252 // }
1253
1254 // return FALSE;
1255 // }
1256
1257
1258 static void UartReset() {
1259 Uart.byteCntMax = 3;
1260 Uart.state = STATE_UNSYNCD;
1261 Uart.byteCnt = 0;
1262 Uart.bitCnt = 0;
1263 Uart.posCnt = 0;
1264 memset(Uart.output, 0x00, 3);
1265 }
1266
1267 // static void UartInit(uint8_t *data) {
1268 // Uart.output = data;
1269 // UartReset();
1270 // }
1271
1272 //=============================================================================
1273 // An LEGIC reader. We take layer two commands, code them
1274 // appropriately, and then send them to the tag. We then listen for the
1275 // tag's response, which we leave in the buffer to be demodulated on the
1276 // PC side.
1277 //=============================================================================
1278
1279 static struct {
1280 enum {
1281 DEMOD_UNSYNCD,
1282 DEMOD_PHASE_REF_TRAINING,
1283 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1284 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1285 DEMOD_AWAITING_START_BIT,
1286 DEMOD_RECEIVING_DATA
1287 } state;
1288 int bitCount;
1289 int posCount;
1290 int thisBit;
1291 uint16_t shiftReg;
1292 uint8_t *output;
1293 int len;
1294 int sumI;
1295 int sumQ;
1296 } Demod;
1297
1298 /*
1299 * Handles reception of a bit from the tag
1300 *
1301 * This function is called 2 times per bit (every 4 subcarrier cycles).
1302 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1303 *
1304 * LED handling:
1305 * LED C -> ON once we have received the SOF and are expecting the rest.
1306 * LED C -> OFF once we have received EOF or are unsynced
1307 *
1308 * Returns: true if we received a EOF
1309 * false if we are still waiting for some more
1310 *
1311 */
1312
1313 #ifndef SUBCARRIER_DETECT_THRESHOLD
1314 # define SUBCARRIER_DETECT_THRESHOLD 8
1315 #endif
1316
1317 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
1318 #ifndef CHECK_FOR_SUBCARRIER
1319 # define CHECK_FOR_SUBCARRIER() { v = MAX(ai, aq) + MIN(halfci, halfcq); }
1320 #endif
1321
1322 // The soft decision on the bit uses an estimate of just the
1323 // quadrant of the reference angle, not the exact angle.
1324 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
1325 #define MAKE_SOFT_DECISION() { \
1326 if(Demod.sumI > 0) \
1327 v = ci; \
1328 else \
1329 v = -ci; \
1330 \
1331 if(Demod.sumQ > 0) \
1332 v += cq; \
1333 else \
1334 v -= cq; \
1335 \
1336 }
1337
1338 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1339 {
1340 int v = 0;
1341 int ai = ABS(ci);
1342 int aq = ABS(cq);
1343 int halfci = (ai >> 1);
1344 int halfcq = (aq >> 1);
1345
1346 switch(Demod.state) {
1347 case DEMOD_UNSYNCD:
1348
1349 CHECK_FOR_SUBCARRIER()
1350
1351 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1352 Demod.state = DEMOD_PHASE_REF_TRAINING;
1353 Demod.sumI = ci;
1354 Demod.sumQ = cq;
1355 Demod.posCount = 1;
1356 }
1357 break;
1358
1359 case DEMOD_PHASE_REF_TRAINING:
1360 if(Demod.posCount < 8) {
1361
1362 CHECK_FOR_SUBCARRIER()
1363
1364 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1365 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1366 // note: synchronization time > 80 1/fs
1367 Demod.sumI += ci;
1368 Demod.sumQ += cq;
1369 ++Demod.posCount;
1370 } else {
1371 // subcarrier lost
1372 Demod.state = DEMOD_UNSYNCD;
1373 }
1374 } else {
1375 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1376 }
1377 break;
1378
1379 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1380
1381 MAKE_SOFT_DECISION()
1382
1383 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1384 // logic '0' detected
1385 if (v <= 0) {
1386
1387 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1388
1389 // start of SOF sequence
1390 Demod.posCount = 0;
1391 } else {
1392 // maximum length of TR1 = 200 1/fs
1393 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1394 }
1395 ++Demod.posCount;
1396 break;
1397
1398 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1399 ++Demod.posCount;
1400
1401 MAKE_SOFT_DECISION()
1402
1403 if(v > 0) {
1404 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1405 if(Demod.posCount < 10*2) {
1406 Demod.state = DEMOD_UNSYNCD;
1407 } else {
1408 LED_C_ON(); // Got SOF
1409 Demod.state = DEMOD_AWAITING_START_BIT;
1410 Demod.posCount = 0;
1411 Demod.len = 0;
1412 }
1413 } else {
1414 // low phase of SOF too long (> 12 etu)
1415 if(Demod.posCount > 13*2) {
1416 Demod.state = DEMOD_UNSYNCD;
1417 LED_C_OFF();
1418 }
1419 }
1420 break;
1421
1422 case DEMOD_AWAITING_START_BIT:
1423 ++Demod.posCount;
1424
1425 MAKE_SOFT_DECISION()
1426
1427 if(v > 0) {
1428 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1429 if(Demod.posCount > 3*2) {
1430 Demod.state = DEMOD_UNSYNCD;
1431 LED_C_OFF();
1432 }
1433 } else {
1434 // start bit detected
1435 Demod.bitCount = 0;
1436 Demod.posCount = 1; // this was the first half
1437 Demod.thisBit = v;
1438 Demod.shiftReg = 0;
1439 Demod.state = DEMOD_RECEIVING_DATA;
1440 }
1441 break;
1442
1443 case DEMOD_RECEIVING_DATA:
1444
1445 MAKE_SOFT_DECISION()
1446
1447 if(Demod.posCount == 0) {
1448 // first half of bit
1449 Demod.thisBit = v;
1450 Demod.posCount = 1;
1451 } else {
1452 // second half of bit
1453 Demod.thisBit += v;
1454 Demod.shiftReg >>= 1;
1455 // logic '1'
1456 if(Demod.thisBit > 0)
1457 Demod.shiftReg |= 0x200;
1458
1459 ++Demod.bitCount;
1460
1461 if(Demod.bitCount == 10) {
1462
1463 uint16_t s = Demod.shiftReg;
1464
1465 if((s & 0x200) && !(s & 0x001)) {
1466 // stop bit == '1', start bit == '0'
1467 uint8_t b = (s >> 1);
1468 Demod.output[Demod.len] = b;
1469 ++Demod.len;
1470 Demod.state = DEMOD_AWAITING_START_BIT;
1471 } else {
1472 Demod.state = DEMOD_UNSYNCD;
1473 LED_C_OFF();
1474
1475 if(s == 0x000) {
1476 // This is EOF (start, stop and all data bits == '0'
1477 return TRUE;
1478 }
1479 }
1480 }
1481 Demod.posCount = 0;
1482 }
1483 break;
1484
1485 default:
1486 Demod.state = DEMOD_UNSYNCD;
1487 LED_C_OFF();
1488 break;
1489 }
1490 return FALSE;
1491 }
1492
1493 // Clear out the state of the "UART" that receives from the tag.
1494 static void DemodReset() {
1495 Demod.len = 0;
1496 Demod.state = DEMOD_UNSYNCD;
1497 Demod.posCount = 0;
1498 Demod.sumI = 0;
1499 Demod.sumQ = 0;
1500 Demod.bitCount = 0;
1501 Demod.thisBit = 0;
1502 Demod.shiftReg = 0;
1503 memset(Demod.output, 0x00, 3);
1504 }
1505
1506 static void DemodInit(uint8_t *data) {
1507 Demod.output = data;
1508 DemodReset();
1509 }
1510
1511 /*
1512 * Demodulate the samples we received from the tag, also log to tracebuffer
1513 * quiet: set to 'TRUE' to disable debug output
1514 */
1515 #define LEGIC_DMA_BUFFER_SIZE 256
1516 static void GetSamplesForLegicDemod(int n, bool quiet)
1517 {
1518 int max = 0;
1519 bool gotFrame = FALSE;
1520 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1521 int ci, cq, samples = 0;
1522
1523 BigBuf_free();
1524
1525 // And put the FPGA in the appropriate mode
1526 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1527
1528 // The response (tag -> reader) that we're receiving.
1529 // Set up the demodulator for tag -> reader responses.
1530 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1531
1532 // The DMA buffer, used to stream samples from the FPGA
1533 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1534 int8_t *upTo = dmaBuf;
1535
1536 // Setup and start DMA.
1537 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1538 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1539 return;
1540 }
1541
1542 // Signal field is ON with the appropriate LED:
1543 LED_D_ON();
1544 for(;;) {
1545 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1546 if(behindBy > max) max = behindBy;
1547
1548 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1549 ci = upTo[0];
1550 cq = upTo[1];
1551 upTo += 2;
1552 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1553 upTo = dmaBuf;
1554 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1555 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1556 }
1557 lastRxCounter -= 2;
1558 if(lastRxCounter <= 0)
1559 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1560
1561 samples += 2;
1562
1563 gotFrame = HandleLegicSamplesDemod(ci , cq );
1564 if ( gotFrame )
1565 break;
1566 }
1567
1568 if(samples > n || gotFrame)
1569 break;
1570 }
1571
1572 FpgaDisableSscDma();
1573
1574 if (!quiet && Demod.len == 0) {
1575 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1576 max,
1577 samples,
1578 gotFrame,
1579 Demod.len,
1580 Demod.sumI,
1581 Demod.sumQ
1582 );
1583 }
1584
1585 //Tracing
1586 if (Demod.len > 0) {
1587 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1588 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1589 }
1590 }
1591 //-----------------------------------------------------------------------------
1592 // Transmit the command (to the tag) that was placed in ToSend[].
1593 //-----------------------------------------------------------------------------
1594 static void TransmitForLegic(void)
1595 {
1596 int c;
1597
1598 FpgaSetupSsc();
1599
1600 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1601 AT91C_BASE_SSC->SSC_THR = 0xff;
1602
1603 // Signal field is ON with the appropriate Red LED
1604 LED_D_ON();
1605
1606 // Signal we are transmitting with the Green LED
1607 LED_B_ON();
1608 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1609
1610 for(c = 0; c < 10;) {
1611 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1612 AT91C_BASE_SSC->SSC_THR = 0xff;
1613 c++;
1614 }
1615 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1616 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1617 (void)r;
1618 }
1619 WDT_HIT();
1620 }
1621
1622 c = 0;
1623 for(;;) {
1624 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1625 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1626 legic_prng_forward(1); // forward the lfsr
1627 c++;
1628 if(c >= ToSendMax) {
1629 break;
1630 }
1631 }
1632 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1633 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1634 (void)r;
1635 }
1636 WDT_HIT();
1637 }
1638 LED_B_OFF();
1639 }
1640
1641
1642 //-----------------------------------------------------------------------------
1643 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1644 // so that it is ready to transmit to the tag using TransmitForLegic().
1645 //-----------------------------------------------------------------------------
1646 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1647 {
1648 int i, j;
1649 uint8_t b;
1650
1651 ToSendReset();
1652
1653 // Send SOF
1654 for(i = 0; i < 7; i++)
1655 ToSendStuffBit(1);
1656
1657
1658 for(i = 0; i < cmdlen; i++) {
1659 // Start bit
1660 ToSendStuffBit(0);
1661
1662 // Data bits
1663 b = cmd[i];
1664 for(j = 0; j < bits; j++) {
1665 if(b & 1) {
1666 ToSendStuffBit(1);
1667 } else {
1668 ToSendStuffBit(0);
1669 }
1670 b >>= 1;
1671 }
1672 }
1673
1674 // Convert from last character reference to length
1675 ++ToSendMax;
1676 }
1677
1678 /**
1679 Convenience function to encode, transmit and trace Legic comms
1680 **/
1681 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1682 {
1683 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1684 TransmitForLegic();
1685 if (tracing) {
1686 uint8_t parity[1] = {0x00};
1687 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1688 }
1689 }
1690
1691 int ice_legic_select_card()
1692 {
1693 //int cmd_size=0, card_size=0;
1694 uint8_t wakeup[] = { 0x7F };
1695 uint8_t getid[] = {0x19};
1696
1697 //legic_prng_init(SESSION_IV);
1698
1699 // first, wake up the tag, 7bits
1700 CodeAndTransmitLegicAsReader(wakeup, sizeof(wakeup), 7);
1701
1702 GetSamplesForLegicDemod(1000, TRUE);
1703
1704 //frame_receiveAsReader(&current_frame, 6, 1);
1705
1706 legic_prng_forward(1); /* we wait anyways */
1707
1708 //while(timer->TC_CV < 387) ; /* ~ 258us */
1709 //frame_sendAsReader(0x19, 6);
1710 CodeAndTransmitLegicAsReader(getid, sizeof(getid), 8);
1711 GetSamplesForLegicDemod(1000, TRUE);
1712
1713 //if (Demod.len < 14) return 2;
1714 Dbprintf("CARD TYPE: %02x LEN: %d", Demod.output[0], Demod.len);
1715
1716 switch(Demod.output[0]) {
1717 case 0x1d:
1718 DbpString("MIM 256 card found");
1719 // cmd_size = 9;
1720 // card_size = 256;
1721 break;
1722 case 0x3d:
1723 DbpString("MIM 1024 card found");
1724 // cmd_size = 11;
1725 // card_size = 1024;
1726 break;
1727 default:
1728 return -1;
1729 }
1730
1731 // if(bytes == -1)
1732 // bytes = card_size;
1733
1734 // if(bytes + offset >= card_size)
1735 // bytes = card_size - offset;
1736
1737 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1738 set_tracing(FALSE);
1739 return 1;
1740 }
1741
1742 // Set up LEGIC communication
1743 void ice_legic_setup() {
1744
1745 // standard things.
1746 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1747 BigBuf_free(); BigBuf_Clear_ext(false);
1748 clear_trace();
1749 set_tracing(TRUE);
1750 DemodReset();
1751 UartReset();
1752
1753 // Set up the synchronous serial port
1754 FpgaSetupSsc();
1755
1756 // connect Demodulated Signal to ADC:
1757 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1758
1759 // Signal field is on with the appropriate LED
1760 LED_D_ON();
1761 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1762 SpinDelay(20);
1763 // Start the timer
1764 //StartCountSspClk();
1765
1766 // initalize CRC
1767 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
1768
1769 // initalize prng
1770 legic_prng_init(0);
1771 }
Impressum, Datenschutz