Merge pull request #1331 from Guilhem7/master
[RRG-proxmark3.git] / armsrc / em4x50.c
blobd775f02cc657c8ca1fe1c0cfd72ed5409bc04d2a
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2020 tharexde
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // Low frequency EM4x50 commands
9 //-----------------------------------------------------------------------------
11 #include "fpgaloader.h"
12 #include "ticks.h"
13 #include "dbprint.h"
14 #include "lfsampling.h"
15 #include "lfadc.h"
16 #include "lfdemod.h"
17 #include "commonutil.h"
18 #include "em4x50.h"
19 #include "BigBuf.h"
20 #include "spiffs.h"
21 #include "appmain.h" // tear
23 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
24 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
25 // EM4x50 units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
26 // T0 = TIMER_CLOCK1 / 125000 = 192
27 #ifndef T0
28 #define T0 192
29 #endif
31 // conversions (carrier frequency 125 kHz):
32 // 1 us = 1.5 ticks
33 // 1 cycle = 1 period = 8 us = 12 ticks
34 // 1 bit = 64 cycles = 768 ticks = 512 us (for Opt64)
35 #define CYCLES2TICKS 12
36 #define CYCLES2MUSEC 8
38 // given in cycles/periods
39 #define EM4X50_T_TAG_QUARTER_PERIOD 16
40 #define EM4X50_T_TAG_HALF_PERIOD 32
41 #define EM4X50_T_TAG_THREE_QUARTER_PERIOD 48
42 #define EM4X50_T_TAG_FULL_PERIOD 64
43 #define EM4X50_T_TAG_TPP 64
44 #define EM4X50_T_TAG_TWA 64
45 #define EM4X50_T_TAG_TINIT 2112
46 #define EM4X50_T_TAG_TWEE 3200
47 #define EM4X50_T_TAG_WAITING_FOR_SIGNAL 75
48 #define EM4X50_T_WAITING_FOR_DBLLIW 1550
49 #define EM4X50_T_WAITING_FOR_ACK 4
50 #define EM4X50_T_TOLERANCE 8
51 #define EM4X50_T_ZERO_DETECTION 3
53 // timeout values (empirical) for simulation mode (may vary with regard to reader)
54 #define EM4X50_T_SIMULATION_TIMEOUT_READ 600
55 #define EM4X50_T_SIMULATION_TIMEOUT_WAIT 50
57 // the following value (pulses) seems to be critical; if it's too low
58 //(e.g. < 120) some cards are no longer readable although they're ok
59 #define EM4X50_T_WAITING_FOR_SNGLLIW 140
61 // div
62 #define EM4X50_TAG_WORD 45
63 #define EM4X50_TAG_MAX_NO_BYTES 136
64 #define EM4X50_TIMEOUT_PULSE_EVAL 2500
66 int gHigh = 190;
67 int gLow = 60;
69 // indication whether a previous login has been successful, so operations
70 // that require authentication can be handled
71 bool gLogin = false;
72 // WritePassword process in simulation mode is handled in a different way
73 // compared to operations like read, write, login, so it is necessary to
74 // to be able to identfiy it
75 bool gWritePasswordProcess = false;
76 // if reader sends a different password than "expected" -> save it
77 uint32_t gPassword = 0;
79 // extract and check parities
80 // return result of parity check and extracted plain data
81 static bool extract_parities(uint64_t word, uint32_t *data) {
83 uint8_t row_parities = 0x0, col_parities = 0x0;
84 uint8_t row_parities_calculated = 0x0, col_parities_calculated = 0x0;
86 *data = 0x0;
88 // extract plain data (32 bits) from raw word (45 bits)
89 for (int i = 0; i < 4; i++) {
90 *data <<= 8;
91 *data |= (word >> ((4 - i) * 9 + 1)) & 0xFF;
94 // extract row parities (4 bits + stop bit) from raw word (45 bits)
95 for (int i = 0; i < 5; i++) {
96 row_parities <<= 1;
97 row_parities |= (word >> ((4 - i) * 9)) & 0x1;
100 // extract col_parities (8 bits, no stop bit) from raw word (45 bits)
101 col_parities = (word >> 1) & 0xFF;
103 // check extracted parities against extracted data
105 // calculate row parities from data
106 for (int i = 0; i < 4; i++) {
107 row_parities_calculated <<= 1;
108 for (int j = 0; j < 8; j++) {
109 row_parities_calculated ^= (*data >> ((3 - i) * 8 + (7 - j))) & 0x1;
113 // add stop bit (always zero)
114 row_parities_calculated <<= 1;
116 // calculate column parities from data
117 for (int i = 0; i < 8; i++) {
118 col_parities_calculated <<= 1;
119 for (int j = 0; j < 4; j++) {
120 col_parities_calculated ^= (*data >> ((3 - j) * 8 + (7 - i))) & 0x1;
124 if ((row_parities == row_parities_calculated) && (col_parities == col_parities_calculated))
125 return true;
127 return false;
130 void em4x50_setup_read(void) {
132 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
133 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
135 StartTicks();
137 // 50ms for the resonant antenna to settle.
138 WaitMS(50);
140 // Now set up the SSC to get the ADC samples that are now streaming at us.
141 FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER);
143 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125);
145 // Connect the A/D to the peak-detected low-frequency path.
146 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
148 // Steal this pin from the SSP (SPI communication channel with fpga) and
149 // use it to control the modulation
150 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
151 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
153 // Disable modulation at default, which means enable the field
154 LOW(GPIO_SSC_DOUT);
156 // Watchdog hit
157 WDT_HIT();
160 void em4x50_setup_sim(void) {
161 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
162 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT);
163 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125);
165 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT | GPIO_SSC_CLK;
166 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
167 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK;
169 StartTicks();
171 // Watchdog hit
172 WDT_HIT();
175 // calculate signal properties (mean amplitudes) from measured data:
176 // 32 amplitudes (maximum values) -> mean amplitude value -> gHigh -> gLow
177 static bool get_signalproperties(void) {
179 bool signal_found = false;
180 int no_periods = 32, pct = 75, noise = 140;
181 uint8_t sample_ref = 127;
182 uint8_t sample_max_mean = 0;
183 uint8_t sample_max[no_periods];
184 uint32_t sample_max_sum = 0;
185 memset(sample_max, 0x00, sizeof(sample_max));
187 // wait until signal/noise > 1 (max. 32 periods)
188 for (int i = 0; i < EM4X50_T_TAG_WAITING_FOR_SIGNAL; i++) {
190 if (BUTTON_PRESS()) return false;
192 // about 2 samples per bit period
193 WaitUS(EM4X50_T_TAG_HALF_PERIOD * CYCLES2MUSEC);
195 // ignore first samples
196 if ((i > SIGNAL_IGNORE_FIRST_SAMPLES) && (AT91C_BASE_SSC->SSC_RHR > noise)) {
197 signal_found = true;
198 break;
202 if (signal_found == false) {
203 return false;
206 // calculate mean maximum value of 32 periods, each period has a length of
207 // 3 single "full periods" to eliminate the influence of a listen window
208 for (int i = 0; i < no_periods; i++) {
210 uint32_t tval = GetTicks();
211 while (GetTicks() - tval < 12 * 3 * EM4X50_T_TAG_FULL_PERIOD) {
213 if (BUTTON_PRESS()) return false;
215 volatile uint8_t sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
216 if (sample > sample_max[i])
217 sample_max[i] = sample;
221 sample_max_sum += sample_max[i];
224 sample_max_mean = sample_max_sum / no_periods;
226 // set global envelope variables
227 gHigh = sample_ref + pct * (sample_max_mean - sample_ref) / 100;
228 gLow = sample_ref - pct * (sample_max_mean - sample_ref) / 100;
230 return true;
233 // returns true if bit is undefined by evaluating a single sample within
234 // a bit period (given there is no LIW, ACK or NAK)
235 // This function is used for identifying a listen window in functions
236 // "find_double_listen_window" and "check_ack"
237 static bool invalid_bit(void) {
239 // get sample at 3/4 of bit period
240 WaitUS(EM4X50_T_TAG_THREE_QUARTER_PERIOD * CYCLES2MUSEC);
242 uint8_t sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
244 // wait until end of bit period
245 WaitUS(EM4X50_T_TAG_QUARTER_PERIOD * CYCLES2MUSEC);
247 // bit in "undefined" state?
248 if (sample <= gHigh && sample >= gLow)
249 return true;
251 return false;
254 static uint32_t get_pulse_length(void) {
256 int32_t timeout = EM4X50_TIMEOUT_PULSE_EVAL, tval = 0;
258 // iterates pulse lengths (low -> high -> low)
260 volatile uint8_t sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
262 while (sample > gLow && (timeout--))
263 sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
265 if (timeout <= 0)
266 return 0;
268 tval = GetTicks();
269 timeout = EM4X50_TIMEOUT_PULSE_EVAL;
271 while (sample < gHigh && (timeout--))
272 sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
274 if (timeout <= 0)
275 return 0;
277 timeout = EM4X50_TIMEOUT_PULSE_EVAL;
278 while (sample > gLow && (timeout--))
279 sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
281 if (timeout <= 0)
282 return 0;
284 return GetTicks() - tval;
288 // check if pulse length <pl> corresponds to given length <length>
289 static bool check_pulse_length(uint32_t pl, int length) {
290 return ((pl >= (length - EM4X50_T_TOLERANCE) * CYCLES2TICKS) &&
291 (pl <= (length + EM4X50_T_TOLERANCE) * CYCLES2TICKS));
294 // send single bit according to EM4x50 application note and datasheet
295 static void em4x50_reader_send_bit(int bit) {
297 // reset clock for the next bit
298 uint32_t tval = GetTicks();
300 if (bit == 0) {
302 // disable modulation (activate the field) for 7 cycles of carrier
303 // period (Opt64)
304 LOW(GPIO_SSC_DOUT);
305 while (GetTicks() - tval < 7 * CYCLES2TICKS);
307 // enable modulation (drop the field) for remaining first
308 // half of bit period
309 HIGH(GPIO_SSC_DOUT);
310 while (GetTicks() - tval < EM4X50_T_TAG_HALF_PERIOD * CYCLES2TICKS);
312 // disable modulation for second half of bit period
313 LOW(GPIO_SSC_DOUT);
314 while (GetTicks() - tval < EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS);
316 } else {
318 // bit = "1" means disable modulation for full bit period
319 LOW(GPIO_SSC_DOUT);
320 while (GetTicks() - tval < EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS);
324 // send byte (without parity)
325 static void em4x50_reader_send_byte(uint8_t byte) {
326 for (int i = 0; i < 8; i++) {
327 em4x50_reader_send_bit((byte >> (7 - i)) & 1);
331 // send byte followed by its (even) parity bit
332 static void em4x50_reader_send_byte_with_parity(uint8_t byte) {
333 int parity = 0;
335 for (int i = 0; i < 8; i++) {
336 int bit = (byte >> (7 - i)) & 1;
337 em4x50_reader_send_bit(bit);
338 parity ^= bit;
341 em4x50_reader_send_bit(parity);
344 // send 32 bit word with parity bits according to EM4x50 datasheet
345 // word hast be sent in msb notation
346 static void em4x50_reader_send_word(const uint32_t word) {
347 uint8_t bytes[4] = {0x0, 0x0, 0x0, 0x0};
349 for (int i = 0; i < 4; i++) {
350 bytes[i] = (word >> (24 - (8 * i))) & 0xFF;
351 em4x50_reader_send_byte_with_parity(bytes[i]);
354 // send column parities
355 em4x50_reader_send_byte(bytes[0] ^ bytes[1] ^ bytes[2] ^ bytes[3]);
357 // send final stop bit (always "0")
358 em4x50_reader_send_bit(0);
361 // find single listen window
362 static bool find_single_listen_window(void) {
363 int cnt_pulses = 0;
365 while (cnt_pulses < EM4X50_T_WAITING_FOR_SNGLLIW) {
367 // identification of listen window is done via evaluation of
368 // pulse lengths
369 if (check_pulse_length(get_pulse_length(), 3 * EM4X50_T_TAG_FULL_PERIOD)) {
371 if (check_pulse_length(get_pulse_length(), 2 * EM4X50_T_TAG_FULL_PERIOD)) {
373 // found listen window
374 return true;
377 cnt_pulses++;
380 return false;
383 // find two successive listen windows that indicate the beginning of
384 // data transmission
385 // double listen window to be detected within 1600 pulses -> worst case
386 // reason: first detectable double listen window after 34 words
387 // -> 34 words + 34 single listen windows -> about 1600 pulses
388 static int find_double_listen_window(bool bcommand) {
389 int cnt_pulses = 0;
391 while (cnt_pulses < EM4X50_T_WAITING_FOR_DBLLIW) {
393 if (BUTTON_PRESS()) {
394 return PM3_EOPABORTED;
397 // identification of listen window is done via evaluation of
398 // pulse lengths
399 if (check_pulse_length(get_pulse_length(), 3 * EM4X50_T_TAG_FULL_PERIOD)) {
401 if (check_pulse_length(get_pulse_length(), 2 * EM4X50_T_TAG_FULL_PERIOD)) {
403 // first listen window found
405 if (bcommand) {
407 // data transmission from card has to be stopped, because
408 // a commamd shall be issued
410 // unfortunately the position in listen window (where
411 // command request has to be sent) has gone, so if a
412 // second window follows - sync on this to issue a command
414 // skip the next bit...
415 WaitUS(EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC);
417 // ...and check if the following bit does make sense
418 // (if not it is the correct position within the second
419 // listen window)
420 if (invalid_bit()) {
422 // send RM for request mode
423 em4x50_reader_send_bit(0);
424 em4x50_reader_send_bit(0);
426 return PM3_SUCCESS;
431 if (check_pulse_length(get_pulse_length(), 3 * EM4X50_T_TAG_FULL_PERIOD)) {
433 // return although second listen window consists of one
434 // more bit period but this period is necessary for
435 // evaluating further pulse lengths
436 return PM3_SUCCESS;
440 cnt_pulses++;
443 return PM3_EFAILED;
446 // function is used to check wether a tag on the proxmark is an
447 // EM4x50 tag or not -> speed up "lf search" process
448 static bool find_em4x50_tag(void) {
449 return find_single_listen_window();
452 // To issue a command we have to find a listen window first.
453 // Because identification and synchronization at the same time is not
454 // possible when using pulse lengths a double listen window is used.
455 static int request_receive_mode(void) {
456 return find_double_listen_window(true);
459 // returns true if signal structue corresponds to ACK, anything else is
460 // counted as NAK (-> false)
461 // Only relevant for pasword writing function:
462 // If <bliw> is true then within the single listen window right after the
463 // ack signal a RM request has to be sent.
464 static bool check_ack(bool bliw) {
465 int count_cycles = 0;
466 while (count_cycles < EM4X50_T_WAITING_FOR_ACK) {
467 if (BUTTON_PRESS())
468 return false;
470 if (check_pulse_length(get_pulse_length(), 2 * EM4X50_T_TAG_FULL_PERIOD)) {
472 // The received signal is either ACK or NAK.
474 if (check_pulse_length(get_pulse_length(), 2 * EM4X50_T_TAG_FULL_PERIOD)) {
476 // Now the signal must be ACK.
478 if (!bliw) {
480 return true;
482 } else {
484 // send RM request after ack signal
486 // wait for 2 bits (remaining "bit" of ACK signal + first
487 // "bit" of listen window)
488 WaitUS(2 * EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC);
490 // check for listen window (if first bit cannot be interpreted
491 // as a valid bit it must belong to a listen window)
492 if (invalid_bit()) {
494 // send RM for request mode
495 em4x50_reader_send_bit(0);
496 em4x50_reader_send_bit(0);
498 return true;
501 } else {
503 // It's NAK -> stop searching
504 break;
507 count_cycles++;
510 return false;
513 // decodes one word by evaluating pulse lengths and previous bit;
514 // word must have 45 bits in total:
515 // 32 data bits + 4 row parity bits + 8 column parity bits + 1 stop bit
516 static int get_word_from_bitstream(uint32_t *data) {
517 bool bitchange = false;
518 int cnt = 0;
519 uint32_t pl = 0;
520 uint64_t word = 0x0;
522 *data = 0x0;
524 // initial bit value depends on last pulse length of listen window
525 pl = get_pulse_length();
526 if (check_pulse_length(pl, 3 * EM4X50_T_TAG_HALF_PERIOD)) {
528 // pulse length = 1.5
529 word = 0x1;
531 } else if (check_pulse_length(pl, 2 * EM4X50_T_TAG_FULL_PERIOD)) {
533 // pulse length = 2
534 bitchange = true;
536 } else {
538 // pulse length = 2.5
539 word = 0x1;
540 cnt++;
543 // identify remaining bits based on pulse lengths
544 // between two listen windows only pulse lengths of 1, 1.5 and 2 are possible
545 while (BUTTON_PRESS() == false) {
547 cnt++;
548 word <<= 1;
550 pl = get_pulse_length();
552 if (check_pulse_length(pl, EM4X50_T_TAG_FULL_PERIOD)) {
554 // pulse length = 1 -> keep former bit value
555 word |= (word >> 1) & 0x1;
557 } else if (check_pulse_length(pl, 3 * EM4X50_T_TAG_HALF_PERIOD)) {
559 // pulse length = 1.5 -> decision on bit change
561 if (bitchange) {
563 // if number of pulse lengths with 1.5 periods is even -> add bit
564 word |= (word >> 1) & 0x1;
565 word <<= 1;
567 // pulse length of 1.5 changes bit value
568 word |= ((word >> 1) & 0x1) ^ 0x1;
569 cnt++;
571 // next time add only one bit
572 bitchange = false;
574 } else {
576 word |= ((word >> 1) & 0x1) ^ 0x1;
578 // next time two bits have to be added
579 bitchange = true;
582 } else if (check_pulse_length(pl, 2 * EM4X50_T_TAG_FULL_PERIOD)) {
584 // pulse length of 2 means: adding 2 bits "01"
585 cnt++;
587 word <<= 1;
588 word |= 0x1;
590 } else if (check_pulse_length(pl, 3 * EM4X50_T_TAG_FULL_PERIOD)) {
592 // pulse length of 3 indicates listen window -> clear last
593 // bit (= 0) and return (without parities)
594 word >>= 2;
595 return (extract_parities(word, data)) ? --cnt : 0;
599 return PM3_EOPABORTED;
602 // simple login to EM4x50,
603 // used in operations that require authentication
604 static int login(uint32_t password) {
605 if (request_receive_mode() == PM3_SUCCESS) {
607 // send login command
608 em4x50_reader_send_byte_with_parity(EM4X50_COMMAND_LOGIN);
610 // send password
611 em4x50_reader_send_word(password);
613 WaitUS(EM4X50_T_TAG_TPP * CYCLES2MUSEC);
615 // check if ACK is returned
616 if (check_ack(false))
617 return PM3_SUCCESS;
619 } else {
620 if (DBGLEVEL >= DBG_DEBUG)
621 Dbprintf("error in command request");
624 return PM3_EFAILED;
627 // searching for password in given range
628 static bool brute(uint32_t start, uint32_t stop, uint32_t *pwd) {
629 bool pwd_found = false;
630 int cnt = 0;
632 for (*pwd = start; *pwd <= stop; (*pwd)++) {
634 WDT_HIT();
636 if (login(*pwd) == PM3_SUCCESS) {
638 pwd_found = true;
640 // to be safe login 5 more times
641 for (int i = 0; i < 5; i++) {
642 if (login(*pwd) != PM3_SUCCESS) {
643 pwd_found = false;
644 break;
648 if (pwd_found)
649 break;
652 // print password every 500 iterations
653 if ((++cnt % 500) == 0) {
655 // print header
656 if (cnt == 500) {
657 Dbprintf("|---------+------------+------------|");
658 Dbprintf("| no. | pwd (msb) | pwd (lsb) |");
659 Dbprintf("|---------+------------+------------|");
662 // print data
663 Dbprintf("|%8i | 0x%08x | 0x%08x |", cnt, reflect32(*pwd), *pwd);
666 if (BUTTON_PRESS())
667 break;
671 // print footer
672 if (cnt >= 500)
673 Dbprintf("|---------+------------+------------|");
675 return pwd_found;
678 // login into EM4x50
679 void em4x50_login(uint32_t *password) {
680 em4x50_setup_read();
682 int status = PM3_EFAILED;
683 LED_C_ON();
684 if (get_signalproperties() && find_em4x50_tag()) {
685 LED_C_OFF();
686 LED_D_ON();
687 status = login(*password);
690 LEDsoff();
691 lf_finalize();
692 reply_ng(CMD_LF_EM4X50_LOGIN, status, NULL, 0);
695 // envoke password search
696 void em4x50_brute(em4x50_data_t *etd) {
697 em4x50_setup_read();
699 bool bsuccess = false;
700 uint32_t pwd = 0x0;
701 LED_C_ON();
702 if (get_signalproperties() && find_em4x50_tag()) {
703 LED_C_OFF();
704 LED_D_ON();
705 bsuccess = brute(etd->password1, etd->password2, &pwd);
708 LEDsoff();
709 lf_finalize();
710 reply_ng(CMD_LF_EM4X50_BRUTE, bsuccess ? PM3_SUCCESS : PM3_EFAILED, (uint8_t *)(&pwd), sizeof(pwd));
713 // check passwords from dictionary content in flash memory
714 void em4x50_chk(uint8_t *filename) {
715 int status = PM3_EFAILED;
716 uint32_t pwd = 0x0;
718 #ifdef WITH_FLASH
720 BigBuf_free();
722 int changed = rdv40_spiffs_lazy_mount();
723 uint16_t pwd_count = 0;
724 uint32_t size = size_in_spiffs((char *)filename);
725 pwd_count = size / 4;
726 uint8_t *pwds = BigBuf_malloc(size);
728 rdv40_spiffs_read_as_filetype((char *)filename, pwds, size, RDV40_SPIFFS_SAFETY_SAFE);
730 if (changed)
731 rdv40_spiffs_lazy_unmount();
733 em4x50_setup_read();
735 // set gHigh and gLow
736 LED_C_ON();
737 if (get_signalproperties() && find_em4x50_tag()) {
739 LED_C_OFF();
740 LED_D_ON();
742 // try to login with current password
743 for (int i = 0; i < pwd_count; i++) {
745 // manual interruption
746 if (BUTTON_PRESS()) {
747 status = PM3_EOPABORTED;
748 break;
751 // get next password
752 pwd = 0x0;
753 for (int j = 0; j < 4; j++)
754 pwd |= (*(pwds + 4 * i + j)) << ((3 - j) * 8);
756 if ((status = login(pwd)) == PM3_SUCCESS) {
757 SpinUp(50);
758 SpinDown(50);
759 break;
764 BigBuf_free();
766 #endif
768 LEDsoff();
769 lf_finalize();
770 reply_ng(CMD_LF_EM4X50_CHK, status, (uint8_t *)&pwd, sizeof(pwd));
773 // resets EM4x50 tag (used by write function)
774 static int reset(void) {
775 if (request_receive_mode() == PM3_SUCCESS) {
777 // send reset command
778 em4x50_reader_send_byte_with_parity(EM4X50_COMMAND_RESET);
780 if (check_ack(false))
781 return PM3_SUCCESS;
783 } else {
784 if (DBGLEVEL >= DBG_DEBUG)
785 Dbprintf("error in command request");
788 return PM3_EFAILED;
791 // reads data that tag transmits when exposed to reader field
792 // (standard read mode); number of read words is saved in <now>
793 int standard_read(int *now, uint32_t *words) {
795 int fwr = *now, res = PM3_EFAILED;
797 // start with the identification of two successive listening windows
798 if ((res = find_double_listen_window(false)) == PM3_SUCCESS) {
800 // read and save words until following double listen window is detected
801 res = get_word_from_bitstream(&words[*now]);
802 while (res == EM4X50_TAG_WORD) {
803 (*now)++;
804 res = get_word_from_bitstream(&words[*now]);
807 // number of detected words
808 *now -= fwr;
810 } else {
811 if (DBGLEVEL >= DBG_DEBUG)
812 Dbprintf("didn't find a listen window");
815 return res;
818 // reads from "first word read" (fwr) to "last word read" (lwr)
819 // result is verified by "standard read mode"
820 static int selective_read(uint32_t addresses, uint32_t *words) {
822 int status = PM3_EFAILED;
823 uint8_t fwr = addresses & 0xFF; // first word read (first byte)
824 uint8_t lwr = (addresses >> 8) & 0xFF; // last word read (second byte)
825 int now = fwr; // number of words
827 if (request_receive_mode() == PM3_SUCCESS) {
829 // send selective read command
830 em4x50_reader_send_byte_with_parity(EM4X50_COMMAND_SELECTIVE_READ);
832 // send address data
833 em4x50_reader_send_word(addresses);
835 // look for ACK sequence
836 if (check_ack(false))
838 // save and verify via standard read mode (compare number of words)
839 if ((status = standard_read(&now, words)) == PM3_SUCCESS)
840 if (now == (lwr - fwr + 1))
841 return status;
843 } else {
844 if (DBGLEVEL >= DBG_DEBUG)
845 Dbprintf("error in command request");
848 return status;
851 // reads by using "selective read mode" -> bidirectional communication
852 void em4x50_read(em4x50_data_t *etd) {
853 int status = PM3_EFAILED;
854 uint32_t words[EM4X50_NO_WORDS] = {0x0};
856 em4x50_setup_read();
858 // set gHigh and gLow
859 LED_C_ON();
860 if (get_signalproperties() && find_em4x50_tag()) {
862 LED_C_OFF();
863 LED_D_ON();
865 bool blogin = true;
867 // try to login with given password
868 if (etd->pwd_given)
869 blogin = (login(etd->password1) == PM3_SUCCESS);
871 // only one word has to be read -> first word read = last word read
872 if (blogin)
873 status = selective_read(etd->addresses, words);
876 LEDsoff();
877 LOW(GPIO_SSC_DOUT);
878 lf_finalize();
879 reply_ng(CMD_LF_EM4X50_READ, status, (uint8_t *)words, EM4X50_TAG_MAX_NO_BYTES);
882 // collects as much information as possible via selective read mode
883 void em4x50_info(em4x50_data_t *etd) {
884 int status = PM3_EFAILED;
885 uint32_t words[EM4X50_NO_WORDS] = {0x0};
887 em4x50_setup_read();
889 LED_C_ON();
890 if (get_signalproperties() && find_em4x50_tag()) {
891 LED_C_OFF();
892 LED_D_ON();
894 bool blogin = true;
895 // login with given password
896 if (etd->pwd_given)
897 blogin = (login(etd->password1) == PM3_SUCCESS);
899 if (blogin) {
900 // read addresses from fwr = 0 to lwr = 33 (0x21)
901 status = selective_read(0x00002100, words);
905 LEDsoff();
906 lf_finalize();
907 reply_ng(CMD_LF_EM4X50_INFO, status, (uint8_t *)words, EM4X50_TAG_MAX_NO_BYTES);
910 // reads data that tag transmits "voluntarily" -> standard read mode
911 void em4x50_reader(void) {
913 int now = 0;
914 uint32_t words[EM4X50_NO_WORDS] = {0x0};
916 em4x50_setup_read();
918 LED_C_ON();
919 if (get_signalproperties() && find_em4x50_tag()) {
920 LED_C_OFF();
921 LED_D_ON();
922 standard_read(&now, words);
925 LEDsoff();
926 LOW(GPIO_SSC_DOUT);
927 lf_finalize();
928 reply_ng(CMD_LF_EM4X50_READER, now, (uint8_t *)words, 4 * now);
931 // writes <word> to specified <addresses>
932 static int write(uint32_t word, uint32_t addresses) {
934 if (request_receive_mode() == PM3_SUCCESS) {
936 // send write command
937 em4x50_reader_send_byte_with_parity(EM4X50_COMMAND_WRITE);
939 // send address data
940 em4x50_reader_send_byte_with_parity(addresses & 0xFF);
942 // send data
943 em4x50_reader_send_word(word);
945 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
946 reply_ng(CMD_LF_EM4X50_WRITE, PM3_ETEAROFF, NULL, 0);
947 return PM3_ETEAROFF;
948 } else {
950 // wait for T0 * EM4X50_T_TAG_TWA (write access time)
951 WaitUS(EM4X50_T_TAG_TWA * CYCLES2MUSEC);
953 // look for ACK sequence
954 if (check_ack(false)) {
956 // now EM4x50 needs T0 * EM4X50_T_TAG_TWEE (EEPROM write time = 3.2ms = 50 * 64 periods)
957 // for saving data and should return with ACK
958 for (int i = 0; i < 50; i++) {
959 WaitUS(EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC);
962 if (check_ack(false))
963 return PM3_SUCCESS;
966 } else {
967 if (DBGLEVEL >= DBG_DEBUG)
968 Dbprintf("error in command request");
971 return PM3_EFAILED;
974 // changes password from <password> to <new_password>
975 static int write_password(uint32_t password, uint32_t new_password) {
976 if (request_receive_mode() == PM3_SUCCESS) {
978 // send write password command
979 em4x50_reader_send_byte_with_parity(EM4X50_COMMAND_WRITE_PASSWORD);
981 // send address data
982 em4x50_reader_send_word(password);
984 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
985 reply_ng(CMD_LF_EM4X50_WRITE, PM3_ETEAROFF, NULL, 0);
986 return PM3_ETEAROFF;
987 } else {
989 // wait for T0 * EM4x50_T_TAG_TPP (processing pause time)
990 WaitUS(EM4X50_T_TAG_TPP * CYCLES2MUSEC);
992 // look for ACK sequence and send rm request
993 // during following listen window
994 if (check_ack(true)) {
996 // send new password
997 em4x50_reader_send_word(new_password);
999 // wait for T0 * EM4X50_T_TAG_TWA (write access time)
1000 WaitUS(EM4X50_T_TAG_TWA * CYCLES2MUSEC);
1002 if (check_ack(false)) {
1004 // now EM4x50 needs T0 * EM4X50_T_TAG_TWEE (EEPROM write time = 3.2ms = 50 * 64 periods)
1005 // for saving data and should return with ACK
1006 for (int i = 0; i < 50; i++) {
1007 WaitUS(EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC);
1010 if (check_ack(false))
1011 return PM3_SUCCESS;
1015 } else {
1016 if (DBGLEVEL >= DBG_DEBUG)
1017 Dbprintf("error in command request");
1020 return PM3_EFAILED;
1023 // write operation process for EM4x50 tag,
1024 // single word is written to given address, verified by selective read operation
1025 // wrong password -> return with PM3_EFAILED
1026 void em4x50_write(em4x50_data_t *etd) {
1027 int status = PM3_EFAILED;
1028 uint32_t words[EM4X50_NO_WORDS] = {0x0};
1030 em4x50_setup_read();
1032 LED_C_ON();
1033 if (get_signalproperties() && find_em4x50_tag()) {
1035 LED_C_OFF();
1036 LED_D_ON();
1038 // if password is given try to login first
1039 status = PM3_SUCCESS;
1040 if (etd->pwd_given)
1041 status = login(etd->password1);
1043 if (status == PM3_SUCCESS) {
1045 // write word to given address
1046 status = write(etd->word, etd->addresses);
1047 if (status == PM3_ETEAROFF) {
1048 lf_finalize();
1049 return;
1052 if (status == PM3_SUCCESS) {
1054 // to verify result reset EM4x50
1055 status = reset();
1056 if (status == PM3_SUCCESS) {
1058 // if password is given renew login after reset
1059 if (etd->pwd_given)
1060 status = login(etd->password1);
1062 if (status == PM3_SUCCESS) {
1064 // call a selective read
1065 status = selective_read(etd->addresses, words);
1066 if (status == PM3_SUCCESS) {
1068 // compare result with given word
1069 if (words[etd->addresses & 0xFF] != reflect32(etd->word))
1070 status = PM3_EFAILED;
1078 LEDsoff();
1079 lf_finalize();
1080 reply_ng(CMD_LF_EM4X50_WRITE, status, (uint8_t *)words, EM4X50_TAG_MAX_NO_BYTES);
1083 // simple change of password
1084 void em4x50_writepwd(em4x50_data_t *etd) {
1085 int status = PM3_EFAILED;
1087 em4x50_setup_read();
1089 LED_C_ON();
1090 if (get_signalproperties() && find_em4x50_tag()) {
1092 LED_C_OFF();
1093 LED_D_ON();
1095 // login and change password
1096 if (login(etd->password1) == PM3_SUCCESS) {
1098 status = write_password(etd->password1, etd->password2);
1099 if (status == PM3_ETEAROFF) {
1100 lf_finalize();
1101 return;
1106 LEDsoff();
1107 lf_finalize();
1108 reply_ng(CMD_LF_EM4X50_WRITEPWD, status, NULL, 0);
1111 // send bit in receive mode by counting carrier cycles
1112 static void em4x50_sim_send_bit(uint8_t bit) {
1114 uint16_t timeout = EM4X50_T_SIMULATION_TIMEOUT_READ;
1116 for (int t = 0; t < EM4X50_T_TAG_FULL_PERIOD; t++) {
1118 // wait until SSC_CLK goes HIGH
1119 // used as a simple detection of a reader field?
1120 while ((timeout--) && !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK));
1122 if (timeout == 0) {
1123 return;
1125 timeout = EM4X50_T_SIMULATION_TIMEOUT_READ;
1127 if (bit)
1128 OPEN_COIL();
1129 else
1130 SHORT_COIL();
1132 //wait until SSC_CLK goes LOW
1133 while ((timeout--) && (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK));
1134 if (timeout == 0) {
1135 return;
1137 timeout = EM4X50_T_SIMULATION_TIMEOUT_READ;
1139 if (t == EM4X50_T_TAG_HALF_PERIOD)
1140 bit ^= 1;
1145 // send byte in receive mode either with or without parity check (even)
1146 static void em4x50_sim_send_byte(uint8_t byte, bool paritycheck) {
1148 // send byte
1149 for (int i = 0; i < 8; i++) {
1150 em4x50_sim_send_bit((byte >> (7 - i)) & 1);
1153 if (paritycheck) {
1155 uint8_t parity = 0x0;
1157 for (int i = 0; i < 8; i++) {
1158 parity ^= (byte >> i) & 1;
1161 em4x50_sim_send_bit(parity);
1165 // send complete word in receive mode (including all parity checks)
1166 static void em4x50_sim_send_word(uint32_t word) {
1168 uint8_t cparity = 0x00;
1170 // word has tobe sent in msb, not lsb
1171 word = reflect32(word);
1173 // 4 bytes each with even row parity bit
1174 for (int i = 0; i < 4; i++) {
1175 em4x50_sim_send_byte((word >> ((3 - i) * 8)) & 0xFF, true);
1178 // column parity
1179 for (int i = 0; i < 8; i++) {
1180 cparity <<= 1;
1181 for (int j = 0; j < 4; j++) {
1182 cparity ^= (((word >> ((3 - j) * 8)) & 0xFF) >> (7 - i)) & 1;
1185 em4x50_sim_send_byte(cparity, false);
1187 // stop bit
1188 em4x50_sim_send_bit(0);
1191 // wait for <maxperiods> pulses of carrier frequency
1192 static void wait_cycles(int maxperiods) {
1194 int period = 0, timeout = EM4X50_T_SIMULATION_TIMEOUT_WAIT;
1196 while (period < maxperiods) {
1198 while ((timeout--) && !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK));
1199 if (timeout <= 0) {
1200 return;
1202 timeout = EM4X50_T_SIMULATION_TIMEOUT_WAIT;
1204 while ((timeout--) && (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK));
1205 if (timeout <= 0) {
1206 return;
1208 timeout = EM4X50_T_SIMULATION_TIMEOUT_WAIT;
1210 period++;
1214 // read single bit in simulation mode
1215 static int em4x50_sim_read_bit(void) {
1217 int cycles = 0;
1218 int timeout = EM4X50_T_SIMULATION_TIMEOUT_READ;
1220 while (cycles < EM4X50_T_TAG_FULL_PERIOD) {
1222 // wait until reader field disappears
1223 while ((timeout--) && !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK));
1224 if (timeout <= 0) {
1225 return PM3_ETIMEOUT;
1227 timeout = EM4X50_T_SIMULATION_TIMEOUT_READ;
1229 // now check until reader switches on carrier field
1230 uint32_t tval = GetTicks();
1231 while ((timeout--) && (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)) {
1233 if (timeout <= 0) {
1234 return PM3_ETIMEOUT;
1237 // check if current cycle takes longer than "usual""
1238 if (GetTicks() - tval > EM4X50_T_ZERO_DETECTION * CYCLES2TICKS) {
1240 // gap detected; wait until reader field is switched on again
1241 while ((timeout--) && (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK));
1243 if (timeout <= 0) {
1244 return PM3_ETIMEOUT;
1247 // now we have a reference "position", from here it will take
1248 // slightly less than 32 cycles until the end of the bit period
1249 wait_cycles(28);
1251 // end of bit period is reached; return with bit value "0"
1252 // (cf. datasheet)
1253 return 0;
1256 timeout = EM4X50_T_SIMULATION_TIMEOUT_READ;
1258 // no gap detected, i.e. reader field is still up;
1259 // continue with counting cycles
1260 cycles++;
1263 // reached 64 cycles (= EM4X50_T_TAG_FULL_PERIOD) -> return bit value "1"
1264 return 1;
1267 // read byte in simulation mode either with or without parity check (even)
1268 static bool em4x50_sim_read_byte(uint8_t *byte, bool paritycheck) {
1270 for (int i = 0; i < 8; i++) {
1271 *byte <<= 1;
1272 *byte |= em4x50_sim_read_bit();
1275 if (paritycheck) {
1277 int pval = em4x50_sim_read_bit();
1278 uint8_t parity = 0;
1280 for (int i = 0; i < 8; i++) {
1281 parity ^= ((*byte) >> i) & 1;
1284 if (parity != pval) {
1285 return false;
1289 return true;
1292 // read complete word in simulation mode
1293 static bool em4x50_sim_read_word(uint32_t *word) {
1295 uint8_t stop_bit = 0;
1296 uint8_t parities = 0, parities_calculated = 0;
1297 uint8_t bytes[4] = {0};
1299 // read plain data
1300 for (int i = 0; i < 4; i++) {
1301 em4x50_sim_read_byte(&bytes[i], true);
1304 // read column parities and stop bit
1305 em4x50_sim_read_byte(&parities, false);
1306 stop_bit = em4x50_sim_read_bit();
1308 // calculate column parities from data
1309 for (int i = 0; i < 8; i++) {
1310 parities_calculated <<= 1;
1311 for (int j = 0; j < 4; j++) {
1312 parities_calculated ^= (bytes[j] >> (7 - i)) & 1;
1316 *word = BYTES2UINT32_BE(bytes);
1318 // check parities
1319 if ((parities == parities_calculated) && (stop_bit == 0)) {
1320 return true;
1323 return false;
1326 // check if reader requests receive mode (rm) by sending two zeros
1327 static int check_rm_request(uint32_t *tag) {
1329 // look for first zero
1330 int bit = em4x50_sim_read_bit();
1331 if (bit == 0) {
1333 // look for second zero
1334 bit = em4x50_sim_read_bit();
1335 if (bit == 0) {
1337 LED_C_ON();
1339 // if command before was EM4X50_COMMAND_WRITE_PASSWORD
1340 // switch to separate process
1341 if (gWritePasswordProcess) {
1342 return EM4X50_COMMAND_WRITE_PASSWORD;
1343 } else {
1344 // read mode request detected, get command from reader
1345 uint8_t command = 0;
1346 em4x50_sim_read_byte(&command, true);
1347 return command;
1352 return (bit != PM3_ETIMEOUT) ? PM3_SUCCESS : PM3_ETIMEOUT;
1355 // send single listen window in simulation mode
1356 static int em4x50_sim_send_listen_window(uint32_t *tag) {
1358 SHORT_COIL();
1359 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1361 OPEN_COIL();
1362 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1364 SHORT_COIL();
1365 wait_cycles(2 * EM4X50_T_TAG_FULL_PERIOD);
1367 OPEN_COIL();
1368 int command = check_rm_request(tag);
1369 if (command != PM3_SUCCESS) {
1370 return command;
1373 SHORT_COIL();
1374 wait_cycles(EM4X50_T_TAG_FULL_PERIOD);
1376 return PM3_SUCCESS;
1379 // send ack
1380 static void em4x50_sim_send_ack(void) {
1382 SHORT_COIL();
1383 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1385 OPEN_COIL();
1386 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1388 SHORT_COIL();
1389 wait_cycles(3 * EM4X50_T_TAG_HALF_PERIOD);
1391 OPEN_COIL();
1392 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1394 SHORT_COIL();
1395 wait_cycles(3 * EM4X50_T_TAG_HALF_PERIOD);
1397 OPEN_COIL();
1398 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1400 SHORT_COIL();
1403 // send nak
1404 static void em4x50_sim_send_nak(void) {
1406 SHORT_COIL();
1407 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1409 OPEN_COIL();
1410 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1412 SHORT_COIL();
1413 wait_cycles(3 * EM4X50_T_TAG_HALF_PERIOD);
1415 OPEN_COIL();
1416 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1418 SHORT_COIL();
1419 wait_cycles(EM4X50_T_TAG_FULL_PERIOD);
1421 OPEN_COIL();
1422 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1424 SHORT_COIL();
1425 wait_cycles(EM4X50_T_TAG_HALF_PERIOD);
1428 // standard read mode process (simulation mode)
1429 static int em4x50_sim_handle_standard_read_command(uint32_t *tag) {
1431 // extract control data
1432 int fwr = reflect32(tag[EM4X50_CONTROL]) & 0xFF; // first word read
1433 int lwr = (reflect32(tag[EM4X50_CONTROL]) >> 8) & 0xFF; // last word read
1434 // extract protection data:
1435 // first word read protected
1436 int fwrp = reflect32(tag[EM4X50_PROTECTION]) & 0xFF;
1437 // last word read protected
1438 int lwrp = (reflect32(tag[EM4X50_PROTECTION]) >> 8) & 0xFF;
1440 while ((BUTTON_PRESS() == false) && (data_available() == false)) {
1442 WDT_HIT();
1444 int res = em4x50_sim_send_listen_window(tag);
1446 if (res != PM3_SUCCESS) {
1447 return res;
1450 for (int i = fwr; i <= lwr; i++) {
1452 res = em4x50_sim_send_listen_window(tag);
1453 if (res != PM3_SUCCESS) {
1454 return res;
1457 if ((gLogin == false) && (i >= fwrp) && (i <= lwrp)) {
1458 em4x50_sim_send_word(0x00);
1459 } else {
1460 em4x50_sim_send_word(reflect32(tag[i]));
1465 return PM3_EOPABORTED;
1468 // selective read mode process (simulation mode)
1469 static int em4x50_sim_handle_selective_read_command(uint32_t *tag) {
1471 // read password
1472 uint32_t address = 0;
1473 bool addr = em4x50_sim_read_word(&address);
1475 // processing pause time (corresponds to a "1" bit)
1476 em4x50_sim_send_bit(1);
1478 if (addr) {
1479 em4x50_sim_send_ack();
1480 } else {
1481 em4x50_sim_send_nak();
1482 return EM4X50_COMMAND_STANDARD_READ;
1485 // extract control data
1486 int fwr = address & 0xFF; // first word read
1487 int lwr = (address >> 8) & 0xFF; // last word read
1489 // extract protection data:
1490 // first word read protected
1491 int fwrp = reflect32(tag[EM4X50_PROTECTION]) & 0xFF;
1492 // last word read protected
1493 int lwrp = (reflect32(tag[EM4X50_PROTECTION]) >> 8) & 0xFF;
1495 while ((BUTTON_PRESS() == false) && (data_available() == false)) {
1497 WDT_HIT();
1499 int command = em4x50_sim_send_listen_window(tag);
1500 if (command != PM3_SUCCESS) {
1501 return command;
1504 for (int i = fwr; i <= lwr; i++) {
1506 command = em4x50_sim_send_listen_window(tag);
1507 if (command != PM3_SUCCESS) {
1508 return command;
1511 // if not authenticated do not send read protected words
1512 if ((gLogin == false) && (i >= fwrp) && (i <= lwrp)) {
1513 em4x50_sim_send_word(0x00);
1514 } else {
1515 em4x50_sim_send_word(reflect32(tag[i]));
1520 return PM3_EOPABORTED;
1523 // login process (simulation mode)
1524 static int em4x50_sim_handle_login_command(uint32_t *tag) {
1526 // read password
1527 uint32_t password = 0;
1528 bool pwd = em4x50_sim_read_word(&password);
1530 // processing pause time (corresponds to a "1" bit)
1531 em4x50_sim_send_bit(1);
1533 if (pwd && (password == reflect32(tag[EM4X50_DEVICE_PASSWORD]))) {
1534 em4x50_sim_send_ack();
1535 gLogin = true;
1536 LED_D_ON();
1537 } else {
1538 em4x50_sim_send_nak();
1539 gLogin = false;
1540 LED_D_OFF();
1542 // save transmitted password (to be used in standalone mode)
1543 gPassword = password;
1545 // continue with standard read mode
1546 return EM4X50_COMMAND_STANDARD_READ;
1549 // reset process (simulation mode)
1550 static int em4x50_sim_handle_reset_command(uint32_t *tag) {
1552 // processing pause time (corresponds to a "1" bit)
1553 em4x50_sim_send_bit(1);
1555 // send ACK
1556 em4x50_sim_send_ack();
1557 gLogin = false;
1558 LED_D_OFF();
1560 // wait for initialization (tinit)
1561 wait_cycles(EM4X50_T_TAG_TINIT);
1563 // continue with standard read mode
1564 return EM4X50_COMMAND_STANDARD_READ;
1567 // write process (simulation mode)
1568 static int em4x50_sim_handle_write_command(uint32_t *tag) {
1570 // read address
1571 uint8_t address = 0;
1572 bool addr = em4x50_sim_read_byte(&address, true);
1573 // read data
1574 uint32_t data = 0;
1575 bool word = em4x50_sim_read_word(&data);
1577 // write access time
1578 wait_cycles(EM4X50_T_TAG_TWA);
1580 if ((addr == false) || (word == false)) {
1581 em4x50_sim_send_nak();
1582 return EM4X50_COMMAND_STANDARD_READ;
1585 // extract necessary control data
1586 bool raw = (tag[EM4X50_CONTROL] >> CONFIG_BLOCK) & READ_AFTER_WRITE;
1587 // extract protection data:
1588 // first word write protected
1589 int fwwp = reflect8((tag[EM4X50_PROTECTION] >> 24) & 0xFF);
1590 // last word write protected
1591 int lwwp = reflect8((tag[EM4X50_PROTECTION] >> 16) & 0xFF);
1593 switch (address) {
1595 case EM4X50_DEVICE_PASSWORD:
1596 em4x50_sim_send_nak();
1597 return EM4X50_COMMAND_STANDARD_READ;
1598 break;
1600 case EM4X50_PROTECTION:
1601 if (gLogin) {
1602 tag[address] = reflect32(data);
1603 em4x50_sim_send_ack();
1604 } else {
1605 em4x50_sim_send_nak();
1606 return EM4X50_COMMAND_STANDARD_READ;
1608 break;
1610 case EM4X50_CONTROL:
1611 if (gLogin) {
1612 tag[address] = reflect32(data);
1613 em4x50_sim_send_ack();
1614 } else {
1615 em4x50_sim_send_nak();
1616 return EM4X50_COMMAND_STANDARD_READ;
1618 break;
1620 case EM4X50_DEVICE_SERIAL:
1621 em4x50_sim_send_nak();
1622 return EM4X50_COMMAND_STANDARD_READ;
1623 break;
1625 case EM4X50_DEVICE_ID:
1626 em4x50_sim_send_nak();
1627 return EM4X50_COMMAND_STANDARD_READ;
1628 break;
1630 default:
1631 if ((address >= fwwp) && (address <= lwwp)) {
1632 if (gLogin) {
1633 tag[address] = reflect32(data);
1634 em4x50_sim_send_ack();
1635 } else {
1636 em4x50_sim_send_nak();
1637 return EM4X50_COMMAND_STANDARD_READ;
1639 } else {
1640 tag[address] = reflect32(data);
1641 em4x50_sim_send_ack();
1643 break;
1646 // EEPROM write time
1647 // strange: need some sort of 'waveform correction', otherwise ack signal
1648 // will not be detected; sending a single "1" as last "bit" of Twee
1649 // seems to solve the problem
1650 wait_cycles(EM4X50_T_TAG_TWEE - EM4X50_T_TAG_FULL_PERIOD);
1651 em4x50_sim_send_bit(1);
1652 em4x50_sim_send_ack();
1654 // if "read after write" (raw) bit is set, send written data once
1655 if (raw) {
1656 int command = em4x50_sim_send_listen_window(tag);
1657 if (command != PM3_SUCCESS) {
1658 return command;
1661 command = em4x50_sim_send_listen_window(tag);
1662 if (command != PM3_SUCCESS) {
1663 return command;
1666 em4x50_sim_send_word(tag[address]);
1669 // continue with standard read mode
1670 return EM4X50_COMMAND_STANDARD_READ;
1673 // write password process (simulation mode)
1674 static int em4x50_sim_handle_writepwd_command(uint32_t *tag) {
1676 bool pwd = false;
1678 gWritePasswordProcess = true;
1680 // read password
1681 uint32_t act_password = 0;
1682 pwd = em4x50_sim_read_word(&act_password);
1684 // processing pause time tpp (corresponds to a "1" bit)
1685 em4x50_sim_send_bit(1);
1687 if (pwd && (act_password == reflect32(tag[EM4X50_DEVICE_PASSWORD]))) {
1688 em4x50_sim_send_ack();
1689 gLogin = true;
1690 } else {
1691 em4x50_sim_send_nak();
1692 gLogin = false;
1693 gWritePasswordProcess = false;
1695 // save transmitted password (to be used in standalone mode)
1696 gPassword = act_password;
1698 return EM4X50_COMMAND_STANDARD_READ;
1701 int command = em4x50_sim_send_listen_window(tag);
1702 gWritePasswordProcess = false;
1703 if (command != EM4X50_COMMAND_WRITE_PASSWORD) {
1704 return command;
1707 // read new password
1708 uint32_t new_password = 0;
1709 pwd = em4x50_sim_read_word(&new_password);
1711 // write access time twa
1712 wait_cycles(EM4X50_T_TAG_TWA);
1714 if (pwd) {
1715 em4x50_sim_send_ack();
1716 tag[EM4X50_DEVICE_PASSWORD] = reflect32(new_password);
1717 gPassword = new_password;
1718 } else {
1719 em4x50_sim_send_nak();
1720 return EM4X50_COMMAND_STANDARD_READ;
1723 // EEPROM write time
1724 // strange: need some sort of 'waveform correction', otherwise ack signal
1725 // will not be detected; sending a single "1" as last part of Twee
1726 // seems to solve the problem
1727 wait_cycles(EM4X50_T_TAG_TWEE - EM4X50_T_TAG_FULL_PERIOD);
1728 em4x50_sim_send_bit(1);
1729 em4x50_sim_send_ack();
1731 // continue with standard read mode
1732 return EM4X50_COMMAND_STANDARD_READ;
1735 void em4x50_handle_commands(int *command, uint32_t *tag) {
1737 switch (*command) {
1739 case EM4X50_COMMAND_LOGIN:
1740 *command = em4x50_sim_handle_login_command(tag);
1741 break;
1743 case EM4X50_COMMAND_RESET:
1744 *command = em4x50_sim_handle_reset_command(tag);
1745 break;
1747 case EM4X50_COMMAND_WRITE:
1748 *command = em4x50_sim_handle_write_command(tag);
1749 break;
1751 case EM4X50_COMMAND_WRITE_PASSWORD:
1752 *command = em4x50_sim_handle_writepwd_command(tag);
1753 break;
1755 case EM4X50_COMMAND_SELECTIVE_READ:
1756 *command = em4x50_sim_handle_selective_read_command(tag);
1757 break;
1759 case EM4X50_COMMAND_STANDARD_READ:
1760 LED_C_OFF();
1761 *command = em4x50_sim_handle_standard_read_command(tag);
1762 break;
1764 // bit errors during reading may lead to unknown commands
1765 // -> continue with standard read mode
1766 default:
1767 *command = EM4X50_COMMAND_STANDARD_READ;
1768 break;
1772 // simulate uploaded data in emulator memory
1773 // LED C -> reader command has been detected
1774 // LED D -> operations that require authentication are possible
1775 void em4x50_sim(uint32_t *password) {
1777 int command = PM3_ENODATA;
1779 uint8_t *em4x50_mem = BigBuf_get_EM_addr();
1780 uint32_t tag[EM4X50_NO_WORDS] = {0x0};
1782 for (int i = 0; i < EM4X50_NO_WORDS; i++)
1783 tag[i] = bytes_to_num(em4x50_mem + (i * 4), 4);
1785 // via eload uploaded dump usually does not contain a password
1786 if (tag[EM4X50_DEVICE_PASSWORD] == 0) {
1787 tag[EM4X50_DEVICE_PASSWORD] = reflect32(*password);
1790 // only if valid em4x50 data (e.g. uid == serial)
1791 if (tag[EM4X50_DEVICE_SERIAL] != tag[EM4X50_DEVICE_ID]) {
1793 // init
1794 LEDsoff();
1795 em4x50_setup_sim();
1796 gLogin = false;
1797 gWritePasswordProcess = false;
1799 // start with inital command = standard read mode
1800 command = EM4X50_COMMAND_STANDARD_READ;
1802 for (;;) {
1804 em4x50_handle_commands(&command, tag);
1806 // stop if key (pm3 button or enter key) has been pressed
1807 if (command == PM3_EOPABORTED) {
1808 break;
1811 // if timeout (e.g. no reader field) continue with standard read
1812 // mode and reset former authentication
1813 if (command == PM3_ETIMEOUT) {
1814 command = EM4X50_COMMAND_STANDARD_READ;
1815 gLogin = false;
1816 LED_D_OFF();
1821 BigBuf_free();
1822 lf_finalize();
1823 reply_ng(CMD_LF_EM4X50_SIM, command, NULL, 0);