]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/legicrf.c
Added loading parameters from json to several emv commands (#686)
[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
e30c654b 13#include "proxmark3.h"
a7247d85 14#include "apps.h"
f7e3ed82 15#include "util.h"
9ab7a6c7 16#include "string.h"
a7247d85 17
f7e3ed82 18#include "legicrf.h"
8e220a91 19#include "legic_prng.h"
da05bc6e 20#include "legic.h"
8e220a91 21#include "crc.h"
22
da05bc6e 23static legic_card_select_t card;/* metadata of currently selected card */
1b902aa0 24static crc_t legic_crc;
da05bc6e
A
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
42static 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
da05bc6e
A
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
da05bc6e
A
62//-----------------------------------------------------------------------------
63// I/O interface abstraction (FPGA -> ARM)
64//-----------------------------------------------------------------------------
65
6a5d4e17 66static inline uint16_t rx_frame_from_fpga() {
da05bc6e
A
67 for(;;) {
68 WDT_HIT();
69
6a5d4e17 70 // wait for frame be become available in rx holding register
da05bc6e
A
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//
da05bc6e
A
91// The bit time is 99.1us (21 I/Q pairs). The receiver skips the first 5 samples
92// and averages the next (most stable) 8 samples. The final 8 samples are dropped
93// also.
94//
6a5d4e17 95// The demodulated should be alligned to the bit period by the caller. This is
1b902aa0
A
96// done in rx_bit and rx_ack.
97static inline bool rx_bit() {
6a5d4e17 98 int32_t sum_cq = 0;
99 int32_t sum_ci = 0;
da05bc6e
A
100
101 // skip first 5 I/Q pairs
102 for(size_t i = 0; i<5; ++i) {
6a5d4e17 103 (void)rx_frame_from_fpga();
da05bc6e
A
104 }
105
106 // sample next 8 I/Q pairs
107 for(size_t i = 0; i<8; ++i) {
6a5d4e17 108 uint16_t iq = rx_frame_from_fpga();
109 int8_t ci = (int8_t)(iq >> 8);
110 int8_t cq = (int8_t)(iq & 0xff);
111 sum_ci += ci;
112 sum_cq += cq;
da05bc6e
A
113 }
114
115 // calculate power
6a5d4e17 116 int32_t power = (MAX(ABS(sum_ci), ABS(sum_cq)) + MIN(ABS(sum_ci), ABS(sum_cq))/2);
da05bc6e
A
117
118 // compare average (power / 8) to threshold
119 return ((power >> 3) > INPUT_THRESHOLD);
120}
121
122//-----------------------------------------------------------------------------
123// Modulation (Reader)
124//
125// I've tried to modulate the Legic specific pause-puls using ssc and the default
126// ssc clock of 105.4 kHz (bit periode of 9.4us) - previous commit. However,
127// the timing was not precise enough. By increasing the ssc clock this could
128// be circumvented, but the adventage over bitbang would be little.
129//-----------------------------------------------------------------------------
130
1b902aa0 131static inline void tx_bit(bool bit) {
da05bc6e 132 // insert pause
6a5d4e17 133 HIGH(GPIO_SSC_DOUT);
da05bc6e
A
134 last_frame_end += RWD_TIME_PAUSE;
135 while(GET_TICKS < last_frame_end) { };
da05bc6e 136
6a5d4e17 137 // return to carrier on, wait for bit periode to end
138 LOW(GPIO_SSC_DOUT);
da05bc6e
A
139 last_frame_end += (bit ? RWD_TIME_1 : RWD_TIME_0) - RWD_TIME_PAUSE;
140 while(GET_TICKS < last_frame_end) { };
141}
142
143//-----------------------------------------------------------------------------
144// Frame Handling (Reader)
145//
146// The LEGIC RF protocol from card to reader does not include explicit frame
147// start/stop information or length information. The reader must know beforehand
148// how many bits it wants to receive.
149// Notably: a card sending a stream of 0-bits is indistinguishable from no card
150// present.
151//-----------------------------------------------------------------------------
152
1b902aa0 153static void tx_frame(uint32_t frame, uint8_t len) {
da05bc6e
A
154 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
155
156 // wait for next tx timeslot
157 last_frame_end += RWD_FRAME_WAIT;
158 while(GET_TICKS < last_frame_end) { };
159
160 // transmit frame, MSB first
161 for(uint8_t i = 0; i < len; ++i) {
162 bool bit = (frame >> i) & 0x01;
1b902aa0 163 tx_bit(bit ^ legic_prng_get_bit());
da05bc6e
A
164 legic_prng_forward(1);
165 };
166
167 // add pause to mark end of the frame
6a5d4e17 168 HIGH(GPIO_SSC_DOUT);
da05bc6e
A
169 last_frame_end += RWD_TIME_PAUSE;
170 while(GET_TICKS < last_frame_end) { };
6a5d4e17 171 LOW(GPIO_SSC_DOUT);
da05bc6e
A
172}
173
1b902aa0 174static uint32_t rx_frame(uint8_t len) {
da05bc6e
A
175 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
176 | FPGA_HF_READER_RX_XCORR_848_KHZ
177 | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
178
179 // hold sampling until card is expected to respond
180 last_frame_end += TAG_FRAME_WAIT;
181 while(GET_TICKS < last_frame_end) { };
182
183 uint32_t frame = 0;
1b902aa0
A
184 for(uint8_t i = 0; i < len; ++i) {
185 frame |= (rx_bit() ^ legic_prng_get_bit()) << i;
da05bc6e
A
186 legic_prng_forward(1);
187
1b902aa0 188 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
da05bc6e
A
189 last_frame_end += TAG_BIT_PERIOD;
190 while(GET_TICKS < last_frame_end) { };
191 }
192
193 return frame;
194}
195
1b902aa0 196static bool rx_ack() {
da05bc6e
A
197 // change fpga into rx mode
198 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
199 | FPGA_HF_READER_RX_XCORR_848_KHZ
200 | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
201
202 // hold sampling until card is expected to respond
203 last_frame_end += TAG_FRAME_WAIT;
204 while(GET_TICKS < last_frame_end) { };
205
206 uint32_t ack = 0;
207 for(uint8_t i = 0; i < TAG_WRITE_TIMEOUT; ++i) {
208 // sample bit
1b902aa0 209 ack = rx_bit();
da05bc6e
A
210 legic_prng_forward(1);
211
1b902aa0 212 // rx_bit runs only 95us, resync to TAG_BIT_PERIOD
da05bc6e
A
213 last_frame_end += TAG_BIT_PERIOD;
214 while(GET_TICKS < last_frame_end) { };
215
216 // check if it was an ACK
217 if(ack) {
218 break;
219 }
220 }
221
222 return ack;
223}
224
225//-----------------------------------------------------------------------------
226// Legic Reader
227//-----------------------------------------------------------------------------
228
1b902aa0 229static int init_card(uint8_t cardtype, legic_card_select_t *p_card) {
da05bc6e
A
230 p_card->tagtype = cardtype;
231
232 switch(p_card->tagtype) {
233 case 0x0d:
234 p_card->cmdsize = 6;
235 p_card->addrsize = 5;
236 p_card->cardsize = 22;
237 break;
238 case 0x1d:
239 p_card->cmdsize = 9;
240 p_card->addrsize = 8;
241 p_card->cardsize = 256;
242 break;
243 case 0x3d:
244 p_card->cmdsize = 11;
245 p_card->addrsize = 10;
246 p_card->cardsize = 1024;
247 break;
248 default:
249 p_card->cmdsize = 0;
250 p_card->addrsize = 0;
251 p_card->cardsize = 0;
252 return 2;
253 }
254 return 0;
255}
256
257static void init_reader(bool clear_mem) {
258 // configure FPGA
259 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
260 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
261 | FPGA_HF_READER_RX_XCORR_848_KHZ
262 | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
263 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
264 LED_D_ON();
265
266 // configure SSC with defaults
6a5d4e17 267 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
da05bc6e
A
268
269 // re-claim GPIO_SSC_DOUT as GPIO and enable output
270 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
271 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
6a5d4e17 272 LOW(GPIO_SSC_DOUT);
da05bc6e
A
273
274 // init crc calculator
275 crc_init(&legic_crc, 4, 0x19 >> 1, 0x05, 0);
276
277 // start us timer
278 StartTicks();
279}
280
281// Setup reader to card connection
282//
283// The setup consists of a three way handshake:
284// - Transmit initialisation vector 7 bits
285// - Receive card type 6 bits
1b902aa0
A
286// - Transmit Acknowledge 6 bits
287static uint32_t setup_phase(uint8_t iv) {
da05bc6e
A
288 // init coordination timestamp
289 last_frame_end = GET_TICKS;
290
291 // Switch on carrier and let the card charge for 5ms.
292 last_frame_end += 7500;
293 while(GET_TICKS < last_frame_end) { };
294
295 legic_prng_init(0);
1b902aa0 296 tx_frame(iv, 7);
da05bc6e 297
1b902aa0 298 // configure prng
da05bc6e
A
299 legic_prng_init(iv);
300 legic_prng_forward(2);
301
302 // receive card type
1b902aa0 303 int32_t card_type = rx_frame(6);
da05bc6e
A
304 legic_prng_forward(3);
305
306 // send obsfuscated acknowledgment frame
307 switch (card_type) {
308 case 0x0D:
1b902aa0 309 tx_frame(0x19, 6); // MIM22 | READCMD = 0x18 | 0x01
da05bc6e
A
310 break;
311 case 0x1D:
312 case 0x3D:
1b902aa0 313 tx_frame(0x39, 6); // MIM256 | READCMD = 0x38 | 0x01
da05bc6e
A
314 break;
315 }
316
317 return card_type;
318}
319
320static uint8_t calc_crc4(uint16_t cmd, uint8_t cmd_sz, uint8_t value) {
321 crc_clear(&legic_crc);
322 crc_update(&legic_crc, (value << cmd_sz) | cmd, 8 + cmd_sz);
323 return crc_finish(&legic_crc);
324}
325
326static int16_t read_byte(uint16_t index, uint8_t cmd_sz) {
327 uint16_t cmd = (index << 1) | LEGIC_READ;
328
329 // read one byte
330 LED_B_ON();
331 legic_prng_forward(2);
1b902aa0 332 tx_frame(cmd, cmd_sz);
da05bc6e 333 legic_prng_forward(2);
1b902aa0 334 uint32_t frame = rx_frame(12);
da05bc6e
A
335 LED_B_OFF();
336
337 // split frame into data and crc
338 uint8_t byte = BYTEx(frame, 0);
339 uint8_t crc = BYTEx(frame, 1);
340
341 // check received against calculated crc
342 uint8_t calc_crc = calc_crc4(cmd, cmd_sz, byte);
343 if(calc_crc != crc) {
344 Dbprintf("!!! crc mismatch: %x != %x !!!", calc_crc, crc);
345 return -1;
346 }
347
348 legic_prng_forward(1);
349
350 return byte;
351}
352
353// Transmit write command, wait until (3.6ms) the tag sends back an unencrypted
354// ACK ('1' bit) and forward the prng time based.
355bool write_byte(uint16_t index, uint8_t byte, uint8_t addr_sz) {
356 uint32_t cmd = index << 1 | LEGIC_WRITE; // prepare command
357 uint8_t crc = calc_crc4(cmd, addr_sz + 1, byte); // calculate crc
358 cmd |= byte << (addr_sz + 1); // append value
359 cmd |= (crc & 0xF) << (addr_sz + 1 + 8); // and crc
360
361 // send write command
362 LED_C_ON();
363 legic_prng_forward(2);
1b902aa0 364 tx_frame(cmd, addr_sz + 1 + 8 + 4); // sz = addr_sz + cmd + data + crc
da05bc6e
A
365 legic_prng_forward(3);
366 LED_C_OFF();
367
368 // wait for ack
1b902aa0 369 return rx_ack();
da05bc6e
A
370}
371
372//-----------------------------------------------------------------------------
373// Command Line Interface
374//
375// Only this functions are public / called from appmain.c
376//-----------------------------------------------------------------------------
377void LegicRfReader(int offset, int bytes) {
378 uint8_t *BigBuf = BigBuf_get_addr();
379 memset(BigBuf, 0, 1024);
380
381 // configure ARM and FPGA
382 init_reader(false);
383
384 // establish shared secret and detect card type
385 DbpString("Reading card ...");
1b902aa0 386 uint8_t card_type = setup_phase(SESSION_IV);
da05bc6e
A
387 if(init_card(card_type, &card) != 0) {
388 Dbprintf("No or unknown card found, aborting");
389 goto OUT;
390 }
391
392 // if no argument is specified create full dump
393 if(bytes == -1) {
394 bytes = card.cardsize;
395 }
396
397 // do not read beyond card memory
398 if(bytes + offset > card.cardsize) {
399 bytes = card.cardsize - offset;
400 }
401
402 for(uint16_t i = 0; i < bytes; ++i) {
403 int16_t byte = read_byte(offset + i, card.cmdsize);
404 if(byte == -1) {
405 Dbprintf("operation failed @ 0x%03.3x", bytes);
406 goto OUT;
407 }
408 BigBuf[i] = byte;
409 }
410
411 // OK
412 Dbprintf("Card (MIM %i) read, use 'hf legic decode' or", card.cardsize);
413 Dbprintf("'data hexsamples %d' to view results", (bytes+7) & ~7);
414
415OUT:
416 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
417 LED_B_OFF();
418 LED_C_OFF();
419 LED_D_OFF();
420 StopTicks();
421}
422
423void LegicRfWriter(int bytes, int offset) {
424 uint8_t *BigBuf = BigBuf_get_addr();
425
426 // configure ARM and FPGA
427 init_reader(false);
428
429 // uid is not writeable
430 if(offset <= WRITE_LOWERLIMIT) {
431 goto OUT;
432 }
433
434 // establish shared secret and detect card type
435 Dbprintf("Writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
1b902aa0 436 uint8_t card_type = setup_phase(SESSION_IV);
da05bc6e
A
437 if(init_card(card_type, &card) != 0) {
438 Dbprintf("No or unknown card found, aborting");
439 goto OUT;
440 }
441
442 // do not write beyond card memory
443 if(bytes + offset > card.cardsize) {
444 bytes = card.cardsize - offset;
445 }
446
447 // write in reverse order, only then is DCF (decremental field) writable
448 while(bytes-- > 0 && !BUTTON_PRESS()) {
f6842317 449 if(!write_byte(bytes + offset, BigBuf[bytes + offset], card.addrsize)) {
da05bc6e
A
450 Dbprintf("operation failed @ 0x%03.3x", bytes);
451 goto OUT;
452 }
453 }
454
455 // OK
456 DbpString("Write successful");
457
458OUT:
459 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
460 LED_B_OFF();
461 LED_C_OFF();
462 LED_D_OFF();
463 StopTicks();
464}
Impressum, Datenschutz