1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
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
9 //-----------------------------------------------------------------------------
10 // LEGIC RF simulation code
11 //-----------------------------------------------------------------------------
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"
21 #include "fpgaloader.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) {
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
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) {
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);
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 //-----------------------------------------------------------------------------
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
) {
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
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
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
178 last_frame_end
+= RWD_TIME_PAUSE
;
179 while (GET_TICKS
< last_frame_end
) { };
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
;
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
) { };
208 uint8_t cmdbytes
[] = {len
, BYTEx(frame
, 0), BYTEx(frame
, 1)};
209 LogTrace(cmdbytes
, sizeof(cmdbytes
), last_frame_start
, last_frame_end
, NULL
, false);
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
;
226 for (uint8_t i
= 0; i
< TAG_WRITE_TIMEOUT
; ++i
) {
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
242 uint8_t cmdbytes
[] = {1, BYTEx(ack
, 0)};
243 LogTrace(cmdbytes
, sizeof(cmdbytes
), last_frame_start
, last_frame_end
, NULL
, false);
248 //-----------------------------------------------------------------------------
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
) {
258 p_card
->addrsize
= 5;
259 p_card
->cardsize
= 22;
263 p_card
->addrsize
= 8;
264 p_card
->cardsize
= 256;
267 p_card
->cmdsize
= 11;
268 p_card
->addrsize
= 10;
269 p_card
->cardsize
= 1024;
273 p_card
->addrsize
= 0;
274 p_card
->cardsize
= 0;
280 static void init_reader(void) {
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
);
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
;
295 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
296 legic_mem
= BigBuf_get_EM_addr();
298 memset(legic_mem
, 0x00, LEGIC_CARD_MEMSIZE
);
305 // init crc calculator
306 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x05, 0);
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
) { };
331 legic_prng_forward(2);
334 int32_t card_type
= rx_frame(6);
335 legic_prng_forward(3);
337 // send obsfuscated acknowledgment frame
340 tx_frame(0x19, 6); // MIM22 | READCMD = 0x18 | 0x01
344 tx_frame(0x39, 6); // MIM256 | READCMD = 0x38 | 0x01
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
;
362 legic_prng_forward(2);
363 tx_frame(cmd
, cmd_sz
);
364 legic_prng_forward(2);
365 uint32_t frame
= rx_frame(12);
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
);
379 legic_prng_forward(1);
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
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);
403 //-----------------------------------------------------------------------------
404 // Command Line Interface
406 // Only this functions are public / called from appmain.c
407 //-----------------------------------------------------------------------------
408 legic_card_select_t
*getLegicCardInfo(void) {
412 void LegicRfInfo(void) {
413 // configure ARM and FPGA
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);
424 for (uint8_t i
= 0; i
< sizeof(card
.uid
); ++i
) {
425 int16_t byte
= read_byte(i
, card
.cmdsize
);
427 reply_mix(CMD_ACK
, 0, 0, 0, 0, 0);
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);
442 reply_mix(CMD_ACK
, 1, 0, 0, (uint8_t *)&card
, sizeof(legic_card_select_t
));
449 int LegicRfReaderEx(uint16_t offset
, uint16_t len
, uint8_t iv
) {
451 int res
= PM3_SUCCESS
;
453 // configure ARM and FPGA
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
) {
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
);
487 void LegicRfReader(uint16_t offset
, uint16_t len
, uint8_t iv
) {
488 // configure ARM and FPGA
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);
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
);
506 reply_mix(CMD_ACK
, 0, 0, 0, 0, 0);
517 reply_mix(CMD_ACK
, 1, len
, 0, 0, 0);
524 void LegicRfWriter(uint16_t offset
, uint16_t len
, uint8_t iv
, uint8_t *data
) {
525 // configure ARM and FPGA
528 // uid is not writeable
529 if (offset
<= WRITE_LOWERLIMIT
) {
530 reply_mix(CMD_ACK
, 0, 0, 0, 0, 0);
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);
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);
556 reply_mix(CMD_ACK
, 1, len
, 0, 0, 0);