Legic Tag Simulator (#666)
[proxmark3-svn] / armsrc / legicrf.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 "legicrf.h"
19 #include "legic_prng.h"
20 #include "legic.h"
21 #include "crc.h"
22
23 static legic_card_select_t card;/* metadata of currently selected card */
24 static crc_t legic_crc;
25
26 //-----------------------------------------------------------------------------
27 // Frame timing and pseudorandom number generator
28 //
29 // The Prng is forwarded every 100us (TAG_BIT_PERIOD), except when the reader is
30 // transmitting. In that case the prng has to be forwarded every bit transmitted:
31 // - 60us for a 0 (RWD_TIME_0)
32 // - 100us for a 1 (RWD_TIME_1)
33 //
34 // The data dependent timing makes writing comprehensible code significantly
35 // harder. The current aproach forwards the prng data based if there is data on
36 // air and time based, using GET_TICKS, during computational and wait periodes.
37 //
38 // To not have the necessity to calculate/guess exection time dependend timeouts
39 // tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
40 //-----------------------------------------------------------------------------
41
42 static uint32_t last_frame_end; /* ts of last bit of previews rx or tx frame */
43
44 #define RWD_TIME_PAUSE 30 /* 20us */
45 #define RWD_TIME_1 150 /* READER_TIME_PAUSE 20us off + 80us on = 100us */
46 #define RWD_TIME_0 90 /* READER_TIME_PAUSE 20us off + 40us on = 60us */
47 #define RWD_FRAME_WAIT 330 /* 220us from TAG frame end to READER frame start */
48 #define TAG_FRAME_WAIT 495 /* 330us from READER frame end to TAG frame start */
49 #define TAG_BIT_PERIOD 150 /* 100us */
50 #define TAG_WRITE_TIMEOUT 60 /* 40 * 100us (write should take at most 3.6ms) */
51
52 #define LEGIC_READ 0x01 /* Read Command */
53 #define LEGIC_WRITE 0x00 /* Write Command */
54
55 #define SESSION_IV 0x55 /* An arbitrary chose session IV, all shoud work */
56 #define OFFSET_LOG 1024 /* The largest Legic Prime card is 1k */
57 #define WRITE_LOWERLIMIT 4 /* UID and MCC are not writable */
58
59 #define INPUT_THRESHOLD 8 /* heuristically determined, lower values */
60 /* lead to detecting false ack during write */
61
62 //-----------------------------------------------------------------------------
63 // I/O interface abstraction (FPGA -> ARM)
64 //-----------------------------------------------------------------------------
65
66 static inline uint8_t rx_byte_from_fpga() {
67 for(;;) {
68 WDT_HIT();
69
70 // wait for byte be become available in rx holding register
71 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
72 return AT91C_BASE_SSC->SSC_RHR;
73 }
74 }
75 }
76
77 //-----------------------------------------------------------------------------
78 // Demodulation (Reader)
79 //-----------------------------------------------------------------------------
80
81 // Returns a demedulated bit
82 //
83 // The FPGA running xcorrelation samples the subcarrier at ~13.56 MHz. The mode
84 // was initialy designed to receive BSPK/2-PSK. Hance, it reports an I/Q pair
85 // every 4.7us (8 bits i and 8 bits q).
86 //
87 // The subcarrier amplitude can be calculated using Pythagoras sqrt(i^2 + q^2).
88 // To reduce CPU time the amplitude is approximated by using linear functions:
89 // am = MAX(ABS(i),ABS(q)) + 1/2*MIN(ABS(i),ABSq))
90 //
91 // Note: The SSC receiver is never synchronized the calculation my be performed
92 // on a I/Q pair from two subsequent correlations, but does not matter.
93 //
94 // The bit time is 99.1us (21 I/Q pairs). The receiver skips the first 5 samples
95 // and averages the next (most stable) 8 samples. The final 8 samples are dropped
96 // also.
97 //
98 // The demedulated should be alligned to the bit periode by the caller. This is
99 // done in rx_bit and rx_ack.
100 static inline bool rx_bit() {
101 int32_t cq = 0;
102 int32_t ci = 0;
103
104 // skip first 5 I/Q pairs
105 for(size_t i = 0; i<5; ++i) {
106 (int8_t)rx_byte_from_fpga();
107 (int8_t)rx_byte_from_fpga();
108 }
109
110 // sample next 8 I/Q pairs
111 for(size_t i = 0; i<8; ++i) {
112 cq += (int8_t)rx_byte_from_fpga();
113 ci += (int8_t)rx_byte_from_fpga();
114 }
115
116 // calculate power
117 int32_t power = (MAX(ABS(ci), ABS(cq)) + (MIN(ABS(ci), ABS(cq)) >> 1));
118
119 // compare average (power / 8) to threshold
120 return ((power >> 3) > INPUT_THRESHOLD);
121 }
122
123 //-----------------------------------------------------------------------------
124 // Modulation (Reader)
125 //
126 // I've tried to modulate the Legic specific pause-puls using ssc and the default
127 // ssc clock of 105.4 kHz (bit periode of 9.4us) - previous commit. However,
128 // the timing was not precise enough. By increasing the ssc clock this could
129 // be circumvented, but the adventage over bitbang would be little.
130 //-----------------------------------------------------------------------------
131
132 static inline void tx_bit(bool bit) {
133 // insert pause
134 LOW(GPIO_SSC_DOUT);
135 last_frame_end += RWD_TIME_PAUSE;
136 while(GET_TICKS < last_frame_end) { };
137 HIGH(GPIO_SSC_DOUT);
138
139 // return to high, wait for bit periode to end
140 last_frame_end += (bit ? RWD_TIME_1 : RWD_TIME_0) - RWD_TIME_PAUSE;
141 while(GET_TICKS < last_frame_end) { };
142 }
143
144 //-----------------------------------------------------------------------------
145 // Frame Handling (Reader)
146 //
147 // The LEGIC RF protocol from card to reader does not include explicit frame
148 // start/stop information or length information. The reader must know beforehand
149 // how many bits it wants to receive.
150 // Notably: a card sending a stream of 0-bits is indistinguishable from no card
151 // present.
152 //-----------------------------------------------------------------------------
153
154 static void tx_frame(uint32_t frame, uint8_t len) {
155 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
156
157 // wait for next tx timeslot
158 last_frame_end += RWD_FRAME_WAIT;
159 while(GET_TICKS < last_frame_end) { };
160
161 // transmit frame, MSB first
162 for(uint8_t i = 0; i < len; ++i) {
163 bool bit = (frame >> i) & 0x01;
164 tx_bit(bit ^ legic_prng_get_bit());
165 legic_prng_forward(1);
166 };
167
168 // add pause to mark end of the frame
169 LOW(GPIO_SSC_DOUT);
170 last_frame_end += RWD_TIME_PAUSE;
171 while(GET_TICKS < last_frame_end) { };
172 HIGH(GPIO_SSC_DOUT);
173 }
174
175 static uint32_t rx_frame(uint8_t len) {
176 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
177 | FPGA_HF_READER_RX_XCORR_848_KHZ
178 | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
179
180 // hold sampling until card is expected to respond
181 last_frame_end += TAG_FRAME_WAIT;
182 while(GET_TICKS < last_frame_end) { };
183
184 uint32_t frame = 0;
185 for(uint8_t i = 0; i < len; ++i) {
186 frame |= (rx_bit() ^ legic_prng_get_bit()) << i;
187 legic_prng_forward(1);
188
189 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
190 last_frame_end += TAG_BIT_PERIOD;
191 while(GET_TICKS < last_frame_end) { };
192 }
193
194 return frame;
195 }
196
197 static bool rx_ack() {
198 // change fpga into rx mode
199 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
200 | FPGA_HF_READER_RX_XCORR_848_KHZ
201 | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
202
203 // hold sampling until card is expected to respond
204 last_frame_end += TAG_FRAME_WAIT;
205 while(GET_TICKS < last_frame_end) { };
206
207 uint32_t ack = 0;
208 for(uint8_t i = 0; i < TAG_WRITE_TIMEOUT; ++i) {
209 // sample bit
210 ack = rx_bit();
211 legic_prng_forward(1);
212
213 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
214 last_frame_end += TAG_BIT_PERIOD;
215 while(GET_TICKS < last_frame_end) { };
216
217 // check if it was an ACK
218 if(ack) {
219 break;
220 }
221 }
222
223 return ack;
224 }
225
226 //-----------------------------------------------------------------------------
227 // Legic Reader
228 //-----------------------------------------------------------------------------
229
230 static int init_card(uint8_t cardtype, legic_card_select_t *p_card) {
231 p_card->tagtype = cardtype;
232
233 switch(p_card->tagtype) {
234 case 0x0d:
235 p_card->cmdsize = 6;
236 p_card->addrsize = 5;
237 p_card->cardsize = 22;
238 break;
239 case 0x1d:
240 p_card->cmdsize = 9;
241 p_card->addrsize = 8;
242 p_card->cardsize = 256;
243 break;
244 case 0x3d:
245 p_card->cmdsize = 11;
246 p_card->addrsize = 10;
247 p_card->cardsize = 1024;
248 break;
249 default:
250 p_card->cmdsize = 0;
251 p_card->addrsize = 0;
252 p_card->cardsize = 0;
253 return 2;
254 }
255 return 0;
256 }
257
258 static void init_reader(bool clear_mem) {
259 // configure FPGA
260 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
261 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
262 | FPGA_HF_READER_RX_XCORR_848_KHZ
263 | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
264 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
265 LED_D_ON();
266
267 // configure SSC with defaults
268 FpgaSetupSsc();
269
270 // re-claim GPIO_SSC_DOUT as GPIO and enable output
271 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
272 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
273 HIGH(GPIO_SSC_DOUT);
274
275 // init crc calculator
276 crc_init(&legic_crc, 4, 0x19 >> 1, 0x05, 0);
277
278 // start us timer
279 StartTicks();
280 }
281
282 // Setup reader to card connection
283 //
284 // The setup consists of a three way handshake:
285 // - Transmit initialisation vector 7 bits
286 // - Receive card type 6 bits
287 // - Transmit Acknowledge 6 bits
288 static uint32_t setup_phase(uint8_t iv) {
289 // init coordination timestamp
290 last_frame_end = GET_TICKS;
291
292 // Switch on carrier and let the card charge for 5ms.
293 last_frame_end += 7500;
294 while(GET_TICKS < last_frame_end) { };
295
296 legic_prng_init(0);
297 tx_frame(iv, 7);
298
299 // configure prng
300 legic_prng_init(iv);
301 legic_prng_forward(2);
302
303 // receive card type
304 int32_t card_type = rx_frame(6);
305 legic_prng_forward(3);
306
307 // send obsfuscated acknowledgment frame
308 switch (card_type) {
309 case 0x0D:
310 tx_frame(0x19, 6); // MIM22 | READCMD = 0x18 | 0x01
311 break;
312 case 0x1D:
313 case 0x3D:
314 tx_frame(0x39, 6); // MIM256 | READCMD = 0x38 | 0x01
315 break;
316 }
317
318 return card_type;
319 }
320
321 static uint8_t calc_crc4(uint16_t cmd, uint8_t cmd_sz, uint8_t value) {
322 crc_clear(&legic_crc);
323 crc_update(&legic_crc, (value << cmd_sz) | cmd, 8 + cmd_sz);
324 return crc_finish(&legic_crc);
325 }
326
327 static int16_t read_byte(uint16_t index, uint8_t cmd_sz) {
328 uint16_t cmd = (index << 1) | LEGIC_READ;
329
330 // read one byte
331 LED_B_ON();
332 legic_prng_forward(2);
333 tx_frame(cmd, cmd_sz);
334 legic_prng_forward(2);
335 uint32_t frame = rx_frame(12);
336 LED_B_OFF();
337
338 // split frame into data and crc
339 uint8_t byte = BYTEx(frame, 0);
340 uint8_t crc = BYTEx(frame, 1);
341
342 // check received against calculated crc
343 uint8_t calc_crc = calc_crc4(cmd, cmd_sz, byte);
344 if(calc_crc != crc) {
345 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc, crc);
346 return -1;
347 }
348
349 legic_prng_forward(1);
350
351 return byte;
352 }
353
354 // Transmit write command, wait until (3.6ms) the tag sends back an unencrypted
355 // ACK ('1' bit) and forward the prng time based.
356 bool write_byte(uint16_t index, uint8_t byte, uint8_t addr_sz) {
357 uint32_t cmd = index << 1 | LEGIC_WRITE; // prepare command
358 uint8_t crc = calc_crc4(cmd, addr_sz + 1, byte); // calculate crc
359 cmd |= byte << (addr_sz + 1); // append value
360 cmd |= (crc & 0xF) << (addr_sz + 1 + 8); // and crc
361
362 // send write command
363 LED_C_ON();
364 legic_prng_forward(2);
365 tx_frame(cmd, addr_sz + 1 + 8 + 4); // sz = addr_sz + cmd + data + crc
366 legic_prng_forward(3);
367 LED_C_OFF();
368
369 // wait for ack
370 return rx_ack();
371 }
372
373 //-----------------------------------------------------------------------------
374 // Command Line Interface
375 //
376 // Only this functions are public / called from appmain.c
377 //-----------------------------------------------------------------------------
378 void LegicRfReader(int offset, int bytes) {
379 uint8_t *BigBuf = BigBuf_get_addr();
380 memset(BigBuf, 0, 1024);
381
382 // configure ARM and FPGA
383 init_reader(false);
384
385 // establish shared secret and detect card type
386 DbpString("Reading card ...");
387 uint8_t card_type = setup_phase(SESSION_IV);
388 if(init_card(card_type, &card) != 0) {
389 Dbprintf("No or unknown card found, aborting");
390 goto OUT;
391 }
392
393 // if no argument is specified create full dump
394 if(bytes == -1) {
395 bytes = card.cardsize;
396 }
397
398 // do not read beyond card memory
399 if(bytes + offset > card.cardsize) {
400 bytes = card.cardsize - offset;
401 }
402
403 for(uint16_t i = 0; i < bytes; ++i) {
404 int16_t byte = read_byte(offset + i, card.cmdsize);
405 if(byte == -1) {
406 Dbprintf("operation failed @ 0x%03.3x", bytes);
407 goto OUT;
408 }
409 BigBuf[i] = byte;
410 }
411
412 // OK
413 Dbprintf("Card (MIM %i) read, use 'hf legic decode' or", card.cardsize);
414 Dbprintf("'data hexsamples %d' to view results", (bytes+7) & ~7);
415
416 OUT:
417 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
418 LED_B_OFF();
419 LED_C_OFF();
420 LED_D_OFF();
421 StopTicks();
422 }
423
424 void LegicRfWriter(int bytes, int offset) {
425 uint8_t *BigBuf = BigBuf_get_addr();
426
427 // configure ARM and FPGA
428 init_reader(false);
429
430 // uid is not writeable
431 if(offset <= WRITE_LOWERLIMIT) {
432 goto OUT;
433 }
434
435 // establish shared secret and detect card type
436 Dbprintf("Writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
437 uint8_t card_type = setup_phase(SESSION_IV);
438 if(init_card(card_type, &card) != 0) {
439 Dbprintf("No or unknown card found, aborting");
440 goto OUT;
441 }
442
443 // do not write beyond card memory
444 if(bytes + offset > card.cardsize) {
445 bytes = card.cardsize - offset;
446 }
447
448 // write in reverse order, only then is DCF (decremental field) writable
449 while(bytes-- > 0 && !BUTTON_PRESS()) {
450 if(!write_byte(bytes + offset, BigBuf[bytes + offset], card.addrsize)) {
451 Dbprintf("operation failed @ 0x%03.3x", bytes);
452 goto OUT;
453 }
454 }
455
456 // OK
457 DbpString("Write successful");
458
459 OUT:
460 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
461 LED_B_OFF();
462 LED_C_OFF();
463 LED_D_OFF();
464 StopTicks();
465 }
Impressum, Datenschutz