Merge pull request #1331 from Guilhem7/master
[RRG-proxmark3.git] / armsrc / legicrf.c
blob92961fd4a9c99f44596b26cdf9ca36ca45629320
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 "legicrf.h"
14 #include "crc.h" /* legic crc-4 */
15 #include "legic_prng.h" /* legic PRNG impl */
16 #include "legic.h" /* legic_card_select_t struct */
18 #include "proxmark3_arm.h"
19 #include "cmd.h"
20 #include "BigBuf.h"
21 #include "fpgaloader.h"
22 #include "ticks.h"
23 #include "dbprint.h"
24 #include "util.h"
25 #include "string.h"
26 #include "protocols.h"
28 static uint8_t *legic_mem; /* card memory, used for read, write */
29 static legic_card_select_t card;/* metadata of currently selected card */
30 static crc_t legic_crc;
32 //-----------------------------------------------------------------------------
33 // Frame timing and pseudorandom number generator
35 // The Prng is forwarded every 100us (TAG_BIT_PERIOD), except when the reader is
36 // transmitting. In that case the prng has to be forwarded every bit transmitted:
37 // - 60us for a 0 (RWD_TIME_0)
38 // - 100us for a 1 (RWD_TIME_1)
40 // The data dependent timing makes writing comprehensible code significantly
41 // harder. The current aproach forwards the prng data based if there is data on
42 // air and time based, using GET_TICKS, during computational and wait periodes.
44 // To not have the necessity to calculate/guess exection time dependend timeouts
45 // tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
46 //-----------------------------------------------------------------------------
48 static uint32_t last_frame_end; /* ts of last bit of previews rx or tx frame */
50 #define RWD_TIME_PAUSE 30 /* 20us */
51 #define RWD_TIME_1 150 /* READER_TIME_PAUSE 20us off + 80us on = 100us */
52 #define RWD_TIME_0 90 /* READER_TIME_PAUSE 20us off + 40us on = 60us */
53 #define RWD_FRAME_WAIT 330 /* 220us from TAG frame end to READER frame start */
54 #define TAG_FRAME_WAIT 495 /* 330us from READER frame end to TAG frame start */
55 #define TAG_BIT_PERIOD 150 /* 100us */
56 #define TAG_WRITE_TIMEOUT 60 /* 40 * 100us (write should take at most 3.6ms) */
58 #define LEGIC_CARD_MEMSIZE 1024 /* The largest Legic Prime card is 1k */
59 #define WRITE_LOWERLIMIT 4 /* UID and MCC are not writable */
61 #define INPUT_THRESHOLD 8 /* heuristically determined, lower values */
62 /* lead to detecting false ack during write */
64 //-----------------------------------------------------------------------------
65 // I/O interface abstraction (FPGA -> ARM)
66 //-----------------------------------------------------------------------------
67 static uint16_t rx_frame_from_fpga(void) {
68 for (;;) {
69 WDT_HIT();
71 // wait for frame be become available in rx holding register
72 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
73 return AT91C_BASE_SSC->SSC_RHR;
78 //-----------------------------------------------------------------------------
79 // Demodulation (Reader)
80 //-----------------------------------------------------------------------------
82 // Returns a demedulated bit
84 // The FPGA running xcorrelation samples the subcarrier at ~13.56 MHz. The mode
85 // was initialy designed to receive BSPK/2-PSK. Hance, it reports an I/Q pair
86 // every 4.7us (8 bits i and 8 bits q).
88 // The subcarrier amplitude can be calculated using Pythagoras sqrt(i^2 + q^2).
89 // To reduce CPU time the amplitude is approximated by using linear functions:
90 // am = MAX(ABS(i),ABS(q)) + 1/2*MIN(ABS(i),ABSq))
92 // The bit time is 99.1us (21 I/Q pairs). The receiver skips the first 5 samples
93 // and averages the next (most stable) 8 samples. The final 8 samples are dropped
94 // also.
96 // The demodulated should be alligned to the bit period by the caller. This is
97 // done in rx_bit and rx_ack.
99 // Note: The demodulator would be drifting (18.9us * 5 != 100us), rx_frame
100 // has a delay loop that aligns rx_bit calls to the TAG tx timeslots.
102 // Note: inlining this function would fail with -Os
103 static bool rx_bit(void) {
104 int32_t sum_cq = 0;
105 int32_t sum_ci = 0;
107 // skip first 5 I/Q pairs
108 for (size_t i = 0; i < 5; ++i) {
109 (void)rx_frame_from_fpga();
112 // sample next 8 I/Q pairs
113 for (uint8_t i = 0; i < 8; ++i) {
114 uint16_t iq = rx_frame_from_fpga();
115 int8_t ci = (int8_t)(iq >> 8);
116 int8_t cq = (int8_t)(iq & 0xff);
117 sum_ci += ci;
118 sum_cq += cq;
121 // calculate power
122 int32_t power = (MAX(ABS(sum_ci), ABS(sum_cq)) + (MIN(ABS(sum_ci), ABS(sum_cq)) >> 1));
124 // compare average (power / 8) to threshold
125 return ((power >> 3) > INPUT_THRESHOLD);
128 //-----------------------------------------------------------------------------
129 // Modulation
131 // I've tried to modulate the Legic specific pause-puls using ssc and the default
132 // ssc clock of 105.4 kHz (bit periode of 9.4us) - previous commit. However,
133 // the timing was not precise enough. By increasing the ssc clock this could
134 // be circumvented, but the adventage over bitbang would be little.
135 //-----------------------------------------------------------------------------
137 static void tx_bit(bool bit) {
138 // insert pause
139 HIGH(GPIO_SSC_DOUT);
140 last_frame_end += RWD_TIME_PAUSE;
141 while (GET_TICKS < last_frame_end) { };
143 // return to carrier on, wait for bit periode to end
144 LOW(GPIO_SSC_DOUT);
145 last_frame_end += (bit ? RWD_TIME_1 : RWD_TIME_0) - RWD_TIME_PAUSE;
146 while (GET_TICKS < last_frame_end) { };
149 //-----------------------------------------------------------------------------
150 // Frame Handling (Reader)
152 // The LEGIC RF protocol from card to reader does not include explicit frame
153 // start/stop information or length information. The reader must know beforehand
154 // how many bits it wants to receive.
155 // Notably: a card sending a stream of 0-bits is indistinguishable from no card
156 // present.
157 //-----------------------------------------------------------------------------
159 static void tx_frame(uint32_t frame, uint8_t len) {
160 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_FULL_MOD);
162 // wait for next tx timeslot
163 last_frame_end += RWD_FRAME_WAIT;
164 while (GET_TICKS < last_frame_end) { };
166 // backup ts for trace log
167 uint32_t last_frame_start = last_frame_end;
169 // transmit frame, MSB first
170 for (uint8_t i = 0; i < len; ++i) {
171 bool bit = (frame >> i) & 0x01;
172 tx_bit(bit ^ legic_prng_get_bit());
173 legic_prng_forward(1);
176 // add pause to mark end of the frame
177 HIGH(GPIO_SSC_DOUT);
178 last_frame_end += RWD_TIME_PAUSE;
179 while (GET_TICKS < last_frame_end) { };
180 LOW(GPIO_SSC_DOUT);
182 // log
183 uint8_t cmdbytes[] = {len, BYTEx(frame, 0), BYTEx(frame, 1), BYTEx(frame, 2)};
184 LogTrace(cmdbytes, sizeof(cmdbytes), last_frame_start, last_frame_end, NULL, true);
187 static uint32_t rx_frame(uint8_t len) {
188 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_212_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
190 // hold sampling until card is expected to respond
191 last_frame_end += TAG_FRAME_WAIT;
192 while (GET_TICKS < last_frame_end) { };
194 // backup ts for trace log
195 uint32_t last_frame_start = last_frame_end;
197 uint32_t frame = 0;
198 for (uint8_t i = 0; i < len; ++i) {
199 frame |= (rx_bit() ^ legic_prng_get_bit()) << i;
200 legic_prng_forward(1);
202 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
203 last_frame_end += TAG_BIT_PERIOD;
204 while (GET_TICKS < last_frame_end) { };
207 // log
208 uint8_t cmdbytes[] = {len, BYTEx(frame, 0), BYTEx(frame, 1)};
209 LogTrace(cmdbytes, sizeof(cmdbytes), last_frame_start, last_frame_end, NULL, false);
211 return frame;
214 static bool rx_ack(void) {
215 // change fpga into rx mode
216 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_212_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
218 // hold sampling until card is expected to respond
219 last_frame_end += TAG_FRAME_WAIT;
220 while (GET_TICKS < last_frame_end) { };
222 // backup ts for trace log
223 uint32_t last_frame_start = last_frame_end;
225 uint32_t ack = 0;
226 for (uint8_t i = 0; i < TAG_WRITE_TIMEOUT; ++i) {
227 // sample bit
228 ack = rx_bit();
229 legic_prng_forward(1);
231 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
232 last_frame_end += TAG_BIT_PERIOD;
233 while (GET_TICKS < last_frame_end) { };
235 // check if it was an ACK
236 if (ack) {
237 break;
241 // log
242 uint8_t cmdbytes[] = {1, BYTEx(ack, 0)};
243 LogTrace(cmdbytes, sizeof(cmdbytes), last_frame_start, last_frame_end, NULL, false);
245 return ack;
248 //-----------------------------------------------------------------------------
249 // Legic Reader
250 //-----------------------------------------------------------------------------
252 static int init_card(uint8_t cardtype, legic_card_select_t *p_card) {
253 p_card->tagtype = cardtype;
255 switch (p_card->tagtype) {
256 case 0x0d:
257 p_card->cmdsize = 6;
258 p_card->addrsize = 5;
259 p_card->cardsize = 22;
260 break;
261 case 0x1d:
262 p_card->cmdsize = 9;
263 p_card->addrsize = 8;
264 p_card->cardsize = 256;
265 break;
266 case 0x3d:
267 p_card->cmdsize = 11;
268 p_card->addrsize = 10;
269 p_card->cardsize = 1024;
270 break;
271 default:
272 p_card->cmdsize = 0;
273 p_card->addrsize = 0;
274 p_card->cardsize = 0;
275 return PM3_ESOFT;
277 return PM3_SUCCESS;
280 static void init_reader(void) {
281 // configure FPGA
282 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
283 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_212_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
284 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
285 LED_A_ON();
287 // configure SSC with defaults
288 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
290 // re-claim GPIO_SSC_DOUT as GPIO and enable output
291 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
292 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
293 LOW(GPIO_SSC_DOUT);
295 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
296 legic_mem = BigBuf_get_EM_addr();
297 if (legic_mem) {
298 memset(legic_mem, 0x00, LEGIC_CARD_MEMSIZE);
301 // start trace
302 clear_trace();
303 set_tracing(true);
305 // init crc calculator
306 crc_init(&legic_crc, 4, 0x19 >> 1, 0x05, 0);
308 // start us timer
309 StartTicks();
312 // Setup reader to card connection
314 // The setup consists of a three way handshake:
315 // - Transmit initialisation vector 7 bits
316 // - Receive card type 6 bits
317 // - Transmit Acknowledge 6 bits
318 static uint32_t setup_phase(uint8_t iv) {
319 // init coordination timestamp
320 last_frame_end = GET_TICKS;
322 // Switch on carrier and let the card charge for 5ms.
323 last_frame_end += 7500;
324 while (GET_TICKS < last_frame_end) { };
326 legic_prng_init(0);
327 tx_frame(iv, 7);
329 // configure prng
330 legic_prng_init(iv);
331 legic_prng_forward(2);
333 // receive card type
334 int32_t card_type = rx_frame(6);
335 legic_prng_forward(3);
337 // send obsfuscated acknowledgment frame
338 switch (card_type) {
339 case 0x0D:
340 tx_frame(0x19, 6); // MIM22 | READCMD = 0x18 | 0x01
341 break;
342 case 0x1D:
343 case 0x3D:
344 tx_frame(0x39, 6); // MIM256 | READCMD = 0x38 | 0x01
345 break;
348 return card_type;
351 static uint8_t calc_crc4(uint16_t cmd, uint8_t cmd_sz, uint8_t value) {
352 crc_clear(&legic_crc);
353 crc_update(&legic_crc, (value << cmd_sz) | cmd, 8 + cmd_sz);
354 return crc_finish(&legic_crc);
357 static int16_t read_byte(uint16_t index, uint8_t cmd_sz) {
358 uint16_t cmd = (index << 1) | LEGIC_READ;
360 // read one byte
361 LED_B_ON();
362 legic_prng_forward(2);
363 tx_frame(cmd, cmd_sz);
364 legic_prng_forward(2);
365 uint32_t frame = rx_frame(12);
366 LED_B_OFF();
368 // split frame into data and crc
369 uint8_t byte = BYTEx(frame, 0);
370 uint8_t crc = BYTEx(frame, 1);
372 // check received against calculated crc
373 uint8_t calc_crc = calc_crc4(cmd, cmd_sz, byte);
374 if (calc_crc != crc) {
375 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc, crc);
376 return -1;
379 legic_prng_forward(1);
381 return byte;
384 // Transmit write command, wait until (3.6ms) the tag sends back an unencrypted
385 // ACK ('1' bit) and forward the prng time based.
386 static bool write_byte(uint16_t index, uint8_t byte, uint8_t addr_sz) {
387 uint32_t cmd = index << 1 | LEGIC_WRITE; // prepare command
388 uint8_t crc = calc_crc4(cmd, addr_sz + 1, byte); // calculate crc
389 cmd |= byte << (addr_sz + 1); // append value
390 cmd |= (crc & 0xF) << (addr_sz + 1 + 8); // and crc
392 // send write command
393 LED_C_ON();
394 legic_prng_forward(2);
395 tx_frame(cmd, addr_sz + 1 + 8 + 4); // cmd_sz = addr_sz + cmd + data + crc
396 legic_prng_forward(3);
397 LED_C_OFF();
399 // wait for ack
400 return rx_ack();
403 //-----------------------------------------------------------------------------
404 // Command Line Interface
406 // Only this functions are public / called from appmain.c
407 //-----------------------------------------------------------------------------
408 legic_card_select_t *getLegicCardInfo(void) {
409 return &card;
412 void LegicRfInfo(void) {
413 // configure ARM and FPGA
414 init_reader();
416 // establish shared secret and detect card type
417 uint8_t card_type = setup_phase(0x01);
418 if (init_card(card_type, &card) != PM3_SUCCESS) {
419 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
420 goto OUT;
423 // read UID
424 for (uint8_t i = 0; i < sizeof(card.uid); ++i) {
425 int16_t byte = read_byte(i, card.cmdsize);
426 if (byte == -1) {
427 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
428 goto OUT;
430 card.uid[i] = byte & 0xFF;
433 // read MCC and check against UID
434 int16_t mcc = read_byte(4, card.cmdsize);
435 int16_t calc_mcc = CRC8Legic(card.uid, 4);
436 if (mcc != calc_mcc) {
437 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
438 goto OUT;
441 // OK
442 reply_mix(CMD_ACK, 1, 0, 0, (uint8_t *)&card, sizeof(legic_card_select_t));
444 OUT:
445 switch_off();
446 StopTicks();
449 int LegicRfReaderEx(uint16_t offset, uint16_t len, uint8_t iv) {
451 int res = PM3_SUCCESS;
453 // configure ARM and FPGA
454 init_reader();
456 // establish shared secret and detect card type
457 uint8_t card_type = setup_phase(iv);
458 if (init_card(card_type, &card) != PM3_SUCCESS) {
459 res = PM3_ESOFT;
460 goto OUT;
463 // do not read beyond card memory
464 if (len + offset > card.cardsize) {
465 len = card.cardsize - offset;
468 for (uint16_t i = 0; i < len; ++i) {
469 int16_t byte = read_byte(offset + i, card.cmdsize);
470 if (byte == -1) {
471 res = PM3_EOVFLOW;
472 goto OUT;
474 legic_mem[i] = byte;
476 if (i < 4) {
477 card.uid[i] = byte;
481 OUT:
482 switch_off();
483 StopTicks();
484 return res;
487 void LegicRfReader(uint16_t offset, uint16_t len, uint8_t iv) {
488 // configure ARM and FPGA
489 init_reader();
491 // establish shared secret and detect card type
492 uint8_t card_type = setup_phase(iv);
493 if (init_card(card_type, &card) != PM3_SUCCESS) {
494 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
495 goto OUT;
498 // do not read beyond card memory
499 if (len + offset > card.cardsize) {
500 len = card.cardsize - offset;
503 for (uint16_t i = 0; i < len; ++i) {
504 int16_t byte = read_byte(offset + i, card.cmdsize);
505 if (byte == -1) {
506 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
507 goto OUT;
509 legic_mem[i] = byte;
511 if (i < 4) {
512 card.uid[i] = byte;
516 // OK
517 reply_mix(CMD_ACK, 1, len, 0, 0, 0);
519 OUT:
520 switch_off();
521 StopTicks();
524 void LegicRfWriter(uint16_t offset, uint16_t len, uint8_t iv, uint8_t *data) {
525 // configure ARM and FPGA
526 init_reader();
528 // uid is not writeable
529 if (offset <= WRITE_LOWERLIMIT) {
530 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
531 goto OUT;
534 // establish shared secret and detect card type
535 uint8_t card_type = setup_phase(iv);
536 if (init_card(card_type, &card) != PM3_SUCCESS) {
537 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
538 goto OUT;
541 // do not write beyond card memory
542 if (len + offset > card.cardsize) {
543 len = card.cardsize - offset;
546 // write in reverse order, only then is DCF (decremental field) writable
547 while (len-- > 0 && BUTTON_PRESS() == false) {
548 if (write_byte(len + offset, data[len], card.addrsize) == false) {
549 Dbprintf("operation failed | %02X | %02X | %02X", len + offset, len, data[len]);
550 reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
551 goto OUT;
555 // OK
556 reply_mix(CMD_ACK, 1, len, 0, 0, 0);
558 OUT:
559 switch_off();
560 StopTicks();