1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
9 //-----------------------------------------------------------------------------
10 // LEGIC RF simulation code
11 //-----------------------------------------------------------------------------
13 #include "proxmark3.h"
18 #include "legicrfsim.h"
19 #include "legic_prng.h"
22 #include "usb_cdc.h" // for usb_poll_validate_length
24 static uint8_t* legic_mem
; /* card memory, used for sim */
25 static legic_card_select_t card
;/* metadata of currently selected card */
26 static crc_t legic_crc
;
28 //-----------------------------------------------------------------------------
29 // Frame timing and pseudorandom number generator
31 // The Prng is forwarded every 99.1us (TAG_BIT_PERIOD), except when the reader is
32 // transmitting. In that case the prng has to be forwarded every bit transmitted:
33 // - 31.3us for a 0 (RWD_TIME_0)
34 // - 99.1us for a 1 (RWD_TIME_1)
36 // The data dependent timing makes writing comprehensible code significantly
37 // harder. The current aproach forwards the prng data based if there is data on
38 // air and time based, using GetCountSspClk(), during computational and wait
39 // periodes. SSP Clock is clocked by the FPGA at 212 kHz (subcarrier frequency).
41 // To not have the necessity to calculate/guess exection time dependend timeouts
42 // tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
43 //-----------------------------------------------------------------------------
45 static uint32_t last_frame_end
; /* ts of last bit of previews rx or tx frame */
47 #define TAG_FRAME_WAIT 70 /* 330us from READER frame end to TAG frame start */
48 #define TAG_ACK_WAIT 758 /* 3.57ms from READER frame end to TAG write ACK */
49 #define TAG_BIT_PERIOD 21 /* 99.1us */
51 #define RWD_TIME_PAUSE 4 /* 18.9us */
52 #define RWD_TIME_1 21 /* RWD_TIME_PAUSE 18.9us off + 80.2us on = 99.1us */
53 #define RWD_TIME_0 13 /* RWD_TIME_PAUSE 18.9us off + 42.4us on = 61.3us */
54 #define RWD_CMD_TIMEOUT 120 /* 120 * 99.1us (arbitrary value) */
55 #define RWD_MIN_FRAME_LEN 6 /* Shortest frame is 6 bits */
56 #define RWD_MAX_FRAME_LEN 23 /* Longest frame is 23 bits */
58 #define RWD_PULSE 1 /* Pulse is signaled with GPIO_SSC_DIN high */
59 #define RWD_PAUSE 0 /* Pause is signaled with GPIO_SSC_DIN low */
61 //-----------------------------------------------------------------------------
63 //-----------------------------------------------------------------------------
65 // Returns true if a pulse/pause is received within timeout
66 static inline bool wait_for(bool value
, const uint32_t timeout
) {
67 while((bool)(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
) != value
) {
68 if(GetCountSspClk() > timeout
) {
75 // Returns a demedulated bit or -1 on code violation
77 // rx_bit decodes bits using a thresholds. rx_bit has to be called by as soon as
78 // a frame starts (first pause is received). rx_bit checks for a pause up to
79 // 18.9us followed by a pulse of 80.2us or 42.4us:
80 // - A bit length <18.9us is a code violation
81 // - A bit length >80.2us is a 1
82 // - A bit length <80.2us is a 0
83 // - A bit length >148.6us is a code violation
84 static inline int8_t rx_bit() {
85 // backup ts for threshold calculation
86 uint32_t bit_start
= last_frame_end
;
88 // wait for pause to end
89 if(!wait_for(RWD_PULSE
, bit_start
+ RWD_TIME_1
*3/2)) {
93 // wait for next pause
94 if(!wait_for(RWD_PAUSE
, bit_start
+ RWD_TIME_1
*3/2)) {
98 // update bit and frame end
99 last_frame_end
= GetCountSspClk();
101 // check for code violation (bit to short)
102 if(last_frame_end
- bit_start
< RWD_TIME_PAUSE
) {
106 // apply threshold (average of RWD_TIME_0 and )
107 return (last_frame_end
- bit_start
> (RWD_TIME_0
+ RWD_TIME_1
) / 2);
110 //-----------------------------------------------------------------------------
113 // LEGIC RF uses a very basic load modulation from card to reader:
114 // - Subcarrier on for a 1
115 // - Subcarrier off for for a 0
117 // The 212kHz subcarrier is generated by the FPGA as well as a mathcing ssp clk.
118 // Each bit is transfered in a 99.1us slot and the first timeslot starts 330us
119 // after the final 20us pause generated by the reader.
120 //-----------------------------------------------------------------------------
124 // Note: The Subcarrier is not disabled during bits to prevent glitches. This is
125 // not mandatory but results in a cleaner signal. tx_frame will disable
126 // the subcarrier when the frame is done.
127 static inline void tx_bit(bool bit
) {
131 // modulate subcarrier
134 // do not modulate subcarrier
138 // wait for tx timeslot to end
139 last_frame_end
+= TAG_BIT_PERIOD
;
140 while(GetCountSspClk() < last_frame_end
) { };
144 //-----------------------------------------------------------------------------
147 // The LEGIC RF protocol from reader to card does not include explicit frame
148 // start/stop information or length information. The tag detects end of frame
149 // trough an extended pulse (>99.1us) without a pause.
150 // In reverse direction (card to reader) the number of bites is well known
151 // and depends only the command received (IV, ACK, READ or WRITE).
152 //-----------------------------------------------------------------------------
154 static void tx_frame(uint32_t frame
, uint8_t len
) {
155 // wait for next tx timeslot
156 last_frame_end
+= TAG_FRAME_WAIT
;
157 legic_prng_forward(TAG_FRAME_WAIT
/TAG_BIT_PERIOD
- 1);
158 while(GetCountSspClk() < last_frame_end
) { };
160 // transmit frame, MSB first
161 for(uint8_t i
= 0; i
< len
; ++i
) {
162 bool bit
= (frame
>> i
) & 0x01;
163 tx_bit(bit
^ legic_prng_get_bit());
164 legic_prng_forward(1);
167 // disable subcarrier
171 static void tx_ack() {
172 // wait for ack timeslot
173 last_frame_end
+= TAG_ACK_WAIT
;
174 legic_prng_forward(TAG_ACK_WAIT
/TAG_BIT_PERIOD
- 1);
175 while(GetCountSspClk() < last_frame_end
) { };
177 // transmit ack (ack is not encrypted)
179 legic_prng_forward(1);
181 // disable subcarrier
185 // Returns a demedulated frame or -1 on code violation
187 // Since TX to RX delay is arbitrary rx_frame has to:
188 // - detect start of frame (first pause)
189 // - forward prng based on ts/TAG_BIT_PERIOD
190 // - receive the frame
191 // - detect end of frame (last pause)
192 static int32_t rx_frame(uint8_t *len
) {
195 // add 2 SSP clock cycles (1 for tx and 1 for rx pipeline delay)
196 // those will be substracted at the end of the rx phase
199 // wait for first pause (start of frame)
200 for(uint8_t i
= 0; true; ++i
) {
201 // increment prng every TAG_BIT_PERIOD
202 last_frame_end
+= TAG_BIT_PERIOD
;
203 legic_prng_forward(1);
205 // if start of frame was received exit delay loop
206 if(wait_for(RWD_PAUSE
, last_frame_end
)) {
207 last_frame_end
= GetCountSspClk();
211 // check for code violation
212 if(i
> RWD_CMD_TIMEOUT
) {
218 for(*len
= 0; true; ++(*len
)) {
221 int8_t bit
= rx_bit();
224 // check for code violation and to short / long frame
225 if((bit
< 0) && ((*len
< RWD_MIN_FRAME_LEN
) || (*len
> RWD_MAX_FRAME_LEN
))) {
229 // check for code violation caused by end of frame
235 frame
|= (bit
^ legic_prng_get_bit()) << (*len
);
236 legic_prng_forward(1);
239 // rx_bit sets coordination timestamp to start of pause, append pause duration
240 // and substract 2 SSP clock cycles (1 for rx and 1 for tx pipeline delay) to
241 // obtain exact end of frame.
242 last_frame_end
+= RWD_TIME_PAUSE
- 2;
247 //-----------------------------------------------------------------------------
249 //-----------------------------------------------------------------------------
251 static int32_t init_card(uint8_t cardtype
, legic_card_select_t
*p_card
) {
252 p_card
->tagtype
= cardtype
;
254 switch(p_card
->tagtype
) {
257 p_card
->addrsize
= 5;
258 p_card
->cardsize
= 22;
262 p_card
->addrsize
= 8;
263 p_card
->cardsize
= 256;
266 p_card
->cmdsize
= 11;
267 p_card
->addrsize
= 10;
268 p_card
->cardsize
= 1024;
272 p_card
->addrsize
= 0;
273 p_card
->cardsize
= 0;
279 static void init_tag() {
281 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
282 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
283 | FPGA_HF_SIMULATOR_MODULATE_212K
);
284 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
286 // configure SSC with defaults
287 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
289 // first pull output to low to prevent glitches then re-claim GPIO_SSC_DOUT
291 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
292 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
294 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
295 legic_mem
= BigBuf_get_addr();
297 // init crc calculator
298 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x05, 0);
300 // start 212kHz timer (running from SSP Clock)
304 // Setup reader to card connection
306 // The setup consists of a three way handshake:
307 // - Receive initialisation vector 7 bits
308 // - Transmit card type 6 bits
309 // - Receive Acknowledge 6 bits
310 static int32_t setup_phase(legic_card_select_t
*p_card
) {
313 // init coordination timestamp
314 last_frame_end
= GetCountSspClk();
320 int32_t iv
= rx_frame(&len
);
321 if((len
!= 7) || (iv
< 0)) {
328 // reply with card type
329 switch(p_card
->tagtype
) {
342 int32_t ack
= rx_frame(&len
);
343 if((len
!= 6) || (ack
< 0)) {
348 switch(p_card
->tagtype
) {
350 if(ack
!= 0x19) return -1;
353 if(ack
!= 0x39) return -1;
356 if(ack
!= 0x39) return -1;
360 // During rx the prng is clocked using the variable reader period.
361 // Since rx_frame detects end of frame by detecting a code violation,
362 // the prng is off by one bit period after each rx phase. Hence, tx
363 // code advances the prng by (TAG_FRAME_WAIT/TAG_BIT_PERIOD - 1).
364 // This is not possible for back to back rx, so this quirk reduces
365 // the gap by one period.
366 last_frame_end
+= TAG_BIT_PERIOD
;
371 static uint8_t calc_crc4(uint16_t cmd
, uint8_t cmd_sz
, uint8_t value
) {
372 crc_clear(&legic_crc
);
373 crc_update(&legic_crc
, (value
<< cmd_sz
) | cmd
, 8 + cmd_sz
);
374 return crc_finish(&legic_crc
);
377 static int32_t connected_phase(legic_card_select_t
*p_card
) {
381 int32_t cmd
= rx_frame(&len
);
386 // check if command is LEGIC_READ
387 if(len
== p_card
->cmdsize
) {
389 uint8_t byte
= legic_mem
[cmd
>> 1];
390 uint8_t crc
= calc_crc4(cmd
, p_card
->cmdsize
, byte
);
393 tx_frame((crc
<< 8) | byte
, 12);
398 // check if command is LEGIC_WRITE
399 if(len
== p_card
->cmdsize
+ 8 + 4) {
401 uint16_t mask
= (1 << p_card
->addrsize
) - 1;
402 uint16_t addr
= (cmd
>> 1) & mask
;
403 uint8_t byte
= (cmd
>> p_card
->cmdsize
) & 0xff;
404 uint8_t crc
= (cmd
>> (p_card
->cmdsize
+ 8)) & 0xf;
406 // check received against calculated crc
407 uint8_t calc_crc
= calc_crc4(addr
<< 1, p_card
->cmdsize
, byte
);
408 if(calc_crc
!= crc
) {
409 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc
, crc
);
414 legic_mem
[addr
] = byte
;
425 //-----------------------------------------------------------------------------
426 // Command Line Interface
428 // Only this function is public / called from appmain.c
429 //-----------------------------------------------------------------------------
431 void LegicRfSimulate(uint8_t cardtype
) {
432 // configure ARM and FPGA
435 // verify command line input
436 if(init_card(cardtype
, &card
) != 0) {
437 DbpString("Unknown tagtype.");
442 DbpString("Starting Legic emulator, press button to end");
443 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
446 // wait for carrier, restart after timeout
447 if(!wait_for(RWD_PULSE
, GetCountSspClk() + TAG_BIT_PERIOD
)) {
451 // wait for connection, restart on error
452 if(setup_phase(&card
)) {
456 // conection is established, process commands until one fails
457 while(!connected_phase(&card
)) {
463 DbpString("Stopped");
464 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);