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