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 // testing calculating in (us) microseconds.
72 #define RWD_TIME_1 120 // READER_TIME_PAUSE 20us off, 80us on = 100us 80 * 1.5 == 120ticks
73 #define RWD_TIME_0 60 // READER_TIME_PAUSE 20us off, 40us on = 60us 40 * 1.5 == 60ticks
74 #define RWD_TIME_PAUSE 30 // 20us == 20 * 1.5 == 30ticks */
75 #define TAG_BIT_PERIOD 143 // 100us == 100 * 1.5 == 150ticks
76 #define TAG_FRAME_WAIT 495 // 330us from READER frame end to TAG frame start. 330 * 1.5 == 495
78 #define RWD_TIME_FUZZ 20 // rather generous 13us, since the peak detector + hysteresis fuzz quite a bit
80 #define SIM_DIVISOR 586 /* prng_time/SIM_DIVISOR count prng needs to be forwared */
81 #define SIM_SHIFT 900 /* prng_time+SIM_SHIFT shift of delayed start */
83 #define OFFSET_LOG 1024
85 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz)))
88 # define SHORT_COIL LOW(GPIO_SSC_DOUT);
91 # define OPEN_COIL HIGH(GPIO_SSC_DOUT);
94 uint32_t sendFrameStop
= 0;
96 // Pause pulse, off in 20us / 30ticks,
97 // ONE / ZERO bit pulse,
98 // one == 80us / 120ticks
99 // zero == 40us / 60ticks
101 # define COIL_PULSE(x) \
104 WaitTicks( (RWD_TIME_PAUSE) ); \
110 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
111 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
112 #define LEGIC_CARD_MEMSIZE 1024
113 static uint8_t* cardmem
;
115 static void frame_append_bit(struct legic_frame
* const f
, uint8_t bit
) {
116 // Overflow, won't happen
117 if (f
->bits
>= 31) return;
119 f
->data
|= (bit
<< f
->bits
);
123 static void frame_clean(struct legic_frame
* const f
) {
128 // Prng works when waiting in 99.1us cycles.
129 // and while sending/receiving in bit frames (100, 60)
130 /*static void CalibratePrng( uint32_t time){
131 // Calculate Cycles based on timer 100us
132 uint32_t i = (time - sendFrameStop) / 100 ;
134 // substract cycles of finished frames
135 int k = i - legic_prng_count()+1;
137 // substract current frame length, rewind to beginning
139 legic_prng_forward(k);
143 /* Generate Keystream */
144 uint32_t get_key_stream(int skip
, int count
) {
148 // Use int to enlarge timer tc to 32bit
149 legic_prng_bc
+= prng_timer
->TC_CV
;
151 // reset the prng timer.
152 ResetTimer(prng_timer
);
154 /* If skip == -1, forward prng time based */
156 i
= (legic_prng_bc
+ SIM_SHIFT
)/SIM_DIVISOR
; /* Calculate Cycles based on timer */
157 i
-= legic_prng_count(); /* substract cycles of finished frames */
158 i
-= count
; /* substract current frame length, rewind to beginning */
159 legic_prng_forward(i
);
161 legic_prng_forward(skip
);
164 i
= (count
== 6) ? -1 : legic_read_count
;
166 /* Write Time Data into LOG */
167 // uint8_t *BigBuf = BigBuf_get_addr();
168 // BigBuf[OFFSET_LOG+128+i] = legic_prng_count();
169 // BigBuf[OFFSET_LOG+256+i*4] = (legic_prng_bc >> 0) & 0xff;
170 // BigBuf[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
171 // BigBuf[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
172 // BigBuf[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
173 // BigBuf[OFFSET_LOG+384+i] = count;
175 /* Generate KeyStream */
176 for(i
=0; i
<count
; i
++) {
177 key
|= legic_prng_get_bit() << i
;
178 legic_prng_forward(1);
183 /* Send a frame in tag mode, the FPGA must have been set up by
186 void frame_send_tag(uint16_t response
, uint8_t bits
, uint8_t crypt
) {
187 /* Bitbang the response */
189 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
190 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
192 /* Use time to crypt frame */
194 legic_prng_forward(2); /* TAG_FRAME_WAIT -> shift by 2 */
195 response
^= legic_prng_get_bits(bits
);
198 /* Wait for the frame start */
199 WaitUS( TAG_FRAME_WAIT
);
202 for(int i
= 0; i
< bits
; i
++) {
217 /* Send a frame in reader mode, the FPGA must have been set up by
220 void frame_sendAsReader(uint32_t data
, uint8_t bits
){
222 uint32_t starttime
= GET_TICKS
, send
= 0;
225 // xor lsfr onto data.
226 send
= data
^ legic_prng_get_bits(bits
);
228 for (; mask
< BITMASK(bits
); mask
<<= 1) {
230 COIL_PULSE(RWD_TIME_1
);
232 COIL_PULSE(RWD_TIME_0
);
236 // Final pause to mark the end of the frame
239 sendFrameStop
= GET_TICKS
;
240 uint8_t cmdbytes
[] = {
247 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, sendFrameStop
, NULL
, TRUE
);
250 /* Receive a frame from the card in reader emulation mode, the FPGA and
251 * timer must have been set up by LegicRfReader and frame_sendAsReader.
253 * The LEGIC RF protocol from card to reader does not include explicit
254 * frame start/stop information or length information. The reader must
255 * know beforehand how many bits it wants to receive. (Notably: a card
256 * sending a stream of 0-bits is indistinguishable from no card present.)
258 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
259 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
260 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
261 * for edges. Count the edges in each bit interval. If they are approximately
262 * 0 this was a 0-bit, if they are approximately equal to the number of edges
263 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
264 * timer that's still running from frame_sendAsReader in order to get a synchronization
265 * with the frame that we just sent.
267 * FIXME: Because we're relying on the hysteresis to just do the right thing
268 * the range is severely reduced (and you'll probably also need a good antenna).
269 * So this should be fixed some time in the future for a proper receiver.
271 static void frame_receiveAsReader(struct legic_frame
* const f
, uint8_t bits
) {
274 if ( bits
> 32 ) return;
276 uint8_t i
= bits
, edges
= 0;
278 uint32_t the_bit
= 1, next_bit_at
= 0, data
= 0;
280 int old_level
= 0, level
= 0;
282 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
283 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
285 // calibrate the prng.
286 legic_prng_forward(2);
287 data
= lsfr
= legic_prng_get_bits(bits
);
289 //FIXED time between sending frame and now listening frame. 330us
290 uint32_t starttime
= GET_TICKS
;
291 //uint16_t mywait = TAG_FRAME_WAIT - (starttime - sendFrameStop);
293 //WaitTicks( 495 - 9 - 9 );
296 //WaitTicks( mywait );
300 next_bit_at
= GET_TICKS
+ TAG_BIT_PERIOD
;
304 while ( GET_TICKS
< next_bit_at
) {
306 level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
308 if (level
!= old_level
)
314 next_bit_at
+= TAG_BIT_PERIOD
;
316 // We expect 42 edges == ONE
328 uint8_t cmdbytes
[] = {bits
, BYTEx(data
, 0), BYTEx(data
, 1)};
329 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, FALSE
);
332 // Setup pm3 as a Legic Reader
333 static uint32_t setup_phase_reader(uint8_t iv
) {
335 // Switch on carrier and let the tag charge for 1ms
345 frame_sendAsReader(iv
, 7);
347 // Now both tag and reader has same IV. Prng can start.
350 frame_receiveAsReader(¤t_frame
, 6);
352 // 292us (438t) - fixed delay before sending ack.
353 // minus log and stuff 100tick?
355 legic_prng_forward(3);
357 // Send obsfuscated acknowledgment frame.
358 // 0x19 = 0x18 MIM22, 0x01 LSB READCMD
359 // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD
360 switch ( current_frame
.data
) {
361 case 0x0D: frame_sendAsReader(0x19, 6); break;
363 case 0x3D: frame_sendAsReader(0x39, 6); break;
367 legic_prng_forward(2);
368 return current_frame
.data
;
371 static void LegicCommonInit(void) {
373 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
374 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
);
375 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
377 /* Bitbang the transmitter */
379 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
380 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
382 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
383 cardmem
= BigBuf_malloc(LEGIC_CARD_MEMSIZE
);
384 memset(cardmem
, 0x00, LEGIC_CARD_MEMSIZE
);
388 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
393 // Switch off carrier, make sure tag is reset
394 static void switch_off_tag_rwd(void) {
400 // calculate crc4 for a legic READ command
401 static uint32_t legic4Crc(uint8_t legicCmd
, uint16_t byte_index
, uint8_t value
, uint8_t cmd_sz
) {
402 crc_clear(&legic_crc
);
403 uint32_t temp
= (value
<< cmd_sz
) | (byte_index
<< 1) | legicCmd
;
404 crc_update(&legic_crc
, temp
, cmd_sz
+ 8 );
405 return crc_finish(&legic_crc
);
408 int legic_read_byte(int byte_index
, int cmd_sz
) {
410 uint8_t byte
= 0, crc
= 0, calcCrc
= 0;
411 uint32_t cmd
= (byte_index
<< 1) | LEGIC_READ
;
415 frame_sendAsReader(cmd
, cmd_sz
);
416 frame_receiveAsReader(¤t_frame
, 12);
418 byte
= BYTEx(current_frame
.data
, 0);
420 calcCrc
= legic4Crc(LEGIC_READ
, byte_index
, byte
, cmd_sz
);
421 crc
= BYTEx(current_frame
.data
, 1);
423 if( calcCrc
!= crc
) {
424 Dbprintf("!!! crc mismatch: expected %x but got %x !!!", calcCrc
, crc
);
428 legic_prng_forward(4);
434 * - assemble a write_cmd_frame with crc and send it
435 * - wait until the tag sends back an ACK ('1' bit unencrypted)
436 * - forward the prng based on the timing
438 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) {
439 int legic_write_byte(uint8_t byte
, uint16_t addr
, uint8_t addr_sz
) {
441 //do not write UID, CRC at offset 0-4.
442 if (addr
<= 4) return 0;
445 crc_clear(&legic_crc
);
446 crc_update(&legic_crc
, 0, 1); /* CMD_WRITE */
447 crc_update(&legic_crc
, addr
, addr_sz
);
448 crc_update(&legic_crc
, byte
, 8);
449 uint32_t crc
= crc_finish(&legic_crc
);
451 uint32_t crc2
= legic4Crc(LEGIC_WRITE
, addr
, byte
, addr_sz
+1);
453 Dbprintf("crc is missmatch");
455 // send write command
456 uint32_t cmd
= ((crc
<<(addr_sz
+1+8)) //CRC
457 |(byte
<<(addr_sz
+1)) //Data
458 |(addr
<<1) //Address
459 | LEGIC_WRITE
); //CMD = Write
461 uint32_t cmd_sz
= addr_sz
+1+8+4; //crc+data+cmd
463 legic_prng_forward(2); /* we wait anyways */
465 WaitUS(TAG_FRAME_WAIT
);
467 frame_sendAsReader(cmd
, cmd_sz
);
469 // wllm-rbnt doesnt have these
470 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
471 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
474 int t
, old_level
= 0, edges
= 0;
477 WaitUS(TAG_FRAME_WAIT
);
479 for( t
= 0; t
< 80; ++t
) {
481 next_bit_at
+= TAG_BIT_PERIOD
;
482 while(timer
->TC_CV
< next_bit_at
) {
483 int level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
484 if(level
!= old_level
)
489 if(edges
> 20 && edges
< 60) { /* expected are 42 edges */
490 int t
= timer
->TC_CV
;
491 int c
= t
/ TAG_BIT_PERIOD
;
494 legic_prng_forward(c
);
503 int LegicRfReader(int offset
, int bytes
, int iv
) {
505 uint16_t byte_index
= 0;
507 legic_card_select_t card
;
511 if ( legic_select_card(&card
) ) {
516 switch_off_tag_rwd();
519 bytes
= card
.cardsize
;
521 if (bytes
+ offset
>= card
.cardsize
)
522 bytes
= card
.cardsize
- offset
;
524 // Start setup and read bytes.
525 setup_phase_reader(iv
);
528 while (byte_index
< bytes
) {
529 int r
= legic_read_byte(byte_index
+ offset
, card
.cmdsize
);
531 if (r
== -1 || BUTTON_PRESS()) {
532 if ( MF_DBGLEVEL
>= 3) DbpString("operation aborted");
536 cardmem
[byte_index
++] = r
;
542 switch_off_tag_rwd();
544 uint8_t len
= (bytes
& 0x3FF);
545 cmd_send(CMD_ACK
,isOK
,len
,0,cardmem
,len
);
549 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
553 setup_phase_reader(iv);
554 //legic_prng_forward(2);
555 while(byte_index < bytes) {
558 //check if the DCF should be changed
559 if ( (offset == 0x05) && (bytes == 0x02) ) {
560 //write DCF in reverse order (addr 0x06 before 0x05)
561 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
562 //legic_prng_forward(1);
565 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
567 //legic_prng_forward(1);
570 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
572 if((r != 0) || BUTTON_PRESS()) {
573 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
574 switch_off_tag_rwd();
582 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
586 DbpString("write successful");
590 void LegicRfWriter(int offset
, int bytes
, int iv
) {
592 int byte_index
= 0, addr_sz
= 0;
596 if ( MF_DBGLEVEL
>= 2) DbpString("setting up legic card");
598 uint32_t tag_type
= setup_phase_reader(iv
);
600 switch_off_tag_rwd();
604 if(offset
+bytes
> 22) {
605 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset
+ bytes
);
609 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
612 if(offset
+bytes
> 0x100) {
613 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset
+ bytes
);
617 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
620 if(offset
+bytes
> 0x400) {
621 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset
+ bytes
);
625 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset
, offset
+ bytes
);
628 Dbprintf("No or unknown card found, aborting");
633 setup_phase_reader(iv
);
635 while(byte_index
< bytes
) {
637 //check if the DCF should be changed
638 if ( ((byte_index
+offset
) == 0x05) && (bytes
>= 0x02) ) {
639 //write DCF in reverse order (addr 0x06 before 0x05)
640 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), addr_sz
);
642 // write second byte on success...
645 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), addr_sz
);
649 r
= legic_write_byte(cardmem
[byte_index
+offset
], byte_index
+offset
, addr_sz
);
652 if ((r
!= 0) || BUTTON_PRESS()) {
653 Dbprintf("operation aborted @ 0x%03.3x", byte_index
);
654 switch_off_tag_rwd();
663 if ( MF_DBGLEVEL
>= 1) DbpString("write successful");
666 void LegicRfRawWriter(int address
, int byte
, int iv
) {
668 int byte_index
= 0, addr_sz
= 0;
672 if ( MF_DBGLEVEL
>= 2) DbpString("setting up legic card");
674 uint32_t tag_type
= setup_phase_reader(iv
);
676 switch_off_tag_rwd();
681 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address
);
685 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
688 if(address
> 0x100) {
689 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address
);
693 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
696 if(address
> 0x400) {
697 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address
);
701 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address
, byte
);
704 Dbprintf("No or unknown card found, aborting");
708 Dbprintf("integer value: %d address: %d addr_sz: %d", byte
, address
, addr_sz
);
711 setup_phase_reader(iv
);
713 int r
= legic_write_byte(byte
, address
, addr_sz
);
715 if((r
!= 0) || BUTTON_PRESS()) {
716 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index
, r
);
717 switch_off_tag_rwd();
723 if ( MF_DBGLEVEL
>= 1) DbpString("write successful");
726 int legic_select_card(legic_card_select_t
*p_card
){
728 if ( p_card
== NULL
) return 1;
730 p_card
->tagtype
= setup_phase_reader(0x1);
732 switch(p_card
->tagtype
) {
735 p_card
->cardsize
= 22;
739 p_card
->cardsize
= 256;
742 p_card
->cmdsize
= 11;
743 p_card
->cardsize
= 1024;
747 p_card
->cardsize
= 0;
754 void LegicRfInfo(void){
756 uint8_t buf
[sizeof(legic_card_select_t
)] = {0x00};
757 legic_card_select_t
*card
= (legic_card_select_t
*) buf
;
761 if ( legic_select_card(card
) ) {
762 cmd_send(CMD_ACK
,0,0,0,0,0);
767 for ( uint8_t i
= 0; i
< sizeof(card
->uid
); ++i
) {
768 int r
= legic_read_byte(i
, card
->cmdsize
);
770 cmd_send(CMD_ACK
,0,0,0,0,0);
773 card
->uid
[i
] = r
& 0xFF;
776 cmd_send(CMD_ACK
, 1 ,0 , 0, buf
, sizeof(legic_card_select_t
));
779 switch_off_tag_rwd();
783 /* Handle (whether to respond) a frame in tag mode
784 * Only called when simulating a tag.
786 static void frame_handle_tag(struct legic_frame
const * const f
)
788 uint8_t *BigBuf
= BigBuf_get_addr();
790 /* First Part of Handshake (IV) */
796 ResetTimer(prng_timer
);
798 legic_prng_init(f
->data
);
799 frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1B */
800 legic_state
= STATE_IV
;
801 legic_read_count
= 0;
803 legic_prng_iv
= f
->data
;
812 if(legic_state
== STATE_IV
) {
813 int local_key
= get_key_stream(3, 6);
814 int xored
= 0x39 ^ local_key
;
815 if((f
->bits
== 6) && (f
->data
== xored
)) {
816 legic_state
= STATE_CON
;
823 legic_state
= STATE_DISCON
;
825 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv
, f
->data
, local_key
, xored
);
832 if(legic_state
== STATE_CON
) {
833 int key
= get_key_stream(2, 11); //legic_phase_drift, 11);
834 int addr
= f
->data
^ key
; addr
= addr
>> 1;
835 int data
= BigBuf
[addr
];
836 int hash
= legic4Crc(LEGIC_READ
, addr
, data
, 11) << 8;
837 BigBuf
[OFFSET_LOG
+legic_read_count
] = (uint8_t)addr
;
840 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
841 legic_prng_forward(legic_reqresp_drift
);
843 frame_send_tag(hash
| data
, 12, 1);
846 legic_prng_forward(2);
854 int key
= get_key_stream(-1, 23); //legic_frame_drift, 23);
855 int addr
= f
->data
^ key
; addr
= addr
>> 1; addr
= addr
& 0x3ff;
856 int data
= f
->data
^ key
; data
= data
>> 11; data
= data
& 0xff;
859 legic_state
= STATE_DISCON
;
861 Dbprintf("write - addr: %x, data: %x", addr
, data
);
865 if(legic_state
!= STATE_DISCON
) {
866 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f
->bits
, f
->data
, legic_state
, legic_read_count
);
868 Dbprintf("IV: %03.3x", legic_prng_iv
);
869 for(i
= 0; i
<legic_read_count
; i
++) {
870 Dbprintf("Read Nb: %u, Addr: %u", i
, BigBuf
[OFFSET_LOG
+i
]);
873 for(i
= -1; i
<legic_read_count
; i
++) {
875 t
= BigBuf
[OFFSET_LOG
+256+i
*4];
876 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+1] << 8;
877 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+2] <<16;
878 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+3] <<24;
880 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
881 BigBuf
[OFFSET_LOG
+128+i
],
882 BigBuf
[OFFSET_LOG
+384+i
],
886 legic_state
= STATE_DISCON
;
887 legic_read_count
= 0;
893 /* Read bit by bit untill full frame is received
894 * Call to process frame end answer
896 static void emit(int bit
) {
900 frame_append_bit(¤t_frame
, 1);
903 frame_append_bit(¤t_frame
, 0);
906 if(current_frame
.bits
<= 4) {
907 frame_clean(¤t_frame
);
909 frame_handle_tag(¤t_frame
);
910 frame_clean(¤t_frame
);
917 void LegicRfSimulate(int phase
, int frame
, int reqresp
)
919 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
920 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
921 * envelope waveform on DIN and should send our response on DOUT.
923 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
924 * measure the time between two rising edges on DIN, and no encoding on the
925 * subcarrier from card to reader, so we'll just shift out our verbatim data
926 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
927 * seems to be 300us-ish.
930 legic_phase_drift
= phase
;
931 legic_frame_drift
= frame
;
932 legic_reqresp_drift
= reqresp
;
934 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
935 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
937 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_212K
);
939 /* Bitbang the receiver */
940 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
941 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
944 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
948 legic_state
= STATE_DISCON
;
951 DbpString("Starting Legic emulator, press button to end");
953 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
954 int level
= !!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
955 int time
= timer
->TC_CV
;
957 if(level
!= old_level
) {
959 timer
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
961 if (FUZZ_EQUAL(time
, RWD_TIME_1
, RWD_TIME_FUZZ
)) {
966 } else if (FUZZ_EQUAL(time
, RWD_TIME_0
, RWD_TIME_FUZZ
)) {
981 if(time
>= (RWD_TIME_1
+RWD_TIME_FUZZ
) && active
) {
987 if(time
>= (20*RWD_TIME_1
) && (timer
->TC_SR
& AT91C_TC_CLKSTA
)) {
988 timer
->TC_CCR
= AT91C_TC_CLKDIS
;
994 if ( MF_DBGLEVEL
>= 1) DbpString("Stopped");
998 //-----------------------------------------------------------------------------
999 // Code up a string of octets at layer 2 (including CRC, we don't generate
1000 // that here) so that they can be transmitted to the reader. Doesn't transmit
1001 // them yet, just leaves them ready to send in ToSend[].
1002 //-----------------------------------------------------------------------------
1003 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
1009 // // Transmit a burst of ones, as the initial thing that lets the
1010 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
1011 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
1012 // // so I will too.
1013 // for(i = 0; i < 20; i++) {
1014 // ToSendStuffBit(1);
1015 // ToSendStuffBit(1);
1016 // ToSendStuffBit(1);
1017 // ToSendStuffBit(1);
1021 // for(i = 0; i < 10; i++) {
1022 // ToSendStuffBit(0);
1023 // ToSendStuffBit(0);
1024 // ToSendStuffBit(0);
1025 // ToSendStuffBit(0);
1027 // for(i = 0; i < 2; i++) {
1028 // ToSendStuffBit(1);
1029 // ToSendStuffBit(1);
1030 // ToSendStuffBit(1);
1031 // ToSendStuffBit(1);
1034 // for(i = 0; i < len; i++) {
1036 // uint8_t b = cmd[i];
1039 // ToSendStuffBit(0);
1040 // ToSendStuffBit(0);
1041 // ToSendStuffBit(0);
1042 // ToSendStuffBit(0);
1045 // for(j = 0; j < 8; j++) {
1047 // ToSendStuffBit(1);
1048 // ToSendStuffBit(1);
1049 // ToSendStuffBit(1);
1050 // ToSendStuffBit(1);
1052 // ToSendStuffBit(0);
1053 // ToSendStuffBit(0);
1054 // ToSendStuffBit(0);
1055 // ToSendStuffBit(0);
1061 // ToSendStuffBit(1);
1062 // ToSendStuffBit(1);
1063 // ToSendStuffBit(1);
1064 // ToSendStuffBit(1);
1068 // for(i = 0; i < 10; i++) {
1069 // ToSendStuffBit(0);
1070 // ToSendStuffBit(0);
1071 // ToSendStuffBit(0);
1072 // ToSendStuffBit(0);
1074 // for(i = 0; i < 2; i++) {
1075 // ToSendStuffBit(1);
1076 // ToSendStuffBit(1);
1077 // ToSendStuffBit(1);
1078 // ToSendStuffBit(1);
1081 // // Convert from last byte pos to length
1085 //-----------------------------------------------------------------------------
1086 // The software UART that receives commands from the reader, and its state
1088 //-----------------------------------------------------------------------------
1093 STATE_GOT_FALLING_EDGE_OF_SOF,
1094 STATE_AWAITING_START_BIT,
1095 STATE_RECEIVING_DATA
1105 /* Receive & handle a bit coming from the reader.
1107 * This function is called 4 times per bit (every 2 subcarrier cycles).
1108 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1111 * LED A -> ON once we have received the SOF and are expecting the rest.
1112 * LED A -> OFF once we have received EOF or are in error state or unsynced
1114 * Returns: true if we received a EOF
1115 * false if we are still waiting for some more
1117 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1119 // switch(Uart.state) {
1120 // case STATE_UNSYNCD:
1122 // // we went low, so this could be the beginning of an SOF
1123 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1129 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1131 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1133 // if(Uart.bitCnt > 9) {
1134 // // we've seen enough consecutive
1135 // // zeros that it's a valid SOF
1137 // Uart.byteCnt = 0;
1138 // Uart.state = STATE_AWAITING_START_BIT;
1139 // LED_A_ON(); // Indicate we got a valid SOF
1141 // // didn't stay down long enough
1142 // // before going high, error
1143 // Uart.state = STATE_UNSYNCD;
1146 // // do nothing, keep waiting
1150 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1151 // if(Uart.bitCnt > 12) {
1152 // // Give up if we see too many zeros without
1155 // Uart.state = STATE_UNSYNCD;
1159 // case STATE_AWAITING_START_BIT:
1162 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1163 // // stayed high for too long between
1164 // // characters, error
1165 // Uart.state = STATE_UNSYNCD;
1168 // // falling edge, this starts the data byte
1171 // Uart.shiftReg = 0;
1172 // Uart.state = STATE_RECEIVING_DATA;
1176 // case STATE_RECEIVING_DATA:
1178 // if(Uart.posCnt == 2) {
1179 // // time to sample a bit
1180 // Uart.shiftReg >>= 1;
1182 // Uart.shiftReg |= 0x200;
1186 // if(Uart.posCnt >= 4) {
1189 // if(Uart.bitCnt == 10) {
1190 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1192 // // this is a data byte, with correct
1193 // // start and stop bits
1194 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1197 // if(Uart.byteCnt >= Uart.byteCntMax) {
1198 // // Buffer overflowed, give up
1200 // Uart.state = STATE_UNSYNCD;
1202 // // so get the next byte now
1204 // Uart.state = STATE_AWAITING_START_BIT;
1206 // } else if (Uart.shiftReg == 0x000) {
1207 // // this is an EOF byte
1208 // LED_A_OFF(); // Finished receiving
1209 // Uart.state = STATE_UNSYNCD;
1210 // if (Uart.byteCnt != 0) {
1214 // // this is an error
1216 // Uart.state = STATE_UNSYNCD;
1223 // Uart.state = STATE_UNSYNCD;
1231 static void UartReset() {
1232 Uart.byteCntMax = 3;
1233 Uart.state = STATE_UNSYNCD;
1237 memset(Uart.output, 0x00, 3);
1240 // static void UartInit(uint8_t *data) {
1241 // Uart.output = data;
1245 //=============================================================================
1246 // An LEGIC reader. We take layer two commands, code them
1247 // appropriately, and then send them to the tag. We then listen for the
1248 // tag's response, which we leave in the buffer to be demodulated on the
1250 //=============================================================================
1255 DEMOD_PHASE_REF_TRAINING,
1256 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1257 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1258 DEMOD_AWAITING_START_BIT,
1259 DEMOD_RECEIVING_DATA
1272 * Handles reception of a bit from the tag
1274 * This function is called 2 times per bit (every 4 subcarrier cycles).
1275 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1278 * LED C -> ON once we have received the SOF and are expecting the rest.
1279 * LED C -> OFF once we have received EOF or are unsynced
1281 * Returns: true if we received a EOF
1282 * false if we are still waiting for some more
1287 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1292 int halfci = (ai >> 1);
1293 int halfcq = (aq >> 1);
1295 switch(Demod.state) {
1298 CHECK_FOR_SUBCARRIER()
1300 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1301 Demod.state = DEMOD_PHASE_REF_TRAINING;
1308 case DEMOD_PHASE_REF_TRAINING:
1309 if(Demod.posCount < 8) {
1311 CHECK_FOR_SUBCARRIER()
1313 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1314 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1315 // note: synchronization time > 80 1/fs
1321 Demod.state = DEMOD_UNSYNCD;
1324 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1328 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1330 MAKE_SOFT_DECISION()
1332 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1333 // logic '0' detected
1336 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1338 // start of SOF sequence
1341 // maximum length of TR1 = 200 1/fs
1342 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1347 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1350 MAKE_SOFT_DECISION()
1353 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1354 if(Demod.posCount < 10*2) {
1355 Demod.state = DEMOD_UNSYNCD;
1357 LED_C_ON(); // Got SOF
1358 Demod.state = DEMOD_AWAITING_START_BIT;
1363 // low phase of SOF too long (> 12 etu)
1364 if(Demod.posCount > 13*2) {
1365 Demod.state = DEMOD_UNSYNCD;
1371 case DEMOD_AWAITING_START_BIT:
1374 MAKE_SOFT_DECISION()
1377 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1378 if(Demod.posCount > 3*2) {
1379 Demod.state = DEMOD_UNSYNCD;
1383 // start bit detected
1385 Demod.posCount = 1; // this was the first half
1388 Demod.state = DEMOD_RECEIVING_DATA;
1392 case DEMOD_RECEIVING_DATA:
1394 MAKE_SOFT_DECISION()
1396 if(Demod.posCount == 0) {
1397 // first half of bit
1401 // second half of bit
1403 Demod.shiftReg >>= 1;
1405 if(Demod.thisBit > 0)
1406 Demod.shiftReg |= 0x200;
1410 if(Demod.bitCount == 10) {
1412 uint16_t s = Demod.shiftReg;
1414 if((s & 0x200) && !(s & 0x001)) {
1415 // stop bit == '1', start bit == '0'
1416 uint8_t b = (s >> 1);
1417 Demod.output[Demod.len] = b;
1419 Demod.state = DEMOD_AWAITING_START_BIT;
1421 Demod.state = DEMOD_UNSYNCD;
1425 // This is EOF (start, stop and all data bits == '0'
1435 Demod.state = DEMOD_UNSYNCD;
1443 // Clear out the state of the "UART" that receives from the tag.
1444 static void DemodReset() {
1446 Demod.state = DEMOD_UNSYNCD;
1453 memset(Demod.output, 0x00, 3);
1456 static void DemodInit(uint8_t *data) {
1457 Demod.output = data;
1463 * Demodulate the samples we received from the tag, also log to tracebuffer
1464 * quiet: set to 'TRUE' to disable debug output
1468 #define LEGIC_DMA_BUFFER_SIZE 256
1470 static void GetSamplesForLegicDemod(int n, bool quiet)
1473 bool gotFrame = FALSE;
1474 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1475 int ci, cq, samples = 0;
1479 // And put the FPGA in the appropriate mode
1480 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1482 // The response (tag -> reader) that we're receiving.
1483 // Set up the demodulator for tag -> reader responses.
1484 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1486 // The DMA buffer, used to stream samples from the FPGA
1487 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1488 int8_t *upTo = dmaBuf;
1490 // Setup and start DMA.
1491 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1492 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1496 // Signal field is ON with the appropriate LED:
1499 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1500 if(behindBy > max) max = behindBy;
1502 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1506 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1508 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1509 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1512 if(lastRxCounter <= 0)
1513 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1517 gotFrame = HandleLegicSamplesDemod(ci , cq );
1522 if(samples > n || gotFrame)
1526 FpgaDisableSscDma();
1528 if (!quiet && Demod.len == 0) {
1529 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1540 if (Demod.len > 0) {
1541 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1542 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1548 //-----------------------------------------------------------------------------
1549 // Transmit the command (to the tag) that was placed in ToSend[].
1550 //-----------------------------------------------------------------------------
1552 static void TransmitForLegic(void)
1558 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1559 AT91C_BASE_SSC->SSC_THR = 0xff;
1561 // Signal field is ON with the appropriate Red LED
1564 // Signal we are transmitting with the Green LED
1566 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1568 for(c = 0; c < 10;) {
1569 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1570 AT91C_BASE_SSC->SSC_THR = 0xff;
1573 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1574 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1582 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1583 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1584 legic_prng_forward(1); // forward the lfsr
1586 if(c >= ToSendMax) {
1590 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1591 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1600 //-----------------------------------------------------------------------------
1601 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1602 // so that it is ready to transmit to the tag using TransmitForLegic().
1603 //-----------------------------------------------------------------------------
1605 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1613 for(i = 0; i < 7; i++)
1617 for(i = 0; i < cmdlen; i++) {
1623 for(j = 0; j < bits; j++) {
1633 // Convert from last character reference to length
1638 Convenience function to encode, transmit and trace Legic comms
1641 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1643 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1646 uint8_t parity[1] = {0x00};
1647 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1652 // Set up LEGIC communication
1654 void ice_legic_setup() {
1657 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1658 BigBuf_free(); BigBuf_Clear_ext(false);
1664 // Set up the synchronous serial port
1667 // connect Demodulated Signal to ADC:
1668 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1670 // Signal field is on with the appropriate LED
1672 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1675 //StartCountSspClk();
1678 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);