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.
151 /* If skip == -1, forward prng time based */
153 i
= (legic_prng_bc
+ SIM_SHIFT
)/SIM_DIVISOR
; /* Calculate Cycles based on timer */
154 i
-= legic_prng_count(); /* substract cycles of finished frames */
155 i
-= count
; /* substract current frame length, rewind to beginning */
156 legic_prng_forward(i
);
158 legic_prng_forward(skip
);
161 i
= (count
== 6) ? -1 : legic_read_count
;
164 //uint8_t cmdbytes[] = {bits, BYTEx(data, 0), BYTEx(data, 1), BYTEx(send, 0), BYTEx(send, 1), legic_prng_count()};
165 //LogTrace(cmdbytes, sizeof(cmdbytes), starttime, GET_TICKS, NULL, TRUE);
167 /* Generate KeyStream */
168 return legic_prng_get_bits(count
);
171 /* Send a frame in tag mode, the FPGA must have been set up by
174 void frame_send_tag(uint16_t response
, uint8_t bits
) {
178 /* Bitbang the response */
180 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
181 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
183 /* TAG_FRAME_WAIT -> shift by 2 */
184 legic_prng_forward(2);
185 response
^= legic_prng_get_bits(bits
);
187 /* Wait for the frame start */
188 WaitTicks( TAG_FRAME_WAIT
);
190 for (; mask
< BITMASK(bits
); mask
<<= 1) {
195 WaitTicks(TAG_BIT_PERIOD
);
200 /* Send a frame in reader mode, the FPGA must have been set up by
203 void frame_sendAsReader(uint32_t data
, uint8_t bits
){
205 uint32_t starttime
= GET_TICKS
, send
= 0;
208 // xor lsfr onto data.
209 send
= data
^ legic_prng_get_bits(bits
);
211 for (; mask
< BITMASK(bits
); mask
<<= 1) {
213 COIL_PULSE(RWD_TIME_1
);
215 COIL_PULSE(RWD_TIME_0
);
218 // Final pause to mark the end of the frame
222 uint8_t cmdbytes
[] = {bits
, BYTEx(data
, 0), BYTEx(data
, 1), BYTEx(send
, 0), BYTEx(send
, 1)};
223 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, TRUE
);
226 /* Receive a frame from the card in reader emulation mode, the FPGA and
227 * timer must have been set up by LegicRfReader and frame_sendAsReader.
229 * The LEGIC RF protocol from card to reader does not include explicit
230 * frame start/stop information or length information. The reader must
231 * know beforehand how many bits it wants to receive. (Notably: a card
232 * sending a stream of 0-bits is indistinguishable from no card present.)
234 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
235 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
236 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
237 * for edges. Count the edges in each bit interval. If they are approximately
238 * 0 this was a 0-bit, if they are approximately equal to the number of edges
239 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
240 * timer that's still running from frame_sendAsReader in order to get a synchronization
241 * with the frame that we just sent.
243 * FIXME: Because we're relying on the hysteresis to just do the right thing
244 * the range is severely reduced (and you'll probably also need a good antenna).
245 * So this should be fixed some time in the future for a proper receiver.
247 static void frame_receiveAsReader(struct legic_frame
* const f
, uint8_t bits
) {
249 if ( bits
> 32 ) return;
251 uint8_t i
= bits
, edges
= 0;
252 uint32_t the_bit
= 1, next_bit_at
= 0, data
= 0;
253 uint32_t old_level
= 0;
254 volatile uint32_t level
= 0;
258 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
259 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
261 // calibrate the prng.
262 legic_prng_forward(2);
263 data
= legic_prng_get_bits(bits
);
265 //FIXED time between sending frame and now listening frame. 330us
266 uint32_t starttime
= GET_TICKS
;
267 // its about 9+9 ticks delay from end-send to here.
270 next_bit_at
= GET_TICKS
+ TAG_BIT_PERIOD
;
274 while ( GET_TICKS
< next_bit_at
) {
276 level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
278 if (level
!= old_level
)
284 next_bit_at
+= TAG_BIT_PERIOD
;
286 // We expect 42 edges (ONE)
298 uint8_t cmdbytes
[] = {bits
, BYTEx(data
, 0), BYTEx(data
, 1)};
299 LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, FALSE
);
302 // Setup pm3 as a Legic Reader
303 static uint32_t setup_phase_reader(uint8_t iv
) {
305 // Switch on carrier and let the tag charge for 1ms
315 frame_sendAsReader(iv
, 7);
317 // Now both tag and reader has same IV. Prng can start.
320 frame_receiveAsReader(¤t_frame
, 6);
322 // 292us (438t) - fixed delay before sending ack.
323 // minus log and stuff 100tick?
325 legic_prng_forward(3);
327 // Send obsfuscated acknowledgment frame.
328 // 0x19 = 0x18 MIM22, 0x01 LSB READCMD
329 // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD
330 switch ( current_frame
.data
) {
331 case 0x0D: frame_sendAsReader(0x19, 6); break;
333 case 0x3D: frame_sendAsReader(0x39, 6); break;
337 legic_prng_forward(2);
338 return current_frame
.data
;
341 static void LegicCommonInit(void) {
343 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
344 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
);
345 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
347 /* Bitbang the transmitter */
349 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
350 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
352 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
353 cardmem
= BigBuf_get_EM_addr();
354 memset(cardmem
, 0x00, LEGIC_CARD_MEMSIZE
);
358 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
363 // Switch off carrier, make sure tag is reset
364 static void switch_off_tag_rwd(void) {
370 // calculate crc4 for a legic READ command
371 static uint32_t legic4Crc(uint8_t cmd
, uint16_t byte_index
, uint8_t value
, uint8_t cmd_sz
) {
372 crc_clear(&legic_crc
);
373 uint32_t temp
= (value
<< cmd_sz
) | (byte_index
<< 1) | cmd
;
374 crc_update(&legic_crc
, temp
, cmd_sz
+ 8 );
375 return crc_finish(&legic_crc
);
378 int legic_read_byte( uint16_t index
, uint8_t cmd_sz
) {
380 uint8_t byte
, crc
, calcCrc
= 0;
381 uint32_t cmd
= (index
<< 1) | LEGIC_READ
;
383 // 90ticks = 60us (should be 100us but crc calc takes time.)
384 //WaitTicks(330); // 330ticks prng(4) - works
385 WaitTicks(240); // 240ticks prng(3) - works
387 frame_sendAsReader(cmd
, cmd_sz
);
388 frame_receiveAsReader(¤t_frame
, 12);
391 byte
= BYTEx(current_frame
.data
, 0);
392 crc
= BYTEx(current_frame
.data
, 1);
393 calcCrc
= legic4Crc(LEGIC_READ
, index
, byte
, cmd_sz
);
395 if( calcCrc
!= crc
) {
396 Dbprintf("!!! crc mismatch: expected %x but got %x !!!", calcCrc
, crc
);
400 legic_prng_forward(3);
405 * - assemble a write_cmd_frame with crc and send it
406 * - wait until the tag sends back an ACK ('1' bit unencrypted)
407 * - forward the prng based on the timing
409 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) {
410 int legic_write_byte(uint8_t byte
, uint16_t addr
, uint8_t addr_sz
) {
412 //do not write UID, CRC at offset 0-4.
413 if (addr
<= 4) return 0;
416 crc_clear(&legic_crc
);
417 crc_update(&legic_crc
, 0, 1); /* CMD_WRITE */
418 crc_update(&legic_crc
, addr
, addr_sz
);
419 crc_update(&legic_crc
, byte
, 8);
420 uint32_t crc
= crc_finish(&legic_crc
);
421 uint32_t crc2
= legic4Crc(LEGIC_WRITE
, addr
, byte
, addr_sz
+1);
423 Dbprintf("crc is missmatch");
426 // send write command
427 uint32_t cmd
= ((crc
<<(addr_sz
+1+8)) //CRC
428 |(byte
<<(addr_sz
+1)) //Data
429 |(addr
<<1) //Address
430 | LEGIC_WRITE
); //CMD = Write
432 uint32_t cmd_sz
= addr_sz
+1+8+4; //crc+data+cmd
434 legic_prng_forward(2);
438 frame_sendAsReader(cmd
, cmd_sz
);
440 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
441 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
444 int t
, old_level
= 0, edges
= 0;
447 WaitTicks(TAG_FRAME_WAIT
);
449 for( t
= 0; t
< 80; ++t
) {
451 next_bit_at
+= TAG_BIT_PERIOD
;
452 while(timer
->TC_CV
< next_bit_at
) {
453 volatile uint32_t level
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
454 if(level
!= old_level
)
459 if(edges
> 20 ) { /* expected are 42 edges */
460 int t
= timer
->TC_CV
;
461 int c
= t
/ TAG_BIT_PERIOD
;
464 legic_prng_forward(c
);
473 int LegicRfReader(uint16_t offset
, uint16_t len
, uint8_t iv
) {
477 legic_card_select_t card
;
481 if ( legic_select_card_iv(&card
, iv
) ) {
486 switch_off_tag_rwd();
488 if (len
+ offset
>= card
.cardsize
)
489 len
= card
.cardsize
- offset
;
491 setup_phase_reader(iv
);
495 int r
= legic_read_byte(offset
+ i
, card
.cmdsize
);
497 if (r
== -1 || BUTTON_PRESS()) {
498 if ( MF_DBGLEVEL
>= 2) DbpString("operation aborted");
508 switch_off_tag_rwd();
510 cmd_send(CMD_ACK
, isOK
, len
, 0, cardmem
, len
);
514 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
518 setup_phase_reader(iv);
519 //legic_prng_forward(2);
520 while(byte_index < bytes) {
523 //check if the DCF should be changed
524 if ( (offset == 0x05) && (bytes == 0x02) ) {
525 //write DCF in reverse order (addr 0x06 before 0x05)
526 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
527 //legic_prng_forward(1);
530 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
532 //legic_prng_forward(1);
535 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
537 if((r != 0) || BUTTON_PRESS()) {
538 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
539 switch_off_tag_rwd();
547 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
551 DbpString("write successful");
555 void LegicRfWriter(uint16_t offset
, uint16_t bytes
, uint8_t iv
) {
559 legic_card_select_t card
;
563 if ( legic_select_card_iv(&card
, iv
) ) {
568 switch_off_tag_rwd();
570 switch(card
.tagtype
) {
572 if(offset
+bytes
> 22) {
573 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset
+ bytes
);
576 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
579 if(offset
+bytes
> 0x100) {
580 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset
+ bytes
);
583 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+ bytes
);
586 if(offset
+bytes
> 0x400) {
587 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset
+ bytes
);
590 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset
, offset
+ bytes
);
597 setup_phase_reader(iv
);
600 while(byte_index
< bytes
) {
602 //check if the DCF should be changed
603 if ( ((byte_index
+offset
) == 0x05) && (bytes
>= 0x02) ) {
604 //write DCF in reverse order (addr 0x06 before 0x05)
605 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), card
.addrsize
);
607 // write second byte on success
610 r
= legic_write_byte(cardmem
[(0x06-byte_index
)], (0x06-byte_index
), card
.addrsize
);
614 r
= legic_write_byte(cardmem
[byte_index
+offset
], byte_index
+offset
, card
.addrsize
);
617 if ((r
!= 0) || BUTTON_PRESS()) {
618 Dbprintf("operation aborted @ 0x%03.3x", byte_index
);
628 cmd_send(CMD_ACK
, isOK
, 0,0,0,0);
629 switch_off_tag_rwd();
633 void LegicRfRawWriter(int address
, int byte
, uint8_t iv
) {
635 int byte_index
= 0, addr_sz
= 0;
639 if ( MF_DBGLEVEL
>= 2) DbpString("setting up legic card");
641 uint32_t tag_type
= setup_phase_reader(iv
);
643 switch_off_tag_rwd();
648 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address
);
652 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
655 if(address
> 0x100) {
656 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address
);
660 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address
, byte
);
663 if(address
> 0x400) {
664 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address
);
668 if ( MF_DBGLEVEL
>= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address
, byte
);
671 Dbprintf("No or unknown card found, aborting");
675 Dbprintf("integer value: %d address: %d addr_sz: %d", byte
, address
, addr_sz
);
678 setup_phase_reader(iv
);
680 int r
= legic_write_byte(byte
, address
, addr_sz
);
682 if((r
!= 0) || BUTTON_PRESS()) {
683 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index
, r
);
684 switch_off_tag_rwd();
690 if ( MF_DBGLEVEL
>= 1) DbpString("write successful");
693 int legic_select_card_iv(legic_card_select_t
*p_card
, uint8_t iv
){
695 if ( p_card
== NULL
) return 1;
697 p_card
->tagtype
= setup_phase_reader(iv
);
699 switch(p_card
->tagtype
) {
702 p_card
->addrsize
= 5;
703 p_card
->cardsize
= 22;
707 p_card
->addrsize
= 8;
708 p_card
->cardsize
= 256;
711 p_card
->cmdsize
= 11;
712 p_card
->addrsize
= 10;
713 p_card
->cardsize
= 1024;
717 p_card
->addrsize
= 0;
718 p_card
->cardsize
= 0;
723 int legic_select_card(legic_card_select_t
*p_card
){
724 return legic_select_card_iv(p_card
, 0x01);
727 void LegicRfInfo(void){
729 uint8_t buf
[sizeof(legic_card_select_t
)] = {0x00};
730 legic_card_select_t
*card
= (legic_card_select_t
*) buf
;
734 if ( legic_select_card(card
) ) {
735 cmd_send(CMD_ACK
,0,0,0,0,0);
740 for ( uint8_t i
= 0; i
< sizeof(card
->uid
); ++i
) {
741 int r
= legic_read_byte(i
, card
->cmdsize
);
743 cmd_send(CMD_ACK
,0,0,0,0,0);
746 card
->uid
[i
] = r
& 0xFF;
749 cmd_send(CMD_ACK
, 1, 0, 0, buf
, sizeof(legic_card_select_t
));
752 switch_off_tag_rwd();
756 /* Handle (whether to respond) a frame in tag mode
757 * Only called when simulating a tag.
759 static void frame_handle_tag(struct legic_frame
const * const f
)
761 uint8_t *BigBuf
= BigBuf_get_addr();
763 /* First Part of Handshake (IV) */
769 ResetTimer(prng_timer
);
771 legic_prng_init(f
->data
);
772 frame_send_tag(0x3d, 6); /* 0x3d^0x26 = 0x1B */
773 legic_state
= STATE_IV
;
774 legic_read_count
= 0;
776 legic_prng_iv
= f
->data
;
785 if(legic_state
== STATE_IV
) {
786 int local_key
= get_key_stream(3, 6);
787 int xored
= 0x39 ^ local_key
;
788 if((f
->bits
== 6) && (f
->data
== xored
)) {
789 legic_state
= STATE_CON
;
796 legic_state
= STATE_DISCON
;
798 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv
, f
->data
, local_key
, xored
);
805 if(legic_state
== STATE_CON
) {
806 int key
= get_key_stream(2, 11); //legic_phase_drift, 11);
807 int addr
= f
->data
^ key
; addr
= addr
>> 1;
808 int data
= BigBuf
[addr
];
809 int hash
= legic4Crc(LEGIC_READ
, addr
, data
, 11) << 8;
810 BigBuf
[OFFSET_LOG
+legic_read_count
] = (uint8_t)addr
;
813 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
814 legic_prng_forward(legic_reqresp_drift
);
816 frame_send_tag(hash
| data
, 12);
819 legic_prng_forward(2);
827 int key
= get_key_stream(-1, 23); //legic_frame_drift, 23);
828 int addr
= f
->data
^ key
; addr
= addr
>> 1; addr
= addr
& 0x3ff;
829 int data
= f
->data
^ key
; data
= data
>> 11; data
= data
& 0xff;
832 legic_state
= STATE_DISCON
;
834 Dbprintf("write - addr: %x, data: %x", addr
, data
);
838 if(legic_state
!= STATE_DISCON
) {
839 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f
->bits
, f
->data
, legic_state
, legic_read_count
);
841 Dbprintf("IV: %03.3x", legic_prng_iv
);
842 for(i
= 0; i
<legic_read_count
; i
++) {
843 Dbprintf("Read Nb: %u, Addr: %u", i
, BigBuf
[OFFSET_LOG
+i
]);
846 for(i
= -1; i
<legic_read_count
; i
++) {
848 t
= BigBuf
[OFFSET_LOG
+256+i
*4];
849 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+1] << 8;
850 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+2] <<16;
851 t
|= BigBuf
[OFFSET_LOG
+256+i
*4+3] <<24;
853 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
854 BigBuf
[OFFSET_LOG
+128+i
],
855 BigBuf
[OFFSET_LOG
+384+i
],
859 legic_state
= STATE_DISCON
;
860 legic_read_count
= 0;
866 /* Read bit by bit untill full frame is received
867 * Call to process frame end answer
869 static void emit(int bit
) {
873 frame_append_bit(¤t_frame
, 1);
876 frame_append_bit(¤t_frame
, 0);
879 if(current_frame
.bits
<= 4) {
880 frame_clean(¤t_frame
);
882 frame_handle_tag(¤t_frame
);
883 frame_clean(¤t_frame
);
890 void LegicRfSimulate(int phase
, int frame
, int reqresp
)
892 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
893 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
894 * envelope waveform on DIN and should send our response on DOUT.
896 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
897 * measure the time between two rising edges on DIN, and no encoding on the
898 * subcarrier from card to reader, so we'll just shift out our verbatim data
899 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
900 * seems to be 300us-ish.
903 legic_phase_drift
= phase
;
904 legic_frame_drift
= frame
;
905 legic_reqresp_drift
= reqresp
;
907 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
908 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
910 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_212K
);
912 /* Bitbang the receiver */
913 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_DIN
;
914 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DIN
;
917 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);
921 legic_state
= STATE_DISCON
;
924 DbpString("Starting Legic emulator, press button to end");
926 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
927 int level
= !!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
);
928 int time
= timer
->TC_CV
;
930 if(level
!= old_level
) {
932 timer
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
934 if (FUZZ_EQUAL(time
, RWD_TIME_1
, RWD_TIME_FUZZ
)) {
939 } else if (FUZZ_EQUAL(time
, RWD_TIME_0
, RWD_TIME_FUZZ
)) {
954 if(time
>= (RWD_TIME_1
+RWD_TIME_FUZZ
) && active
) {
960 if(time
>= (20*RWD_TIME_1
) && (timer
->TC_SR
& AT91C_TC_CLKSTA
)) {
961 timer
->TC_CCR
= AT91C_TC_CLKDIS
;
967 if ( MF_DBGLEVEL
>= 1) DbpString("Stopped");
971 //-----------------------------------------------------------------------------
972 // Code up a string of octets at layer 2 (including CRC, we don't generate
973 // that here) so that they can be transmitted to the reader. Doesn't transmit
974 // them yet, just leaves them ready to send in ToSend[].
975 //-----------------------------------------------------------------------------
976 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
982 // // Transmit a burst of ones, as the initial thing that lets the
983 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
984 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
986 // for(i = 0; i < 20; i++) {
987 // ToSendStuffBit(1);
988 // ToSendStuffBit(1);
989 // ToSendStuffBit(1);
990 // ToSendStuffBit(1);
994 // for(i = 0; i < 10; i++) {
995 // ToSendStuffBit(0);
996 // ToSendStuffBit(0);
997 // ToSendStuffBit(0);
998 // ToSendStuffBit(0);
1000 // for(i = 0; i < 2; i++) {
1001 // ToSendStuffBit(1);
1002 // ToSendStuffBit(1);
1003 // ToSendStuffBit(1);
1004 // ToSendStuffBit(1);
1007 // for(i = 0; i < len; i++) {
1009 // uint8_t b = cmd[i];
1012 // ToSendStuffBit(0);
1013 // ToSendStuffBit(0);
1014 // ToSendStuffBit(0);
1015 // ToSendStuffBit(0);
1018 // for(j = 0; j < 8; j++) {
1020 // ToSendStuffBit(1);
1021 // ToSendStuffBit(1);
1022 // ToSendStuffBit(1);
1023 // ToSendStuffBit(1);
1025 // ToSendStuffBit(0);
1026 // ToSendStuffBit(0);
1027 // ToSendStuffBit(0);
1028 // ToSendStuffBit(0);
1034 // ToSendStuffBit(1);
1035 // ToSendStuffBit(1);
1036 // ToSendStuffBit(1);
1037 // ToSendStuffBit(1);
1041 // for(i = 0; i < 10; i++) {
1042 // ToSendStuffBit(0);
1043 // ToSendStuffBit(0);
1044 // ToSendStuffBit(0);
1045 // ToSendStuffBit(0);
1047 // for(i = 0; i < 2; i++) {
1048 // ToSendStuffBit(1);
1049 // ToSendStuffBit(1);
1050 // ToSendStuffBit(1);
1051 // ToSendStuffBit(1);
1054 // // Convert from last byte pos to length
1058 //-----------------------------------------------------------------------------
1059 // The software UART that receives commands from the reader, and its state
1061 //-----------------------------------------------------------------------------
1066 STATE_GOT_FALLING_EDGE_OF_SOF,
1067 STATE_AWAITING_START_BIT,
1068 STATE_RECEIVING_DATA
1078 /* Receive & handle a bit coming from the reader.
1080 * This function is called 4 times per bit (every 2 subcarrier cycles).
1081 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1084 * LED A -> ON once we have received the SOF and are expecting the rest.
1085 * LED A -> OFF once we have received EOF or are in error state or unsynced
1087 * Returns: true if we received a EOF
1088 * false if we are still waiting for some more
1090 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1092 // switch(Uart.state) {
1093 // case STATE_UNSYNCD:
1095 // // we went low, so this could be the beginning of an SOF
1096 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1102 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1104 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1106 // if(Uart.bitCnt > 9) {
1107 // // we've seen enough consecutive
1108 // // zeros that it's a valid SOF
1110 // Uart.byteCnt = 0;
1111 // Uart.state = STATE_AWAITING_START_BIT;
1112 // LED_A_ON(); // Indicate we got a valid SOF
1114 // // didn't stay down long enough
1115 // // before going high, error
1116 // Uart.state = STATE_UNSYNCD;
1119 // // do nothing, keep waiting
1123 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1124 // if(Uart.bitCnt > 12) {
1125 // // Give up if we see too many zeros without
1128 // Uart.state = STATE_UNSYNCD;
1132 // case STATE_AWAITING_START_BIT:
1135 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1136 // // stayed high for too long between
1137 // // characters, error
1138 // Uart.state = STATE_UNSYNCD;
1141 // // falling edge, this starts the data byte
1144 // Uart.shiftReg = 0;
1145 // Uart.state = STATE_RECEIVING_DATA;
1149 // case STATE_RECEIVING_DATA:
1151 // if(Uart.posCnt == 2) {
1152 // // time to sample a bit
1153 // Uart.shiftReg >>= 1;
1155 // Uart.shiftReg |= 0x200;
1159 // if(Uart.posCnt >= 4) {
1162 // if(Uart.bitCnt == 10) {
1163 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1165 // // this is a data byte, with correct
1166 // // start and stop bits
1167 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1170 // if(Uart.byteCnt >= Uart.byteCntMax) {
1171 // // Buffer overflowed, give up
1173 // Uart.state = STATE_UNSYNCD;
1175 // // so get the next byte now
1177 // Uart.state = STATE_AWAITING_START_BIT;
1179 // } else if (Uart.shiftReg == 0x000) {
1180 // // this is an EOF byte
1181 // LED_A_OFF(); // Finished receiving
1182 // Uart.state = STATE_UNSYNCD;
1183 // if (Uart.byteCnt != 0) {
1187 // // this is an error
1189 // Uart.state = STATE_UNSYNCD;
1196 // Uart.state = STATE_UNSYNCD;
1204 static void UartReset() {
1205 Uart.byteCntMax = 3;
1206 Uart.state = STATE_UNSYNCD;
1210 memset(Uart.output, 0x00, 3);
1213 // static void UartInit(uint8_t *data) {
1214 // Uart.output = data;
1218 //=============================================================================
1219 // An LEGIC reader. We take layer two commands, code them
1220 // appropriately, and then send them to the tag. We then listen for the
1221 // tag's response, which we leave in the buffer to be demodulated on the
1223 //=============================================================================
1228 DEMOD_PHASE_REF_TRAINING,
1229 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1230 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1231 DEMOD_AWAITING_START_BIT,
1232 DEMOD_RECEIVING_DATA
1245 * Handles reception of a bit from the tag
1247 * This function is called 2 times per bit (every 4 subcarrier cycles).
1248 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1251 * LED C -> ON once we have received the SOF and are expecting the rest.
1252 * LED C -> OFF once we have received EOF or are unsynced
1254 * Returns: true if we received a EOF
1255 * false if we are still waiting for some more
1260 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1265 int halfci = (ai >> 1);
1266 int halfcq = (aq >> 1);
1268 switch(Demod.state) {
1271 CHECK_FOR_SUBCARRIER()
1273 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1274 Demod.state = DEMOD_PHASE_REF_TRAINING;
1281 case DEMOD_PHASE_REF_TRAINING:
1282 if(Demod.posCount < 8) {
1284 CHECK_FOR_SUBCARRIER()
1286 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1287 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1288 // note: synchronization time > 80 1/fs
1294 Demod.state = DEMOD_UNSYNCD;
1297 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1301 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1303 MAKE_SOFT_DECISION()
1305 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1306 // logic '0' detected
1309 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1311 // start of SOF sequence
1314 // maximum length of TR1 = 200 1/fs
1315 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1320 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1323 MAKE_SOFT_DECISION()
1326 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1327 if(Demod.posCount < 10*2) {
1328 Demod.state = DEMOD_UNSYNCD;
1330 LED_C_ON(); // Got SOF
1331 Demod.state = DEMOD_AWAITING_START_BIT;
1336 // low phase of SOF too long (> 12 etu)
1337 if(Demod.posCount > 13*2) {
1338 Demod.state = DEMOD_UNSYNCD;
1344 case DEMOD_AWAITING_START_BIT:
1347 MAKE_SOFT_DECISION()
1350 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1351 if(Demod.posCount > 3*2) {
1352 Demod.state = DEMOD_UNSYNCD;
1356 // start bit detected
1358 Demod.posCount = 1; // this was the first half
1361 Demod.state = DEMOD_RECEIVING_DATA;
1365 case DEMOD_RECEIVING_DATA:
1367 MAKE_SOFT_DECISION()
1369 if(Demod.posCount == 0) {
1370 // first half of bit
1374 // second half of bit
1376 Demod.shiftReg >>= 1;
1378 if(Demod.thisBit > 0)
1379 Demod.shiftReg |= 0x200;
1383 if(Demod.bitCount == 10) {
1385 uint16_t s = Demod.shiftReg;
1387 if((s & 0x200) && !(s & 0x001)) {
1388 // stop bit == '1', start bit == '0'
1389 uint8_t b = (s >> 1);
1390 Demod.output[Demod.len] = b;
1392 Demod.state = DEMOD_AWAITING_START_BIT;
1394 Demod.state = DEMOD_UNSYNCD;
1398 // This is EOF (start, stop and all data bits == '0'
1408 Demod.state = DEMOD_UNSYNCD;
1416 // Clear out the state of the "UART" that receives from the tag.
1417 static void DemodReset() {
1419 Demod.state = DEMOD_UNSYNCD;
1426 memset(Demod.output, 0x00, 3);
1429 static void DemodInit(uint8_t *data) {
1430 Demod.output = data;
1436 * Demodulate the samples we received from the tag, also log to tracebuffer
1437 * quiet: set to 'TRUE' to disable debug output
1441 #define LEGIC_DMA_BUFFER_SIZE 256
1443 static void GetSamplesForLegicDemod(int n, bool quiet)
1446 bool gotFrame = FALSE;
1447 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1448 int ci, cq, samples = 0;
1452 // And put the FPGA in the appropriate mode
1453 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1455 // The response (tag -> reader) that we're receiving.
1456 // Set up the demodulator for tag -> reader responses.
1457 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1459 // The DMA buffer, used to stream samples from the FPGA
1460 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1461 int8_t *upTo = dmaBuf;
1463 // Setup and start DMA.
1464 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1465 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1469 // Signal field is ON with the appropriate LED:
1472 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1473 if(behindBy > max) max = behindBy;
1475 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1479 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1481 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1482 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1485 if(lastRxCounter <= 0)
1486 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1490 gotFrame = HandleLegicSamplesDemod(ci , cq );
1495 if(samples > n || gotFrame)
1499 FpgaDisableSscDma();
1501 if (!quiet && Demod.len == 0) {
1502 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1513 if (Demod.len > 0) {
1514 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1515 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1521 //-----------------------------------------------------------------------------
1522 // Transmit the command (to the tag) that was placed in ToSend[].
1523 //-----------------------------------------------------------------------------
1525 static void TransmitForLegic(void)
1531 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1532 AT91C_BASE_SSC->SSC_THR = 0xff;
1534 // Signal field is ON with the appropriate Red LED
1537 // Signal we are transmitting with the Green LED
1539 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1541 for(c = 0; c < 10;) {
1542 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1543 AT91C_BASE_SSC->SSC_THR = 0xff;
1546 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1547 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1555 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1556 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1557 legic_prng_forward(1); // forward the lfsr
1559 if(c >= ToSendMax) {
1563 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1564 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1573 //-----------------------------------------------------------------------------
1574 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1575 // so that it is ready to transmit to the tag using TransmitForLegic().
1576 //-----------------------------------------------------------------------------
1578 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1586 for(i = 0; i < 7; i++)
1590 for(i = 0; i < cmdlen; i++) {
1596 for(j = 0; j < bits; j++) {
1606 // Convert from last character reference to length
1611 Convenience function to encode, transmit and trace Legic comms
1614 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1616 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1619 uint8_t parity[1] = {0x00};
1620 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1625 // Set up LEGIC communication
1627 void ice_legic_setup() {
1630 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1631 BigBuf_free(); BigBuf_Clear_ext(false);
1637 // Set up the synchronous serial port
1640 // connect Demodulated Signal to ADC:
1641 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1643 // Signal field is on with the appropriate LED
1645 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1648 //StartCountSspClk();
1651 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);