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 142 // 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 // Pause pulse, off in 20us / 30ticks,
95 // ONE / ZERO bit pulse,
96 // one == 80us / 120ticks
97 // zero == 40us / 60ticks
99 # define COIL_PULSE(x) \
102 WaitTicks( (RWD_TIME_PAUSE) ); \
108 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
109 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
110 #define LEGIC_CARD_MEMSIZE 1024
111 static uint8_t* cardmem
;
113 static void frame_append_bit(struct legic_frame
* const f
, uint8_t bit
) {
114 // Overflow, won't happen
115 if (f
->bits
>= 31) return;
117 f
->data
|= (bit
<< f
->bits
);
121 static void frame_clean(struct legic_frame
* const f
) {
126 // Prng works when waiting in 99.1us cycles.
127 // and while sending/receiving in bit frames (100, 60)
128 /*static void CalibratePrng( uint32_t time){
129 // Calculate Cycles based on timer 100us
130 uint32_t i = (time - sendFrameStop) / 100 ;
132 // substract cycles of finished frames
133 int k = i - legic_prng_count()+1;
135 // substract current frame length, rewind to beginning
137 legic_prng_forward(k);
141 /* Generate Keystream */
142 uint32_t get_key_stream(int skip
, int count
) {
146 // Use int to enlarge timer tc to 32bit
147 legic_prng_bc
+= prng_timer
->TC_CV
;
149 // reset the prng timer.
150 ResetTimer(prng_timer
);
152 /* If skip == -1, forward prng time based */
154 i
= (legic_prng_bc
+ SIM_SHIFT
)/SIM_DIVISOR
; /* Calculate Cycles based on timer */
155 i
-= legic_prng_count(); /* substract cycles of finished frames */
156 i
-= count
; /* substract current frame length, rewind to beginning */
157 legic_prng_forward(i
);
159 legic_prng_forward(skip
);
162 i
= (count
== 6) ? -1 : legic_read_count
;
164 /* Write Time Data into LOG */
165 // uint8_t *BigBuf = BigBuf_get_addr();
166 // BigBuf[OFFSET_LOG+128+i] = legic_prng_count();
167 // BigBuf[OFFSET_LOG+256+i*4] = (legic_prng_bc >> 0) & 0xff;
168 // BigBuf[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
169 // BigBuf[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
170 // BigBuf[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
171 // BigBuf[OFFSET_LOG+384+i] = count;
173 /* Generate KeyStream */
174 for(i
=0; i
<count
; i
++) {
175 key
|= legic_prng_get_bit() << i
;
176 legic_prng_forward(1);
181 /* Send a frame in tag mode, the FPGA must have been set up by
184 void frame_send_tag(uint16_t response
, uint8_t bits
, uint8_t crypt
) {
185 /* Bitbang the response */
187 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
188 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
190 /* Use time to crypt frame */
192 legic_prng_forward(2); /* TAG_FRAME_WAIT -> shift by 2 */
193 response
^= legic_prng_get_bits(bits
);
196 /* Wait for the frame start */
197 WaitUS( TAG_FRAME_WAIT
);
200 for(int i
= 0; i
< bits
; i
++) {
215 /* Send a frame in reader mode, the FPGA must have been set up by
218 void frame_sendAsReader(uint32_t data
, uint8_t bits
){
220 uint32_t starttime
= GET_TICKS
, send
= 0;
223 // xor lsfr onto data.
224 send
= data
^ legic_prng_get_bits(bits
);
226 for (; mask
< BITMASK(bits
); mask
<<= 1) {
228 COIL_PULSE(RWD_TIME_1
);
230 COIL_PULSE(RWD_TIME_0
);
233 // Final pause to mark the end of the frame
237 uint8_t cmdbytes
[] = {bits
, BYTEx(data
, 0), BYTEx(data
, 1), BYTEx(send
, 0), BYTEx(send
, 1)};
238 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, TRUE
);
241 /* Receive a frame from the card in reader emulation mode, the FPGA and
242 * timer must have been set up by LegicRfReader and frame_sendAsReader.
244 * The LEGIC RF protocol from card to reader does not include explicit
245 * frame start/stop information or length information. The reader must
246 * know beforehand how many bits it wants to receive. (Notably: a card
247 * sending a stream of 0-bits is indistinguishable from no card present.)
249 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
250 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
251 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
252 * for edges. Count the edges in each bit interval. If they are approximately
253 * 0 this was a 0-bit, if they are approximately equal to the number of edges
254 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
255 * timer that's still running from frame_sendAsReader in order to get a synchronization
256 * with the frame that we just sent.
258 * FIXME: Because we're relying on the hysteresis to just do the right thing
259 * the range is severely reduced (and you'll probably also need a good antenna).
260 * So this should be fixed some time in the future for a proper receiver.
262 static void frame_receiveAsReader(struct legic_frame
* const f
, uint8_t bits
) {
264 if ( bits
> 32 ) return;
266 uint8_t i
= bits
, edges
= 0;
267 uint32_t the_bit
= 1, next_bit_at
= 0, data
= 0;
268 uint32_t old_level
= 0;
269 volatile uint32_t level
= 0;
273 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
274 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
276 // calibrate the prng.
277 legic_prng_forward(2);
278 data
= legic_prng_get_bits(bits
);
280 //FIXED time between sending frame and now listening frame. 330us
281 uint32_t starttime
= GET_TICKS
;
282 // its about 9+9 ticks delay from end-send to here.
285 next_bit_at
= GET_TICKS
+ TAG_BIT_PERIOD
;
289 while ( GET_TICKS
< next_bit_at
) {
291 level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
293 if (level
!= old_level
)
299 next_bit_at
+= TAG_BIT_PERIOD
;
301 // We expect 42 edges (ONE)
313 uint8_t cmdbytes
[] = {bits
, BYTEx(data
, 0), BYTEx(data
, 1)};
314 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, FALSE
);
317 // Setup pm3 as a Legic Reader
318 static uint32_t setup_phase_reader(uint8_t iv
) {
320 // Switch on carrier and let the tag charge for 1ms
330 frame_sendAsReader(iv
, 7);
332 // Now both tag and reader has same IV. Prng can start.
335 frame_receiveAsReader(¤t_frame
, 6);
337 // 292us (438t) - fixed delay before sending ack.
338 // minus log and stuff 100tick?
340 legic_prng_forward(3);
342 // Send obsfuscated acknowledgment frame.
343 // 0x19 = 0x18 MIM22, 0x01 LSB READCMD
344 // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD
345 switch ( current_frame
.data
) {
346 case 0x0D: frame_sendAsReader(0x19, 6); break;
348 case 0x3D: frame_sendAsReader(0x39, 6); break;
352 legic_prng_forward(2);
353 return current_frame
.data
;
356 static void LegicCommonInit(void) {
358 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
359 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
);
360 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
362 /* Bitbang the transmitter */
364 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
365 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
367 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
368 cardmem
= BigBuf_get_EM_addr();
369 memset(cardmem
, 0x00, LEGIC_CARD_MEMSIZE
);
373 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
378 // Switch off carrier, make sure tag is reset
379 static void switch_off_tag_rwd(void) {
385 // calculate crc4 for a legic READ command
386 static uint32_t legic4Crc(uint8_t cmd
, uint16_t byte_index
, uint8_t value
, uint8_t cmd_sz
) {
387 crc_clear(&legic_crc
);
388 uint32_t temp
= (value
<< cmd_sz
) | (byte_index
<< 1) | cmd
;
389 crc_update(&legic_crc
, temp
, cmd_sz
+ 8 );
390 return crc_finish(&legic_crc
);
393 int legic_read_byte( uint16_t index
, uint8_t cmd_sz
) {
395 uint8_t byte
, crc
, calcCrc
= 0;
396 uint32_t cmd
= (index
<< 1) | LEGIC_READ
;
401 frame_sendAsReader(cmd
, cmd_sz
);
402 frame_receiveAsReader(¤t_frame
, 12);
405 byte
= BYTEx(current_frame
.data
, 0);
406 crc
= BYTEx(current_frame
.data
, 1);
407 calcCrc
= legic4Crc(LEGIC_READ
, index
, byte
, cmd_sz
);
409 if( calcCrc
!= crc
) {
410 Dbprintf("!!! crc mismatch: expected %x but got %x !!!", calcCrc
, crc
);
414 legic_prng_forward(4);
419 * - assemble a write_cmd_frame with crc and send it
420 * - wait until the tag sends back an ACK ('1' bit unencrypted)
421 * - forward the prng based on the timing
423 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) {
424 int legic_write_byte(uint8_t byte
, uint16_t addr
, uint8_t addr_sz
) {
426 //do not write UID, CRC at offset 0-4.
427 if (addr
<= 4) return 0;
430 crc_clear(&legic_crc
);
431 crc_update(&legic_crc
, 0, 1); /* CMD_WRITE */
432 crc_update(&legic_crc
, addr
, addr_sz
);
433 crc_update(&legic_crc
, byte
, 8);
434 uint32_t crc
= crc_finish(&legic_crc
);
435 uint32_t crc2
= legic4Crc(LEGIC_WRITE
, addr
, byte
, addr_sz
+1);
437 Dbprintf("crc is missmatch");
440 // send write command
441 uint32_t cmd
= ((crc
<<(addr_sz
+1+8)) //CRC
442 |(byte
<<(addr_sz
+1)) //Data
443 |(addr
<<1) //Address
444 | LEGIC_WRITE
); //CMD = Write
446 uint32_t cmd_sz
= addr_sz
+1+8+4; //crc+data+cmd
448 legic_prng_forward(2); /* we wait anyways */
452 frame_sendAsReader(cmd
, cmd_sz
);
454 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
455 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
458 int t
, old_level
= 0, edges
= 0;
461 WaitUS(TAG_FRAME_WAIT
);
463 for( t
= 0; t
< 80; ++t
) {
465 next_bit_at
+= TAG_BIT_PERIOD
;
466 while(timer
->TC_CV
< next_bit_at
) {
467 volatile uint32_t level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
468 if(level
!= old_level
)
473 if(edges
> 20 ) { /* expected are 42 edges */
474 int t
= timer
->TC_CV
;
475 int c
= t
/ TAG_BIT_PERIOD
;
478 legic_prng_forward(c
);
487 int LegicRfReader(uint16_t offset
, uint16_t len
, uint8_t iv
) {
491 legic_card_select_t card
;
495 if ( legic_select_card_iv(&card
, iv
) ) {
500 switch_off_tag_rwd();
502 if (len
+ offset
>= card
.cardsize
)
503 len
= card
.cardsize
- offset
;
505 setup_phase_reader(iv
);
509 int r
= legic_read_byte(offset
+ i
, card
.cmdsize
);
511 if (r
== -1 || BUTTON_PRESS()) {
512 if ( MF_DBGLEVEL
>= 2) DbpString("operation aborted");
522 switch_off_tag_rwd();
524 cmd_send(CMD_ACK
, isOK
, len
, 0, cardmem
, len
);
528 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
532 setup_phase_reader(iv);
533 //legic_prng_forward(2);
534 while(byte_index < bytes) {
537 //check if the DCF should be changed
538 if ( (offset == 0x05) && (bytes == 0x02) ) {
539 //write DCF in reverse order (addr 0x06 before 0x05)
540 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
541 //legic_prng_forward(1);
544 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
546 //legic_prng_forward(1);
549 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
551 if((r != 0) || BUTTON_PRESS()) {
552 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
553 switch_off_tag_rwd();
561 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
565 DbpString("write successful");
569 void LegicRfWriter(uint16_t offset
, uint16_t bytes
, uint8_t iv
) {
573 legic_card_select_t card
;
577 if ( legic_select_card_iv(&card
, iv
) ) {
582 switch_off_tag_rwd();
584 switch(card
.tagtype
) {
586 if(offset
+bytes
> 22) {
587 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset
+ bytes
);
590 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
593 if(offset
+bytes
> 0x100) {
594 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset
+ bytes
);
597 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
600 if(offset
+bytes
> 0x400) {
601 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset
+ bytes
);
604 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset
, offset
+ bytes
);
611 setup_phase_reader(iv
);
614 while(byte_index
< bytes
) {
616 //check if the DCF should be changed
617 if ( ((byte_index
+offset
) == 0x05) && (bytes
>= 0x02) ) {
618 //write DCF in reverse order (addr 0x06 before 0x05)
619 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), card
.addrsize
);
621 // write second byte on success
624 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), card
.addrsize
);
628 r
= legic_write_byte(cardmem
[byte_index
+offset
], byte_index
+offset
, card
.addrsize
);
631 if ((r
!= 0) || BUTTON_PRESS()) {
632 Dbprintf("operation aborted @ 0x%03.3x", byte_index
);
642 cmd_send(CMD_ACK
, isOK
, 0,0,0,0);
643 switch_off_tag_rwd();
647 void LegicRfRawWriter(int address
, int byte
, uint8_t iv
) {
649 int byte_index
= 0, addr_sz
= 0;
653 if ( MF_DBGLEVEL
>= 2) DbpString("setting up legic card");
655 uint32_t tag_type
= setup_phase_reader(iv
);
657 switch_off_tag_rwd();
662 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address
);
666 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
669 if(address
> 0x100) {
670 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address
);
674 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
677 if(address
> 0x400) {
678 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address
);
682 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address
, byte
);
685 Dbprintf("No or unknown card found, aborting");
689 Dbprintf("integer value: %d address: %d addr_sz: %d", byte
, address
, addr_sz
);
692 setup_phase_reader(iv
);
694 int r
= legic_write_byte(byte
, address
, addr_sz
);
696 if((r
!= 0) || BUTTON_PRESS()) {
697 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index
, r
);
698 switch_off_tag_rwd();
704 if ( MF_DBGLEVEL
>= 1) DbpString("write successful");
707 int legic_select_card_iv(legic_card_select_t
*p_card
, uint8_t iv
){
709 if ( p_card
== NULL
) return 1;
711 p_card
->tagtype
= setup_phase_reader(iv
);
713 switch(p_card
->tagtype
) {
716 p_card
->addrsize
= 5;
717 p_card
->cardsize
= 22;
721 p_card
->addrsize
= 8;
722 p_card
->cardsize
= 256;
725 p_card
->cmdsize
= 11;
726 p_card
->addrsize
= 10;
727 p_card
->cardsize
= 1024;
731 p_card
->addrsize
= 0;
732 p_card
->cardsize
= 0;
737 int legic_select_card(legic_card_select_t
*p_card
){
738 return legic_select_card_iv(p_card
, 0x01);
741 void LegicRfInfo(void){
743 uint8_t buf
[sizeof(legic_card_select_t
)] = {0x00};
744 legic_card_select_t
*card
= (legic_card_select_t
*) buf
;
748 if ( legic_select_card(card
) ) {
749 cmd_send(CMD_ACK
,0,0,0,0,0);
754 for ( uint8_t i
= 0; i
< sizeof(card
->uid
); ++i
) {
755 int r
= legic_read_byte(i
, card
->cmdsize
);
757 cmd_send(CMD_ACK
,0,0,0,0,0);
760 card
->uid
[i
] = r
& 0xFF;
763 cmd_send(CMD_ACK
, 1, 0, 0, buf
, sizeof(legic_card_select_t
));
766 switch_off_tag_rwd();
770 /* Handle (whether to respond) a frame in tag mode
771 * Only called when simulating a tag.
773 static void frame_handle_tag(struct legic_frame
const * const f
)
775 uint8_t *BigBuf
= BigBuf_get_addr();
777 /* First Part of Handshake (IV) */
783 ResetTimer(prng_timer
);
785 legic_prng_init(f
->data
);
786 frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1B */
787 legic_state
= STATE_IV
;
788 legic_read_count
= 0;
790 legic_prng_iv
= f
->data
;
799 if(legic_state
== STATE_IV
) {
800 int local_key
= get_key_stream(3, 6);
801 int xored
= 0x39 ^ local_key
;
802 if((f
->bits
== 6) && (f
->data
== xored
)) {
803 legic_state
= STATE_CON
;
810 legic_state
= STATE_DISCON
;
812 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv
, f
->data
, local_key
, xored
);
819 if(legic_state
== STATE_CON
) {
820 int key
= get_key_stream(2, 11); //legic_phase_drift, 11);
821 int addr
= f
->data
^ key
; addr
= addr
>> 1;
822 int data
= BigBuf
[addr
];
823 int hash
= legic4Crc(LEGIC_READ
, addr
, data
, 11) << 8;
824 BigBuf
[OFFSET_LOG
+legic_read_count
] = (uint8_t)addr
;
827 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
828 legic_prng_forward(legic_reqresp_drift
);
830 frame_send_tag(hash
| data
, 12, 1);
833 legic_prng_forward(2);
841 int key
= get_key_stream(-1, 23); //legic_frame_drift, 23);
842 int addr
= f
->data
^ key
; addr
= addr
>> 1; addr
= addr
& 0x3ff;
843 int data
= f
->data
^ key
; data
= data
>> 11; data
= data
& 0xff;
846 legic_state
= STATE_DISCON
;
848 Dbprintf("write - addr: %x, data: %x", addr
, data
);
852 if(legic_state
!= STATE_DISCON
) {
853 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f
->bits
, f
->data
, legic_state
, legic_read_count
);
855 Dbprintf("IV: %03.3x", legic_prng_iv
);
856 for(i
= 0; i
<legic_read_count
; i
++) {
857 Dbprintf("Read Nb: %u, Addr: %u", i
, BigBuf
[OFFSET_LOG
+i
]);
860 for(i
= -1; i
<legic_read_count
; i
++) {
862 t
= BigBuf
[OFFSET_LOG
+256+i
*4];
863 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+1] << 8;
864 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+2] <<16;
865 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+3] <<24;
867 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
868 BigBuf
[OFFSET_LOG
+128+i
],
869 BigBuf
[OFFSET_LOG
+384+i
],
873 legic_state
= STATE_DISCON
;
874 legic_read_count
= 0;
880 /* Read bit by bit untill full frame is received
881 * Call to process frame end answer
883 static void emit(int bit
) {
887 frame_append_bit(¤t_frame
, 1);
890 frame_append_bit(¤t_frame
, 0);
893 if(current_frame
.bits
<= 4) {
894 frame_clean(¤t_frame
);
896 frame_handle_tag(¤t_frame
);
897 frame_clean(¤t_frame
);
904 void LegicRfSimulate(int phase
, int frame
, int reqresp
)
906 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
907 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
908 * envelope waveform on DIN and should send our response on DOUT.
910 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
911 * measure the time between two rising edges on DIN, and no encoding on the
912 * subcarrier from card to reader, so we'll just shift out our verbatim data
913 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
914 * seems to be 300us-ish.
917 legic_phase_drift
= phase
;
918 legic_frame_drift
= frame
;
919 legic_reqresp_drift
= reqresp
;
921 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
922 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
924 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_212K
);
926 /* Bitbang the receiver */
927 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
928 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
931 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
935 legic_state
= STATE_DISCON
;
938 DbpString("Starting Legic emulator, press button to end");
940 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
941 int level
= !!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
942 int time
= timer
->TC_CV
;
944 if(level
!= old_level
) {
946 timer
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
948 if (FUZZ_EQUAL(time
, RWD_TIME_1
, RWD_TIME_FUZZ
)) {
953 } else if (FUZZ_EQUAL(time
, RWD_TIME_0
, RWD_TIME_FUZZ
)) {
968 if(time
>= (RWD_TIME_1
+RWD_TIME_FUZZ
) && active
) {
974 if(time
>= (20*RWD_TIME_1
) && (timer
->TC_SR
& AT91C_TC_CLKSTA
)) {
975 timer
->TC_CCR
= AT91C_TC_CLKDIS
;
981 if ( MF_DBGLEVEL
>= 1) DbpString("Stopped");
985 //-----------------------------------------------------------------------------
986 // Code up a string of octets at layer 2 (including CRC, we don't generate
987 // that here) so that they can be transmitted to the reader. Doesn't transmit
988 // them yet, just leaves them ready to send in ToSend[].
989 //-----------------------------------------------------------------------------
990 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
996 // // Transmit a burst of ones, as the initial thing that lets the
997 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
998 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
1000 // for(i = 0; i < 20; i++) {
1001 // ToSendStuffBit(1);
1002 // ToSendStuffBit(1);
1003 // ToSendStuffBit(1);
1004 // ToSendStuffBit(1);
1008 // for(i = 0; i < 10; i++) {
1009 // ToSendStuffBit(0);
1010 // ToSendStuffBit(0);
1011 // ToSendStuffBit(0);
1012 // ToSendStuffBit(0);
1014 // for(i = 0; i < 2; i++) {
1015 // ToSendStuffBit(1);
1016 // ToSendStuffBit(1);
1017 // ToSendStuffBit(1);
1018 // ToSendStuffBit(1);
1021 // for(i = 0; i < len; i++) {
1023 // uint8_t b = cmd[i];
1026 // ToSendStuffBit(0);
1027 // ToSendStuffBit(0);
1028 // ToSendStuffBit(0);
1029 // ToSendStuffBit(0);
1032 // for(j = 0; j < 8; j++) {
1034 // ToSendStuffBit(1);
1035 // ToSendStuffBit(1);
1036 // ToSendStuffBit(1);
1037 // ToSendStuffBit(1);
1039 // ToSendStuffBit(0);
1040 // ToSendStuffBit(0);
1041 // ToSendStuffBit(0);
1042 // ToSendStuffBit(0);
1048 // ToSendStuffBit(1);
1049 // ToSendStuffBit(1);
1050 // ToSendStuffBit(1);
1051 // ToSendStuffBit(1);
1055 // for(i = 0; i < 10; i++) {
1056 // ToSendStuffBit(0);
1057 // ToSendStuffBit(0);
1058 // ToSendStuffBit(0);
1059 // ToSendStuffBit(0);
1061 // for(i = 0; i < 2; i++) {
1062 // ToSendStuffBit(1);
1063 // ToSendStuffBit(1);
1064 // ToSendStuffBit(1);
1065 // ToSendStuffBit(1);
1068 // // Convert from last byte pos to length
1072 //-----------------------------------------------------------------------------
1073 // The software UART that receives commands from the reader, and its state
1075 //-----------------------------------------------------------------------------
1080 STATE_GOT_FALLING_EDGE_OF_SOF,
1081 STATE_AWAITING_START_BIT,
1082 STATE_RECEIVING_DATA
1092 /* Receive & handle a bit coming from the reader.
1094 * This function is called 4 times per bit (every 2 subcarrier cycles).
1095 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1098 * LED A -> ON once we have received the SOF and are expecting the rest.
1099 * LED A -> OFF once we have received EOF or are in error state or unsynced
1101 * Returns: true if we received a EOF
1102 * false if we are still waiting for some more
1104 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1106 // switch(Uart.state) {
1107 // case STATE_UNSYNCD:
1109 // // we went low, so this could be the beginning of an SOF
1110 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1116 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1118 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1120 // if(Uart.bitCnt > 9) {
1121 // // we've seen enough consecutive
1122 // // zeros that it's a valid SOF
1124 // Uart.byteCnt = 0;
1125 // Uart.state = STATE_AWAITING_START_BIT;
1126 // LED_A_ON(); // Indicate we got a valid SOF
1128 // // didn't stay down long enough
1129 // // before going high, error
1130 // Uart.state = STATE_UNSYNCD;
1133 // // do nothing, keep waiting
1137 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1138 // if(Uart.bitCnt > 12) {
1139 // // Give up if we see too many zeros without
1142 // Uart.state = STATE_UNSYNCD;
1146 // case STATE_AWAITING_START_BIT:
1149 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1150 // // stayed high for too long between
1151 // // characters, error
1152 // Uart.state = STATE_UNSYNCD;
1155 // // falling edge, this starts the data byte
1158 // Uart.shiftReg = 0;
1159 // Uart.state = STATE_RECEIVING_DATA;
1163 // case STATE_RECEIVING_DATA:
1165 // if(Uart.posCnt == 2) {
1166 // // time to sample a bit
1167 // Uart.shiftReg >>= 1;
1169 // Uart.shiftReg |= 0x200;
1173 // if(Uart.posCnt >= 4) {
1176 // if(Uart.bitCnt == 10) {
1177 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1179 // // this is a data byte, with correct
1180 // // start and stop bits
1181 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1184 // if(Uart.byteCnt >= Uart.byteCntMax) {
1185 // // Buffer overflowed, give up
1187 // Uart.state = STATE_UNSYNCD;
1189 // // so get the next byte now
1191 // Uart.state = STATE_AWAITING_START_BIT;
1193 // } else if (Uart.shiftReg == 0x000) {
1194 // // this is an EOF byte
1195 // LED_A_OFF(); // Finished receiving
1196 // Uart.state = STATE_UNSYNCD;
1197 // if (Uart.byteCnt != 0) {
1201 // // this is an error
1203 // Uart.state = STATE_UNSYNCD;
1210 // Uart.state = STATE_UNSYNCD;
1218 static void UartReset() {
1219 Uart.byteCntMax = 3;
1220 Uart.state = STATE_UNSYNCD;
1224 memset(Uart.output, 0x00, 3);
1227 // static void UartInit(uint8_t *data) {
1228 // Uart.output = data;
1232 //=============================================================================
1233 // An LEGIC reader. We take layer two commands, code them
1234 // appropriately, and then send them to the tag. We then listen for the
1235 // tag's response, which we leave in the buffer to be demodulated on the
1237 //=============================================================================
1242 DEMOD_PHASE_REF_TRAINING,
1243 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1244 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1245 DEMOD_AWAITING_START_BIT,
1246 DEMOD_RECEIVING_DATA
1259 * Handles reception of a bit from the tag
1261 * This function is called 2 times per bit (every 4 subcarrier cycles).
1262 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1265 * LED C -> ON once we have received the SOF and are expecting the rest.
1266 * LED C -> OFF once we have received EOF or are unsynced
1268 * Returns: true if we received a EOF
1269 * false if we are still waiting for some more
1274 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1279 int halfci = (ai >> 1);
1280 int halfcq = (aq >> 1);
1282 switch(Demod.state) {
1285 CHECK_FOR_SUBCARRIER()
1287 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1288 Demod.state = DEMOD_PHASE_REF_TRAINING;
1295 case DEMOD_PHASE_REF_TRAINING:
1296 if(Demod.posCount < 8) {
1298 CHECK_FOR_SUBCARRIER()
1300 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1301 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1302 // note: synchronization time > 80 1/fs
1308 Demod.state = DEMOD_UNSYNCD;
1311 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1315 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1317 MAKE_SOFT_DECISION()
1319 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1320 // logic '0' detected
1323 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1325 // start of SOF sequence
1328 // maximum length of TR1 = 200 1/fs
1329 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1334 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1337 MAKE_SOFT_DECISION()
1340 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1341 if(Demod.posCount < 10*2) {
1342 Demod.state = DEMOD_UNSYNCD;
1344 LED_C_ON(); // Got SOF
1345 Demod.state = DEMOD_AWAITING_START_BIT;
1350 // low phase of SOF too long (> 12 etu)
1351 if(Demod.posCount > 13*2) {
1352 Demod.state = DEMOD_UNSYNCD;
1358 case DEMOD_AWAITING_START_BIT:
1361 MAKE_SOFT_DECISION()
1364 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1365 if(Demod.posCount > 3*2) {
1366 Demod.state = DEMOD_UNSYNCD;
1370 // start bit detected
1372 Demod.posCount = 1; // this was the first half
1375 Demod.state = DEMOD_RECEIVING_DATA;
1379 case DEMOD_RECEIVING_DATA:
1381 MAKE_SOFT_DECISION()
1383 if(Demod.posCount == 0) {
1384 // first half of bit
1388 // second half of bit
1390 Demod.shiftReg >>= 1;
1392 if(Demod.thisBit > 0)
1393 Demod.shiftReg |= 0x200;
1397 if(Demod.bitCount == 10) {
1399 uint16_t s = Demod.shiftReg;
1401 if((s & 0x200) && !(s & 0x001)) {
1402 // stop bit == '1', start bit == '0'
1403 uint8_t b = (s >> 1);
1404 Demod.output[Demod.len] = b;
1406 Demod.state = DEMOD_AWAITING_START_BIT;
1408 Demod.state = DEMOD_UNSYNCD;
1412 // This is EOF (start, stop and all data bits == '0'
1422 Demod.state = DEMOD_UNSYNCD;
1430 // Clear out the state of the "UART" that receives from the tag.
1431 static void DemodReset() {
1433 Demod.state = DEMOD_UNSYNCD;
1440 memset(Demod.output, 0x00, 3);
1443 static void DemodInit(uint8_t *data) {
1444 Demod.output = data;
1450 * Demodulate the samples we received from the tag, also log to tracebuffer
1451 * quiet: set to 'TRUE' to disable debug output
1455 #define LEGIC_DMA_BUFFER_SIZE 256
1457 static void GetSamplesForLegicDemod(int n, bool quiet)
1460 bool gotFrame = FALSE;
1461 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1462 int ci, cq, samples = 0;
1466 // And put the FPGA in the appropriate mode
1467 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1469 // The response (tag -> reader) that we're receiving.
1470 // Set up the demodulator for tag -> reader responses.
1471 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1473 // The DMA buffer, used to stream samples from the FPGA
1474 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1475 int8_t *upTo = dmaBuf;
1477 // Setup and start DMA.
1478 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1479 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1483 // Signal field is ON with the appropriate LED:
1486 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1487 if(behindBy > max) max = behindBy;
1489 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1493 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1495 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1496 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1499 if(lastRxCounter <= 0)
1500 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1504 gotFrame = HandleLegicSamplesDemod(ci , cq );
1509 if(samples > n || gotFrame)
1513 FpgaDisableSscDma();
1515 if (!quiet && Demod.len == 0) {
1516 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1527 if (Demod.len > 0) {
1528 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1529 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1535 //-----------------------------------------------------------------------------
1536 // Transmit the command (to the tag) that was placed in ToSend[].
1537 //-----------------------------------------------------------------------------
1539 static void TransmitForLegic(void)
1545 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1546 AT91C_BASE_SSC->SSC_THR = 0xff;
1548 // Signal field is ON with the appropriate Red LED
1551 // Signal we are transmitting with the Green LED
1553 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1555 for(c = 0; c < 10;) {
1556 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1557 AT91C_BASE_SSC->SSC_THR = 0xff;
1560 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1561 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1569 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1570 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1571 legic_prng_forward(1); // forward the lfsr
1573 if(c >= ToSendMax) {
1577 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1578 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1587 //-----------------------------------------------------------------------------
1588 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1589 // so that it is ready to transmit to the tag using TransmitForLegic().
1590 //-----------------------------------------------------------------------------
1592 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1600 for(i = 0; i < 7; i++)
1604 for(i = 0; i < cmdlen; i++) {
1610 for(j = 0; j < bits; j++) {
1620 // Convert from last character reference to length
1625 Convenience function to encode, transmit and trace Legic comms
1628 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1630 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1633 uint8_t parity[1] = {0x00};
1634 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1639 // Set up LEGIC communication
1641 void ice_legic_setup() {
1644 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1645 BigBuf_free(); BigBuf_Clear_ext(false);
1651 // Set up the synchronous serial port
1654 // connect Demodulated Signal to ADC:
1655 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1657 // Signal field is on with the appropriate LED
1659 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1662 //StartCountSspClk();
1665 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);