text
[RRG-proxmark3.git] / armsrc / legicrfsim.c
blob00b40efb2fac203dc1ca1aa8741ff53c2429060c
1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
3 // 2016 Iceman
4 // 2018 AntiCat
5 //
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
8 // the license.
9 //-----------------------------------------------------------------------------
10 // LEGIC RF simulation code
11 //-----------------------------------------------------------------------------
12 #include "legicrfsim.h"
13 #include "legicrf.h"
15 #include "crc.h" /* legic crc-4 */
16 #include "legic_prng.h" /* legic PRNG impl */
17 #include "legic.h" /* legic_card_select_t struct */
18 #include "cmd.h"
19 #include "proxmark3_arm.h"
20 #include "BigBuf.h"
21 #include "fpgaloader.h"
22 #include "ticks.h"
23 #include "dbprint.h"
24 #include "util.h"
26 static uint8_t *legic_mem; /* card memory, used for sim */
27 static legic_card_select_t card;/* metadata of currently selected card */
28 static crc_t legic_crc;
30 //-----------------------------------------------------------------------------
31 // Frame timing and pseudorandom number generator
33 // The Prng is forwarded every 99.1us (TAG_BIT_PERIOD), except when the reader is
34 // transmitting. In that case the prng has to be forwarded every bit transmitted:
35 // - 31.3us for a 0 (RWD_TIME_0)
36 // - 99.1us for a 1 (RWD_TIME_1)
38 // The data dependent timing makes writing comprehensible code significantly
39 // harder. The current aproach forwards the prng data based if there is data on
40 // air and time based, using GetCountSspClk(), during computational and wait
41 // periodes. SSP Clock is clocked by the FPGA at 212 kHz (subcarrier frequency).
43 // To not have the necessity to calculate/guess exection time dependend timeouts
44 // tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
45 //-----------------------------------------------------------------------------
47 static uint32_t last_frame_end; /* ts of last bit of previews rx or tx frame */
49 #define TAG_FRAME_WAIT 70 /* 330us from READER frame end to TAG frame start */
50 #define TAG_ACK_WAIT 758 /* 3.57ms from READER frame end to TAG write ACK */
51 #define TAG_BIT_PERIOD 21 /* 99.1us */
53 #define RWD_TIME_PAUSE 4 /* 18.9us */
54 #define RWD_TIME_1 21 /* RWD_TIME_PAUSE 18.9us off + 80.2us on = 99.1us */
55 #define RWD_TIME_0 13 /* RWD_TIME_PAUSE 18.9us off + 42.4us on = 61.3us */
56 #define RWD_CMD_TIMEOUT 400 /* 120 * 99.1us (arbitrary value) */
57 #define RWD_MIN_FRAME_LEN 6 /* Shortest frame is 6 bits */
58 #define RWD_MAX_FRAME_LEN 23 /* Longest frame is 23 bits */
60 #define RWD_PULSE 1 /* Pulse is signaled with GPIO_SSC_DIN high */
61 #define RWD_PAUSE 0 /* Pause is signaled with GPIO_SSC_DIN low */
63 //-----------------------------------------------------------------------------
64 // Demodulation
65 //-----------------------------------------------------------------------------
67 // Returns true if a pulse/pause is received within timeout
68 // Note: inlining this function would fail with -Os
69 static bool wait_for(bool value, const uint32_t timeout) {
70 while ((bool)(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN) != value) {
71 WDT_HIT();
72 if (GetCountSspClk() > timeout) {
73 return false;
76 return true;
79 // Returns a demedulated bit or -1 on code violation
81 // rx_bit decodes bits using a thresholds. rx_bit has to be called by as soon as
82 // a frame starts (first pause is received). rx_bit checks for a pause up to
83 // 18.9us followed by a pulse of 80.2us or 42.4us:
84 // - A bit length <18.9us is a code violation
85 // - A bit length >80.2us is a 1
86 // - A bit length <80.2us is a 0
87 // - A bit length >148.6us is a code violation
88 static int8_t rx_bit(void) {
89 // backup ts for threshold calculation
90 uint32_t bit_start = last_frame_end;
92 // wait for pause to end
93 if (!wait_for(RWD_PULSE, bit_start + RWD_TIME_1 * 3 / 2)) {
94 return -1;
97 // wait for next pause
98 if (!wait_for(RWD_PAUSE, bit_start + RWD_TIME_1 * 3 / 2)) {
99 return -1;
102 // update bit and frame end
103 last_frame_end = GetCountSspClk();
105 // check for code violation (bit to short)
106 if (last_frame_end - bit_start < RWD_TIME_PAUSE) {
107 return -1;
110 // apply threshold (average of RWD_TIME_0 and )
111 return (last_frame_end - bit_start > (RWD_TIME_0 + RWD_TIME_1) / 2);
114 //-----------------------------------------------------------------------------
115 // Modulation
117 // LEGIC RF uses a very basic load modulation from card to reader:
118 // - Subcarrier on for a 1
119 // - Subcarrier off for for a 0
121 // The 212kHz subcarrier is generated by the FPGA as well as a mathcing ssp clk.
122 // Each bit is transfered in a 99.1us slot and the first timeslot starts 330us
123 // after the final 20us pause generated by the reader.
124 //-----------------------------------------------------------------------------
126 // Transmits a bit
128 // Note: The Subcarrier is not disabled during bits to prevent glitches. This is
129 // not mandatory but results in a cleaner signal. tx_frame will disable
130 // the subcarrier when the frame is done.
131 // Note: inlining this function would fail with -Os
132 static void tx_bit(bool bit) {
133 LED_C_ON();
135 if (bit) {
136 // modulate subcarrier
137 HIGH(GPIO_SSC_DOUT);
138 } else {
139 // do not modulate subcarrier
140 LOW(GPIO_SSC_DOUT);
143 // wait for tx timeslot to end
144 last_frame_end += TAG_BIT_PERIOD;
145 while (GetCountSspClk() < last_frame_end) { };
146 LED_C_OFF();
149 //-----------------------------------------------------------------------------
150 // Frame Handling
152 // The LEGIC RF protocol from reader to card does not include explicit frame
153 // start/stop information or length information. The tag detects end of frame
154 // trough an extended pulse (>99.1us) without a pause.
155 // In reverse direction (card to reader) the number of bites is well known
156 // and depends only the command received (IV, ACK, READ or WRITE).
157 //-----------------------------------------------------------------------------
159 static void tx_frame(uint32_t frame, uint8_t len) {
160 // wait for next tx timeslot
161 last_frame_end += TAG_FRAME_WAIT;
162 legic_prng_forward(TAG_FRAME_WAIT / TAG_BIT_PERIOD - 1);
163 while (GetCountSspClk() < last_frame_end) { };
165 // backup ts for trace log
166 uint32_t last_frame_start = last_frame_end;
168 // transmit frame, MSB first
169 for (uint8_t i = 0; i < len; ++i) {
170 bool bit = (frame >> i) & 0x01;
171 tx_bit(bit ^ legic_prng_get_bit());
172 legic_prng_forward(1);
175 // disable subcarrier
176 LOW(GPIO_SSC_DOUT);
178 // log
179 uint8_t cmdbytes[] = {len, BYTEx(frame, 0), BYTEx(frame, 1)};
180 LogTrace(cmdbytes, sizeof(cmdbytes), last_frame_start, last_frame_end, NULL, false);
183 static void tx_ack(void) {
184 // wait for ack timeslot
185 last_frame_end += TAG_ACK_WAIT;
186 legic_prng_forward(TAG_ACK_WAIT / TAG_BIT_PERIOD - 1);
187 while (GetCountSspClk() < last_frame_end) { };
189 // backup ts for trace log
190 uint32_t last_frame_start = last_frame_end;
192 // transmit ack (ack is not encrypted)
193 tx_bit(true);
194 legic_prng_forward(1);
196 // disable subcarrier
197 LOW(GPIO_SSC_DOUT);
199 // log
200 uint8_t cmdbytes[] = {1, 1};
201 LogTrace(cmdbytes, sizeof(cmdbytes), last_frame_start, last_frame_end, NULL, false);
204 // Returns a demedulated frame or -1 on code violation
206 // Since TX to RX delay is arbitrary rx_frame has to:
207 // - detect start of frame (first pause)
208 // - forward prng based on ts/TAG_BIT_PERIOD
209 // - receive the frame
210 // - detect end of frame (last pause)
211 static int32_t rx_frame(uint8_t *len) {
212 int32_t frame = 0;
214 // add 2 SSP clock cycles (1 for tx and 1 for rx pipeline delay)
215 // those will be substracted at the end of the rx phase
216 last_frame_end -= 2;
218 // wait for first pause (start of frame)
219 for (uint16_t i = 0; true; ++i) {
220 // increment prng every TAG_BIT_PERIOD
221 last_frame_end += TAG_BIT_PERIOD;
222 legic_prng_forward(1);
224 // if start of frame was received exit delay loop
225 if (wait_for(RWD_PAUSE, last_frame_end)) {
226 last_frame_end = GetCountSspClk();
227 break;
230 // check for code violation
231 if (i > RWD_CMD_TIMEOUT) {
232 return -1;
236 // backup ts for trace log
237 uint32_t last_frame_start = last_frame_end;
239 // receive frame
240 for (*len = 0; true; ++(*len)) {
241 // receive next bit
242 LED_B_ON();
243 int8_t bit = rx_bit();
244 LED_B_OFF();
246 // check for code violation and to short / long frame
247 if ((bit < 0) && ((*len < RWD_MIN_FRAME_LEN) || (*len > RWD_MAX_FRAME_LEN))) {
248 return -1;
251 // check for code violation caused by end of frame
252 if (bit < 0) {
253 break;
256 // append bit
257 frame |= (bit ^ legic_prng_get_bit()) << (*len);
258 legic_prng_forward(1);
261 // rx_bit sets coordination timestamp to start of pause, append pause duration
262 // and substract 2 SSP clock cycles (1 for rx and 1 for tx pipeline delay) to
263 // obtain exact end of frame.
264 last_frame_end += RWD_TIME_PAUSE - 2;
266 // log
267 uint8_t cmdbytes[] = {*len, BYTEx(frame, 0), BYTEx(frame, 1), BYTEx(frame, 2)};
268 LogTrace(cmdbytes, sizeof(cmdbytes), last_frame_start, last_frame_end, NULL, true);
269 return frame;
272 //-----------------------------------------------------------------------------
273 // Legic Simulator
274 //-----------------------------------------------------------------------------
276 static int32_t init_card(uint8_t cardtype, legic_card_select_t *p_card) {
277 p_card->tagtype = cardtype;
279 switch (p_card->tagtype) {
280 case 0:
281 p_card->cmdsize = 6;
282 p_card->addrsize = 5;
283 p_card->cardsize = 22;
284 break;
285 case 1:
286 p_card->cmdsize = 9;
287 p_card->addrsize = 8;
288 p_card->cardsize = 256;
289 break;
290 case 2:
291 p_card->cmdsize = 11;
292 p_card->addrsize = 10;
293 p_card->cardsize = 1024;
294 break;
295 default:
296 p_card->cmdsize = 0;
297 p_card->addrsize = 0;
298 p_card->cardsize = 0;
299 return PM3_ESOFT;
301 return PM3_SUCCESS;
304 static void init_tag(void) {
305 // configure FPGA
306 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
307 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_212K);
308 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
310 // configure SSC with defaults
311 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
313 // first pull output to low to prevent glitches then re-claim GPIO_SSC_DOUT
314 LOW(GPIO_SSC_DOUT);
315 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
316 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
318 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
319 legic_mem = BigBuf_get_EM_addr();
321 // start trace
322 clear_trace();
323 set_tracing(true);
325 // init crc calculator
326 crc_init(&legic_crc, 4, 0x19 >> 1, 0x05, 0);
328 // start 212kHz timer (running from SSP Clock)
329 StartCountSspClk();
332 // Setup reader to card connection
334 // The setup consists of a three way handshake:
335 // - Receive initialisation vector 7 bits
336 // - Transmit card type 6 bits
337 // - Receive Acknowledge 6 bits
338 static int32_t setup_phase(legic_card_select_t *p_card) {
339 uint8_t len = 0;
341 // init coordination timestamp
342 last_frame_end = GetCountSspClk();
344 // reset prng
345 legic_prng_init(0);
347 // wait for iv
348 int32_t iv = rx_frame(&len);
349 if ((len != 7) || (iv < 0)) {
350 return -1;
353 // configure prng
354 legic_prng_init(iv);
356 // reply with card type
357 switch (p_card->tagtype) {
358 case 0:
359 tx_frame(0x0D, 6);
360 break;
361 case 1:
362 tx_frame(0x1D, 6);
363 break;
364 case 2:
365 tx_frame(0x3D, 6);
366 break;
369 // wait for ack
370 int32_t ack = rx_frame(&len);
371 if ((len != 6) || (ack < 0)) {
372 return -1;
375 // validate data
376 switch (p_card->tagtype) {
377 case 0:
378 if (ack != 0x19) return -1;
379 break;
380 case 1:
381 if (ack != 0x39) return -1;
382 break;
383 case 2:
384 if (ack != 0x39) return -1;
385 break;
388 // During rx the prng is clocked using the variable reader period.
389 // Since rx_frame detects end of frame by detecting a code violation,
390 // the prng is off by one bit period after each rx phase. Hence, tx
391 // code advances the prng by (TAG_FRAME_WAIT/TAG_BIT_PERIOD - 1).
392 // This is not possible for back to back rx, so this quirk reduces
393 // the gap by one period.
394 last_frame_end += TAG_BIT_PERIOD;
396 return 0;
399 static uint8_t calc_crc4(uint16_t cmd, uint8_t cmd_sz, uint8_t value) {
400 crc_clear(&legic_crc);
401 crc_update(&legic_crc, (value << cmd_sz) | cmd, 8 + cmd_sz);
402 return crc_finish(&legic_crc);
405 static int32_t connected_phase(legic_card_select_t *p_card) {
406 uint8_t len = 0;
408 // wait for command
409 int32_t cmd = rx_frame(&len);
410 if (cmd < 0) {
411 return -1;
414 // check if command is LEGIC_READ
415 if (len == p_card->cmdsize) {
416 // prepare data
417 uint8_t byte = legic_mem[cmd >> 1];
418 uint8_t crc = calc_crc4(cmd, p_card->cmdsize, byte);
420 // transmit data
421 tx_frame((crc << 8) | byte, 12);
423 return 0;
426 // check if command is LEGIC_WRITE
427 if (len == p_card->cmdsize + 8 + 4) {
428 // decode data
429 uint16_t mask = (1 << p_card->addrsize) - 1;
430 uint16_t addr = (cmd >> 1) & mask;
431 uint8_t byte = (cmd >> p_card->cmdsize) & 0xff;
432 uint8_t crc = (cmd >> (p_card->cmdsize + 8)) & 0xf;
434 // check received against calculated crc
435 uint8_t calc_crc = calc_crc4(addr << 1, p_card->cmdsize, byte);
436 if (calc_crc != crc) {
437 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc, crc);
438 return -1;
441 // store data
442 legic_mem[addr] = byte;
444 // transmit ack
445 tx_ack();
447 return 0;
450 return -1;
453 //-----------------------------------------------------------------------------
454 // Command Line Interface
456 // Only this function is public / called from appmain.c
457 //-----------------------------------------------------------------------------
459 void LegicRfSimulate(uint8_t tagtype, bool send_reply) {
460 // configure ARM and FPGA
461 init_tag();
463 int res = PM3_SUCCESS;
464 // verify command line input
465 if (init_card(tagtype, &card) != PM3_SUCCESS) {
466 DbpString("Unknown tagtype to simulate");
467 res = PM3_ESOFT;
468 goto OUT;
471 uint16_t counter = 0;
472 LED_A_ON();
474 Dbprintf("Legic Prime, simulating uid: %02X%02X%02X%02X", legic_mem[0], legic_mem[1], legic_mem[2], legic_mem[3]);
476 while (BUTTON_PRESS() == false) {
477 WDT_HIT();
479 if (counter >= 2000) {
480 if (data_available()) {
481 res = PM3_EOPABORTED;
482 break;
484 counter = 0;
486 counter++;
488 // wait for carrier, restart after timeout
489 if (wait_for(RWD_PULSE, GetCountSspClk() + TAG_BIT_PERIOD) == false) {
490 continue;
493 // wait for connection, restart on error
494 if (setup_phase(&card)) {
495 continue;
498 // conection is established, process commands until one fails
499 while (connected_phase(&card) == false) {
500 WDT_HIT();
504 OUT:
506 if (DBGLEVEL >= DBG_ERROR) {
507 Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", get_tracing(), BigBuf_get_traceLen());
510 if (res == PM3_EOPABORTED)
511 DbpString("aborted by user");
513 switch_off();
514 StopTicks();
516 if (send_reply)
517 reply_ng(CMD_HF_LEGIC_SIMULATE, res, NULL, 0);
519 BigBuf_free_keep_EM();