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