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"
23 static uint8_t* legic_mem
; /* card memory, used for sim */
24 static legic_card_select_t card
;/* metadata of currently selected card */
25 static crc_t legic_crc
;
27 //-----------------------------------------------------------------------------
28 // Frame timing and pseudorandom number generator
30 // The Prng is forwarded every 99.1us (TAG_BIT_PERIOD), except when the reader is
31 // transmitting. In that case the prng has to be forwarded every bit transmitted:
32 // - 31.3us for a 0 (RWD_TIME_0)
33 // - 99.1us for a 1 (RWD_TIME_1)
35 // The data dependent timing makes writing comprehensible code significantly
36 // harder. The current aproach forwards the prng data based if there is data on
37 // air and time based, using GetCountSspClk(), during computational and wait
38 // periodes. SSP Clock is clocked by the FPGA at 212 kHz (subcarrier frequency).
40 // To not have the necessity to calculate/guess exection time dependend timeouts
41 // tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
42 //-----------------------------------------------------------------------------
44 static uint32_t last_frame_end
; /* ts of last bit of previews rx or tx frame */
46 #define TAG_FRAME_WAIT 70 /* 330us from READER frame end to TAG frame start */
47 #define TAG_ACK_WAIT 758 /* 3.57ms from READER frame end to TAG write ACK */
48 #define TAG_BIT_PERIOD 21 /* 99.1us */
50 #define RWD_TIME_PAUSE 4 /* 18.9us */
51 #define RWD_TIME_1 21 /* RWD_TIME_PAUSE 18.9us off + 80.2us on = 99.1us */
52 #define RWD_TIME_0 13 /* RWD_TIME_PAUSE 18.9us off + 42.4us on = 61.3us */
53 #define RWD_CMD_TIMEOUT 40 /* 40 * 99.1us (arbitrary value) */
54 #define RWD_MIN_FRAME_LEN 6 /* Shortest frame is 6 bits */
55 #define RWD_MAX_FRAME_LEN 23 /* Longest frame is 23 bits */
57 #define RWD_PULSE 1 /* Pulse is signaled with GPIO_SSC_DIN high */
58 #define RWD_PAUSE 0 /* Pause is signaled with GPIO_SSC_DIN low */
60 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
64 // Returns true if a pulse/pause is received within timeout
65 static inline bool wait_for(bool value
, const uint32_t timeout
) {
66 while((bool)(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
) != value
) {
67 if(GetCountSspClk() > timeout
) {
74 // Returns a demedulated bit or -1 on code violation
76 // rx_bit decodes bits using a thresholds. rx_bit has to be called by as soon as
77 // a frame starts (first pause is received). rx_bit checks for a pause up to
78 // 18.9us followed by a pulse of 80.2us or 42.4us:
79 // - A bit length <18.9us is a code violation
80 // - A bit length >80.2us is a 1
81 // - A bit length <80.2us is a 0
82 // - A bit length >148.6us is a code violation
83 static inline int8_t rx_bit() {
84 // backup ts for threshold calculation
85 uint32_t bit_start
= last_frame_end
;
87 // wait for pause to end
88 if(!wait_for(RWD_PULSE
, bit_start
+ RWD_TIME_1
*3/2)) {
92 // wait for next pause
93 if(!wait_for(RWD_PAUSE
, bit_start
+ RWD_TIME_1
*3/2)) {
97 // update bit and frame end
98 last_frame_end
= GetCountSspClk();
100 // check for code violation (bit to short)
101 if(last_frame_end
- bit_start
< RWD_TIME_PAUSE
) {
105 // apply threshold (average of RWD_TIME_0 and )
106 return (last_frame_end
- bit_start
> (RWD_TIME_0
+ RWD_TIME_1
) / 2);
109 //-----------------------------------------------------------------------------
112 // LEGIC RF uses a very basic load modulation from card to reader:
113 // - Subcarrier on for a 1
114 // - Subcarrier off for for a 0
116 // The 212kHz subcarrier is generated by the FPGA as well as a mathcing ssp clk.
117 // Each bit is transfered in a 99.1us slot and the first timeslot starts 330us
118 // after the final 20us pause generated by the reader.
119 //-----------------------------------------------------------------------------
123 // Note: The Subcarrier is not disabled during bits to prevent glitches. This is
124 // not mandatory but results in a cleaner signal. tx_frame will disable
125 // the subcarrier when the frame is done.
126 static inline void tx_bit(bool bit
) {
130 // modulate subcarrier
133 // do not modulate subcarrier
137 // wait for tx timeslot to end
138 last_frame_end
+= TAG_BIT_PERIOD
;
139 while(GetCountSspClk() < last_frame_end
) { };
143 //-----------------------------------------------------------------------------
146 // The LEGIC RF protocol from reader to card does not include explicit frame
147 // start/stop information or length information. The tag detects end of frame
148 // trough an extended pulse (>99.1us) without a pause.
149 // In reverse direction (card to reader) the number of bites is well known
150 // and depends only the command received (IV, ACK, READ or WRITE).
151 //-----------------------------------------------------------------------------
153 static void tx_frame(uint32_t frame
, uint8_t len
) {
154 // wait for next tx timeslot
155 last_frame_end
+= TAG_FRAME_WAIT
;
156 legic_prng_forward(TAG_FRAME_WAIT
/TAG_BIT_PERIOD
- 1);
157 while(GetCountSspClk() < last_frame_end
) { };
159 // transmit frame, MSB first
160 for(uint8_t i
= 0; i
< len
; ++i
) {
161 bool bit
= (frame
>> i
) & 0x01;
162 tx_bit(bit
^ legic_prng_get_bit());
163 legic_prng_forward(1);
166 // disable subcarrier
170 static void tx_ack() {
171 // wait for ack timeslot
172 last_frame_end
+= TAG_ACK_WAIT
;
173 legic_prng_forward(TAG_ACK_WAIT
/TAG_BIT_PERIOD
- 1);
174 while(GetCountSspClk() < last_frame_end
) { };
176 // transmit ack (ack is not encrypted)
178 legic_prng_forward(1);
180 // disable subcarrier
184 // Returns a demedulated frame or -1 on code violation
186 // Since TX to RX delay is arbitrary rx_frame has to:
187 // - detect start of frame (first pause)
188 // - forward prng based on ts/TAG_BIT_PERIOD
189 // - receive the frame
190 // - detect end of frame (last pause)
191 static int32_t rx_frame(uint8_t *len
) {
194 // add 2 SSP clock cycles (1 for tx and 1 for rx pipeline delay)
195 // those will be substracted at the end of the rx phase
198 // wait for first pause (start of frame)
199 for(uint8_t i
= 0; true; ++i
) {
200 // increment prng every TAG_BIT_PERIOD
201 last_frame_end
+= TAG_BIT_PERIOD
;
202 legic_prng_forward(1);
204 // if start of frame was received exit delay loop
205 if(wait_for(RWD_PAUSE
, last_frame_end
)) {
206 last_frame_end
= GetCountSspClk();
210 // check for code violation
211 if(i
> RWD_CMD_TIMEOUT
) {
217 for(*len
= 0; true; ++(*len
)) {
220 int8_t bit
= rx_bit();
223 // check for code violation and to short / long frame
224 if((bit
< 0) && ((*len
< RWD_MIN_FRAME_LEN
) || (*len
> RWD_MAX_FRAME_LEN
))) {
228 // check for code violation caused by end of frame
234 frame
|= (bit
^ legic_prng_get_bit()) << (*len
);
235 legic_prng_forward(1);
238 // rx_bit sets coordination timestamp to start of pause, append pause duration
239 // and substract 2 SSP clock cycles (1 for rx and 1 for tx pipeline delay) to
240 // obtain exact end of frame.
241 last_frame_end
+= RWD_TIME_PAUSE
- 2;
246 //-----------------------------------------------------------------------------
248 //-----------------------------------------------------------------------------
250 static int32_t init_card(uint8_t cardtype
, legic_card_select_t
*p_card
) {
251 p_card
->tagtype
= cardtype
;
253 switch(p_card
->tagtype
) {
256 p_card
->addrsize
= 5;
257 p_card
->cardsize
= 22;
261 p_card
->addrsize
= 8;
262 p_card
->cardsize
= 256;
265 p_card
->cmdsize
= 11;
266 p_card
->addrsize
= 10;
267 p_card
->cardsize
= 1024;
271 p_card
->addrsize
= 0;
272 p_card
->cardsize
= 0;
278 static void init_tag() {
280 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
281 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
282 | FPGA_HF_SIMULATOR_MODULATE_212K
);
283 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
285 // configure SSC with defaults
288 // first pull output to low to prevent glitches then re-claim GPIO_SSC_DOUT
290 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
291 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
293 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
294 legic_mem
= BigBuf_get_addr();
296 // init crc calculator
297 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x05, 0);
299 // start 212kHz timer (running from SSP Clock)
303 // Setup reader to card connection
305 // The setup consists of a three way handshake:
306 // - Receive initialisation vector 7 bits
307 // - Transmit card type 6 bits
308 // - Receive Acknowledge 6 bits
309 static int32_t setup_phase(legic_card_select_t
*p_card
) {
312 // init coordination timestamp
313 last_frame_end
= GetCountSspClk();
319 int32_t iv
= rx_frame(&len
);
320 if((len
!= 7) || (iv
< 0)) {
327 // reply with card type
328 switch(p_card
->tagtype
) {
341 int32_t ack
= rx_frame(&len
);
342 if((len
!= 6) || (ack
< 0)) {
347 switch(p_card
->tagtype
) {
349 if(ack
!= 0x19) return -1;
352 if(ack
!= 0x39) return -1;
355 if(ack
!= 0x39) return -1;
359 // During rx the prng is clocked using the variable reader period.
360 // Since rx_frame detects end of frame by detecting a code violation,
361 // the prng is off by one bit period after each rx phase. Hence, tx
362 // code advances the prng by (TAG_FRAME_WAIT/TAG_BIT_PERIOD - 1).
363 // This is not possible for back to back rx, so this quirk reduces
364 // the gap by one period.
365 last_frame_end
+= TAG_BIT_PERIOD
;
370 static uint8_t calc_crc4(uint16_t cmd
, uint8_t cmd_sz
, uint8_t value
) {
371 crc_clear(&legic_crc
);
372 crc_update(&legic_crc
, (value
<< cmd_sz
) | cmd
, 8 + cmd_sz
);
373 return crc_finish(&legic_crc
);
376 static int32_t connected_phase(legic_card_select_t
*p_card
) {
380 int32_t cmd
= rx_frame(&len
);
385 // check if command is LEGIC_READ
386 if(len
== p_card
->cmdsize
) {
388 uint8_t byte
= legic_mem
[cmd
>> 1];
389 uint8_t crc
= calc_crc4(cmd
, p_card
->cmdsize
, byte
);
392 tx_frame((crc
<< 8) | byte
, 12);
397 // check if command is LEGIC_WRITE
398 if(len
== p_card
->cmdsize
+ 8 + 4) {
400 uint16_t mask
= (1 << p_card
->addrsize
) - 1;
401 uint16_t addr
= (cmd
>> 1) & mask
;
402 uint8_t byte
= (cmd
>> p_card
->cmdsize
) & 0xff;
403 uint8_t crc
= (cmd
>> (p_card
->cmdsize
+ 8)) & 0xf;
405 // check received against calculated crc
406 uint8_t calc_crc
= calc_crc4(addr
<< 1, p_card
->cmdsize
, byte
);
407 if(calc_crc
!= crc
) {
408 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc
, crc
);
413 legic_mem
[addr
] = byte
;
424 //-----------------------------------------------------------------------------
425 // Command Line Interface
427 // Only this function is public / called from appmain.c
428 //-----------------------------------------------------------------------------
430 void LegicRfSimulate(uint8_t cardtype
) {
431 // configure ARM and FPGA
434 // verify command line input
435 if(init_card(cardtype
, &card
) != 0) {
436 DbpString("Unknown tagtype.");
441 DbpString("Starting Legic emulator, press button to end");
442 while(!BUTTON_PRESS()) {
445 // wait for carrier, restart after timeout
446 if(!wait_for(RWD_PULSE
, GetCountSspClk() + TAG_BIT_PERIOD
)) {
450 // wait for connection, restart on error
451 if(setup_phase(&card
)) {
455 // conection is established, process commands until one fails
456 while(!connected_phase(&card
)) {
462 DbpString("Stopped");
463 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);