]> cvs.zerfleddert.de Git - proxmark3-svn/blame - armsrc/legicrf.c
fix 'hf iclass sim':
[proxmark3-svn] / armsrc / legicrf.c
CommitLineData
bd20f8f4 1//-----------------------------------------------------------------------------
2// (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
da05bc6e 3// 2016 Iceman
1b902aa0 4// 2018 AntiCat
bd20f8f4 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//-----------------------------------------------------------------------------
a7247d85 12
fc52fbd4 13#include "legicrf.h"
14
e30c654b 15#include "proxmark3.h"
a7247d85 16#include "apps.h"
f7e3ed82 17#include "util.h"
9ab7a6c7 18#include "string.h"
8e220a91 19#include "legic_prng.h"
da05bc6e 20#include "legic.h"
8e220a91 21#include "crc.h"
fc52fbd4 22#include "fpgaloader.h"
8e220a91 23
da05bc6e 24static legic_card_select_t card;/* metadata of currently selected card */
1b902aa0 25static crc_t legic_crc;
da05bc6e
A
26
27//-----------------------------------------------------------------------------
28// Frame timing and pseudorandom number generator
29//
30// The Prng is forwarded every 100us (TAG_BIT_PERIOD), except when the reader is
31// transmitting. In that case the prng has to be forwarded every bit transmitted:
32// - 60us for a 0 (RWD_TIME_0)
33// - 100us for a 1 (RWD_TIME_1)
34//
35// The data dependent timing makes writing comprehensible code significantly
36// harder. The current aproach forwards the prng data based if there is data on
37// air and time based, using GET_TICKS, during computational and wait periodes.
38//
39// To not have the necessity to calculate/guess exection time dependend timeouts
40// tx_frame and rx_frame use a shared timestamp to coordinate tx and rx timeslots.
41//-----------------------------------------------------------------------------
42
43static uint32_t last_frame_end; /* ts of last bit of previews rx or tx frame */
44
45#define RWD_TIME_PAUSE 30 /* 20us */
46#define RWD_TIME_1 150 /* READER_TIME_PAUSE 20us off + 80us on = 100us */
47#define RWD_TIME_0 90 /* READER_TIME_PAUSE 20us off + 40us on = 60us */
48#define RWD_FRAME_WAIT 330 /* 220us from TAG frame end to READER frame start */
49#define TAG_FRAME_WAIT 495 /* 330us from READER frame end to TAG frame start */
50#define TAG_BIT_PERIOD 150 /* 100us */
51#define TAG_WRITE_TIMEOUT 60 /* 40 * 100us (write should take at most 3.6ms) */
52
da05bc6e
A
53#define LEGIC_READ 0x01 /* Read Command */
54#define LEGIC_WRITE 0x00 /* Write Command */
55
56#define SESSION_IV 0x55 /* An arbitrary chose session IV, all shoud work */
57#define OFFSET_LOG 1024 /* The largest Legic Prime card is 1k */
58#define WRITE_LOWERLIMIT 4 /* UID and MCC are not writable */
59
60#define INPUT_THRESHOLD 8 /* heuristically determined, lower values */
61 /* lead to detecting false ack during write */
62
da05bc6e
A
63//-----------------------------------------------------------------------------
64// I/O interface abstraction (FPGA -> ARM)
65//-----------------------------------------------------------------------------
66
6a5d4e17 67static inline uint16_t rx_frame_from_fpga() {
da05bc6e
A
68 for(;;) {
69 WDT_HIT();
70
6a5d4e17 71 // wait for frame be become available in rx holding register
da05bc6e
A
72 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
73 return AT91C_BASE_SSC->SSC_RHR;
74 }
75 }
76}
77
78//-----------------------------------------------------------------------------
79// Demodulation (Reader)
80//-----------------------------------------------------------------------------
81
82// Returns a demedulated bit
83//
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).
87//
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))
91//
da05bc6e
A
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.
95//
6a5d4e17 96// The demodulated should be alligned to the bit period by the caller. This is
1b902aa0
A
97// done in rx_bit and rx_ack.
98static inline bool rx_bit() {
6a5d4e17 99 int32_t sum_cq = 0;
100 int32_t sum_ci = 0;
da05bc6e
A
101
102 // skip first 5 I/Q pairs
103 for(size_t i = 0; i<5; ++i) {
6a5d4e17 104 (void)rx_frame_from_fpga();
da05bc6e
A
105 }
106
107 // sample next 8 I/Q pairs
108 for(size_t i = 0; i<8; ++i) {
6a5d4e17 109 uint16_t iq = rx_frame_from_fpga();
110 int8_t ci = (int8_t)(iq >> 8);
111 int8_t cq = (int8_t)(iq & 0xff);
112 sum_ci += ci;
113 sum_cq += cq;
da05bc6e
A
114 }
115
116 // calculate power
6a5d4e17 117 int32_t power = (MAX(ABS(sum_ci), ABS(sum_cq)) + MIN(ABS(sum_ci), ABS(sum_cq))/2);
da05bc6e
A
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
1b902aa0 132static inline void tx_bit(bool bit) {
da05bc6e 133 // insert pause
6a5d4e17 134 HIGH(GPIO_SSC_DOUT);
da05bc6e
A
135 last_frame_end += RWD_TIME_PAUSE;
136 while(GET_TICKS < last_frame_end) { };
da05bc6e 137
6a5d4e17 138 // return to carrier on, wait for bit periode to end
139 LOW(GPIO_SSC_DOUT);
da05bc6e
A
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
1b902aa0 154static void tx_frame(uint32_t frame, uint8_t len) {
5ea2a248 155 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_FULL_MOD);
da05bc6e
A
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;
1b902aa0 164 tx_bit(bit ^ legic_prng_get_bit());
da05bc6e
A
165 legic_prng_forward(1);
166 };
167
168 // add pause to mark end of the frame
6a5d4e17 169 HIGH(GPIO_SSC_DOUT);
da05bc6e
A
170 last_frame_end += RWD_TIME_PAUSE;
171 while(GET_TICKS < last_frame_end) { };
6a5d4e17 172 LOW(GPIO_SSC_DOUT);
da05bc6e
A
173}
174
1b902aa0 175static uint32_t rx_frame(uint8_t len) {
5ea2a248 176 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_212_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
da05bc6e
A
177
178 // hold sampling until card is expected to respond
179 last_frame_end += TAG_FRAME_WAIT;
180 while(GET_TICKS < last_frame_end) { };
181
182 uint32_t frame = 0;
1b902aa0
A
183 for(uint8_t i = 0; i < len; ++i) {
184 frame |= (rx_bit() ^ legic_prng_get_bit()) << i;
da05bc6e
A
185 legic_prng_forward(1);
186
1b902aa0 187 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
da05bc6e
A
188 last_frame_end += TAG_BIT_PERIOD;
189 while(GET_TICKS < last_frame_end) { };
190 }
191
192 return frame;
193}
194
1b902aa0 195static bool rx_ack() {
da05bc6e 196 // change fpga into rx mode
5ea2a248 197 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_212_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
da05bc6e
A
198
199 // hold sampling until card is expected to respond
200 last_frame_end += TAG_FRAME_WAIT;
201 while(GET_TICKS < last_frame_end) { };
202
203 uint32_t ack = 0;
204 for(uint8_t i = 0; i < TAG_WRITE_TIMEOUT; ++i) {
205 // sample bit
1b902aa0 206 ack = rx_bit();
da05bc6e
A
207 legic_prng_forward(1);
208
1b902aa0 209 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
da05bc6e
A
210 last_frame_end += TAG_BIT_PERIOD;
211 while(GET_TICKS < last_frame_end) { };
212
213 // check if it was an ACK
214 if(ack) {
215 break;
216 }
217 }
218
219 return ack;
220}
221
222//-----------------------------------------------------------------------------
223// Legic Reader
224//-----------------------------------------------------------------------------
225
1b902aa0 226static int init_card(uint8_t cardtype, legic_card_select_t *p_card) {
da05bc6e
A
227 p_card->tagtype = cardtype;
228
229 switch(p_card->tagtype) {
230 case 0x0d:
231 p_card->cmdsize = 6;
232 p_card->addrsize = 5;
233 p_card->cardsize = 22;
234 break;
235 case 0x1d:
236 p_card->cmdsize = 9;
237 p_card->addrsize = 8;
238 p_card->cardsize = 256;
239 break;
240 case 0x3d:
241 p_card->cmdsize = 11;
242 p_card->addrsize = 10;
243 p_card->cardsize = 1024;
244 break;
245 default:
246 p_card->cmdsize = 0;
247 p_card->addrsize = 0;
248 p_card->cardsize = 0;
249 return 2;
250 }
251 return 0;
252}
253
254static void init_reader(bool clear_mem) {
255 // configure FPGA
256 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
5ea2a248 257 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_212_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
da05bc6e
A
258 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
259 LED_D_ON();
260
261 // configure SSC with defaults
5ea2a248 262 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
da05bc6e
A
263
264 // re-claim GPIO_SSC_DOUT as GPIO and enable output
265 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
266 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
6a5d4e17 267 LOW(GPIO_SSC_DOUT);
da05bc6e
A
268
269 // init crc calculator
270 crc_init(&legic_crc, 4, 0x19 >> 1, 0x05, 0);
271
272 // start us timer
273 StartTicks();
274}
275
276// Setup reader to card connection
277//
278// The setup consists of a three way handshake:
279// - Transmit initialisation vector 7 bits
280// - Receive card type 6 bits
1b902aa0
A
281// - Transmit Acknowledge 6 bits
282static uint32_t setup_phase(uint8_t iv) {
da05bc6e
A
283 // init coordination timestamp
284 last_frame_end = GET_TICKS;
285
286 // Switch on carrier and let the card charge for 5ms.
287 last_frame_end += 7500;
288 while(GET_TICKS < last_frame_end) { };
289
290 legic_prng_init(0);
1b902aa0 291 tx_frame(iv, 7);
da05bc6e 292
1b902aa0 293 // configure prng
da05bc6e
A
294 legic_prng_init(iv);
295 legic_prng_forward(2);
296
297 // receive card type
1b902aa0 298 int32_t card_type = rx_frame(6);
da05bc6e
A
299 legic_prng_forward(3);
300
301 // send obsfuscated acknowledgment frame
302 switch (card_type) {
303 case 0x0D:
1b902aa0 304 tx_frame(0x19, 6); // MIM22 | READCMD = 0x18 | 0x01
da05bc6e
A
305 break;
306 case 0x1D:
307 case 0x3D:
1b902aa0 308 tx_frame(0x39, 6); // MIM256 | READCMD = 0x38 | 0x01
da05bc6e
A
309 break;
310 }
311
312 return card_type;
313}
314
315static uint8_t calc_crc4(uint16_t cmd, uint8_t cmd_sz, uint8_t value) {
316 crc_clear(&legic_crc);
317 crc_update(&legic_crc, (value << cmd_sz) | cmd, 8 + cmd_sz);
318 return crc_finish(&legic_crc);
319}
320
321static int16_t read_byte(uint16_t index, uint8_t cmd_sz) {
322 uint16_t cmd = (index << 1) | LEGIC_READ;
323
324 // read one byte
325 LED_B_ON();
326 legic_prng_forward(2);
1b902aa0 327 tx_frame(cmd, cmd_sz);
da05bc6e 328 legic_prng_forward(2);
1b902aa0 329 uint32_t frame = rx_frame(12);
da05bc6e
A
330 LED_B_OFF();
331
332 // split frame into data and crc
333 uint8_t byte = BYTEx(frame, 0);
334 uint8_t crc = BYTEx(frame, 1);
335
336 // check received against calculated crc
337 uint8_t calc_crc = calc_crc4(cmd, cmd_sz, byte);
338 if(calc_crc != crc) {
339 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc, crc);
340 return -1;
341 }
342
343 legic_prng_forward(1);
344
345 return byte;
346}
347
348// Transmit write command, wait until (3.6ms) the tag sends back an unencrypted
349// ACK ('1' bit) and forward the prng time based.
350bool write_byte(uint16_t index, uint8_t byte, uint8_t addr_sz) {
351 uint32_t cmd = index << 1 | LEGIC_WRITE; // prepare command
352 uint8_t crc = calc_crc4(cmd, addr_sz + 1, byte); // calculate crc
353 cmd |= byte << (addr_sz + 1); // append value
354 cmd |= (crc & 0xF) << (addr_sz + 1 + 8); // and crc
355
356 // send write command
357 LED_C_ON();
358 legic_prng_forward(2);
1b902aa0 359 tx_frame(cmd, addr_sz + 1 + 8 + 4); // sz = addr_sz + cmd + data + crc
da05bc6e
A
360 legic_prng_forward(3);
361 LED_C_OFF();
362
363 // wait for ack
1b902aa0 364 return rx_ack();
da05bc6e
A
365}
366
367//-----------------------------------------------------------------------------
368// Command Line Interface
369//
370// Only this functions are public / called from appmain.c
371//-----------------------------------------------------------------------------
372void LegicRfReader(int offset, int bytes) {
373 uint8_t *BigBuf = BigBuf_get_addr();
374 memset(BigBuf, 0, 1024);
375
376 // configure ARM and FPGA
377 init_reader(false);
378
379 // establish shared secret and detect card type
380 DbpString("Reading card ...");
1b902aa0 381 uint8_t card_type = setup_phase(SESSION_IV);
bad58246 382 uint8_t result = 0;
da05bc6e 383 if(init_card(card_type, &card) != 0) {
bad58246 384 result = 1;
da05bc6e
A
385 goto OUT;
386 }
387
388 // if no argument is specified create full dump
389 if(bytes == -1) {
390 bytes = card.cardsize;
391 }
392
393 // do not read beyond card memory
394 if(bytes + offset > card.cardsize) {
395 bytes = card.cardsize - offset;
396 }
397
398 for(uint16_t i = 0; i < bytes; ++i) {
399 int16_t byte = read_byte(offset + i, card.cmdsize);
400 if(byte == -1) {
bad58246 401 result = 2;
da05bc6e
A
402 goto OUT;
403 }
404 BigBuf[i] = byte;
405 }
406
da05bc6e 407OUT:
bad58246 408 cmd_send(CMD_ACK, result, bytes, 0, &card, sizeof(card));
da05bc6e
A
409 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
410 LED_B_OFF();
411 LED_C_OFF();
412 LED_D_OFF();
413 StopTicks();
414}
415
416void LegicRfWriter(int bytes, int offset) {
417 uint8_t *BigBuf = BigBuf_get_addr();
418
419 // configure ARM and FPGA
420 init_reader(false);
421
422 // uid is not writeable
423 if(offset <= WRITE_LOWERLIMIT) {
424 goto OUT;
425 }
426
427 // establish shared secret and detect card type
428 Dbprintf("Writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
1b902aa0 429 uint8_t card_type = setup_phase(SESSION_IV);
da05bc6e
A
430 if(init_card(card_type, &card) != 0) {
431 Dbprintf("No or unknown card found, aborting");
432 goto OUT;
433 }
434
435 // do not write beyond card memory
436 if(bytes + offset > card.cardsize) {
437 bytes = card.cardsize - offset;
438 }
439
440 // write in reverse order, only then is DCF (decremental field) writable
441 while(bytes-- > 0 && !BUTTON_PRESS()) {
f6842317 442 if(!write_byte(bytes + offset, BigBuf[bytes + offset], card.addrsize)) {
da05bc6e
A
443 Dbprintf("operation failed @ 0x%03.3x", bytes);
444 goto OUT;
445 }
446 }
447
448 // OK
449 DbpString("Write successful");
450
451OUT:
452 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
453 LED_B_OFF();
454 LED_C_OFF();
455 LED_D_OFF();
456 StopTicks();
457}
Impressum, Datenschutz