1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
16 // LEGIC RF simulation code
17 //-----------------------------------------------------------------------------
18 #include "legicrfsim.h"
21 #include "crc.h" /* legic crc-4 */
22 #include "legic_prng.h" /* legic PRNG impl */
23 #include "legic.h" /* legic_card_select_t struct */
25 #include "proxmark3_arm.h"
27 #include "fpgaloader.h"
32 static uint8_t *legic_mem
; /* card memory, used for sim */
33 static legic_card_select_t card
;/* metadata of currently selected card */
34 static crc_t legic_crc
;
36 //-----------------------------------------------------------------------------
37 // Frame timing and pseudorandom number generator
39 // The Prng is forwarded every 99.1us (TAG_BIT_PERIOD), except when the reader is
40 // transmitting. In that case the prng has to be forwarded every bit transmitted:
41 // - 31.3us for a 0 (RWD_TIME_0)
42 // - 99.1us for a 1 (RWD_TIME_1)
44 // The data dependent timing makes writing comprehensible code significantly
45 // harder. The current approach forwards the prng data based if there is data on
46 // air and time based, using GetCountSspClk(), during computational and wait
47 // periodes. SSP Clock is clocked by the FPGA at 212 kHz (subcarrier frequency).
49 // To not have the necessity to calculate/guess execution time dependent timeouts
50 // tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
51 //-----------------------------------------------------------------------------
53 static uint32_t last_frame_end
; /* ts of last bit of previews rx or tx frame */
55 #define TAG_FRAME_WAIT 70 /* 330us from READER frame end to TAG frame start */
56 #define TAG_ACK_WAIT 758 /* 3.57ms from READER frame end to TAG write ACK */
57 #define TAG_BIT_PERIOD 21 /* 99.1us */
59 #define RWD_TIME_PAUSE 4 /* 18.9us */
60 #define RWD_TIME_1 21 /* RWD_TIME_PAUSE 18.9us off + 80.2us on = 99.1us */
61 #define RWD_TIME_0 13 /* RWD_TIME_PAUSE 18.9us off + 42.4us on = 61.3us */
62 #define RWD_CMD_TIMEOUT 400 /* 120 * 99.1us (arbitrary value) */
63 #define RWD_MIN_FRAME_LEN 6 /* Shortest frame is 6 bits */
64 #define RWD_MAX_FRAME_LEN 23 /* Longest frame is 23 bits */
66 #define RWD_PULSE 1 /* Pulse is signaled with GPIO_SSC_DIN high */
67 #define RWD_PAUSE 0 /* Pause is signaled with GPIO_SSC_DIN low */
69 //-----------------------------------------------------------------------------
71 //-----------------------------------------------------------------------------
73 // Returns true if a pulse/pause is received within timeout
74 // Note: inlining this function would fail with -Os
75 static bool wait_for(bool value
, const uint32_t timeout
) {
76 while ((bool)(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_DIN
) != value
) {
78 if (GetCountSspClk() > timeout
) {
85 // Returns a demodulated bit or -1 on code violation
87 // rx_bit decodes bits using a thresholds. rx_bit has to be called by as soon as
88 // a frame starts (first pause is received). rx_bit checks for a pause up to
89 // 18.9us followed by a pulse of 80.2us or 42.4us:
90 // - A bit length <18.9us is a code violation
91 // - A bit length >80.2us is a 1
92 // - A bit length <80.2us is a 0
93 // - A bit length >148.6us is a code violation
94 static int32_t rx_bit(void) {
95 // backup ts for threshold calculation
96 uint32_t bit_start
= last_frame_end
;
98 // wait for pause to end
99 if (wait_for(RWD_PULSE
, bit_start
+ RWD_TIME_1
* 3 / 2) == false) {
103 // wait for next pause
104 if (wait_for(RWD_PAUSE
, bit_start
+ RWD_TIME_1
* 3 / 2) == false) {
108 // update bit and frame end
109 last_frame_end
= GetCountSspClk();
111 // check for code violation (bit to short)
112 if (last_frame_end
- bit_start
< RWD_TIME_PAUSE
) {
116 // apply threshold (average of RWD_TIME_0 and )
117 return (last_frame_end
- bit_start
> (RWD_TIME_0
+ RWD_TIME_1
) / 2);
120 //-----------------------------------------------------------------------------
123 // LEGIC RF uses a very basic load modulation from card to reader:
124 // - Subcarrier on for a 1
125 // - Subcarrier off for for a 0
127 // The 212kHz subcarrier is generated by the FPGA as well as a matching ssp clk.
128 // Each bit is transferred in a 99.1us slot and the first timeslot starts 330us
129 // after the final 20us pause generated by the reader.
130 //-----------------------------------------------------------------------------
134 // Note: The Subcarrier is not disabled during bits to prevent glitches. This is
135 // not mandatory but results in a cleaner signal. tx_frame will disable
136 // the subcarrier when the frame is done.
137 // Note: inlining this function would fail with -Os
138 static void tx_bit(bool bit
) {
142 // modulate subcarrier
145 // do not modulate subcarrier
149 // wait for tx timeslot to end
150 last_frame_end
+= TAG_BIT_PERIOD
;
151 while (GetCountSspClk() < last_frame_end
) { };
155 //-----------------------------------------------------------------------------
158 // The LEGIC RF protocol from reader to card does not include explicit frame
159 // start/stop information or length information. The tag detects end of frame
160 // trough an extended pulse (>99.1us) without a pause.
161 // In reverse direction (card to reader) the number of bites is well known
162 // and depends only the command received (IV, ACK, READ or WRITE).
163 //-----------------------------------------------------------------------------
165 static void tx_frame(uint32_t frame
, uint8_t len
) {
166 // wait for next tx timeslot
167 last_frame_end
+= TAG_FRAME_WAIT
;
168 legic_prng_forward(TAG_FRAME_WAIT
/ TAG_BIT_PERIOD
- 1);
169 while (GetCountSspClk() < last_frame_end
) { };
171 // backup ts for trace log
172 uint32_t last_frame_start
= last_frame_end
;
174 // transmit frame, MSB first
175 for (uint8_t i
= 0; i
< len
; ++i
) {
176 bool bit
= (frame
>> i
) & 0x01;
177 tx_bit(bit
^ legic_prng_get_bit());
178 legic_prng_forward(1);
181 // disable subcarrier
185 uint8_t cmdbytes
[] = {len
, BYTEx(frame
, 0), BYTEx(frame
, 1)};
186 LogTrace(cmdbytes
, sizeof(cmdbytes
), last_frame_start
, last_frame_end
, NULL
, false);
189 static void tx_ack(void) {
190 // wait for ack timeslot
191 last_frame_end
+= TAG_ACK_WAIT
;
192 legic_prng_forward(TAG_ACK_WAIT
/ TAG_BIT_PERIOD
- 1);
193 while (GetCountSspClk() < last_frame_end
) { };
195 // backup ts for trace log
196 uint32_t last_frame_start
= last_frame_end
;
198 // transmit ack (ack is not encrypted)
200 legic_prng_forward(1);
202 // disable subcarrier
206 uint8_t cmdbytes
[] = {1, 1};
207 LogTrace(cmdbytes
, sizeof(cmdbytes
), last_frame_start
, last_frame_end
, NULL
, false);
210 // Returns a demodulated frame or -1 on code violation
212 // Since TX to RX delay is arbitrary rx_frame has to:
213 // - detect start of frame (first pause)
214 // - forward prng based on ts/TAG_BIT_PERIOD
215 // - receive the frame
216 // - detect end of frame (last pause)
217 static int32_t rx_frame(uint8_t *len
) {
219 // add 2 SSP clock cycles (1 for tx and 1 for rx pipeline delay)
220 // those will be subtracted at the end of the rx phase
223 // wait for first pause (start of frame)
224 for (uint16_t i
= 0; true; ++i
) {
225 // increment prng every TAG_BIT_PERIOD
226 last_frame_end
+= TAG_BIT_PERIOD
;
227 legic_prng_forward(1);
229 // if start of frame was received exit delay loop
230 if (wait_for(RWD_PAUSE
, last_frame_end
)) {
231 last_frame_end
= GetCountSspClk();
235 // check for code violation
236 if (i
> RWD_CMD_TIMEOUT
) {
241 // backup ts for trace log
242 uint32_t last_frame_start
= last_frame_end
;
246 for (*len
= 0; true; ++(*len
)) {
249 int32_t bit
= rx_bit();
252 // check for code violation and to short / long frame
253 if ((bit
< 0) && ((*len
< RWD_MIN_FRAME_LEN
) || (*len
> RWD_MAX_FRAME_LEN
))) {
257 // check for code violation caused by end of frame
263 frame
|= (bit
^ legic_prng_get_bit()) << (*len
);
264 legic_prng_forward(1);
267 // rx_bit sets coordination timestamp to start of pause, append pause duration
268 // and subtract 2 SSP clock cycles (1 for rx and 1 for tx pipeline delay) to
269 // obtain exact end of frame.
270 last_frame_end
+= RWD_TIME_PAUSE
- 2;
273 uint8_t cmdbytes
[] = {*len
, BYTEx(frame
, 0), BYTEx(frame
, 1), BYTEx(frame
, 2)};
274 LogTrace(cmdbytes
, sizeof(cmdbytes
), last_frame_start
, last_frame_end
, NULL
, true);
278 //-----------------------------------------------------------------------------
280 //-----------------------------------------------------------------------------
282 static int32_t init_card(uint8_t cardtype
, legic_card_select_t
*p_card
) {
283 p_card
->tagtype
= cardtype
;
285 switch (p_card
->tagtype
) {
288 p_card
->addrsize
= 5;
289 p_card
->cardsize
= 22;
293 p_card
->addrsize
= 8;
294 p_card
->cardsize
= 256;
297 p_card
->cmdsize
= 11;
298 p_card
->addrsize
= 10;
299 p_card
->cardsize
= 1024;
303 p_card
->addrsize
= 0;
304 p_card
->cardsize
= 0;
310 static void init_tag(void) {
312 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
313 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_212K
);
314 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
316 // configure SSC with defaults
317 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
319 // first pull output to low to prevent glitches then re-claim GPIO_SSC_DOUT
321 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
322 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
324 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
325 legic_mem
= BigBuf_get_EM_addr();
331 // init crc calculator
332 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x05, 0);
334 // start 212kHz timer (running from SSP Clock)
338 // Setup reader to card connection
340 // The setup consists of a three way handshake:
341 // - Receive initialisation vector 7 bits
342 // - Transmit card type 6 bits
343 // - Receive Acknowledge 6 bits
344 static int32_t setup_phase(legic_card_select_t
*p_card
) {
347 // init coordination timestamp
348 last_frame_end
= GetCountSspClk();
354 int32_t iv
= rx_frame(&len
);
355 if ((len
!= 7) || (iv
< 0)) {
362 // reply with card type
363 switch (p_card
->tagtype
) {
376 int32_t ack
= rx_frame(&len
);
377 if ((len
!= 6) || (ack
< 0)) {
382 switch (p_card
->tagtype
) {
384 if (ack
!= 0x19) return PM3_ERFTRANS
;
387 if (ack
!= 0x39) return PM3_ERFTRANS
;
390 if (ack
!= 0x39) return PM3_ERFTRANS
;
394 // During rx the prng is clocked using the variable reader period.
395 // Since rx_frame detects end of frame by detecting a code violation,
396 // the prng is off by one bit period after each rx phase. Hence, tx
397 // code advances the prng by (TAG_FRAME_WAIT/TAG_BIT_PERIOD - 1).
398 // This is not possible for back to back rx, so this quirk reduces
399 // the gap by one period.
400 last_frame_end
+= TAG_BIT_PERIOD
;
405 static uint8_t calc_crc4(uint16_t cmd
, uint8_t cmd_sz
, uint8_t value
) {
406 crc_clear(&legic_crc
);
407 crc_update(&legic_crc
, (value
<< cmd_sz
) | cmd
, 8 + cmd_sz
);
408 return crc_finish(&legic_crc
);
411 static int32_t connected_phase(legic_card_select_t
*p_card
) {
415 int32_t cmd
= rx_frame(&len
);
420 // check if command is LEGIC_READ
421 if (len
== p_card
->cmdsize
) {
423 uint8_t byte
= legic_mem
[cmd
>> 1];
424 uint8_t crc
= calc_crc4(cmd
, p_card
->cmdsize
, byte
);
427 tx_frame((crc
<< 8) | byte
, 12);
431 // check if command is LEGIC_WRITE
432 if (len
== p_card
->cmdsize
+ 8 + 4) {
434 uint16_t mask
= (1 << p_card
->addrsize
) - 1;
435 uint16_t addr
= (cmd
>> 1) & mask
;
436 uint8_t byte
= (cmd
>> p_card
->cmdsize
) & 0xff;
437 uint8_t crc
= (cmd
>> (p_card
->cmdsize
+ 8)) & 0xf;
439 // check received against calculated crc
440 uint8_t calc_crc
= calc_crc4(addr
<< 1, p_card
->cmdsize
, byte
);
441 if (calc_crc
!= crc
) {
442 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc
, crc
);
447 legic_mem
[addr
] = byte
;
457 //-----------------------------------------------------------------------------
458 // Command Line Interface
460 // Only this function is public / called from appmain.c
461 //-----------------------------------------------------------------------------
463 void LegicRfSimulate(uint8_t tagtype
, bool send_reply
) {
464 // configure ARM and FPGA
467 int res
= init_card(tagtype
, &card
);
468 // verify command line input
469 if (res
!= PM3_SUCCESS
) {
470 DbpString("Unknown tagtype to simulate");
476 Dbprintf("Legic Prime, simulating MCD... " _YELLOW_("%02X") " MSN... " _YELLOW_("%02X%02X%02X"), legic_mem
[0], legic_mem
[1], legic_mem
[2], legic_mem
[3]);
478 uint16_t counter
= 0;
479 while (BUTTON_PRESS() == false) {
483 if (counter
>= 2000) {
484 if (data_available()) {
485 res
= PM3_EOPABORTED
;
492 // wait for carrier, restart after timeout
493 if (wait_for(RWD_PULSE
, GetCountSspClk() + TAG_BIT_PERIOD
) == false) {
497 // wait for connection, restart on error
498 if (setup_phase(&card
) != PM3_SUCCESS
) {
502 // connection is established, process commands until one fails
503 while (connected_phase(&card
) == PM3_SUCCESS
) {
510 if (g_dbglevel
>= DBG_ERROR
) {
511 Dbprintf("Emulator stopped. Trace length... " _YELLOW_("%d"), BigBuf_get_traceLen());
514 if (res
== PM3_EOPABORTED
) {
515 DbpString("Aborted by user");
522 reply_ng(CMD_HF_LEGIC_SIMULATE
, res
, NULL
, 0);
525 BigBuf_free_keep_EM();