Legic Tag Simulator (#666)
[proxmark3-svn] / armsrc / legicrfsim.c
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
13 #include "proxmark3.h"
14 #include "apps.h"
15 #include "util.h"
16 #include "string.h"
17
18 #include "legicrfsim.h"
19 #include "legic_prng.h"
20 #include "legic.h"
21 #include "crc.h"
22
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;
26
27 //-----------------------------------------------------------------------------
28 // Frame timing and pseudorandom number generator
29 //
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)
34 //
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).
39 //
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 //-----------------------------------------------------------------------------
43
44 static uint32_t last_frame_end; /* ts of last bit of previews rx or tx frame */
45
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 */
49
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 */
56
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 */
59
60 //-----------------------------------------------------------------------------
61 // Demodulation
62 //-----------------------------------------------------------------------------
63
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) {
68 return false;
69 }
70 }
71 return true;
72 }
73
74 // Returns a demedulated bit or -1 on code violation
75 //
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;
86
87 // wait for pause to end
88 if(!wait_for(RWD_PULSE, bit_start + RWD_TIME_1*3/2)) {
89 return -1;
90 }
91
92 // wait for next pause
93 if(!wait_for(RWD_PAUSE, bit_start + RWD_TIME_1*3/2)) {
94 return -1;
95 }
96
97 // update bit and frame end
98 last_frame_end = GetCountSspClk();
99
100 // check for code violation (bit to short)
101 if(last_frame_end - bit_start < RWD_TIME_PAUSE) {
102 return -1;
103 }
104
105 // apply threshold (average of RWD_TIME_0 and )
106 return (last_frame_end - bit_start > (RWD_TIME_0 + RWD_TIME_1) / 2);
107 }
108
109 //-----------------------------------------------------------------------------
110 // Modulation
111 //
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
115 //
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 //-----------------------------------------------------------------------------
120
121 // Transmits a bit
122 //
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) {
127 LED_C_ON();
128
129 if(bit) {
130 // modulate subcarrier
131 HIGH(GPIO_SSC_DOUT);
132 } else {
133 // do not modulate subcarrier
134 LOW(GPIO_SSC_DOUT);
135 }
136
137 // wait for tx timeslot to end
138 last_frame_end += TAG_BIT_PERIOD;
139 while(GetCountSspClk() < last_frame_end) { };
140 LED_C_OFF();
141 }
142
143 //-----------------------------------------------------------------------------
144 // Frame Handling
145 //
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 //-----------------------------------------------------------------------------
152
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) { };
158
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);
164 };
165
166 // disable subcarrier
167 LOW(GPIO_SSC_DOUT);
168 }
169
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) { };
175
176 // transmit ack (ack is not encrypted)
177 tx_bit(true);
178 legic_prng_forward(1);
179
180 // disable subcarrier
181 LOW(GPIO_SSC_DOUT);
182 }
183
184 // Returns a demedulated frame or -1 on code violation
185 //
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) {
192 int32_t frame = 0;
193
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
196 last_frame_end -= 2;
197
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);
203
204 // if start of frame was received exit delay loop
205 if(wait_for(RWD_PAUSE, last_frame_end)) {
206 last_frame_end = GetCountSspClk();
207 break;
208 }
209
210 // check for code violation
211 if(i > RWD_CMD_TIMEOUT) {
212 return -1;
213 }
214 }
215
216 // receive frame
217 for(*len = 0; true; ++(*len)) {
218 // receive next bit
219 LED_D_ON();
220 int8_t bit = rx_bit();
221 LED_D_OFF();
222
223 // check for code violation and to short / long frame
224 if((bit < 0) && ((*len < RWD_MIN_FRAME_LEN) || (*len > RWD_MAX_FRAME_LEN))) {
225 return -1;
226 }
227
228 // check for code violation caused by end of frame
229 if(bit < 0) {
230 break;
231 }
232
233 // append bit
234 frame |= (bit ^ legic_prng_get_bit()) << (*len);
235 legic_prng_forward(1);
236 }
237
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;
242
243 return frame;
244 }
245
246 //-----------------------------------------------------------------------------
247 // Legic Simulator
248 //-----------------------------------------------------------------------------
249
250 static int32_t init_card(uint8_t cardtype, legic_card_select_t *p_card) {
251 p_card->tagtype = cardtype;
252
253 switch(p_card->tagtype) {
254 case 0:
255 p_card->cmdsize = 6;
256 p_card->addrsize = 5;
257 p_card->cardsize = 22;
258 break;
259 case 1:
260 p_card->cmdsize = 9;
261 p_card->addrsize = 8;
262 p_card->cardsize = 256;
263 break;
264 case 2:
265 p_card->cmdsize = 11;
266 p_card->addrsize = 10;
267 p_card->cardsize = 1024;
268 break;
269 default:
270 p_card->cmdsize = 0;
271 p_card->addrsize = 0;
272 p_card->cardsize = 0;
273 return 2;
274 }
275 return 0;
276 }
277
278 static void init_tag() {
279 // configure FPGA
280 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
281 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
282 | FPGA_HF_SIMULATOR_MODULATE_212K);
283 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
284
285 // configure SSC with defaults
286 FpgaSetupSsc();
287
288 // first pull output to low to prevent glitches then re-claim GPIO_SSC_DOUT
289 LOW(GPIO_SSC_DOUT);
290 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
291 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
292
293 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
294 legic_mem = BigBuf_get_addr();
295
296 // init crc calculator
297 crc_init(&legic_crc, 4, 0x19 >> 1, 0x05, 0);
298
299 // start 212kHz timer (running from SSP Clock)
300 StartCountSspClk();
301 }
302
303 // Setup reader to card connection
304 //
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) {
310 uint8_t len = 0;
311
312 // init coordination timestamp
313 last_frame_end = GetCountSspClk();
314
315 // reset prng
316 legic_prng_init(0);
317
318 // wait for iv
319 int32_t iv = rx_frame(&len);
320 if((len != 7) || (iv < 0)) {
321 return -1;
322 }
323
324 // configure prng
325 legic_prng_init(iv);
326
327 // reply with card type
328 switch(p_card->tagtype) {
329 case 0:
330 tx_frame(0x0D, 6);
331 break;
332 case 1:
333 tx_frame(0x1D, 6);
334 break;
335 case 2:
336 tx_frame(0x3D, 6);
337 break;
338 }
339
340 // wait for ack
341 int32_t ack = rx_frame(&len);
342 if((len != 6) || (ack < 0)) {
343 return -1;
344 }
345
346 // validate data
347 switch(p_card->tagtype) {
348 case 0:
349 if(ack != 0x19) return -1;
350 break;
351 case 1:
352 if(ack != 0x39) return -1;
353 break;
354 case 2:
355 if(ack != 0x39) return -1;
356 break;
357 }
358
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;
366
367 return 0;
368 }
369
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);
374 }
375
376 static int32_t connected_phase(legic_card_select_t *p_card) {
377 uint8_t len = 0;
378
379 // wait for command
380 int32_t cmd = rx_frame(&len);
381 if(cmd < 0) {
382 return -1;
383 }
384
385 // check if command is LEGIC_READ
386 if(len == p_card->cmdsize) {
387 // prepare data
388 uint8_t byte = legic_mem[cmd >> 1];
389 uint8_t crc = calc_crc4(cmd, p_card->cmdsize, byte);
390
391 // transmit data
392 tx_frame((crc << 8) | byte, 12);
393
394 return 0;
395 }
396
397 // check if command is LEGIC_WRITE
398 if(len == p_card->cmdsize + 8 + 4) {
399 // decode data
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;
404
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);
409 return -1;
410 }
411
412 // store data
413 legic_mem[addr] = byte;
414
415 // transmit ack
416 tx_ack();
417
418 return 0;
419 }
420
421 return -1;
422 }
423
424 //-----------------------------------------------------------------------------
425 // Command Line Interface
426 //
427 // Only this function is public / called from appmain.c
428 //-----------------------------------------------------------------------------
429
430 void LegicRfSimulate(uint8_t cardtype) {
431 // configure ARM and FPGA
432 init_tag();
433
434 // verify command line input
435 if(init_card(cardtype, &card) != 0) {
436 DbpString("Unknown tagtype.");
437 goto OUT;
438 }
439
440 LED_A_ON();
441 DbpString("Starting Legic emulator, press button to end");
442 while(!BUTTON_PRESS()) {
443 WDT_HIT();
444
445 // wait for carrier, restart after timeout
446 if(!wait_for(RWD_PULSE, GetCountSspClk() + TAG_BIT_PERIOD)) {
447 continue;
448 }
449
450 // wait for connection, restart on error
451 if(setup_phase(&card)) {
452 continue;
453 }
454
455 // conection is established, process commands until one fails
456 while(!connected_phase(&card)) {
457 WDT_HIT();
458 }
459 }
460
461 OUT:
462 DbpString("Stopped");
463 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
464 LED_A_OFF();
465 LED_C_OFF();
466 LED_D_OFF();
467 StopTicks();
468 }
Impressum, Datenschutz