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 //-----------------------------------------------------------------------------
15 #include "proxmark3.h"
20 #include "legic_prng.h"
23 #include "fpgaloader.h"
25 static legic_card_select_t card
;/* metadata of currently selected card */
26 static crc_t legic_crc
;
28 //-----------------------------------------------------------------------------
29 // Frame timing and pseudorandom number generator
31 // The Prng is forwarded every 100us (TAG_BIT_PERIOD), except when the reader is
32 // transmitting. In that case the prng has to be forwarded every bit transmitted:
33 // - 60us for a 0 (RWD_TIME_0)
34 // - 100us for a 1 (RWD_TIME_1)
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 GET_TICKS, during computational and wait periodes.
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 //-----------------------------------------------------------------------------
44 static uint32_t last_frame_end
; /* ts of last bit of previews rx or tx frame */
46 #define RWD_TIME_PAUSE 30 /* 20us */
47 #define RWD_TIME_1 150 /* READER_TIME_PAUSE 20us off + 80us on = 100us */
48 #define RWD_TIME_0 90 /* READER_TIME_PAUSE 20us off + 40us on = 60us */
49 #define RWD_FRAME_WAIT 330 /* 220us from TAG frame end to READER frame start */
50 #define TAG_FRAME_WAIT 495 /* 330us from READER frame end to TAG frame start */
51 #define TAG_BIT_PERIOD 150 /* 100us */
52 #define TAG_WRITE_TIMEOUT 60 /* 40 * 100us (write should take at most 3.6ms) */
54 #define LEGIC_READ 0x01 /* Read Command */
55 #define LEGIC_WRITE 0x00 /* Write Command */
57 #define SESSION_IV 0x55 /* An arbitrary chose session IV, all shoud work */
58 #define OFFSET_LOG 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 //-----------------------------------------------------------------------------
68 static inline uint16_t rx_frame_from_fpga() {
72 // wait for frame be become available in rx holding register
73 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
74 return AT91C_BASE_SSC
->SSC_RHR
;
79 //-----------------------------------------------------------------------------
80 // Demodulation (Reader)
81 //-----------------------------------------------------------------------------
83 // Returns a demedulated bit
85 // The FPGA running xcorrelation samples the subcarrier at ~13.56 MHz. The mode
86 // was initialy designed to receive BSPK/2-PSK. Hance, it reports an I/Q pair
87 // every 4.7us (8 bits i and 8 bits q).
89 // The subcarrier amplitude can be calculated using Pythagoras sqrt(i^2 + q^2).
90 // To reduce CPU time the amplitude is approximated by using linear functions:
91 // am = MAX(ABS(i),ABS(q)) + 1/2*MIN(ABS(i),ABSq))
93 // The bit time is 99.1us (21 I/Q pairs). The receiver skips the first 5 samples
94 // and averages the next (most stable) 8 samples. The final 8 samples are dropped
97 // The demodulated should be alligned to the bit period by the caller. This is
98 // done in rx_bit and rx_ack.
99 static inline bool rx_bit() {
103 // skip first 5 I/Q pairs
104 for(size_t i
= 0; i
<5; ++i
) {
105 (void)rx_frame_from_fpga();
108 // sample next 8 I/Q pairs
109 for(size_t i
= 0; i
<8; ++i
) {
110 uint16_t iq
= rx_frame_from_fpga();
111 int8_t ci
= (int8_t)(iq
>> 8);
112 int8_t cq
= (int8_t)(iq
& 0xff);
118 int32_t power
= (MAX(ABS(sum_ci
), ABS(sum_cq
)) + MIN(ABS(sum_ci
), ABS(sum_cq
))/2);
120 // compare average (power / 8) to threshold
121 return ((power
>> 3) > INPUT_THRESHOLD
);
124 //-----------------------------------------------------------------------------
125 // Modulation (Reader)
127 // I've tried to modulate the Legic specific pause-puls using ssc and the default
128 // ssc clock of 105.4 kHz (bit periode of 9.4us) - previous commit. However,
129 // the timing was not precise enough. By increasing the ssc clock this could
130 // be circumvented, but the adventage over bitbang would be little.
131 //-----------------------------------------------------------------------------
133 static inline void tx_bit(bool bit
) {
136 last_frame_end
+= RWD_TIME_PAUSE
;
137 while(GET_TICKS
< last_frame_end
) { };
139 // return to carrier on, wait for bit periode to end
141 last_frame_end
+= (bit
? RWD_TIME_1
: RWD_TIME_0
) - RWD_TIME_PAUSE
;
142 while(GET_TICKS
< last_frame_end
) { };
145 //-----------------------------------------------------------------------------
146 // Frame Handling (Reader)
148 // The LEGIC RF protocol from card to reader does not include explicit frame
149 // start/stop information or length information. The reader must know beforehand
150 // how many bits it wants to receive.
151 // Notably: a card sending a stream of 0-bits is indistinguishable from no card
153 //-----------------------------------------------------------------------------
155 static void tx_frame(uint32_t frame
, uint8_t len
) {
156 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_FULL_MOD
);
158 // wait for next tx timeslot
159 last_frame_end
+= RWD_FRAME_WAIT
;
160 while(GET_TICKS
< last_frame_end
) { };
162 // transmit frame, MSB first
163 for(uint8_t i
= 0; i
< len
; ++i
) {
164 bool bit
= (frame
>> i
) & 0x01;
165 tx_bit(bit
^ legic_prng_get_bit());
166 legic_prng_forward(1);
169 // add pause to mark end of the frame
171 last_frame_end
+= RWD_TIME_PAUSE
;
172 while(GET_TICKS
< last_frame_end
) { };
176 static uint32_t rx_frame(uint8_t len
) {
177 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_212_KHZ
| FPGA_HF_READER_MODE_RECEIVE_IQ
);
179 // hold sampling until card is expected to respond
180 last_frame_end
+= TAG_FRAME_WAIT
;
181 while(GET_TICKS
< last_frame_end
) { };
184 for(uint8_t i
= 0; i
< len
; ++i
) {
185 frame
|= (rx_bit() ^ legic_prng_get_bit()) << i
;
186 legic_prng_forward(1);
188 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
189 last_frame_end
+= TAG_BIT_PERIOD
;
190 while(GET_TICKS
< last_frame_end
) { };
196 static bool rx_ack() {
197 // change fpga into rx mode
198 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_212_KHZ
| FPGA_HF_READER_MODE_RECEIVE_IQ
);
200 // hold sampling until card is expected to respond
201 last_frame_end
+= TAG_FRAME_WAIT
;
202 while(GET_TICKS
< last_frame_end
) { };
205 for(uint8_t i
= 0; i
< TAG_WRITE_TIMEOUT
; ++i
) {
208 legic_prng_forward(1);
210 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
211 last_frame_end
+= TAG_BIT_PERIOD
;
212 while(GET_TICKS
< last_frame_end
) { };
214 // check if it was an ACK
223 //-----------------------------------------------------------------------------
225 //-----------------------------------------------------------------------------
227 static int init_card(uint8_t cardtype
, legic_card_select_t
*p_card
) {
228 p_card
->tagtype
= cardtype
;
230 switch(p_card
->tagtype
) {
233 p_card
->addrsize
= 5;
234 p_card
->cardsize
= 22;
238 p_card
->addrsize
= 8;
239 p_card
->cardsize
= 256;
242 p_card
->cmdsize
= 11;
243 p_card
->addrsize
= 10;
244 p_card
->cardsize
= 1024;
248 p_card
->addrsize
= 0;
249 p_card
->cardsize
= 0;
255 static void init_reader(bool clear_mem
) {
257 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
258 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_212_KHZ
| FPGA_HF_READER_MODE_RECEIVE_IQ
);
259 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
262 // configure SSC with defaults
263 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
265 // re-claim GPIO_SSC_DOUT as GPIO and enable output
266 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
267 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
270 // init crc calculator
271 crc_init(&legic_crc
, 4, 0x19 >> 1, 0x05, 0);
277 // Setup reader to card connection
279 // The setup consists of a three way handshake:
280 // - Transmit initialisation vector 7 bits
281 // - Receive card type 6 bits
282 // - Transmit Acknowledge 6 bits
283 static uint32_t setup_phase(uint8_t iv
) {
284 // init coordination timestamp
285 last_frame_end
= GET_TICKS
;
287 // Switch on carrier and let the card charge for 5ms.
288 last_frame_end
+= 7500;
289 while(GET_TICKS
< last_frame_end
) { };
296 legic_prng_forward(2);
299 int32_t card_type
= rx_frame(6);
300 legic_prng_forward(3);
302 // send obsfuscated acknowledgment frame
305 tx_frame(0x19, 6); // MIM22 | READCMD = 0x18 | 0x01
309 tx_frame(0x39, 6); // MIM256 | READCMD = 0x38 | 0x01
316 static uint8_t calc_crc4(uint16_t cmd
, uint8_t cmd_sz
, uint8_t value
) {
317 crc_clear(&legic_crc
);
318 crc_update(&legic_crc
, (value
<< cmd_sz
) | cmd
, 8 + cmd_sz
);
319 return crc_finish(&legic_crc
);
322 static int16_t read_byte(uint16_t index
, uint8_t cmd_sz
) {
323 uint16_t cmd
= (index
<< 1) | LEGIC_READ
;
327 legic_prng_forward(2);
328 tx_frame(cmd
, cmd_sz
);
329 legic_prng_forward(2);
330 uint32_t frame
= rx_frame(12);
333 // split frame into data and crc
334 uint8_t byte
= BYTEx(frame
, 0);
335 uint8_t crc
= BYTEx(frame
, 1);
337 // check received against calculated crc
338 uint8_t calc_crc
= calc_crc4(cmd
, cmd_sz
, byte
);
339 if(calc_crc
!= crc
) {
340 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc
, crc
);
344 legic_prng_forward(1);
349 // Transmit write command, wait until (3.6ms) the tag sends back an unencrypted
350 // ACK ('1' bit) and forward the prng time based.
351 bool write_byte(uint16_t index
, uint8_t byte
, uint8_t addr_sz
) {
352 uint32_t cmd
= index
<< 1 | LEGIC_WRITE
; // prepare command
353 uint8_t crc
= calc_crc4(cmd
, addr_sz
+ 1, byte
); // calculate crc
354 cmd
|= byte
<< (addr_sz
+ 1); // append value
355 cmd
|= (crc
& 0xF) << (addr_sz
+ 1 + 8); // and crc
357 // send write command
359 legic_prng_forward(2);
360 tx_frame(cmd
, addr_sz
+ 1 + 8 + 4); // sz = addr_sz + cmd + data + crc
361 legic_prng_forward(3);
368 //-----------------------------------------------------------------------------
369 // Command Line Interface
371 // Only this functions are public / called from appmain.c
372 //-----------------------------------------------------------------------------
373 void LegicRfReader(int offset
, int bytes
) {
374 uint8_t *BigBuf
= BigBuf_get_addr();
375 memset(BigBuf
, 0, 1024);
377 // configure ARM and FPGA
380 // establish shared secret and detect card type
381 DbpString("Reading card ...");
382 uint8_t card_type
= setup_phase(SESSION_IV
);
384 if(init_card(card_type
, &card
) != 0) {
389 // if no argument is specified create full dump
391 bytes
= card
.cardsize
;
394 // do not read beyond card memory
395 if(bytes
+ offset
> card
.cardsize
) {
396 bytes
= card
.cardsize
- offset
;
399 for(uint16_t i
= 0; i
< bytes
; ++i
) {
400 int16_t byte
= read_byte(offset
+ i
, card
.cmdsize
);
409 cmd_send(CMD_ACK
, result
, bytes
, 0, &card
, sizeof(card
));
410 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
417 void LegicRfWriter(int bytes
, int offset
) {
418 uint8_t *BigBuf
= BigBuf_get_addr();
420 // configure ARM and FPGA
423 // uid is not writeable
424 if(offset
<= WRITE_LOWERLIMIT
) {
428 // establish shared secret and detect card type
429 Dbprintf("Writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+bytes
);
430 uint8_t card_type
= setup_phase(SESSION_IV
);
431 if(init_card(card_type
, &card
) != 0) {
432 Dbprintf("No or unknown card found, aborting");
436 // do not write beyond card memory
437 if(bytes
+ offset
> card
.cardsize
) {
438 bytes
= card
.cardsize
- offset
;
441 // write in reverse order, only then is DCF (decremental field) writable
442 while(bytes
-- > 0 && !BUTTON_PRESS()) {
443 if(!write_byte(bytes
+ offset
, BigBuf
[bytes
+ offset
], card
.addrsize
)) {
444 Dbprintf("operation failed @ 0x%03.3x", bytes
);
450 DbpString("Write successful");
453 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);