1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
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
7 //-----------------------------------------------------------------------------
8 // LEGIC RF simulation code
9 //-----------------------------------------------------------------------------
12 static struct legic_frame
{
23 static crc_t legic_crc
;
24 static int legic_read_count
;
25 static uint32_t legic_prng_bc
;
26 static uint32_t legic_prng_iv
;
28 static int legic_phase_drift
;
29 static int legic_frame_drift
;
30 static int legic_reqresp_drift
;
36 static void setup_timer(void) {
37 // Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging
38 // this it won't be terribly accurate but should be good enough.
40 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
41 timer = AT91C_BASE_TC1;
42 timer->TC_CCR = AT91C_TC_CLKDIS;
43 timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
44 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
47 // Set up Timer 2 to use for measuring time between frames in
48 // tag simulation mode. Runs 4x faster as Timer 1
50 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC2);
51 prng_timer = AT91C_BASE_TC2;
52 prng_timer->TC_CCR = AT91C_TC_CLKDIS;
53 prng_timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV2_CLOCK;
54 prng_timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
57 AT91C_BASE_PMC->PMC_PCER |= (0x1 << 12) | (0x1 << 13) | (0x1 << 14);
58 AT91C_BASE_TCB->TCB_BMR = AT91C_TCB_TC0XC0S_NONE | AT91C_TCB_TC1XC1S_TIOA0 | AT91C_TCB_TC2XC2S_NONE;
61 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable
62 AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz)/32 -- tick=1.5mks
63 AT91C_TC_WAVE | AT91C_TC_WAVESEL_UP_AUTO | AT91C_TC_ACPA_CLEAR |
64 AT91C_TC_ACPC_SET | AT91C_TC_ASWTRG_SET;
65 AT91C_BASE_TC0->TC_RA = 1;
66 AT91C_BASE_TC0->TC_RC = 0xBFFF + 1; // 0xC000
70 // At TIMER_CLOCK3 (MCK/32)
71 //#define RWD_TIME_1 150 /* RWD_TIME_PAUSE off, 80us on = 100us */
72 //#define RWD_TIME_0 90 /* RWD_TIME_PAUSE off, 40us on = 60us */
73 //#define RWD_TIME_PAUSE 30 /* 20us */
75 // testing calculating in (us) microseconds.
76 #define RWD_TIME_1 120 // READER_TIME_PAUSE 20us off, 80us on = 100us 80 * 1.5 == 120ticks
77 #define RWD_TIME_0 60 // READER_TIME_PAUSE 20us off, 40us on = 60us 40 * 1.5 == 60ticks
78 #define RWD_TIME_PAUSE 30 // 20us == 20 * 1.5 == 30ticks */
79 #define TAG_BIT_PERIOD 150 // 100us == 100 * 1.5 == 150ticks
80 #define TAG_FRAME_WAIT 495 // 330us from READER frame end to TAG frame start. 330 * 1.5 == 495
82 #define RWD_TIME_FUZZ 20 // rather generous 13us, since the peak detector + hysteresis fuzz quite a bit
84 #define SIM_DIVISOR 586 /* prng_time/SIM_DIVISOR count prng needs to be forwared */
85 #define SIM_SHIFT 900 /* prng_time+SIM_SHIFT shift of delayed start */
87 #define OFFSET_LOG 1024
89 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz)))
92 # define SHORT_COIL LOW(GPIO_SSC_DOUT);
95 # define OPEN_COIL HIGH(GPIO_SSC_DOUT);
98 uint32_t sendFrameStop
= 0;
100 // Pause pulse, off in 20us / 30ticks,
101 // ONE / ZERO bit pulse,
102 // one == 80us / 120ticks
103 // zero == 40us / 60ticks
105 # define COIL_PULSE(x) \
108 WaitTicks( (RWD_TIME_PAUSE) ); \
114 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
115 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
116 #define LEGIC_CARD_MEMSIZE 1024
117 static uint8_t* cardmem
;
119 static void frame_append_bit(struct legic_frame
* const f
, uint8_t bit
) {
120 // Overflow, won't happen
121 if (f
->bits
>= 31) return;
123 f
->data
|= (bit
<< f
->bits
);
127 static void frame_clean(struct legic_frame
* const f
) {
132 // Prng works when waiting in 99.1us cycles.
133 // and while sending/receiving in bit frames (100, 60)
134 /*static void CalibratePrng( uint32_t time){
135 // Calculate Cycles based on timer 100us
136 uint32_t i = (time - sendFrameStop) / 100 ;
138 // substract cycles of finished frames
139 int k = i - legic_prng_count()+1;
141 // substract current frame length, rewind to beginning
143 legic_prng_forward(k);
147 /* Generate Keystream */
148 uint32_t get_key_stream(int skip
, int count
) {
152 // Use int to enlarge timer tc to 32bit
153 legic_prng_bc
+= prng_timer
->TC_CV
;
155 // reset the prng timer.
156 ResetTimer(prng_timer
);
158 /* If skip == -1, forward prng time based */
160 i
= (legic_prng_bc
+ SIM_SHIFT
)/SIM_DIVISOR
; /* Calculate Cycles based on timer */
161 i
-= legic_prng_count(); /* substract cycles of finished frames */
162 i
-= count
; /* substract current frame length, rewind to beginning */
163 legic_prng_forward(i
);
165 legic_prng_forward(skip
);
168 i
= (count
== 6) ? -1 : legic_read_count
;
170 /* Write Time Data into LOG */
171 // uint8_t *BigBuf = BigBuf_get_addr();
172 // BigBuf[OFFSET_LOG+128+i] = legic_prng_count();
173 // BigBuf[OFFSET_LOG+256+i*4] = (legic_prng_bc >> 0) & 0xff;
174 // BigBuf[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
175 // BigBuf[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
176 // BigBuf[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
177 // BigBuf[OFFSET_LOG+384+i] = count;
179 /* Generate KeyStream */
180 for(i
=0; i
<count
; i
++) {
181 key
|= legic_prng_get_bit() << i
;
182 legic_prng_forward(1);
187 /* Send a frame in tag mode, the FPGA must have been set up by
190 void frame_send_tag(uint16_t response
, uint8_t bits
, uint8_t crypt
) {
191 /* Bitbang the response */
193 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
194 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
196 /* Use time to crypt frame */
198 legic_prng_forward(2); /* TAG_FRAME_WAIT -> shift by 2 */
199 response
^= legic_prng_get_bits(bits
);
202 /* Wait for the frame start */
203 WaitUS( TAG_FRAME_WAIT
);
206 for(int i
= 0; i
< bits
; i
++) {
221 /* Send a frame in reader mode, the FPGA must have been set up by
224 void frame_sendAsReader(uint32_t data
, uint8_t bits
){
226 uint32_t starttime
= GET_TICKS
, send
= 0;
228 uint8_t prngstart
= legic_prng_count() ;
230 // xor lsfr onto data.
231 send
= data
^ legic_prng_get_bits(bits
);
233 for (; mask
< BITMASK(bits
); mask
<<= 1) {
235 COIL_PULSE(RWD_TIME_1
);
237 COIL_PULSE(RWD_TIME_0
);
241 // Final pause to mark the end of the frame
244 sendFrameStop
= GET_TICKS
;
245 uint8_t cmdbytes
[] = {
254 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, sendFrameStop
, NULL
, TRUE
);
257 /* Receive a frame from the card in reader emulation mode, the FPGA and
258 * timer must have been set up by LegicRfReader and frame_sendAsReader.
260 * The LEGIC RF protocol from card to reader does not include explicit
261 * frame start/stop information or length information. The reader must
262 * know beforehand how many bits it wants to receive. (Notably: a card
263 * sending a stream of 0-bits is indistinguishable from no card present.)
265 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
266 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
267 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
268 * for edges. Count the edges in each bit interval. If they are approximately
269 * 0 this was a 0-bit, if they are approximately equal to the number of edges
270 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
271 * timer that's still running from frame_sendAsReader in order to get a synchronization
272 * with the frame that we just sent.
274 * FIXME: Because we're relying on the hysteresis to just do the right thing
275 * the range is severely reduced (and you'll probably also need a good antenna).
276 * So this should be fixed some time in the future for a proper receiver.
278 static void frame_receiveAsReader(struct legic_frame
* const f
, uint8_t bits
) {
281 if ( bits
> 32 ) return;
283 uint8_t i
= bits
, edges
= 0;
285 uint32_t the_bit
= 1, next_bit_at
= 0, data
;
287 int old_level
= 0, level
= 0;
289 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
290 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
292 // calibrate the prng.
294 legic_prng_forward(2);
296 // precompute the cipher
297 uint8_t prngstart
= legic_prng_count() ;
299 data
= lsfr
= legic_prng_get_bits(bits
);
301 //FIXED time between sending frame and now listening frame. 330us
302 // 387 = 0x19 0001 1001
304 // 500 = 0x1C 0001 1100
305 uint32_t starttime
= GET_TICKS
;
306 //uint16_t mywait = TAG_FRAME_WAIT - (starttime - sendFrameStop);
307 //uint16_t mywait = 495 - (starttime - sendFrameStop);
309 //Dbprintf("6 WAIT %d", 495 - 9 - 9 );
310 WaitTicks( 495 - 9 - 9 );
312 //Dbprintf("x WAIT %d", mywait );
313 //WaitTicks( mywait );
317 next_bit_at
= GET_TICKS
+ TAG_BIT_PERIOD
;
322 while ( GET_TICKS
< next_bit_at
) {
324 level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
326 if (level
!= old_level
)
331 if(edges
> 20 && adjust
== 0) {
337 next_bit_at
+= TAG_BIT_PERIOD
;
339 // We expect 42 edges == ONE
340 //if (edges > 20 && edges < 64)
351 uint8_t cmdbytes
[] = {
355 BYTEx(data
, 0) ^ BYTEx(lsfr
,0),
356 BYTEx(data
, 1) ^ BYTEx(lsfr
,1),
360 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, FALSE
);
363 // Setup pm3 as a Legic Reader
364 static uint32_t setup_phase_reader(uint8_t iv
) {
366 // Switch on carrier and let the tag charge for 1ms
376 frame_sendAsReader(iv
, 7);
378 // Now both tag and reader has same IV. Prng can start.
381 frame_receiveAsReader(¤t_frame
, 6);
383 // fixed delay before sending ack.
384 WaitTicks(366); // 244us
385 legic_prng_forward(1); //240us / 100 == 2.4 iterations
387 // Send obsfuscated acknowledgment frame.
388 // 0x19 = 0x18 MIM22, 0x01 LSB READCMD
389 // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD
390 switch ( current_frame
.data
) {
391 case 0x0D: frame_sendAsReader(0x19, 6); break;
393 case 0x3D: frame_sendAsReader(0x39, 6); break;
396 return current_frame
.data
;
399 static void LegicCommonInit(void) {
401 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
402 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
);
403 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
405 /* Bitbang the transmitter */
407 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
408 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
410 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
411 cardmem
= BigBuf_malloc(LEGIC_CARD_MEMSIZE
);
412 memset(cardmem
, 0x00, LEGIC_CARD_MEMSIZE
);
416 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
421 // Switch off carrier, make sure tag is reset
422 static void switch_off_tag_rwd(void) {
429 // calculate crc4 for a legic READ command
430 // 5,8,10 address size.
431 static uint32_t legic4Crc(uint8_t legicCmd
, uint16_t byte_index
, uint8_t value
, uint8_t cmd_sz
) {
432 crc_clear(&legic_crc
);
433 //uint32_t temp = (value << cmd_sz) | (byte_index << 1) | legicCmd;
434 //crc_update(&legic_crc, temp, cmd_sz + 8 );
435 crc_update(&legic_crc
, 1, 1); /* CMD_READ */
436 crc_update(&legic_crc
, byte_index
, cmd_sz
-1);
437 crc_update(&legic_crc
, value
, 8);
438 return crc_finish(&legic_crc
);
441 int legic_read_byte(int byte_index
, int cmd_sz
) {
443 uint8_t byte
= 0, crc
= 0, calcCrc
= 0;
444 uint32_t cmd
= (byte_index
<< 1) | LEGIC_READ
;
453 legic_prng_forward(4); // 460 / 100 = 4.6 iterations
455 frame_sendAsReader(cmd
, cmd_sz
);
456 frame_receiveAsReader(¤t_frame
, 12);
458 byte
= BYTEx(current_frame
.data
, 0);
459 calcCrc
= legic4Crc(LEGIC_READ
, byte_index
, byte
, cmd_sz
);
460 crc
= BYTEx(current_frame
.data
, 1);
462 if( calcCrc
!= crc
) {
463 Dbprintf("!!! crc mismatch: expected %x but got %x !!!", calcCrc
, crc
);
470 * - assemble a write_cmd_frame with crc and send it
471 * - wait until the tag sends back an ACK ('1' bit unencrypted)
472 * - forward the prng based on the timing
474 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) {
475 int legic_write_byte(uint8_t byte
, uint16_t addr
, uint8_t addr_sz
) {
477 //do not write UID, CRC at offset 0-4.
478 if (addr
<= 4) return 0;
481 crc_clear(&legic_crc
);
482 crc_update(&legic_crc
, 0, 1); /* CMD_WRITE */
483 crc_update(&legic_crc
, addr
, addr_sz
);
484 crc_update(&legic_crc
, byte
, 8);
485 uint32_t crc
= crc_finish(&legic_crc
);
487 uint32_t crc2
= legic4Crc(LEGIC_WRITE
, addr
, byte
, addr_sz
+1);
489 Dbprintf("crc is missmatch");
491 // send write command
492 uint32_t cmd
= ((crc
<<(addr_sz
+1+8)) //CRC
493 |(byte
<<(addr_sz
+1)) //Data
494 |(addr
<<1) //Address
495 | LEGIC_WRITE
); //CMD = Write
497 uint32_t cmd_sz
= addr_sz
+1+8+4; //crc+data+cmd
499 legic_prng_forward(2); /* we wait anyways */
501 WaitUS(TAG_FRAME_WAIT
);
503 frame_sendAsReader(cmd
, cmd_sz
);
505 // wllm-rbnt doesnt have these
506 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
507 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
510 int t
, old_level
= 0, edges
= 0;
513 WaitUS(TAG_FRAME_WAIT
);
515 for( t
= 0; t
< 80; ++t
) {
517 next_bit_at
+= TAG_BIT_PERIOD
;
518 while(timer
->TC_CV
< next_bit_at
) {
519 int level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
520 if(level
!= old_level
)
525 if(edges
> 20 && edges
< 60) { /* expected are 42 edges */
526 int t
= timer
->TC_CV
;
527 int c
= t
/ TAG_BIT_PERIOD
;
530 legic_prng_forward(c
);
539 int LegicRfReader(int offset
, int bytes
, int iv
) {
541 uint16_t byte_index
= 0;
542 uint8_t cmd_sz
= 0, isOK
= 1;
547 uint32_t tag_type
= setup_phase_reader(iv
);
549 switch_off_tag_rwd();
553 if ( MF_DBGLEVEL
>= 2) DbpString("MIM22 card found, reading card");
558 if ( MF_DBGLEVEL
>= 2) DbpString("MIM256 card found, reading card");
563 if ( MF_DBGLEVEL
>= 2) DbpString("MIM1024 card found, reading card");
568 if ( MF_DBGLEVEL
>= 1) Dbprintf("Unknown card format: %x", tag_type
);
576 if (bytes
+ offset
>= card_sz
)
577 bytes
= card_sz
- offset
;
579 // Start setup and read bytes.
580 setup_phase_reader(iv
);
583 while (byte_index
< bytes
) {
584 int r
= legic_read_byte(byte_index
+ offset
, cmd_sz
);
586 if (r
== -1 || BUTTON_PRESS()) {
587 if ( MF_DBGLEVEL
>= 3) DbpString("operation aborted");
591 cardmem
[++byte_index
] = r
;
597 switch_off_tag_rwd();
599 uint8_t len
= (bytes
& 0x3FF);
600 cmd_send(CMD_ACK
,isOK
,len
,0,cardmem
,len
);
604 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
608 setup_phase_reader(iv);
609 //legic_prng_forward(2);
610 while(byte_index < bytes) {
613 //check if the DCF should be changed
614 if ( (offset == 0x05) && (bytes == 0x02) ) {
615 //write DCF in reverse order (addr 0x06 before 0x05)
616 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
617 //legic_prng_forward(1);
620 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
622 //legic_prng_forward(1);
625 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
627 if((r != 0) || BUTTON_PRESS()) {
628 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
629 switch_off_tag_rwd();
637 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
641 DbpString("write successful");
645 void LegicRfWriter(int offset
, int bytes
, int iv
) {
647 int byte_index
= 0, addr_sz
= 0;
651 if ( MF_DBGLEVEL
>= 2) DbpString("setting up legic card");
653 uint32_t tag_type
= setup_phase_reader(iv
);
655 switch_off_tag_rwd();
659 if(offset
+bytes
> 22) {
660 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset
+ bytes
);
664 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
667 if(offset
+bytes
> 0x100) {
668 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset
+ bytes
);
672 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
675 if(offset
+bytes
> 0x400) {
676 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset
+ bytes
);
680 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset
, offset
+ bytes
);
683 Dbprintf("No or unknown card found, aborting");
688 setup_phase_reader(iv
);
690 while(byte_index
< bytes
) {
692 //check if the DCF should be changed
693 if ( ((byte_index
+offset
) == 0x05) && (bytes
>= 0x02) ) {
694 //write DCF in reverse order (addr 0x06 before 0x05)
695 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), addr_sz
);
697 // write second byte on success...
700 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), addr_sz
);
704 r
= legic_write_byte(cardmem
[byte_index
+offset
], byte_index
+offset
, addr_sz
);
707 if ((r
!= 0) || BUTTON_PRESS()) {
708 Dbprintf("operation aborted @ 0x%03.3x", byte_index
);
709 switch_off_tag_rwd();
718 if ( MF_DBGLEVEL
>= 1) DbpString("write successful");
721 void LegicRfRawWriter(int address
, int byte
, int iv
) {
723 int byte_index
= 0, addr_sz
= 0;
727 if ( MF_DBGLEVEL
>= 2) DbpString("setting up legic card");
729 uint32_t tag_type
= setup_phase_reader(iv
);
731 switch_off_tag_rwd();
736 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address
);
740 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
743 if(address
> 0x100) {
744 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address
);
748 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
751 if(address
> 0x400) {
752 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address
);
756 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address
, byte
);
759 Dbprintf("No or unknown card found, aborting");
763 Dbprintf("integer value: %d address: %d addr_sz: %d", byte
, address
, addr_sz
);
766 setup_phase_reader(iv
);
768 int r
= legic_write_byte(byte
, address
, addr_sz
);
770 if((r
!= 0) || BUTTON_PRESS()) {
771 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index
, r
);
772 switch_off_tag_rwd();
778 if ( MF_DBGLEVEL
>= 1) DbpString("write successful");
781 void LegicRfInfo(void){
784 uint32_t tag_type
= setup_phase_reader(0x55);
786 uint16_t card_sz
= 0;
802 cmd_send(CMD_ACK
,0,0,0,0,0);
807 uint8_t uid
[] = {0,0,0,0};
808 for ( uint8_t i
= 0; i
< sizeof(uid
); ++i
) {
809 int r
= legic_read_byte(i
, cmd_sz
);
811 cmd_send(CMD_ACK
,0,0,0,0,0);
817 cmd_send(CMD_ACK
,1,card_sz
,0,uid
,sizeof(uid
));
819 switch_off_tag_rwd();
824 /* Handle (whether to respond) a frame in tag mode
825 * Only called when simulating a tag.
827 static void frame_handle_tag(struct legic_frame
const * const f
)
829 uint8_t *BigBuf
= BigBuf_get_addr();
831 /* First Part of Handshake (IV) */
837 ResetTimer(prng_timer
);
839 legic_prng_init(f
->data
);
840 frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1B */
841 legic_state
= STATE_IV
;
842 legic_read_count
= 0;
844 legic_prng_iv
= f
->data
;
853 if(legic_state
== STATE_IV
) {
854 int local_key
= get_key_stream(3, 6);
855 int xored
= 0x39 ^ local_key
;
856 if((f
->bits
== 6) && (f
->data
== xored
)) {
857 legic_state
= STATE_CON
;
864 legic_state
= STATE_DISCON
;
866 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv
, f
->data
, local_key
, xored
);
873 if(legic_state
== STATE_CON
) {
874 int key
= get_key_stream(2, 11); //legic_phase_drift, 11);
875 int addr
= f
->data
^ key
; addr
= addr
>> 1;
876 int data
= BigBuf
[addr
];
877 int hash
= legic4Crc(LEGIC_READ
, addr
, data
, 11) << 8;
878 BigBuf
[OFFSET_LOG
+legic_read_count
] = (uint8_t)addr
;
881 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
882 legic_prng_forward(legic_reqresp_drift
);
884 frame_send_tag(hash
| data
, 12, 1);
887 legic_prng_forward(2);
895 int key
= get_key_stream(-1, 23); //legic_frame_drift, 23);
896 int addr
= f
->data
^ key
; addr
= addr
>> 1; addr
= addr
& 0x3ff;
897 int data
= f
->data
^ key
; data
= data
>> 11; data
= data
& 0xff;
900 legic_state
= STATE_DISCON
;
902 Dbprintf("write - addr: %x, data: %x", addr
, data
);
906 if(legic_state
!= STATE_DISCON
) {
907 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f
->bits
, f
->data
, legic_state
, legic_read_count
);
909 Dbprintf("IV: %03.3x", legic_prng_iv
);
910 for(i
= 0; i
<legic_read_count
; i
++) {
911 Dbprintf("Read Nb: %u, Addr: %u", i
, BigBuf
[OFFSET_LOG
+i
]);
914 for(i
= -1; i
<legic_read_count
; i
++) {
916 t
= BigBuf
[OFFSET_LOG
+256+i
*4];
917 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+1] << 8;
918 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+2] <<16;
919 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+3] <<24;
921 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
922 BigBuf
[OFFSET_LOG
+128+i
],
923 BigBuf
[OFFSET_LOG
+384+i
],
927 legic_state
= STATE_DISCON
;
928 legic_read_count
= 0;
934 /* Read bit by bit untill full frame is received
935 * Call to process frame end answer
937 static void emit(int bit
) {
941 frame_append_bit(¤t_frame
, 1);
944 frame_append_bit(¤t_frame
, 0);
947 if(current_frame
.bits
<= 4) {
948 frame_clean(¤t_frame
);
950 frame_handle_tag(¤t_frame
);
951 frame_clean(¤t_frame
);
958 void LegicRfSimulate(int phase
, int frame
, int reqresp
)
960 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
961 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
962 * envelope waveform on DIN and should send our response on DOUT.
964 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
965 * measure the time between two rising edges on DIN, and no encoding on the
966 * subcarrier from card to reader, so we'll just shift out our verbatim data
967 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
968 * seems to be 300us-ish.
971 legic_phase_drift
= phase
;
972 legic_frame_drift
= frame
;
973 legic_reqresp_drift
= reqresp
;
975 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
976 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
978 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_212K
);
980 /* Bitbang the receiver */
981 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
982 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
985 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
989 legic_state
= STATE_DISCON
;
992 DbpString("Starting Legic emulator, press button to end");
994 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
995 int level
= !!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
996 int time
= timer
->TC_CV
;
998 if(level
!= old_level
) {
1000 timer
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1002 if (FUZZ_EQUAL(time
, RWD_TIME_1
, RWD_TIME_FUZZ
)) {
1007 } else if (FUZZ_EQUAL(time
, RWD_TIME_0
, RWD_TIME_FUZZ
)) {
1012 } else if (active
) {
1022 if(time
>= (RWD_TIME_1
+RWD_TIME_FUZZ
) && active
) {
1028 if(time
>= (20*RWD_TIME_1
) && (timer
->TC_SR
& AT91C_TC_CLKSTA
)) {
1029 timer
->TC_CCR
= AT91C_TC_CLKDIS
;
1035 if ( MF_DBGLEVEL
>= 1) DbpString("Stopped");
1039 //-----------------------------------------------------------------------------
1040 // Code up a string of octets at layer 2 (including CRC, we don't generate
1041 // that here) so that they can be transmitted to the reader. Doesn't transmit
1042 // them yet, just leaves them ready to send in ToSend[].
1043 //-----------------------------------------------------------------------------
1044 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
1050 // // Transmit a burst of ones, as the initial thing that lets the
1051 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
1052 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
1053 // // so I will too.
1054 // for(i = 0; i < 20; i++) {
1055 // ToSendStuffBit(1);
1056 // ToSendStuffBit(1);
1057 // ToSendStuffBit(1);
1058 // ToSendStuffBit(1);
1062 // for(i = 0; i < 10; i++) {
1063 // ToSendStuffBit(0);
1064 // ToSendStuffBit(0);
1065 // ToSendStuffBit(0);
1066 // ToSendStuffBit(0);
1068 // for(i = 0; i < 2; i++) {
1069 // ToSendStuffBit(1);
1070 // ToSendStuffBit(1);
1071 // ToSendStuffBit(1);
1072 // ToSendStuffBit(1);
1075 // for(i = 0; i < len; i++) {
1077 // uint8_t b = cmd[i];
1080 // ToSendStuffBit(0);
1081 // ToSendStuffBit(0);
1082 // ToSendStuffBit(0);
1083 // ToSendStuffBit(0);
1086 // for(j = 0; j < 8; j++) {
1088 // ToSendStuffBit(1);
1089 // ToSendStuffBit(1);
1090 // ToSendStuffBit(1);
1091 // ToSendStuffBit(1);
1093 // ToSendStuffBit(0);
1094 // ToSendStuffBit(0);
1095 // ToSendStuffBit(0);
1096 // ToSendStuffBit(0);
1102 // ToSendStuffBit(1);
1103 // ToSendStuffBit(1);
1104 // ToSendStuffBit(1);
1105 // ToSendStuffBit(1);
1109 // for(i = 0; i < 10; i++) {
1110 // ToSendStuffBit(0);
1111 // ToSendStuffBit(0);
1112 // ToSendStuffBit(0);
1113 // ToSendStuffBit(0);
1115 // for(i = 0; i < 2; i++) {
1116 // ToSendStuffBit(1);
1117 // ToSendStuffBit(1);
1118 // ToSendStuffBit(1);
1119 // ToSendStuffBit(1);
1122 // // Convert from last byte pos to length
1126 //-----------------------------------------------------------------------------
1127 // The software UART that receives commands from the reader, and its state
1129 //-----------------------------------------------------------------------------
1134 STATE_GOT_FALLING_EDGE_OF_SOF,
1135 STATE_AWAITING_START_BIT,
1136 STATE_RECEIVING_DATA
1146 /* Receive & handle a bit coming from the reader.
1148 * This function is called 4 times per bit (every 2 subcarrier cycles).
1149 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1152 * LED A -> ON once we have received the SOF and are expecting the rest.
1153 * LED A -> OFF once we have received EOF or are in error state or unsynced
1155 * Returns: true if we received a EOF
1156 * false if we are still waiting for some more
1158 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1160 // switch(Uart.state) {
1161 // case STATE_UNSYNCD:
1163 // // we went low, so this could be the beginning of an SOF
1164 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1170 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1172 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1174 // if(Uart.bitCnt > 9) {
1175 // // we've seen enough consecutive
1176 // // zeros that it's a valid SOF
1178 // Uart.byteCnt = 0;
1179 // Uart.state = STATE_AWAITING_START_BIT;
1180 // LED_A_ON(); // Indicate we got a valid SOF
1182 // // didn't stay down long enough
1183 // // before going high, error
1184 // Uart.state = STATE_UNSYNCD;
1187 // // do nothing, keep waiting
1191 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1192 // if(Uart.bitCnt > 12) {
1193 // // Give up if we see too many zeros without
1196 // Uart.state = STATE_UNSYNCD;
1200 // case STATE_AWAITING_START_BIT:
1203 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1204 // // stayed high for too long between
1205 // // characters, error
1206 // Uart.state = STATE_UNSYNCD;
1209 // // falling edge, this starts the data byte
1212 // Uart.shiftReg = 0;
1213 // Uart.state = STATE_RECEIVING_DATA;
1217 // case STATE_RECEIVING_DATA:
1219 // if(Uart.posCnt == 2) {
1220 // // time to sample a bit
1221 // Uart.shiftReg >>= 1;
1223 // Uart.shiftReg |= 0x200;
1227 // if(Uart.posCnt >= 4) {
1230 // if(Uart.bitCnt == 10) {
1231 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1233 // // this is a data byte, with correct
1234 // // start and stop bits
1235 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1238 // if(Uart.byteCnt >= Uart.byteCntMax) {
1239 // // Buffer overflowed, give up
1241 // Uart.state = STATE_UNSYNCD;
1243 // // so get the next byte now
1245 // Uart.state = STATE_AWAITING_START_BIT;
1247 // } else if (Uart.shiftReg == 0x000) {
1248 // // this is an EOF byte
1249 // LED_A_OFF(); // Finished receiving
1250 // Uart.state = STATE_UNSYNCD;
1251 // if (Uart.byteCnt != 0) {
1255 // // this is an error
1257 // Uart.state = STATE_UNSYNCD;
1264 // Uart.state = STATE_UNSYNCD;
1272 static void UartReset() {
1273 Uart.byteCntMax = 3;
1274 Uart.state = STATE_UNSYNCD;
1278 memset(Uart.output, 0x00, 3);
1281 // static void UartInit(uint8_t *data) {
1282 // Uart.output = data;
1286 //=============================================================================
1287 // An LEGIC reader. We take layer two commands, code them
1288 // appropriately, and then send them to the tag. We then listen for the
1289 // tag's response, which we leave in the buffer to be demodulated on the
1291 //=============================================================================
1296 DEMOD_PHASE_REF_TRAINING,
1297 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1298 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1299 DEMOD_AWAITING_START_BIT,
1300 DEMOD_RECEIVING_DATA
1313 * Handles reception of a bit from the tag
1315 * This function is called 2 times per bit (every 4 subcarrier cycles).
1316 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1319 * LED C -> ON once we have received the SOF and are expecting the rest.
1320 * LED C -> OFF once we have received EOF or are unsynced
1322 * Returns: true if we received a EOF
1323 * false if we are still waiting for some more
1328 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1333 int halfci = (ai >> 1);
1334 int halfcq = (aq >> 1);
1336 switch(Demod.state) {
1339 CHECK_FOR_SUBCARRIER()
1341 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1342 Demod.state = DEMOD_PHASE_REF_TRAINING;
1349 case DEMOD_PHASE_REF_TRAINING:
1350 if(Demod.posCount < 8) {
1352 CHECK_FOR_SUBCARRIER()
1354 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1355 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1356 // note: synchronization time > 80 1/fs
1362 Demod.state = DEMOD_UNSYNCD;
1365 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1369 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1371 MAKE_SOFT_DECISION()
1373 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1374 // logic '0' detected
1377 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1379 // start of SOF sequence
1382 // maximum length of TR1 = 200 1/fs
1383 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1388 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1391 MAKE_SOFT_DECISION()
1394 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1395 if(Demod.posCount < 10*2) {
1396 Demod.state = DEMOD_UNSYNCD;
1398 LED_C_ON(); // Got SOF
1399 Demod.state = DEMOD_AWAITING_START_BIT;
1404 // low phase of SOF too long (> 12 etu)
1405 if(Demod.posCount > 13*2) {
1406 Demod.state = DEMOD_UNSYNCD;
1412 case DEMOD_AWAITING_START_BIT:
1415 MAKE_SOFT_DECISION()
1418 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1419 if(Demod.posCount > 3*2) {
1420 Demod.state = DEMOD_UNSYNCD;
1424 // start bit detected
1426 Demod.posCount = 1; // this was the first half
1429 Demod.state = DEMOD_RECEIVING_DATA;
1433 case DEMOD_RECEIVING_DATA:
1435 MAKE_SOFT_DECISION()
1437 if(Demod.posCount == 0) {
1438 // first half of bit
1442 // second half of bit
1444 Demod.shiftReg >>= 1;
1446 if(Demod.thisBit > 0)
1447 Demod.shiftReg |= 0x200;
1451 if(Demod.bitCount == 10) {
1453 uint16_t s = Demod.shiftReg;
1455 if((s & 0x200) && !(s & 0x001)) {
1456 // stop bit == '1', start bit == '0'
1457 uint8_t b = (s >> 1);
1458 Demod.output[Demod.len] = b;
1460 Demod.state = DEMOD_AWAITING_START_BIT;
1462 Demod.state = DEMOD_UNSYNCD;
1466 // This is EOF (start, stop and all data bits == '0'
1476 Demod.state = DEMOD_UNSYNCD;
1484 // Clear out the state of the "UART" that receives from the tag.
1485 static void DemodReset() {
1487 Demod.state = DEMOD_UNSYNCD;
1494 memset(Demod.output, 0x00, 3);
1497 static void DemodInit(uint8_t *data) {
1498 Demod.output = data;
1504 * Demodulate the samples we received from the tag, also log to tracebuffer
1505 * quiet: set to 'TRUE' to disable debug output
1509 #define LEGIC_DMA_BUFFER_SIZE 256
1511 static void GetSamplesForLegicDemod(int n, bool quiet)
1514 bool gotFrame = FALSE;
1515 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1516 int ci, cq, samples = 0;
1520 // And put the FPGA in the appropriate mode
1521 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1523 // The response (tag -> reader) that we're receiving.
1524 // Set up the demodulator for tag -> reader responses.
1525 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1527 // The DMA buffer, used to stream samples from the FPGA
1528 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1529 int8_t *upTo = dmaBuf;
1531 // Setup and start DMA.
1532 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1533 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1537 // Signal field is ON with the appropriate LED:
1540 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1541 if(behindBy > max) max = behindBy;
1543 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1547 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1549 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1550 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1553 if(lastRxCounter <= 0)
1554 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1558 gotFrame = HandleLegicSamplesDemod(ci , cq );
1563 if(samples > n || gotFrame)
1567 FpgaDisableSscDma();
1569 if (!quiet && Demod.len == 0) {
1570 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1581 if (Demod.len > 0) {
1582 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1583 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1589 //-----------------------------------------------------------------------------
1590 // Transmit the command (to the tag) that was placed in ToSend[].
1591 //-----------------------------------------------------------------------------
1593 static void TransmitForLegic(void)
1599 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1600 AT91C_BASE_SSC->SSC_THR = 0xff;
1602 // Signal field is ON with the appropriate Red LED
1605 // Signal we are transmitting with the Green LED
1607 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1609 for(c = 0; c < 10;) {
1610 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1611 AT91C_BASE_SSC->SSC_THR = 0xff;
1614 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1615 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1623 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1624 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1625 legic_prng_forward(1); // forward the lfsr
1627 if(c >= ToSendMax) {
1631 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1632 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1641 //-----------------------------------------------------------------------------
1642 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1643 // so that it is ready to transmit to the tag using TransmitForLegic().
1644 //-----------------------------------------------------------------------------
1646 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1654 for(i = 0; i < 7; i++)
1658 for(i = 0; i < cmdlen; i++) {
1664 for(j = 0; j < bits; j++) {
1674 // Convert from last character reference to length
1679 Convenience function to encode, transmit and trace Legic comms
1682 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1684 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1687 uint8_t parity[1] = {0x00};
1688 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1693 // Set up LEGIC communication
1695 void ice_legic_setup() {
1698 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1699 BigBuf_free(); BigBuf_Clear_ext(false);
1705 // Set up the synchronous serial port
1708 // connect Demodulated Signal to ADC:
1709 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1711 // Signal field is on with the appropriate LED
1713 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1716 //StartCountSspClk();
1719 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);