Merge pull request #2654 from Antiklesys/master
[RRG-proxmark3.git] / armsrc / em4x70.c
blob547ce5ce24b528e059c92b2f9d6a55cd80c872fc
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
16 // Low frequency EM4x70 commands
17 //-----------------------------------------------------------------------------
19 #include "fpgaloader.h"
20 #include "ticks.h"
21 #include "dbprint.h"
22 #include "lfadc.h"
23 #include "commonutil.h"
24 #include "optimized_cipherutils.h"
25 #include "em4x70.h"
26 #include "appmain.h" // tear
28 static em4x70_tag_t tag = { 0 };
30 // EM4170 requires a parity bit on commands, other variants do not.
31 static bool command_parity = true;
34 #if 1 // Calculation of ticks for timing functions
35 // Conversion from Ticks to RF periods
36 // 1 us = 1.5 ticks
37 // 1RF Period = 8us = 12 Ticks
38 #define TICKS_PER_FC 12
40 // Chip timing from datasheet
41 // Converted into Ticks for timing functions
42 #define EM4X70_T_TAG_QUARTER_PERIOD (8 * TICKS_PER_FC)
43 #define EM4X70_T_TAG_HALF_PERIOD (16 * TICKS_PER_FC)
44 #define EM4X70_T_TAG_THREE_QUARTER_PERIOD (24 * TICKS_PER_FC)
45 #define EM4X70_T_TAG_FULL_PERIOD (32 * TICKS_PER_FC) // 1 Bit Period
46 #define EM4X70_T_TAG_TWA (128 * TICKS_PER_FC) // Write Access Time
47 #define EM4X70_T_TAG_DIV (224 * TICKS_PER_FC) // Divergency Time
48 #define EM4X70_T_TAG_AUTH (4224 * TICKS_PER_FC) // Authentication Time
49 #define EM4X70_T_TAG_WEE (3072 * TICKS_PER_FC) // EEPROM write Time
50 #define EM4X70_T_TAG_TWALB (672 * TICKS_PER_FC) // Write Access Time of Lock Bits
51 #define EM4X70_T_TAG_BITMOD (4 * TICKS_PER_FC) // Initial time to stop modulation when sending 0
52 #define EM4X70_T_TAG_TOLERANCE (8 * TICKS_PER_FC) // Tolerance in RF periods for receive/LIW
54 #define EM4X70_T_TAG_TIMEOUT (4 * EM4X70_T_TAG_FULL_PERIOD) // Timeout if we ever get a pulse longer than this
55 #define EM4X70_T_WAITING_FOR_LIW 50 // Pulses to wait for listen window
56 #define EM4X70_T_READ_HEADER_LEN 16 // Read header length (16 bit periods)
58 #define EM4X70_COMMAND_RETRIES 5 // Attempts to send/read command
59 #define EM4X70_MAX_RECEIVE_LENGTH 96 // Maximum bits to expect from any command
60 #endif // Calculation of ticks for timing functions
62 #if 1 // EM4x70 Command IDs
63 /**
64 * These IDs are from the EM4170 datasheet.
65 * Some versions of the chip require a
66 * (even) parity bit, others do not.
67 * The command is thus stored only in the
68 * three least significant bits (mask 0x07).
70 #define EM4X70_COMMAND_ID 0x01
71 #define EM4X70_COMMAND_UM1 0x02
72 #define EM4X70_COMMAND_AUTH 0x03
73 #define EM4X70_COMMAND_PIN 0x04
74 #define EM4X70_COMMAND_WRITE 0x05
75 #define EM4X70_COMMAND_UM2 0x07
76 #endif // EM4x70 Command IDs
78 // Constants used to determine high/low state of signal
79 #define EM4X70_NOISE_THRESHOLD 13 // May depend on noise in environment
80 #define HIGH_SIGNAL_THRESHOLD (127 + EM4X70_NOISE_THRESHOLD)
81 #define LOW_SIGNAL_THRESHOLD (127 - EM4X70_NOISE_THRESHOLD)
83 #define IS_HIGH(sample) (sample > LOW_SIGNAL_THRESHOLD ? true : false)
84 #define IS_LOW(sample) (sample < HIGH_SIGNAL_THRESHOLD ? true : false)
86 // Timing related macros
87 #define IS_TIMEOUT(timeout_ticks) (GetTicks() > timeout_ticks)
88 #define TICKS_ELAPSED(start_ticks) (GetTicks() - start_ticks)
90 static uint8_t encoded_bit_array_to_byte(const uint8_t *bits, int count_of_bits);
91 static void encoded_bit_array_to_bytes(const uint8_t *bits, int count_of_bits, uint8_t *out);
92 static int em4x70_receive(uint8_t *bits, size_t maximum_bits_to_read);
93 static bool find_listen_window(bool command);
95 static void init_tag(void) {
96 memset(tag.data, 0x00, sizeof(tag.data));
99 static void em4x70_setup_read(void) {
101 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
102 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
104 // 50ms for the resonant antenna to settle.
105 SpinDelay(50);
107 // Now set up the SSC to get the ADC samples that are now streaming at us.
108 FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER);
110 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125);
112 // Connect the A/D to the peak-detected low-frequency path.
113 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
115 // Steal this pin from the SSP (SPI communication channel with fpga) and
116 // use it to control the modulation
117 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
118 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
120 // Disable modulation at default, which means enable the field
121 LOW(GPIO_SSC_DOUT);
123 // Start the timer
124 StartTicks();
126 // Watchdog hit
127 WDT_HIT();
130 static bool get_signalproperties(void) {
132 // Simple check to ensure we see a signal above the noise threshold
133 uint32_t no_periods = 32;
135 // wait until signal/noise > 1 (max. 32 periods)
136 for (int i = 0; i < EM4X70_T_TAG_FULL_PERIOD * no_periods; i++) {
138 // about 2 samples per bit period
139 WaitTicks(EM4X70_T_TAG_HALF_PERIOD);
141 if (AT91C_BASE_SSC->SSC_RHR > HIGH_SIGNAL_THRESHOLD) {
142 return true;
145 return false;
149 * get_falling_pulse_length
151 * Returns time between falling edge pulse in ticks
153 static uint32_t get_falling_pulse_length(void) {
155 uint32_t timeout = GetTicks() + EM4X70_T_TAG_TIMEOUT;
157 while (IS_HIGH(AT91C_BASE_SSC->SSC_RHR) && !IS_TIMEOUT(timeout));
159 if (IS_TIMEOUT(timeout))
160 return 0;
162 uint32_t start_ticks = GetTicks();
164 while (IS_LOW(AT91C_BASE_SSC->SSC_RHR) && !IS_TIMEOUT(timeout));
166 if (IS_TIMEOUT(timeout))
167 return 0;
169 while (IS_HIGH(AT91C_BASE_SSC->SSC_RHR) && !IS_TIMEOUT(timeout));
171 if (IS_TIMEOUT(timeout))
172 return 0;
174 return TICKS_ELAPSED(start_ticks);
178 * get_rising_pulse_length
180 * Returns time between rising edge pulse in ticks
182 static uint32_t get_rising_pulse_length(void) {
184 uint32_t timeout = GetTicks() + EM4X70_T_TAG_TIMEOUT;
186 while (IS_LOW(AT91C_BASE_SSC->SSC_RHR) && !IS_TIMEOUT(timeout));
188 if (IS_TIMEOUT(timeout))
189 return 0;
191 uint32_t start_ticks = GetTicks();
193 while (IS_HIGH(AT91C_BASE_SSC->SSC_RHR) && !IS_TIMEOUT(timeout));
195 if (IS_TIMEOUT(timeout))
196 return 0;
198 while (IS_LOW(AT91C_BASE_SSC->SSC_RHR) && !IS_TIMEOUT(timeout));
200 if (IS_TIMEOUT(timeout))
201 return 0;
203 return TICKS_ELAPSED(start_ticks);
207 static uint32_t get_pulse_length(edge_detection_t edge) {
209 if (edge == RISING_EDGE)
210 return get_rising_pulse_length();
211 else if (edge == FALLING_EDGE)
212 return get_falling_pulse_length();
214 return 0;
217 static bool check_pulse_length(uint32_t pulse_tick_length, uint32_t target_tick_length) {
218 // check if pulse tick length corresponds to target length (+/- tolerance)
219 return ((pulse_tick_length >= (target_tick_length - EM4X70_T_TAG_TOLERANCE)) &&
220 (pulse_tick_length <= (target_tick_length + EM4X70_T_TAG_TOLERANCE)));
223 static void em4x70_send_bit(bool bit) {
225 // send single bit according to EM4170 application note and datasheet
226 uint32_t start_ticks = GetTicks();
228 if (bit == 0) {
230 // disable modulation (drop the field) n cycles of carrier
231 LOW(GPIO_SSC_DOUT);
232 while (TICKS_ELAPSED(start_ticks) <= EM4X70_T_TAG_BITMOD);
234 // enable modulation (activates the field) for remaining first
235 // half of bit period
236 HIGH(GPIO_SSC_DOUT);
237 while (TICKS_ELAPSED(start_ticks) <= EM4X70_T_TAG_HALF_PERIOD);
239 // disable modulation for second half of bit period
240 LOW(GPIO_SSC_DOUT);
241 while (TICKS_ELAPSED(start_ticks) <= EM4X70_T_TAG_FULL_PERIOD);
243 } else {
245 // bit = "1" means disable modulation for full bit period
246 LOW(GPIO_SSC_DOUT);
247 while (TICKS_ELAPSED(start_ticks) <= EM4X70_T_TAG_FULL_PERIOD);
252 * em4x70_send_nibble
254 * sends 4 bits of data + 1 bit of parity (with_parity)
257 static void em4x70_send_nibble(uint8_t nibble, bool with_parity) {
258 int parity = 0;
259 int msb_bit = 0;
261 // Non automotive EM4x70 based tags are 3 bits + 1 parity.
262 // So drop the MSB and send a parity bit instead after the command
263 if (command_parity)
264 msb_bit = 1;
266 for (int i = msb_bit; i < 4; i++) {
267 int bit = (nibble >> (3 - i)) & 1;
268 em4x70_send_bit(bit);
269 parity ^= bit;
272 if (with_parity)
273 em4x70_send_bit(parity);
276 static void em4x70_send_byte(uint8_t byte) {
277 // Send byte msb first
278 for (int i = 0; i < 8; i++)
279 em4x70_send_bit((byte >> (7 - i)) & 1);
282 static void em4x70_send_word(const uint16_t word) {
284 // Split into nibbles
285 uint8_t nibbles[4];
286 uint8_t j = 0;
287 for (int i = 0; i < 2; i++) {
288 uint8_t byte = (word >> (8 * i)) & 0xff;
289 nibbles[j++] = (byte >> 4) & 0xf;
290 nibbles[j++] = byte & 0xf;
293 // send 16 bit word with parity bits according to EM4x70 datasheet
294 // sent as 4 x nibbles (4 bits + parity)
295 for (int i = 0; i < 4; i++) {
296 em4x70_send_nibble(nibbles[i], true);
299 // send column parities (4 bit)
300 em4x70_send_nibble(nibbles[0] ^ nibbles[1] ^ nibbles[2] ^ nibbles[3], false);
302 // send final stop bit (always "0")
303 em4x70_send_bit(0);
306 static bool check_ack(void) {
307 // returns true if signal structue corresponds to ACK, anything else is
308 // counted as NAK (-> false)
309 // ACK 64 + 64
310 // NAK 64 + 48
311 if (check_pulse_length(get_pulse_length(FALLING_EDGE), 2 * EM4X70_T_TAG_FULL_PERIOD) &&
312 check_pulse_length(get_pulse_length(FALLING_EDGE), 2 * EM4X70_T_TAG_FULL_PERIOD)) {
313 // ACK
314 return true;
317 // Otherwise it was a NAK or Listen Window
318 return false;
321 // TODO: define and use structs for rnd, frnd, response
322 static int authenticate(const uint8_t *rnd, const uint8_t *frnd, uint8_t *response) {
324 if (find_listen_window(true)) {
326 em4x70_send_nibble(EM4X70_COMMAND_AUTH, true);
328 // Send 56-bit Random number
329 for (int i = 0; i < 7; i++) {
330 em4x70_send_byte(rnd[i]);
333 // Send 7 x 0's (Diversity bits)
334 for (int i = 0; i < 7; i++) {
335 em4x70_send_bit(0);
338 // Send 28-bit f(RN)
340 // Send first 24 bits
341 for (int i = 0; i < 3; i++) {
342 em4x70_send_byte(frnd[i]);
345 // Send last 4 bits (no parity)
346 em4x70_send_nibble((frnd[3] >> 4) & 0xf, false);
348 // Receive header, 20-bit g(RN), LIW
349 uint8_t grnd[EM4X70_MAX_RECEIVE_LENGTH] = {0};
350 int num = em4x70_receive(grnd, 20);
351 if (num < 20) {
352 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Auth failed");
353 return PM3_ESOFT;
355 // although only received 20 bits
356 // ask for 24 bits converted because
357 // this utility function requires
358 // decoding in multiples of 8 bits
359 encoded_bit_array_to_bytes(grnd, 24, response);
360 return PM3_SUCCESS;
363 return PM3_ESOFT;
366 // Sets one (reflected) byte and returns carry bit
367 // (1 if `value` parameter was greater than 0xFF)
368 static int set_byte(uint8_t *target, uint16_t value) {
369 int c = value > 0xFF ? 1 : 0; // be explicit about carry bit values
370 *target = reflect8(value);
371 return c;
374 static int bruteforce(const uint8_t address, const uint8_t *rnd, const uint8_t *frnd, uint16_t start_key, uint8_t *response) {
376 uint8_t auth_resp[3] = {0};
377 uint8_t rev_rnd[7];
378 uint8_t temp_rnd[7];
380 reverse_arraybytes_copy((uint8_t *)rnd, rev_rnd, sizeof(rev_rnd));
381 memcpy(temp_rnd, rnd, sizeof(temp_rnd));
383 for (int k = start_key; k <= 0xFFFF; ++k) {
384 int c = 0;
386 WDT_HIT();
388 uint16_t rev_k = reflect16(k);
389 switch (address) {
390 case 9:
391 c = set_byte(&temp_rnd[0], rev_rnd[0] + ((rev_k) & 0xFFu));
392 c = set_byte(&temp_rnd[1], rev_rnd[1] + c + ((rev_k >> 8) & 0xFFu));
393 c = set_byte(&temp_rnd[2], rev_rnd[2] + c);
394 c = set_byte(&temp_rnd[3], rev_rnd[3] + c);
395 c = set_byte(&temp_rnd[4], rev_rnd[4] + c);
396 c = set_byte(&temp_rnd[5], rev_rnd[5] + c);
397 set_byte(&temp_rnd[6], rev_rnd[6] + c);
398 break;
400 case 8:
401 c = set_byte(&temp_rnd[2], rev_rnd[2] + ((rev_k) & 0xFFu));
402 c = set_byte(&temp_rnd[3], rev_rnd[3] + c + ((rev_k >> 8) & 0xFFu));
403 c = set_byte(&temp_rnd[4], rev_rnd[4] + c);
404 c = set_byte(&temp_rnd[5], rev_rnd[5] + c);
405 set_byte(&temp_rnd[6], rev_rnd[6] + c);
406 break;
408 case 7:
409 c = set_byte(&temp_rnd[4], rev_rnd[4] + ((rev_k) & 0xFFu));
410 c = set_byte(&temp_rnd[5], rev_rnd[5] + c + ((rev_k >> 8) & 0xFFu));
411 set_byte(&temp_rnd[6], rev_rnd[6] + c);
412 break;
414 default:
415 Dbprintf("Bad block number given: %d", address);
416 return PM3_ESOFT;
419 // Report progress every 256 attempts
420 if ((k % 0x100) == 0) {
421 Dbprintf("Trying: %04X", k);
424 // Due to performance reason, we only try it once. Therefore you need a very stable RFID communcation.
425 if (authenticate(temp_rnd, frnd, auth_resp) == PM3_SUCCESS) {
426 if (g_dbglevel >= DBG_INFO)
427 Dbprintf("Authentication success with rnd: %02X%02X%02X%02X%02X%02X%02X", temp_rnd[0], temp_rnd[1], temp_rnd[2], temp_rnd[3], temp_rnd[4], temp_rnd[5], temp_rnd[6]);
428 response[0] = (k >> 8) & 0xFF;
429 response[1] = k & 0xFF;
430 return PM3_SUCCESS;
433 if (BUTTON_PRESS() || data_available()) {
434 Dbprintf("EM4x70 Bruteforce Interrupted");
435 return PM3_EOPABORTED;
439 return PM3_ESOFT;
442 static int send_pin(const uint32_t pin) {
444 // sends pin code for unlocking
445 if (find_listen_window(true)) {
447 // send PIN command
448 em4x70_send_nibble(EM4X70_COMMAND_PIN, true);
450 // --> Send TAG ID (bytes 4-7)
451 for (int i = 0; i < 4; i++) {
452 em4x70_send_byte(tag.data[7 - i]);
455 // --> Send PIN
456 for (int i = 0; i < 4 ; i++) {
457 em4x70_send_byte((pin >> (i * 8)) & 0xff);
460 // Wait TWALB (write access lock bits)
461 WaitTicks(EM4X70_T_TAG_TWALB);
463 // <-- Receive ACK
464 if (check_ack()) {
466 // <w> Writes Lock Bits
467 WaitTicks(EM4X70_T_TAG_WEE);
468 // <-- Receive header + ID
469 uint8_t tag_id[EM4X70_MAX_RECEIVE_LENGTH];
470 int count_of_bits_received = em4x70_receive(tag_id, 32);
471 if (count_of_bits_received < 32) {
472 Dbprintf("Invalid ID Received");
473 return PM3_ESOFT;
475 encoded_bit_array_to_bytes(tag_id, count_of_bits_received, &tag.data[4]);
476 return PM3_SUCCESS;
480 return PM3_ESOFT;
483 static int write(const uint16_t word, const uint8_t address) {
485 // writes <word> to specified <address>
486 if (find_listen_window(true)) {
488 // send write command
489 em4x70_send_nibble(EM4X70_COMMAND_WRITE, true);
491 // send address data with parity bit
492 em4x70_send_nibble(address, true);
494 // send data word
495 em4x70_send_word(word);
497 // Wait TWA
498 WaitTicks(EM4X70_T_TAG_TWA);
500 // look for ACK sequence
501 if (check_ack()) {
503 // now EM4x70 needs EM4X70_T_TAG_TWEE (EEPROM write time)
504 // for saving data and should return with ACK
505 WaitTicks(EM4X70_T_TAG_WEE);
506 if (check_ack()) {
508 return PM3_SUCCESS;
512 return PM3_ESOFT;
516 static bool find_listen_window(bool command) {
518 int cnt = 0;
519 while (cnt < EM4X70_T_WAITING_FOR_LIW) {
521 80 ( 64 + 16 )
522 80 ( 64 + 16 )
523 Flip Polarity
524 96 ( 64 + 32 )
525 64 ( 32 + 16 +16 )*/
527 if (check_pulse_length(get_pulse_length(RISING_EDGE), (2 * EM4X70_T_TAG_FULL_PERIOD) + EM4X70_T_TAG_HALF_PERIOD) &&
528 check_pulse_length(get_pulse_length(RISING_EDGE), (2 * EM4X70_T_TAG_FULL_PERIOD) + EM4X70_T_TAG_HALF_PERIOD) &&
529 check_pulse_length(get_pulse_length(FALLING_EDGE), (2 * EM4X70_T_TAG_FULL_PERIOD) + EM4X70_T_TAG_FULL_PERIOD) &&
530 check_pulse_length(get_pulse_length(FALLING_EDGE), EM4X70_T_TAG_FULL_PERIOD + (2 * EM4X70_T_TAG_HALF_PERIOD))) {
532 if (command) {
533 /* Here we are after the 64 duration edge.
534 * em4170 says we need to wait about 48 RF clock cycles.
535 * depends on the delay between tag and us
537 * I've found between 4-5 quarter periods (32-40) works best
539 WaitTicks(4 * EM4X70_T_TAG_QUARTER_PERIOD);
540 // Send RM Command
541 em4x70_send_bit(0);
542 em4x70_send_bit(0);
544 return true;
546 cnt++;
549 return false;
552 // *bits == array of bytes, each byte storing a single bit.
553 // *out == array of bytes, storing converted bits --> bytes.
555 // [in, bcount(count_of_bits) ] const uint8_t *bits
556 // [out, bcount(count_of_bits/8)] uint8_t *out
557 static void encoded_bit_array_to_bytes(const uint8_t *bits, int count_of_bits, uint8_t *out) {
559 if (count_of_bits % 8 != 0) {
560 Dbprintf("Should have a multiple of 8 bits, was sent %d", count_of_bits);
563 int num_bytes = count_of_bits / 8; // We should have a multiple of 8 here
565 for (int i = 1; i <= num_bytes; i++) {
566 out[num_bytes - i] = encoded_bit_array_to_byte(bits, 8);
567 bits += 8;
571 static uint8_t encoded_bit_array_to_byte(const uint8_t *bits, int count_of_bits) {
573 // converts <count_of_bits> separate bits into a single "byte"
574 uint8_t byte = 0;
575 for (int i = 0; i < count_of_bits; i++) {
576 byte <<= 1;
577 byte |= bits[i];
580 return byte;
583 static bool send_command_and_read(uint8_t command, uint8_t *bytes, size_t expected_byte_count) {
585 int retries = EM4X70_COMMAND_RETRIES;
586 while (retries) {
587 retries--;
589 if (find_listen_window(true)) {
590 uint8_t bits[EM4X70_MAX_RECEIVE_LENGTH] = {0};
591 size_t out_length_bits = expected_byte_count * 8;
592 em4x70_send_nibble(command, command_parity);
593 int len = em4x70_receive(bits, out_length_bits);
594 if (len < out_length_bits) {
595 Dbprintf("Invalid data received length: %d, expected %d", len, out_length_bits);
596 return false;
598 encoded_bit_array_to_bytes(bits, len, bytes);
599 return true;
602 return false;
608 * em4x70_read_id
610 * read pre-programmed ID (4 bytes)
612 static bool em4x70_read_id(void) {
614 return send_command_and_read(EM4X70_COMMAND_ID, &tag.data[4], 4);
619 * em4x70_read_um1
621 * read user memory 1 (4 bytes including lock bits)
623 static bool em4x70_read_um1(void) {
625 return send_command_and_read(EM4X70_COMMAND_UM1, &tag.data[0], 4);
630 * em4x70_read_um2
632 * read user memory 2 (8 bytes)
634 static bool em4x70_read_um2(void) {
636 return send_command_and_read(EM4X70_COMMAND_UM2, &tag.data[24], 8);
640 static bool find_em4x70_tag(void) {
641 // function is used to check whether a tag on the proxmark is an
642 // EM4170 tag or not -> speed up "lf search" process
643 return find_listen_window(false);
646 static int em4x70_receive(uint8_t *bits, size_t maximum_bits_to_read) {
648 uint32_t pl;
649 int bit_pos = 0;
650 edge_detection_t edge = RISING_EDGE;
651 bool foundheader = false;
653 // Read out the header
654 // 12 Manchester 1's (may miss some during settle period)
655 // 4 Manchester 0's
657 // Skip a few leading 1's as it could be noisy
658 WaitTicks(6 * EM4X70_T_TAG_FULL_PERIOD);
660 // wait until we get the transition from 1's to 0's which is 1.5 full windows
661 for (int i = 0; i < EM4X70_T_READ_HEADER_LEN; i++) {
662 pl = get_pulse_length(edge);
663 if (check_pulse_length(pl, 3 * EM4X70_T_TAG_HALF_PERIOD)) {
664 foundheader = true;
665 break;
669 if (!foundheader) {
670 if (g_dbglevel >= DBG_EXTENDED) Dbprintf("Failed to find read header");
671 return 0;
674 // Skip next 3 0's, header check consumes the first 0
675 for (int i = 0; i < 3; i++) {
676 // If pulse length is not 1 bit, then abort early
677 if (!check_pulse_length(get_pulse_length(edge), EM4X70_T_TAG_FULL_PERIOD)) {
678 return 0;
682 // identify remaining bits based on pulse lengths
683 // between listen windows only pulse lengths of 1, 1.5 and 2 are possible
684 while (bit_pos < maximum_bits_to_read) {
686 pl = get_pulse_length(edge);
688 if (check_pulse_length(pl, EM4X70_T_TAG_FULL_PERIOD)) {
690 // pulse length 1 -> assign bit
691 bits[bit_pos++] = edge == FALLING_EDGE ? 1 : 0;
693 } else if (check_pulse_length(pl, 3 * EM4X70_T_TAG_HALF_PERIOD)) {
695 // pulse length 1.5 -> 2 bits + flip edge detection
696 if (edge == FALLING_EDGE) {
697 bits[bit_pos++] = 0;
698 if (bit_pos < maximum_bits_to_read) {
699 bits[bit_pos++] = 0;
701 edge = RISING_EDGE;
702 } else {
703 bits[bit_pos++] = 1;
704 if (bit_pos < maximum_bits_to_read) {
705 bits[bit_pos++] = 1;
707 edge = FALLING_EDGE;
710 } else if (check_pulse_length(pl, 2 * EM4X70_T_TAG_FULL_PERIOD)) {
712 // pulse length of 2 -> two bits
713 if (edge == FALLING_EDGE) {
714 bits[bit_pos++] = 0;
715 if (bit_pos < maximum_bits_to_read) {
716 bits[bit_pos++] = 1;
718 } else {
719 bits[bit_pos++] = 1;
720 if (bit_pos < maximum_bits_to_read) {
721 bits[bit_pos++] = 0;
725 } else {
726 // Listen Window, or invalid bit
727 break;
731 return bit_pos;
734 void em4x70_info(const em4x70_data_t *etd, bool ledcontrol) {
736 bool success = false;
738 // Support tags with and without command parity bits
739 command_parity = etd->parity;
741 init_tag();
742 em4x70_setup_read();
744 // Find the Tag
745 if (get_signalproperties() && find_em4x70_tag()) {
746 // Read ID, UM1 and UM2
747 success = em4x70_read_id() && em4x70_read_um1() && em4x70_read_um2();
750 StopTicks();
751 lf_finalize(ledcontrol);
752 int status = success ? PM3_SUCCESS : PM3_ESOFT;
753 reply_ng(CMD_LF_EM4X70_INFO, status, tag.data, sizeof(tag.data));
756 void em4x70_write(const em4x70_data_t *etd, bool ledcontrol) {
757 int status = PM3_ESOFT;
759 command_parity = etd->parity;
761 // Disable to prevent sending corrupted data to the tag.
762 if (command_parity) {
763 Dbprintf("Use of `--par` option with `lf em 4x70 write` is disabled to prevent corrupting tag data");
764 reply_ng(CMD_LF_EM4X70_WRITE, PM3_ENOTIMPL, NULL, 0);
765 return;
768 init_tag();
769 em4x70_setup_read();
771 // Find the Tag
772 if (get_signalproperties() && find_em4x70_tag()) {
774 // Write
775 status = write(etd->word, etd->address);
777 if (status == PM3_SUCCESS) {
778 // Read Tag after writing
779 if (em4x70_read_id()) {
780 em4x70_read_um1();
781 em4x70_read_um2();
786 StopTicks();
787 lf_finalize(ledcontrol);
788 reply_ng(CMD_LF_EM4X70_WRITE, status, tag.data, sizeof(tag.data));
791 void em4x70_unlock(const em4x70_data_t *etd, bool ledcontrol) {
793 int status = PM3_ESOFT;
795 command_parity = etd->parity;
797 init_tag();
798 em4x70_setup_read();
800 // Find the Tag
801 if (get_signalproperties() && find_em4x70_tag()) {
803 // Read ID (required for send_pin command)
804 if (em4x70_read_id()) {
806 // Send PIN
807 status = send_pin(etd->pin);
809 // If the write succeeded, read the rest of the tag
810 if (status == PM3_SUCCESS) {
811 // Read Tag
812 // ID doesn't change
813 em4x70_read_um1();
814 em4x70_read_um2();
819 StopTicks();
820 lf_finalize(ledcontrol);
821 reply_ng(CMD_LF_EM4X70_UNLOCK, status, tag.data, sizeof(tag.data));
824 void em4x70_auth(const em4x70_data_t *etd, bool ledcontrol) {
826 int status = PM3_ESOFT;
828 uint8_t response[3] = {0};
830 command_parity = etd->parity;
832 // Disable to prevent sending corrupted data to the tag.
833 if (command_parity) {
834 Dbprintf("Use of `--par` option with `lf em 4x70 auth` is disabled to prevent corrupting tag data");
835 reply_ng(CMD_LF_EM4X70_WRITE, PM3_ENOTIMPL, NULL, 0);
836 return;
839 init_tag();
840 em4x70_setup_read();
842 // Find the Tag
843 if (get_signalproperties() && find_em4x70_tag()) {
845 // Authenticate and get tag response
846 status = authenticate(etd->rnd, etd->frnd, response);
849 StopTicks();
850 lf_finalize(ledcontrol);
851 reply_ng(CMD_LF_EM4X70_AUTH, status, response, sizeof(response));
854 void em4x70_brute(const em4x70_data_t *etd, bool ledcontrol) {
855 int status = PM3_ESOFT;
856 uint8_t response[2] = {0};
858 command_parity = etd->parity;
860 // Disable to prevent sending corrupted data to the tag.
861 if (command_parity) {
862 Dbprintf("Use of `--par` option with `lf em 4x70 brute` is disabled to prevent corrupting tag data");
863 reply_ng(CMD_LF_EM4X70_WRITE, PM3_ENOTIMPL, NULL, 0);
864 return;
867 init_tag();
868 em4x70_setup_read();
870 // Find the Tag
871 if (get_signalproperties() && find_em4x70_tag()) {
873 // Bruteforce partial key
874 status = bruteforce(etd->address, etd->rnd, etd->frnd, etd->start_key, response);
877 StopTicks();
878 lf_finalize(ledcontrol);
879 reply_ng(CMD_LF_EM4X70_BRUTE, status, response, sizeof(response));
882 void em4x70_write_pin(const em4x70_data_t *etd, bool ledcontrol) {
884 int status = PM3_ESOFT;
886 command_parity = etd->parity;
888 // Disable to prevent sending corrupted data to the tag.
889 if (command_parity) {
890 Dbprintf("Use of `--par` option with `lf em 4x70 setpin` is disabled to prevent corrupting tag data");
891 reply_ng(CMD_LF_EM4X70_WRITE, PM3_ENOTIMPL, NULL, 0);
892 return;
895 init_tag();
896 em4x70_setup_read();
898 // Find the Tag
899 if (get_signalproperties() && find_em4x70_tag()) {
901 // Read ID (required for send_pin command)
902 if (em4x70_read_id()) {
904 // Write the pin
905 status = write((etd->pin) & 0xFFFF, EM4X70_PIN_WORD_UPPER);
906 if (status == PM3_SUCCESS) {
907 status = write((etd->pin >> 16) & 0xFFFF, EM4X70_PIN_WORD_LOWER);
909 if (status == PM3_SUCCESS) {
910 // Now Try to authenticate using the new PIN
912 // Send PIN
913 status = send_pin(etd->pin);
915 // If the write succeeded, read the rest of the tag
916 if (status == PM3_SUCCESS) {
917 // Read Tag
918 // ID doesn't change
919 em4x70_read_um1();
920 em4x70_read_um2();
926 StopTicks();
927 lf_finalize(ledcontrol);
928 reply_ng(CMD_LF_EM4X70_SETPIN, status, tag.data, sizeof(tag.data));
931 void em4x70_write_key(const em4x70_data_t *etd, bool ledcontrol) {
933 int status = PM3_ESOFT;
935 command_parity = etd->parity;
937 // Disable to prevent sending corrupted data to the tag.
938 if (command_parity) {
939 Dbprintf("Use of `--par` option with `lf em 4x70 setkey` is disabled to prevent corrupting tag data");
940 reply_ng(CMD_LF_EM4X70_WRITE, PM3_ENOTIMPL, NULL, 0);
941 return;
944 init_tag();
945 em4x70_setup_read();
947 // Find the Tag
948 if (get_signalproperties() && find_em4x70_tag()) {
950 // Read ID to ensure we can write to card
951 if (em4x70_read_id()) {
952 status = PM3_SUCCESS;
954 // Write each crypto block
955 for (int i = 0; i < 6; i++) {
957 uint16_t key_word = (etd->crypt_key[(i * 2) + 1] << 8) + etd->crypt_key[i * 2];
958 // Write each word, abort if any failure occurs
959 status = write(key_word, 9 - i);
960 if (status != PM3_SUCCESS) {
961 break;
964 // The client now has support for test authentication after
965 // writing a new key, thus allowing to verify that the new
966 // key was written correctly. This is what the datasheet
967 // suggests. Not currently implemented in the firmware,
968 // although ID48LIB has no dependencies that would prevent
969 // use within the firmware layer.
973 StopTicks();
974 lf_finalize(ledcontrol);
975 reply_ng(CMD_LF_EM4X70_SETKEY, status, tag.data, sizeof(tag.data));