fix one too small
[RRG-proxmark3.git] / client / src / cmdlfem4x05.c
blob2a1fcf3874478728280a67311cde2961fc35805f
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 EM4x05 commands
17 //-----------------------------------------------------------------------------
19 #include "cmdlfem4x05.h"
21 #include <stdio.h>
22 #include <string.h>
23 #include <inttypes.h>
24 #include <ctype.h>
25 #include <stdlib.h>
27 #include "util_posix.h" // msclock
28 #include "fileutils.h"
29 #include "cmdparser.h" // command_t
30 #include "comms.h"
31 #include "commonutil.h"
32 #include "common.h"
33 #include "util_posix.h"
34 #include "protocols.h"
35 #include "ui.h"
36 #include "proxgui.h"
37 #include "graph.h"
38 #include "cmddata.h"
39 #include "cmdlf.h"
40 #include "lfdemod.h"
41 #include "generator.h"
42 #include "cliparser.h"
43 #include "cmdhw.h"
44 #include "util.h"
46 //////////////// 4205 / 4305 commands
48 #define EM_PREAMBLE_LEN 8
50 typedef struct {
51 uint16_t cnt;
52 uint32_t value;
53 } em4x05_unlock_item_t;
56 static const char *em4x05_annotation[] = {"Info/User", "UID", "Password", "User", "Config", "User", "User", "User", "User", "User", "User", "User", "User", "User", "Lock", "Lock"};
57 static const char *em4x69_annotation [] = {"Info", "UID", "Password", "Lock", "Config", "User", "User", "User", "User", "User", "User", "User", "User", "User", "User", "User"};
59 static int CmdHelp(const char *Cmd);
61 static int CmdEM4x05CloneHelp(const char *Cmd) {
62 CLIParserContext *ctx;
63 CLIParserInit(&ctx, "lf em 4x05 clonehelp",
64 "Display a list of available commands for cloning specific techs on EM4305/4469 tags",
65 "lf em 4x05 clonehelp"
67 void *argtable[] = {
68 arg_param_begin,
69 arg_param_end
71 CLIExecWithReturn(ctx, Cmd, argtable, true);
72 CLIParserFree(ctx);
73 PrintAndLogEx(NORMAL, "For cloning specific techs on EM4305/4469 tags, see commands available in corresponding LF sub-menus, e.g.:");
74 PrintAndLogEx(NORMAL, _GREEN_("lf awid clone --em"));
75 PrintAndLogEx(NORMAL, _GREEN_("lf destron clone --em"));
76 PrintAndLogEx(NORMAL, _GREEN_("lf em 410x clone --em"));
77 PrintAndLogEx(NORMAL, _GREEN_("lf fdxb clone --em"));
78 PrintAndLogEx(NORMAL, _GREEN_("lf gallagher clone --em"));
79 PrintAndLogEx(NORMAL, _GREEN_("lf hid clone --em"));
80 PrintAndLogEx(NORMAL, _GREEN_("lf jablotron clone --em"));
81 PrintAndLogEx(NORMAL, _GREEN_("lf keri clone --em"));
82 PrintAndLogEx(NORMAL, _GREEN_("lf nedap clone --em"));
83 PrintAndLogEx(NORMAL, _GREEN_("lf nexwatch clone --em"));
84 PrintAndLogEx(NORMAL, _GREEN_("lf noralsy clone --em"));
85 PrintAndLogEx(NORMAL, _GREEN_("lf pac clone --em"));
86 PrintAndLogEx(NORMAL, _GREEN_("lf paradox clone --em"));
87 PrintAndLogEx(NORMAL, _GREEN_("lf presco clone --em"));
88 PrintAndLogEx(NORMAL, _GREEN_("lf pyramid clone --em"));
89 PrintAndLogEx(NORMAL, _GREEN_("lf securakey clone --em"));
90 PrintAndLogEx(NORMAL, _GREEN_("lf viking clone --em"));
91 PrintAndLogEx(NORMAL, _GREEN_("lf visa2000 clone --em"));
92 return PM3_SUCCESS;
95 // 1 = EM4x69
96 // 2 = EM4x05
97 static em_tech_type_t em_get_card_type(uint32_t config) {
98 uint8_t t = (config >> 1) & 0xF;
99 switch (t) {
100 case 4:
101 return EM_4469;
102 case 8:
103 return EM_4205;
104 case 9:
105 return EM_4305;
106 case 12:
107 return EM_4369;
109 return EM_UNKNOWN;
112 static void em4x05_print_type(em_tech_type_t ct) {
113 switch (ct) {
114 case EM_4469: {
115 PrintAndLogEx(INFO, "Identified... " _GREEN_("EM 4469"));
116 break;
118 case EM_4369: {
119 PrintAndLogEx(INFO, "Identified... " _GREEN_("EM 4369"));
120 break;
122 case EM_4205: {
123 PrintAndLogEx(INFO, "Identified... " _GREEN_("EM 4205"));
124 break;
126 case EM_4305: {
127 PrintAndLogEx(INFO, "Identified... " _GREEN_("EM 4305"));
128 break;
130 case EM_UNKNOWN:
131 default:
132 PrintAndLogEx(FAILED, "Unknown card type");
133 break;
137 static const char *em_get_card_str(uint32_t config) {
138 switch (em_get_card_type(config)) {
139 case EM_4305:
140 return "EM4305";
141 case EM_4469:
142 return "EM4469";
143 case EM_4205:
144 return "EM4205";
145 case EM_4369:
146 return "EM4369";
147 case EM_UNKNOWN:
148 break;
150 return "Unknown";
153 // even parity COLUMN
154 static bool em4x05_col_parity_test(const uint8_t *bs, size_t size, uint8_t rows, uint8_t cols, uint8_t pType) {
155 if (rows * cols > size) return false;
156 uint8_t colP = 0;
158 for (uint8_t c = 0; c < cols - 1; c++) {
159 for (uint8_t r = 0; r < rows; r++) {
160 colP ^= bs[(r * cols) + c];
162 if (colP != pType) return false;
163 colP = 0;
165 return true;
168 // download samples from device and copy to Graphbuffer
169 static bool em4x05_download_samples(void) {
171 // 8 bit preamble + 32 bit word response (max clock (128) * 40bits = 5120 samples)
172 uint8_t got[6000];
173 if (!GetFromDevice(BIG_BUF, got, sizeof(got), 0, NULL, 0, NULL, 2500, false)) {
174 PrintAndLogEx(WARNING, "(em_download_samples) command execution time out");
175 return false;
178 setGraphBuffer(got, sizeof(got));
179 // set signal properties low/high/mean/amplitude and is_noise detection
180 computeSignalProperties(got, sizeof(got));
181 RepaintGraphWindow();
182 if (getSignalProperties()->isnoise) {
183 PrintAndLogEx(DEBUG, "No tag found - signal looks like noise");
184 return false;
186 return true;
189 // em_demod
190 static int doPreambleSearch(size_t *startIdx) {
192 // sanity check
193 if (g_DemodBufferLen < EM_PREAMBLE_LEN) {
194 PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 DemodBuffer too small");
195 return PM3_ESOFT;
198 // set size to 11 to only test first 3 positions for the preamble
199 // do not set it too long else an error preamble followed by 010 could be seen as success.
200 size_t size = (11 > g_DemodBufferLen) ? g_DemodBufferLen : 11;
201 *startIdx = 0;
203 // skip first two 0 bits as they might have been missed in the demod
204 uint8_t preamble[EM_PREAMBLE_LEN] = {0, 0, 0, 0, 1, 0, 1, 0};
205 if (!preambleSearchEx(g_DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, startIdx, true)) {
207 uint8_t errpreamble[EM_PREAMBLE_LEN] = {0, 0, 0, 0, 0, 0, 0, 1};
208 if (!preambleSearchEx(g_DemodBuffer, errpreamble, EM_PREAMBLE_LEN, &size, startIdx, true)) {
209 PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 preamble not found :: %zu", *startIdx);
210 return PM3_ESOFT;
212 return PM3_EFAILED; // Error preamble found
215 return PM3_SUCCESS;
218 static bool detectFSK(void) {
219 // detect fsk clock
220 if (GetFskClock("", false) == 0) {
221 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: FSK clock failed");
222 return false;
224 // demod
225 int ans = FSKrawDemod(0, 0, 0, 0, false);
226 if (ans != PM3_SUCCESS) {
227 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: FSK Demod failed");
228 return false;
230 return true;
232 // PSK clocks should be easy to detect ( but difficult to demod a non-repeating pattern... )
233 static bool detectPSK(void) {
234 int ans = GetPskClock("", false);
235 if (ans <= 0) {
236 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: PSK clock failed");
237 return false;
239 //demod
240 //try psk1 -- 0 0 6 (six errors?!?)
241 ans = PSKDemod(0, 0, 6, false);
242 if (ans != PM3_SUCCESS) {
243 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: PSK1 Demod failed");
244 return false;
247 // In order to hit the INVERT, we need to demod here
248 if (g_DemodBufferLen < 11) {
249 PrintAndLogEx(INFO, " demod buff len less than PREAMBLE lEN");
252 size_t size = (11 > g_DemodBufferLen) ? g_DemodBufferLen : 11;
253 size_t startIdx = 0;
254 uint8_t preamble[EM_PREAMBLE_LEN] = {0, 0, 0, 0, 1, 0, 1, 0};
255 if (!preambleSearchEx(g_DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, &startIdx, true)) {
257 //try psk1 inverted
258 ans = PSKDemod(0, 1, 6, false);
259 if (ans != PM3_SUCCESS) {
260 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: PSK1 inverted Demod failed");
261 return false;
264 if (!preambleSearchEx(g_DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, &startIdx, true)) {
265 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: PSK1 inverted Demod failed 2");
266 return false;
270 // either PSK1 or PSK1 inverted is ok from here.
271 // lets check PSK2 later.
272 return true;
274 // try manchester - NOTE: ST only applies to T55x7 tags.
275 static bool detectASK_MAN(void) {
276 bool stcheck = false;
277 if (ASKDemod_ext(0, 0, 50, 0, false, false, false, 1, &stcheck) != PM3_SUCCESS) {
278 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/Manchester Demod failed");
279 return false;
281 return true;
284 static bool detectASK_BI(void) {
285 int ans = ASKbiphaseDemod(0, 0, 1, 50, false);
286 if (ans != PM3_SUCCESS) {
287 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/biphase normal demod failed");
289 ans = ASKbiphaseDemod(0, 1, 1, 50, false);
290 if (ans != PM3_SUCCESS) {
291 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/biphase inverted demod failed");
292 return false;
295 return true;
297 static bool detectNRZ(void) {
298 int ans = NRZrawDemod(0, 0, 1, false);
299 if (ans != PM3_SUCCESS) {
300 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: NRZ normal demod failed");
302 ans = NRZrawDemod(0, 1, 1, false);
303 if (ans != PM3_SUCCESS) {
304 PrintAndLogEx(DEBUG, "DEBUG: Error - EM: NRZ inverted demod failed");
305 return false;
309 return true;
312 // param: idx - start index in demoded data.
313 static int em4x05_setdemod_buffer(uint32_t *word, size_t idx) {
315 //test for even parity bits.
316 uint8_t parity[45] = {0};
317 memcpy(parity, g_DemodBuffer, 45);
318 if (!em4x05_col_parity_test(g_DemodBuffer + idx + EM_PREAMBLE_LEN, 45, 5, 9, 0)) {
319 PrintAndLogEx(DEBUG, "DEBUG: Error - End Parity check failed");
320 return PM3_ESOFT;
323 // test for even parity bits and remove them. (leave out the end row of parities so 36 bits)
324 if (!removeParity(g_DemodBuffer, idx + EM_PREAMBLE_LEN, 9, 0, 36)) {
325 PrintAndLogEx(DEBUG, "DEBUG: Error - EM, failed removing parity");
326 return PM3_ESOFT;
328 setDemodBuff(g_DemodBuffer, 32, 0);
329 *word = bytebits_to_byteLSBF(g_DemodBuffer, 32);
330 return PM3_SUCCESS;
333 // FSK, PSK, ASK/MANCHESTER, ASK/BIPHASE, ASK/DIPHASE, NRZ
334 // should cover 90% of known used configs
335 // the rest will need to be manually demoded for now...
336 static int em4x05_demod_resp(uint32_t *word, bool onlyPreamble) {
337 *word = 0;
338 int res;
339 size_t idx = 0;
340 bool found_err = false;
341 do {
342 if (detectASK_MAN()) {
343 res = doPreambleSearch(&idx);
344 if (res == PM3_SUCCESS)
345 break;
346 if (res == PM3_EFAILED)
347 // go on, maybe it's false positive and another modulation will work
348 found_err = true;
350 if (detectASK_BI()) {
351 res = doPreambleSearch(&idx);
352 if (res == PM3_SUCCESS)
353 break;
354 if (res == PM3_EFAILED)
355 found_err = true;
357 if (detectNRZ()) {
358 res = doPreambleSearch(&idx);
359 if (res == PM3_SUCCESS)
360 break;
361 if (res == PM3_EFAILED)
362 found_err = true;
364 if (detectFSK()) {
365 res = doPreambleSearch(&idx);
366 if (res == PM3_SUCCESS)
367 break;
368 if (res == PM3_EFAILED)
369 found_err = true;
371 if (detectPSK()) {
372 res = doPreambleSearch(&idx);
373 if (res == PM3_SUCCESS)
374 break;
376 if (res == PM3_EFAILED)
377 found_err = true;
379 psk1TOpsk2(g_DemodBuffer, g_DemodBufferLen);
380 res = doPreambleSearch(&idx);
381 if (res == PM3_SUCCESS)
382 break;
384 if (res == PM3_EFAILED)
385 found_err = true;
388 if (found_err)
389 return PM3_EFAILED;
391 return PM3_ESOFT;
392 } while (0);
394 if (onlyPreamble)
395 return PM3_SUCCESS;
397 res = em4x05_setdemod_buffer(word, idx);
398 if (res == PM3_SUCCESS)
399 return res;
401 if (found_err)
402 return PM3_EFAILED;
403 return res;
406 //////////////// 4205 / 4305 commands
408 static bool em4x05_verify_write(uint8_t addr, uint32_t pwd, bool use_pwd, uint32_t data) {
409 uint32_t r = 0;
410 int res = em4x05_read_word_ext(addr, pwd, use_pwd, &r);
411 if (res == PM3_SUCCESS) {
412 PrintAndLogEx(INFO, "%08x == %08x", r, data);
413 return (r == data);
415 return false;
418 int em4x05_clone_tag(uint32_t *blockdata, uint8_t numblocks, uint32_t pwd, bool use_pwd) {
420 if (blockdata == NULL)
421 return PM3_EINVARG;
423 if (numblocks < 1 || numblocks > 8)
424 return PM3_EINVARG;
426 // fast push mode
427 g_conn.block_after_ACK = true;
428 int res = 0;
429 for (int8_t i = 0; i < numblocks; i++) {
431 // Disable fast mode on last packet
432 if (i == numblocks - 1) {
433 g_conn.block_after_ACK = false;
436 if (i != 0) {
437 blockdata[i] = reflect(blockdata[i], 32);
440 res = em4x05_write_word_ext(4 + i, pwd, use_pwd, blockdata[i]);
441 if (res != PM3_SUCCESS) {
442 PrintAndLogEx(FAILED, "(em4x05_clone_tag) Time out writing to tag");
443 return res;
447 res = 0;
448 for (int8_t i = 0; i < numblocks; i++) {
449 if (em4x05_verify_write(4 + i, use_pwd, pwd, blockdata[i]) == false) {
450 res++;
454 if (res == 0)
455 PrintAndLogEx(SUCCESS, "Data written and verified");
457 return PM3_SUCCESS;
460 static int em4x05_login_ext(uint32_t pwd) {
462 struct {
463 uint32_t password;
464 } PACKED payload;
466 payload.password = pwd;
468 clearCommandBuffer();
469 SendCommandNG(CMD_LF_EM4X_LOGIN, (uint8_t *)&payload, sizeof(payload));
470 PacketResponseNG resp;
471 if (WaitForResponseTimeout(CMD_LF_EM4X_LOGIN, &resp, 10000) == false) {
472 PrintAndLogEx(WARNING, "(em4x05_login_ext) timeout while waiting for reply.");
473 return PM3_ETIMEOUT;
476 if (em4x05_download_samples() == false) {
477 return PM3_ESOFT;
479 uint32_t word;
480 return em4x05_demod_resp(&word, true);
483 int em4x05_read_word_ext(uint8_t addr, uint32_t pwd, bool use_pwd, uint32_t *word) {
485 struct {
486 uint32_t password;
487 uint8_t address;
488 uint8_t usepwd;
489 } PACKED payload;
491 payload.password = pwd;
492 payload.address = addr;
493 payload.usepwd = use_pwd;
495 clearCommandBuffer();
496 SendCommandNG(CMD_LF_EM4X_READWORD, (uint8_t *)&payload, sizeof(payload));
497 PacketResponseNG resp;
498 if (WaitForResponseTimeout(CMD_LF_EM4X_READWORD, &resp, 10000) == false) {
499 PrintAndLogEx(WARNING, "(em4x05_read_word_ext) timeout while waiting for reply.");
500 return PM3_ETIMEOUT;
503 if (em4x05_download_samples() == false) {
504 return PM3_ESOFT;
506 return em4x05_demod_resp(word, false);
509 int em4x05_write_word_ext(uint8_t addr, uint32_t pwd, bool use_pwd, uint32_t data) {
510 struct {
511 uint32_t password;
512 uint32_t data;
513 uint8_t address;
514 uint8_t usepwd;
515 } PACKED payload;
517 payload.password = pwd;
518 payload.data = data;
519 payload.address = addr;
520 payload.usepwd = use_pwd;
522 clearCommandBuffer();
523 SendCommandNG(CMD_LF_EM4X_WRITEWORD, (uint8_t *)&payload, sizeof(payload));
524 PacketResponseNG resp;
525 if (WaitForResponseTimeout(CMD_LF_EM4X_WRITEWORD, &resp, 2000) == false) {
526 PrintAndLogEx(ERR, "Error occurred, device did not respond during write operation.");
527 return PM3_ETIMEOUT;
529 return PM3_SUCCESS;
532 static int em4x05_protect(uint32_t pwd, bool use_pwd, uint32_t data) {
533 struct {
534 uint32_t password;
535 uint32_t data;
536 uint8_t usepwd;
537 } PACKED payload;
539 payload.password = pwd;
540 payload.data = data;
541 payload.usepwd = use_pwd;
543 clearCommandBuffer();
544 SendCommandNG(CMD_LF_EM4X_PROTECTWORD, (uint8_t *)&payload, sizeof(payload));
545 PacketResponseNG resp;
546 if (WaitForResponseTimeout(CMD_LF_EM4X_PROTECTWORD, &resp, 2000) == false) {
547 PrintAndLogEx(ERR, "Error occurred, device did not respond during write operation.");
548 return PM3_ETIMEOUT;
550 return PM3_SUCCESS;
553 static const char *print_em4x05_known(uint32_t word) {
555 // EM4305_DEFAULT_CONFIG_BLOCK same as PRESCO
556 if ((word & EM4305_PRESCO_CONFIG_BLOCK) == EM4305_PRESCO_CONFIG_BLOCK) {
557 return "EM4305 DEFAULT / PRESCO";
560 // EM4305_PAXTON_CONFIG_BLOCK same as unique
561 if ((word & EM4305_EM_UNIQUE_CONFIG_BLOCK) == EM4305_EM_UNIQUE_CONFIG_BLOCK) {
562 return "EM UNIQUE / PAXTON";
565 if ((word & EM4305_VISA2000_CONFIG_BLOCK) == EM4305_VISA2000_CONFIG_BLOCK) {
566 return "VISA2000";
569 if ((word & EM4305_VIKING_CONFIG_BLOCK) == EM4305_VIKING_CONFIG_BLOCK) {
570 return "VIKING";
573 if ((word & EM4305_NORALSY_CONFIG_BLOCK) == EM4305_NORALSY_CONFIG_BLOCK) {
574 return "NORALSY";
577 if ((word & EM4305_SECURAKEY_CONFIG_BLOCK) == EM4305_SECURAKEY_CONFIG_BLOCK) {
578 return "SECURAKEY";
581 // EM4305_HID_26_CONFIG_BLOCK sane as AWID
582 // EM4305_PARADOX_CONFIG_BLOCK same as AWID
583 if ((word & EM4305_AWID_CONFIG_BLOCK) == EM4305_AWID_CONFIG_BLOCK) {
584 return "HID26 / PARADOX / AWID";
587 if ((word & EM4305_PYRAMID_CONFIG_BLOCK) == EM4305_PYRAMID_CONFIG_BLOCK) {
588 return "PYRAMID";
591 if ((word & EM4305_IOPROX_CONFIG_BLOCK) == EM4305_IOPROX_CONFIG_BLOCK) {
592 return "IOPROX";
595 // EM4305_KERI_CONFIG_BLOCK same as Indala
596 if ((word & EM4305_INDALA_64_CONFIG_BLOCK) == EM4305_INDALA_64_CONFIG_BLOCK) {
597 return "INDALA 64 / KERI";
600 if ((word & EM4305_INDALA_224_CONFIG_BLOCK) == EM4305_INDALA_224_CONFIG_BLOCK) {
601 return "INDALA 224";
604 if ((word & EM4305_MOTOROLA_CONFIG_BLOCK) == EM4305_MOTOROLA_CONFIG_BLOCK) {
605 return "MOTOROLA";
608 if ((word & EM4305_NEXWATCH_CONFIG_BLOCK) == EM4305_NEXWATCH_CONFIG_BLOCK) {
609 return "NEXWATCH";
612 // EM4305_NEDAP_64_CONFIG_BLOCK same as jablotron
613 if ((word & EM4305_JABLOTRON_CONFIG_BLOCK) == EM4305_JABLOTRON_CONFIG_BLOCK) {
614 return "JABLOTRON / NEDAP 64";
617 if ((word & EM4305_GUARDPROXII_CONFIG_BLOCK) == EM4305_GUARDPROXII_CONFIG_BLOCK) {
618 return "GUARD PROXII";
621 if ((word & EM4305_NEDAP_128_CONFIG_BLOCK) == EM4305_NEDAP_128_CONFIG_BLOCK) {
622 return "NEDAP 128";
625 if ((word & EM4305_PAC_CONFIG_BLOCK) == EM4305_PAC_CONFIG_BLOCK) {
626 return "PAC/Stanley";
629 if ((word & EM4305_VERICHIP_CONFIG_BLOCK) == EM4305_VERICHIP_CONFIG_BLOCK) {
630 return "VERICHIP";
632 return "";
635 static void printEM4x05config(em_tech_type_t card_type, uint32_t wordData) {
636 uint16_t datarate = (((wordData & 0x3F) + 1) * 2);
637 uint8_t encoder = ((wordData >> 6) & 0xF);
638 char enc[14];
639 memset(enc, 0, sizeof(enc));
641 uint8_t PSKcf = (wordData >> 10) & 0x3;
642 char cf[20];
643 memset(cf, 0, sizeof(cf));
645 uint8_t delay = (wordData >> 12) & 0x3;
646 char cdelay[33];
647 memset(cdelay, 0, sizeof(cdelay));
649 uint8_t numblks = EM4x05_GET_NUM_BLOCKS(wordData);
651 uint8_t LWR = numblks + 5 - 1; //last word read
652 switch (encoder) {
653 case 0:
654 snprintf(enc, sizeof(enc), "NRZ");
655 break;
656 case 1:
657 snprintf(enc, sizeof(enc), "Manchester");
658 break;
659 case 2:
660 snprintf(enc, sizeof(enc), "Biphase");
661 break;
662 case 3:
663 snprintf(enc, sizeof(enc), "Miller");
664 break;
665 case 4:
666 snprintf(enc, sizeof(enc), "PSK1");
667 break;
668 case 5:
669 snprintf(enc, sizeof(enc), "PSK2");
670 break;
671 case 6:
672 snprintf(enc, sizeof(enc), "PSK3");
673 break;
674 case 7:
675 snprintf(enc, sizeof(enc), "Unknown");
676 break;
677 case 8:
678 snprintf(enc, sizeof(enc), "FSK1");
679 break;
680 case 9:
681 snprintf(enc, sizeof(enc), "FSK2");
682 break;
683 default:
684 snprintf(enc, sizeof(enc), "Unknown");
685 break;
688 switch (PSKcf) {
689 case 0:
690 snprintf(cf, sizeof(cf), "PSK RF/2");
691 break;
692 case 1:
693 snprintf(cf, sizeof(cf), "PSK RF/8");
694 break;
695 case 2:
696 snprintf(cf, sizeof(cf), "PSK RF/4");
697 break;
698 case 3:
699 snprintf(cf, sizeof(cf), "unknown");
700 break;
703 switch (delay) {
704 case 0:
705 snprintf(cdelay, sizeof(cdelay), "no delay");
706 break;
707 case 1:
708 snprintf(cdelay, sizeof(cdelay), "BP/8 or 1/8th bit period delay");
709 break;
710 case 2:
711 snprintf(cdelay, sizeof(cdelay), "BP/4 or 1/4th bit period delay");
712 break;
713 case 3:
714 snprintf(cdelay, sizeof(cdelay), "no delay");
715 break;
717 uint8_t readLogin = (wordData & EM4x05_READ_LOGIN_REQ) >> 18;
718 uint8_t readHKL = (wordData & EM4x05_READ_HK_LOGIN_REQ) >> 19;
719 uint8_t writeLogin = (wordData & EM4x05_WRITE_LOGIN_REQ) >> 20;
720 uint8_t writeHKL = (wordData & EM4x05_WRITE_HK_LOGIN_REQ) >> 21;
721 uint8_t raw = (wordData & EM4x05_READ_AFTER_WRITE) >> 22;
722 uint8_t disable = (wordData & EM4x05_DISABLE_ALLOWED) >> 23;
723 uint8_t rtf = (wordData & EM4x05_READER_TALK_FIRST) >> 24;
724 uint8_t invert = (wordData & EM4x05_INVERT) >> 25;
725 uint8_t pigeon = (wordData & EM4x05_PIGEON) >> 26;
727 PrintAndLogEx(NORMAL, "");
728 PrintAndLogEx(INFO, "--- " _CYAN_("Config Information") " ------------------------");
729 PrintAndLogEx(INFO, "Data rate........ "_YELLOW_("RF/%u") " ( %02u )", datarate, (wordData & 0x3F));
730 PrintAndLogEx(INFO, "Encoder.......... " _YELLOW_("%s") " ( %u )", enc, encoder);
731 PrintAndLogEx(INFO, " ident..... " _YELLOW_("%s"), print_em4x05_known(wordData));
732 PrintAndLogEx(INFO, "Default read..... " _YELLOW_("%u") " blocks", numblks);
733 PrintAndLogEx(INFO, "Last word read... " _YELLOW_("%u") " th block", LWR);
735 uint8_t bits[32 + 1] = {0};
736 num_to_bytebitsLSBF(wordData, 32, bits);
737 const char *bs = sprint_bytebits_bin(bits, 32);
739 PrintAndLogEx(INFO, "");
740 PrintAndLogEx(INFO, "Config........... %08X", wordData);
741 PrintAndLogEx(INFO, "--------------------------------");
742 PrintAndLogEx(INFO, "0 LSB 31");
743 PrintAndLogEx(INFO, "%s", bs);
745 char datarate_str[10] = {0};
746 snprintf(datarate_str, sizeof(datarate_str), "RF/%u", datarate);
748 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 0, 6, datarate_str));
749 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 6, 4, enc));
751 if (card_type == EM_4369 || card_type == EM_4469) {
752 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 10, 2, cf));
753 } else {
754 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((PSKcf) ? C_RED : C_NONE, bs, 32, 10, 2, "Must be 0"));
757 if (card_type == EM_4305) {
758 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 12, 2, "Delayed ON"));
759 } else {
760 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((delay) ? C_RED : C_NONE, bs, 32, 12, 2, "Must be 0"));
763 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 14, 4, "LWR, Last default read word "));
765 if (readLogin) {
766 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_RED, bs, 32, 18, 1, "Read login required"));
767 } else {
768 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_GREEN, bs, 32, 18, 1, "Read login not required"));
771 if (card_type == EM_4369 || card_type == EM_4469) {
772 if (readHKL) {
773 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_RED, bs, 32, 19, 1, "Read HK, login required"));
774 } else {
775 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_GREEN, bs, 32, 19, 1, "Read HK, not required"));
777 } else {
778 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((readHKL) ? C_RED : C_NONE, bs, 32, 19, 1, "Must be 0"));
781 if (writeLogin) {
782 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_RED, bs, 32, 20, 1, "Write login required"));
783 } else {
784 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_GREEN, bs, 32, 20, 1, "Write login not required"));
787 if (card_type == EM_4369 || card_type == EM_4469) {
788 if (writeHKL) {
789 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 21, 1, "Write HK, login required"));
790 } else {
791 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 21, 1, "Write HK, login not required"));
793 } else {
794 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((writeHKL) ? C_RED : C_NONE, bs, 32, 21, 1, "Must be 0"));
797 if (card_type == EM_4369 || card_type == EM_4469) {
798 if (raw) {
799 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 22, 1, "Read after write is on"));
800 } else {
801 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 22, 1, "Read after write is OFF"));
803 } else {
804 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((raw) ? C_RED : C_NONE, bs, 32, 22, 1, "Must be 0"));
807 if (disable) {
808 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 23, 1, "Disable command accepted"));
809 } else {
810 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 23, 1, "Disable command not accepted"));
813 if (rtf) {
814 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_RED, bs, 32, 24, 1, "R.T.F, Reader talk first enabled"));
815 } else {
816 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 24, 1, "R.T.F. Reader talk first disabled"));
819 if (card_type == EM_4369) {
820 if (invert) {
821 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_RED, bs, 32, 25, 1, "Invert data? yes"));
822 } else {
823 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 25, 1, "Invert data? no"));
825 } else {
826 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((invert) ? C_RED : C_NONE, bs, 32, 25, 1, "Must be 0"));
829 if (card_type == EM_4305) {
830 if (pigeon) {
831 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_YELLOW, bs, 32, 26, 1, "Pigeon mode enabled"));
832 } else {
833 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 26, 1, "Pigeon mode disabled"));
835 } else {
836 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin((pigeon) ? C_RED : C_NONE, bs, 32, 26, 1, "Must be 0"));
839 PrintAndLogEx(INFO, "%s", sprint_breakdown_bin(C_NONE, bs, 32, 27, 5, "RFU, Reserved for future use"));
840 PrintAndLogEx(INFO, "--------------------------------");
843 static void printEM4x05info(uint32_t block0, uint32_t serial) {
845 uint8_t chipType = (block0 >> 1) & 0xF;
846 uint8_t cap = (block0 >> 5) & 3;
847 uint16_t custCode = (block0 >> 9) & 0x2FF;
849 /* bits
850 // 0, rfu
851 // 1,2,3,4 chip type
852 // 5,6 resonant cap
853 // 7,8, rfu
854 // 9 - 18 customer code
855 // 19, rfu
857 98765432109876543210
858 001000000000
859 // 00100000000001111000
860 xxx----
861 // 1100
862 // 011
863 // 00100000000
866 PrintAndLogEx(NORMAL, "");
867 PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------");
869 PrintAndLogEx(SUCCESS, "Chip type..... " _YELLOW_("%s"), em_get_card_str(block0));
870 if (serial != 0) {
871 PrintAndLogEx(SUCCESS, "Serialno...... " _YELLOW_("%08X"), serial);
873 PrintAndLogEx(SUCCESS, "Block0........ %08x", block0);
875 switch (cap) {
876 case 3:
877 PrintAndLogEx(SUCCESS, "Cap type...... 330pF ( %u )", cap);
878 break;
879 case 2:
880 PrintAndLogEx(SUCCESS, "Cap type...... %spF ( %u )", (chipType == 4) ? "75" : "210", cap);
881 break;
882 case 1:
883 PrintAndLogEx(SUCCESS, "Cap type...... 250pF ( %u )", cap);
884 break;
885 case 0:
886 PrintAndLogEx(SUCCESS, "Cap type...... no resonant capacitor ( %u )", cap);
887 break;
888 default:
889 PrintAndLogEx(SUCCESS, "Cap type...... unknown ( %u )", cap);
890 break;
893 PrintAndLogEx(SUCCESS, "Custum code... %s ( %u )", (custCode == 0x200) ? "default" : "unknown", custCode);
896 static void printEM4x05ProtectionBits(uint32_t word, uint8_t addr) {
897 PrintAndLogEx(NORMAL, "");
898 PrintAndLogEx(INFO, "--- " _CYAN_("Protection") " --------------------------------");
899 PrintAndLogEx(INFO, "");
900 PrintAndLogEx(INFO, "Protection word "_YELLOW_("%i") " - %08X", addr, word);
901 PrintAndLogEx(INFO, "");
902 PrintAndLogEx(INFO, " # | status");
903 PrintAndLogEx(INFO, "----+-------------");
904 for (uint8_t i = 0; i < 15; i++) {
905 PrintAndLogEx(INFO, " %02u | %s", i, ((1 << i) & word) ? _RED_("write locked") : "unlocked");
906 if (i == 14) {
907 PrintAndLogEx(INFO, " %02u | %s", i + 1, ((1 << i) & word) ? _RED_("write locked") : "unlocked");
910 PrintAndLogEx(INFO, "----+-------------");
913 //quick test for EM4x05/EM4x69 tag
914 bool em4x05_isblock0(uint32_t *word) {
915 return (em4x05_read_word_ext(0, 0, false, word) == PM3_SUCCESS);
918 static bool is_cancelled(void) {
919 if (kbd_enter_pressed()) {
920 PrintAndLogEx(WARNING, "\naborted via keyboard!\n");
921 return true;
923 return false;
926 static void em4x05_print_hdr(void) {
927 PrintAndLogEx(NORMAL, "");
928 PrintAndLogEx(INFO, "Addr | data | ascii |lck| info");
929 PrintAndLogEx(INFO, "-----+----------+-------+---+-----");
932 static void em4x05_print_footer(void) {
933 PrintAndLogEx(INFO, "-----+----------+-------+---+-----");
934 PrintAndLogEx(NORMAL, "");
937 static void em4x05_print_blocks(em_tech_type_t cardtype, uint8_t *data, uint8_t dlen) {
939 // must have 4 byte alignment
940 if ((data == NULL) || (dlen % EM4X05_BLOCK_SIZE) != 0) {
941 return;
944 uint32_t *d = (void *)data;
946 uint8_t i;
947 for (i = 0; i < (dlen >> 2); i++) {
948 d[i] = BSWAP_32(d[i]);
950 i = 0;
952 bool got_lock_bits = false;
953 uint32_t lock = 0;
954 bool p15_active = false;
955 uint8_t lockbit;
956 uint8_t rev[EM4X05_BLOCK_SIZE] = {0};
958 if (cardtype == EM_4205 || cardtype == EM_4305) {
960 // which protection block is ACTIVE?
961 if ((d[EM4305_PROT1_BLOCK] & 0x00008000) != 0x00) {
962 got_lock_bits = true;
963 lock = d[EM4305_PROT1_BLOCK];
964 } else if ((d[EM4305_PROT2_BLOCK] & 0x00008000) != 0x00) {
965 // assume block 15 is the current lock block
966 p15_active = true;
967 got_lock_bits = true;
968 lock = d[EM4305_PROT2_BLOCK];
971 // Now read blocks 0 - 13 as we have 14 and 15
972 for (; i < 14; i++) {
974 lockbit = ((lock >> i) & 1);
976 // hack: since sprint_ascii doesnt handle MSB/LSB swaps
977 reverse_array_copy(data + (i * EM4X05_BLOCK_SIZE), EM4X05_BLOCK_SIZE, rev);
979 if (i == EM_SERIAL_BLOCK) {
980 PrintAndLogEx(INFO, " %02u | " _GREEN_("%08X") " | %s | %s | " _GREEN_("%s")
982 , d[i]
983 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
984 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
985 , em4x05_annotation[i]
987 } else if (i == EM_CONFIG_BLOCK) {
988 PrintAndLogEx(INFO, " %02u | " _YELLOW_("%08X") " | %s | %s | " _YELLOW_("%s")
990 , d[i]
991 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
992 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
993 , em4x05_annotation[i]
995 } else {
997 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %s"
999 , d[i]
1000 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1001 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1002 , em4x05_annotation[i]
1007 // Print blocks 14 and 15
1008 // Both lock bits are protected with bit idx 14 (special case)
1010 i = 14;
1011 lockbit = ((lock >> i) & 1);
1012 reverse_array_copy(data + (i * EM4X05_BLOCK_SIZE), EM4X05_BLOCK_SIZE, rev);
1014 if (p15_active) {
1015 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %-10s %s"
1017 , d[i]
1018 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1019 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1020 , em4x05_annotation[i]
1021 , ""
1023 } else {
1024 PrintAndLogEx(INFO, " %02u | " _GREEN_("%08X") " | %s | %s | %-10s %s"
1026 , d[i]
1027 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1028 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1029 , em4x05_annotation[i]
1030 , _GREEN_("active")
1034 i = 15;
1035 // beware lock bit of word15 is pr14
1036 lockbit = (d[EM4305_PROT1_BLOCK] >> 14) & 1;
1037 reverse_array_copy(data + (i * EM4X05_BLOCK_SIZE), EM4X05_BLOCK_SIZE, rev);
1039 if (p15_active) {
1040 PrintAndLogEx(INFO, " %02u | " _GREEN_("%08X") " | %s | %s | %-10s %s"
1042 , d[i]
1043 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1044 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1045 , em4x05_annotation[i]
1046 , _GREEN_("active")
1048 } else {
1049 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %-10s %s"
1051 , d[i]
1052 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1053 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1054 , em4x05_annotation[i]
1055 , ""
1060 if (cardtype == EM_4369 || cardtype == EM_4469) {
1062 // To flag any blocks locked we need to read block 3 first
1063 // don't swap endian until we get block lock flags.
1064 // data[EM4469_PROT_BLOCK] = word;
1065 for (; i < 16; i++) {
1067 lockbit = ((d[EM4469_PROT_BLOCK] >> (i * 2)) & 3);
1068 reverse_array_copy(data + (i * EM4X05_BLOCK_SIZE), EM4X05_BLOCK_SIZE, rev);
1070 if (i == EM_SERIAL_BLOCK) {
1071 PrintAndLogEx(INFO, " %02u | " _GREEN_("%08X") " | %s | %s | " _GREEN_("%s")
1073 , d[i]
1074 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1075 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1076 , em4x69_annotation[i]
1078 } else if (i == EM_CONFIG_BLOCK) {
1079 PrintAndLogEx(INFO, " %02u | " _YELLOW_("%08X") " | %s | %s | " _YELLOW_("%s")
1081 , d[i]
1082 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1083 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1084 , em4x69_annotation[i]
1086 } else {
1087 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %s"
1089 , d[i]
1090 , sprint_ascii(rev, EM4X05_BLOCK_SIZE)
1091 , (got_lock_bits) ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?")
1092 , em4x69_annotation[i]
1099 int CmdEM4x05Demod(const char *Cmd) {
1100 CLIParserContext *ctx;
1101 CLIParserInit(&ctx, "lf em 4x05 demod",
1102 "Try to find EM 4x05 preamble, if found decode / descramble data",
1103 "lf em 4x05 demod"
1106 void *argtable[] = {
1107 arg_param_begin,
1108 arg_param_end
1110 CLIExecWithReturn(ctx, Cmd, argtable, true);
1111 CLIParserFree(ctx);
1112 uint32_t dummy = 0;
1113 return em4x05_demod_resp(&dummy, false);
1116 int CmdEM4x05Dump(const char *Cmd) {
1118 CLIParserContext *ctx;
1119 CLIParserInit(&ctx, "lf em 4x05 dump",
1120 "Dump EM4x05/EM4x69. Tag must be on antenna.",
1121 "lf em 4x05 dump\n"
1122 "lf em 4x05 dump -p 11223344\n"
1123 "lf em 4x05 dump -f myfile -p 11223344"
1126 void *argtable[] = {
1127 arg_param_begin,
1128 arg_str0("p", "pwd", "<hex>", "password (00000000)"),
1129 arg_str0("f", "file", "<fn>", "override filename prefix (optional). Default is based on UID"),
1130 arg_lit0(NULL, "ns", "no save to file"),
1131 arg_param_end
1133 CLIExecWithReturn(ctx, Cmd, argtable, true);
1135 uint64_t inputpwd = arg_get_u64_hexstr_def(ctx, 1, 0xFFFFFFFFFFFFFFFF);
1136 int fnlen = 0;
1137 char filename[FILE_PATH_SIZE] = {0};
1138 CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
1139 bool nosave = arg_get_lit(ctx, 3);
1140 CLIParserFree(ctx);
1142 // sanitize checks
1143 uint32_t block0 = 0;
1144 // read word 0 (chip info)
1145 // block 0 can be read even without a password.
1146 if (em4x05_isblock0(&block0) == false) {
1147 return PM3_ESOFT;
1150 uint32_t pwd = 0;
1151 bool usePwd = false;
1152 if (inputpwd != 0xFFFFFFFFFFFFFFFF) {
1154 if (inputpwd & 0xFFFFFFFF00000000) {
1155 PrintAndLogEx(FAILED, "Pwd too large");
1156 return PM3_EINVARG;
1159 usePwd = true;
1160 pwd = (inputpwd & 0xFFFFFFFF);
1163 // EM4305 vs EM4469
1164 em_tech_type_t card_type = em_get_card_type(block0);
1166 PrintAndLogEx(INFO, "Found a " _GREEN_("%s") " tag", em_get_card_str(block0));
1168 if (usePwd) {
1169 // Test first if the password is correct
1170 int status = em4x05_login_ext(pwd);
1171 if (status == PM3_SUCCESS) {
1172 PrintAndLogEx(INFO, "password ( " _GREEN_("ok") " )");
1173 } else if (status == PM3_EFAILED) {
1174 PrintAndLogEx(WARNING, "password ( " _RED_("fail") ") , will try without password");
1175 usePwd = false;
1176 } else if (status != PM3_EFAILED) {
1177 PrintAndLogEx(WARNING, "Login attempt: no answer from tag");
1178 return status;
1182 em4x05_print_hdr();
1184 uint8_t bytes[4] = {0};
1185 uint32_t data[16] = {0};
1187 uint32_t lock_bits = 0x00; // no blocks locked
1188 bool gotLockBits = false;
1189 uint8_t addr = 0;
1190 uint32_t word = 0;
1191 int success = PM3_SUCCESS;
1193 if (card_type == EM_4205 || card_type == EM_4305 || card_type == EM_UNKNOWN) {
1194 bool lockInPW2 = false;
1195 // To flag any blocks locked we need to read blocks 14 and 15 first
1196 // don't swap endian until we get block lock flags.
1197 int status14 = em4x05_read_word_ext(EM4305_PROT1_BLOCK, pwd, usePwd, &word);
1198 if (status14 == PM3_SUCCESS) {
1199 if ((word & 0x00008000) != 0x00) {
1200 lock_bits = word;
1201 gotLockBits = true;
1203 data[EM4305_PROT1_BLOCK] = word;
1204 } else {
1205 success = PM3_ESOFT; // If any error ensure fail is set so not to save invalid data
1208 int status15 = em4x05_read_word_ext(EM4305_PROT2_BLOCK, pwd, usePwd, &word);
1209 if (status15 == PM3_SUCCESS) {
1210 if ((word & 0x00008000) != 0x00) { // assume block 15 is the current lock block
1211 lock_bits = word;
1212 gotLockBits = true;
1213 lockInPW2 = true;
1215 data[EM4305_PROT2_BLOCK] = word;
1216 } else {
1217 success = PM3_ESOFT; // If any error ensure fail is set so not to save invalid data
1220 uint32_t lockbit;
1221 // Now read blocks 0 - 13 as we have 14 and 15
1222 for (; addr < 14; addr++) {
1224 lockbit = (lock_bits >> addr) & 1;
1226 if (addr == 2) {
1227 if (usePwd) {
1228 data[addr] = BSWAP_32(pwd);
1229 num_to_bytes(pwd, 4, bytes);
1230 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %s", addr, pwd, sprint_ascii(bytes, 4), gotLockBits ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?"), em4x05_annotation[addr]);
1231 } else {
1232 data[addr] = 0x00; // Unknown password, but not used to set to zeros
1233 PrintAndLogEx(INFO, " %02u | | | | %-10s " _YELLOW_("write only"), addr, em4x05_annotation[addr]);
1235 } else {
1236 // success &= em4x05_read_word_ext(addr, pwd, usePwd, &word);
1237 int status = em4x05_read_word_ext(addr, pwd, usePwd, &word); // Get status for single read
1238 if (status != PM3_SUCCESS) {
1239 success = PM3_ESOFT; // If any error ensure fail is set so not to save invalid data
1242 data[addr] = BSWAP_32(word);
1243 if (status == PM3_SUCCESS) {
1244 num_to_bytes(word, 4, bytes);
1245 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %s", addr, word, sprint_ascii(bytes, 4), gotLockBits ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?"), em4x05_annotation[addr]);
1246 } else
1247 PrintAndLogEx(INFO, " %02u | | | | %-10s %s", addr, em4x05_annotation[addr], status == PM3_EFAILED ? _RED_("read denied") : _RED_("read failed"));
1251 // Print blocks 14 and 15
1252 // Both lock bits are protected with bit idx 14 (special case)
1254 addr = 14;
1255 if (status14 == PM3_SUCCESS) {
1256 lockbit = (lock_bits >> addr) & 1;
1257 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %-10s %s", addr, data[addr], sprint_ascii(bytes, 4), gotLockBits ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?"), em4x05_annotation[addr], lockInPW2 ? "" : _GREEN_("active"));
1258 } else {
1259 PrintAndLogEx(INFO, " %02u | | | | %-10s %s", addr, em4x05_annotation[addr], status14 == PM3_EFAILED ? _RED_("read denied") : _RED_("read failed"));
1262 addr = 15;
1263 if (status15 == PM3_SUCCESS) {
1264 lockbit = (lock_bits >> 14) & 1; // beware lock bit of word15 is pr14
1265 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %-10s %s", addr, data[addr], sprint_ascii(bytes, 4), gotLockBits ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?"), em4x05_annotation[addr], lockInPW2 ? _GREEN_("active") : "");
1266 } else {
1267 PrintAndLogEx(INFO, " %02u | | | | %-10s %s", addr, em4x05_annotation[addr], status15 == PM3_EFAILED ? _RED_("read denied") : _RED_("read failed"));
1269 // Update endian for files
1270 data[14] = BSWAP_32(data[14]);
1271 data[15] = BSWAP_32(data[15]);
1273 } else if (card_type == EM_4369 || card_type == EM_4469) {
1275 // To flag any blocks locked we need to read block 3 first
1276 // don't swap endian until we get block lock flags.
1277 int status14 = em4x05_read_word_ext(EM4469_PROT_BLOCK, pwd, usePwd, &word);
1278 if (status14 == PM3_SUCCESS) {
1279 lock_bits = word;
1280 gotLockBits = true;
1281 data[EM4469_PROT_BLOCK] = word;
1282 } else {
1283 success = PM3_ESOFT; // If any error ensure fail is set so not to save invalid data
1286 for (; addr < 16; addr++) {
1288 uint32_t lockbit = (lock_bits >> (addr * 2)) & 3;
1289 if (addr == 2) {
1290 if (usePwd) {
1291 data[addr] = BSWAP_32(pwd);
1292 num_to_bytes(pwd, 4, bytes);
1293 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %s", addr, pwd, sprint_ascii(bytes, 4), gotLockBits ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?"), em4x69_annotation[addr]);
1294 } else {
1295 data[addr] = 0x00; // Unknown password, but not used to set to zeros
1296 PrintAndLogEx(INFO, " %02u | | | | %-10s " _YELLOW_("write only"), addr, em4x69_annotation[addr]);
1298 } else {
1300 int status = em4x05_read_word_ext(addr, pwd, usePwd, &word);
1301 if (status != PM3_SUCCESS) {
1302 success = PM3_ESOFT; // If any error ensure fail is set so not to save invalid data
1305 data[addr] = BSWAP_32(word);
1306 if (status == PM3_SUCCESS) {
1307 num_to_bytes(word, 4, bytes);
1308 PrintAndLogEx(INFO, " %02u | %08X | %s | %s | %s", addr, word, sprint_ascii(bytes, 4), gotLockBits ? (lockbit ? _RED_("x") : " ") : _YELLOW_("?"), em4x69_annotation[addr]);
1309 } else {
1310 PrintAndLogEx(INFO, " %02u | | | | %-10s %s", addr, em4x69_annotation[addr], status == PM3_EFAILED ? _RED_("read denied") : _RED_("read failed"));
1315 } else {
1318 em4x05_print_footer();
1320 if (nosave) {
1321 PrintAndLogEx(NORMAL, "");
1322 PrintAndLogEx(INFO, "Called with no save option");
1323 PrintAndLogEx(NORMAL, "");
1324 return PM3_SUCCESS;
1327 // all ok save dump to file
1328 if (success == PM3_SUCCESS) {
1330 if (strcmp(filename, "") == 0) {
1332 if (card_type == EM_4369) {
1333 snprintf(filename, sizeof(filename), "lf-4369-%08X-dump", BSWAP_32(data[1]));
1334 } else if (card_type == EM_4469) {
1335 snprintf(filename, sizeof(filename), "lf-4469-%08X-dump", BSWAP_32(data[1]));
1336 } else {
1337 snprintf(filename, sizeof(filename), "lf-4x05-%08X-dump", BSWAP_32(data[1]));
1341 PrintAndLogEx(NORMAL, "");
1342 if (card_type == EM_4369 || card_type == EM_4469)
1343 pm3_save_dump(filename, (uint8_t *)data, sizeof(data), jsfEM4x69);
1344 else
1345 pm3_save_dump(filename, (uint8_t *)data, sizeof(data), jsfEM4x05);
1348 PrintAndLogEx(NORMAL, "");
1349 return success;
1352 int CmdEM4x05Read(const char *Cmd) {
1354 CLIParserContext *ctx;
1355 CLIParserInit(&ctx, "lf em 4x05 read",
1356 "Read EM4x05/EM4x69. Tag must be on antenna.",
1357 "lf em 4x05 read -a 1\n"
1358 "lf em 4x05 read --addr 1 --pwd 11223344"
1361 void *argtable[] = {
1362 arg_param_begin,
1363 arg_int1("a", "addr", "<dec>", "memory address to read. (0-15)"),
1364 arg_str0("p", "pwd", "<hex>", "optional - password, 4 bytes hex"),
1365 arg_param_end
1367 CLIExecWithReturn(ctx, Cmd, argtable, true);
1368 uint8_t addr = (uint8_t)arg_get_int_def(ctx, 1, 50);
1369 uint64_t inputpwd = arg_get_u64_hexstr_def(ctx, 2, 0xFFFFFFFFFFFFFFFF);
1370 CLIParserFree(ctx);
1372 uint32_t pwd = 0;
1373 bool use_pwd = false;
1375 if (addr > 15) {
1376 PrintAndLogEx(ERR, "Address must be between 0 and 15, got " _RED_("%d"), addr);
1377 return PM3_EINVARG;
1380 if (inputpwd == 0xFFFFFFFFFFFFFFFF) {
1381 PrintAndLogEx(INFO, "Reading address " _YELLOW_("%02u"), addr);
1382 } else {
1383 pwd = (inputpwd & 0xFFFFFFFF);
1384 use_pwd = true;
1385 PrintAndLogEx(INFO, "Reading address " _YELLOW_("%02u") " using password " _YELLOW_("%08X"), addr, pwd);
1388 uint32_t word = 0;
1389 int status = em4x05_read_word_ext(addr, pwd, use_pwd, &word);
1390 if (status == PM3_SUCCESS)
1391 PrintAndLogEx(SUCCESS, "Address %02d | %08X - %s", addr, word, (addr > 13) ? "Lock" : "");
1392 else if (status == PM3_EFAILED)
1393 PrintAndLogEx(ERR, "Tag denied Read operation");
1394 else
1395 PrintAndLogEx(WARNING, "No answer from tag");
1396 return status;
1399 int CmdEM4x05Write(const char *Cmd) {
1400 CLIParserContext *ctx;
1401 CLIParserInit(&ctx, "lf em 4x05 write",
1402 "Write EM4x05/EM4x69. Tag must be on antenna.",
1403 "lf em 4x05 write -a 1 -d deadc0de\n"
1404 "lf em 4x05 write --addr 1 --pwd 11223344 --data deadc0de\n"
1405 "lf em 4x05 write --po --pwd 11223344 --data deadc0de\n"
1408 void *argtable[] = {
1409 arg_param_begin,
1410 arg_int0("a", "addr", "<dec>", "memory address to write to. (0-13)"),
1411 arg_str1("d", "data", "<hex>", "data to write (4 hex bytes)"),
1412 arg_str0("p", "pwd", "<hex>", "password (4 hex bytes)"),
1413 arg_lit0(NULL, "po", "protect operation"),
1414 arg_param_end
1416 CLIExecWithReturn(ctx, Cmd, argtable, true);
1417 uint8_t addr = (uint8_t)arg_get_int_def(ctx, 1, 50);
1418 uint32_t data = 0;
1419 int res = arg_get_u32_hexstr_def(ctx, 2, 0, &data);
1420 if (res == 2) {
1421 CLIParserFree(ctx);
1422 PrintAndLogEx(WARNING, "Data must be 4 hex bytes");
1423 return PM3_EINVARG;
1424 } else if (res == 0) {
1425 CLIParserFree(ctx);
1426 PrintAndLogEx(WARNING, "Data must be 4 hex bytes");
1427 return PM3_EINVARG;
1430 bool use_pwd = false;
1431 uint32_t pwd = 0;
1432 res = arg_get_u32_hexstr_def_nlen(ctx, 3, 0, &pwd, 4, true);
1433 if (res == 2) {
1434 CLIParserFree(ctx);
1435 PrintAndLogEx(WARNING, "Password must be 4 hex bytes");
1436 return PM3_EINVARG;
1437 } else if (res == 3) {
1438 use_pwd = false;
1439 } else if (res == 1) {
1440 use_pwd = true;
1443 bool protect_operation = arg_get_lit(ctx, 4);
1444 CLIParserFree(ctx);
1446 if ((addr > 13) && (protect_operation == false)) {
1447 PrintAndLogEx(WARNING, "Address must be between 0 and 13");
1448 return PM3_EINVARG;
1451 if (use_pwd) {
1452 if (protect_operation)
1453 PrintAndLogEx(INFO, "Writing protection words data " _YELLOW_("%08X") " using password " _YELLOW_("%08X"), data, pwd);
1454 else
1455 PrintAndLogEx(INFO, "Writing address " _YELLOW_("%d") " data " _YELLOW_("%08X") " using password " _YELLOW_("%08X"), addr, data, pwd);
1456 } else {
1457 if (protect_operation)
1458 PrintAndLogEx(INFO, "Writing protection words data " _YELLOW_("%08X"), data);
1459 else
1460 PrintAndLogEx(INFO, "Writing address " _YELLOW_("%d") " data " _YELLOW_("%08X"), addr, data);
1463 res = PM3_SUCCESS;
1464 // set Protect Words
1465 if (protect_operation) {
1466 res = em4x05_protect(pwd, use_pwd, data);
1467 if (res != PM3_SUCCESS) {
1468 return res;
1470 } else {
1471 res = em4x05_write_word_ext(addr, pwd, use_pwd, data);
1472 if (res != PM3_SUCCESS) {
1473 return res;
1477 if (em4x05_download_samples() == false)
1478 return PM3_ENODATA;
1480 uint32_t dummy = 0;
1481 int status = em4x05_demod_resp(&dummy, true);
1482 if (status == PM3_SUCCESS)
1483 PrintAndLogEx(SUCCESS, "Data written and verified");
1484 else if (status == PM3_EFAILED)
1485 PrintAndLogEx(ERR, "Tag denied " _RED_("%s") " operation", protect_operation ? "Protect" : "Write");
1486 else
1487 PrintAndLogEx(DEBUG, "No answer from tag");
1489 PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`lf em 4x05 read`") " to verify");
1490 return status;
1493 int CmdEM4x05Wipe(const char *Cmd) {
1495 CLIParserContext *ctx;
1496 CLIParserInit(&ctx, "lf em 4x05 wipe",
1497 "Wipe EM4x05/EM4x69. Tag must be on antenna.",
1498 "lf em 4x05 wipe --4305 -p 11223344 -> wipe EM 4305 w pwd\n"
1499 "lf em 4x05 wipe --4205 -> wipe EM 4205\n"
1500 "lf em 4x05 wipe --4369 -> wipe EM 4369"
1503 void *argtable[] = {
1504 arg_param_begin,
1505 arg_lit0(NULL, "4205", "target chip type EM 4205"),
1506 arg_lit0(NULL, "4305", "target chip type EM 4305 (default)"),
1507 arg_lit0(NULL, "4369", "target chip type EM 4369"),
1508 arg_lit0(NULL, "4469", "target chip type EM 4469"),
1509 arg_str0("p", "pwd", "<hex>", "optional - password, 4 bytes hex"),
1510 arg_param_end
1512 CLIExecWithReturn(ctx, Cmd, argtable, false);
1514 bool target_4205 = arg_get_lit(ctx, 1);
1515 bool target_4305 = arg_get_lit(ctx, 2);
1516 bool target_4369 = arg_get_lit(ctx, 3);
1517 bool target_4469 = arg_get_lit(ctx, 4);
1518 uint64_t inputpwd = arg_get_u64_hexstr_def(ctx, 5, 0xFFFFFFFFFFFFFFFF);
1519 CLIParserFree(ctx);
1521 uint8_t foo = target_4205 + target_4305 + target_4369 + target_4469;
1523 if (foo > 1) {
1524 PrintAndLogEx(ERR, "Can't target multiple chip types at the same time");
1525 return PM3_EINVARG;
1528 uint8_t addr = 0;
1529 uint32_t chip_info = 0x00040072; // Chip info/User Block normal 4305 Chip Type
1530 uint32_t chip_UID = 0x614739AE; // UID normally readonly, but just in case
1531 uint32_t block_data = 0x00000000; // UserBlock/Password (set to 0x00000000 for a wiped card1
1532 uint32_t config = 0x0001805F; // Default config (no password)
1534 if (target_4205) {
1535 chip_info = 0x00040070;
1537 if (target_4369) {
1538 chip_info = 0x00020078; // found on HID Prox
1540 if (target_4469) {
1541 // chip_info = 0x00020078; // need to get a normal 4469 chip info block
1544 bool use_pwd = false;
1545 uint32_t pwd = 0;
1546 if (inputpwd != 0xFFFFFFFFFFFFFFFF) {
1547 pwd = (inputpwd & 0xFFFFFFFF);
1548 use_pwd = true;
1550 // block 0 : User Data or Chip Info
1551 int res = em4x05_write_word_ext(0, pwd, use_pwd, chip_info);
1552 if (res != PM3_SUCCESS) {
1553 return res;
1556 // block 1 : UID - this should be read only for EM4205 and EM4305 not sure about others
1557 res = em4x05_write_word_ext(1, pwd, use_pwd, chip_UID);
1558 if (res != PM3_SUCCESS) {
1559 PrintAndLogEx(INFO, "UID block write failed");
1562 // block 2 : password
1563 res = em4x05_write_word_ext(2, pwd, use_pwd, block_data);
1564 if (res != PM3_SUCCESS) {
1565 return res;
1568 // Password should now have changed, so use new password
1569 pwd = block_data;
1570 // block 3 : user data
1571 res = em4x05_write_word_ext(3, pwd, use_pwd, block_data);
1572 if (res != PM3_SUCCESS) {
1573 return res;
1576 // block 4 : config
1577 res = em4x05_write_word_ext(4, pwd, use_pwd, config);
1578 if (res != PM3_SUCCESS) {
1579 return res;
1582 // Remainder of user/data blocks
1583 for (addr = 5; addr < 14; addr++) {// Clear user data blocks
1584 res = em4x05_write_word_ext(addr, pwd, use_pwd, block_data);
1585 if (res != PM3_SUCCESS) {
1586 return res;
1589 return PM3_SUCCESS;
1592 int CmdEM4x05Info(const char *Cmd) {
1594 CLIParserContext *ctx;
1595 CLIParserInit(&ctx, "lf em 4x05 info",
1596 "Tag information EM4205/4305/4469//4569 tags. Tag must be on antenna.",
1597 "lf em 4x05 info\n"
1598 "lf em 4x05 info -p 11223344"
1601 void *argtable[] = {
1602 arg_param_begin,
1603 arg_str0("p", "pwd", "<hex>", "optional - password, 4 hex bytes"),
1604 arg_lit0("v", "verbose", "Verbose output"),
1605 arg_param_end
1607 CLIExecWithReturn(ctx, Cmd, argtable, true);
1608 uint64_t inputpwd = arg_get_u64_hexstr_def(ctx, 1, 0xFFFFFFFFFFFFFFFF);
1609 bool verbose = arg_get_lit(ctx, 2);
1610 CLIParserFree(ctx);
1612 bool use_pwd = false;
1613 uint32_t pwd = 0;
1614 if (inputpwd != 0xFFFFFFFFFFFFFFFF) {
1615 pwd = inputpwd & 0xFFFFFFFF;
1616 use_pwd = true;
1619 uint32_t word = 0, block0 = 0, serial = 0;
1621 // read word 0 (chip info)
1622 // block 0 can be read even without a password.
1623 if (em4x05_isblock0(&block0) == false) {
1624 return PM3_ESOFT;
1627 // based on Block0 , decide type.
1628 em_tech_type_t card_type = em_get_card_type(block0);
1630 // read word 1 (serial #) doesn't need pwd
1631 // continue if failed, .. non blocking fail.
1632 int res = em4x05_read_word_ext(EM_SERIAL_BLOCK, 0, false, &serial);
1633 (void)res;
1635 printEM4x05info(block0, serial);
1637 // read word 4 (config block)
1638 // needs password if one is set
1639 if (em4x05_read_word_ext(EM_CONFIG_BLOCK, pwd, use_pwd, &word) != PM3_SUCCESS) {
1640 PrintAndLogEx(DEBUG, "(CmdEM4x05Info) failed to read CONFIG BLOCK");
1641 return PM3_ESOFT;
1644 printEM4x05config(card_type, word);
1646 // skip printing lock bits if not VERBOSE
1647 if (verbose == false) {
1648 return PM3_SUCCESS;
1650 // if 4469 read EM4469_PROT_BLOCK
1651 // if 4305 read 14,15
1652 if (card_type == EM_4205 || card_type == EM_4305) {
1654 // read word 14 and 15 to see which is being used for the protection bits
1655 if (em4x05_read_word_ext(EM4305_PROT1_BLOCK, pwd, use_pwd, &word) != PM3_SUCCESS) {
1656 return PM3_ESOFT;
1659 if (word & 0x8000) {
1660 printEM4x05ProtectionBits(word, EM4305_PROT1_BLOCK);
1661 return PM3_SUCCESS;
1662 } else { // if status bit says this is not the used protection word
1663 if (em4x05_read_word_ext(EM4305_PROT2_BLOCK, pwd, use_pwd, &word) != PM3_SUCCESS) {
1664 return PM3_ESOFT;
1667 if (word & 0x8000) {
1668 printEM4x05ProtectionBits(word, EM4305_PROT2_BLOCK);
1669 return PM3_SUCCESS;
1673 } else if (card_type == EM_4369 || card_type == EM_4469) {
1674 // read word 3 to see which is being used for the protection bits
1675 if (em4x05_read_word_ext(EM4469_PROT_BLOCK, pwd, use_pwd, &word) != PM3_SUCCESS) {
1676 return PM3_ESOFT;
1678 printEM4x05ProtectionBits(word, EM4469_PROT_BLOCK);
1681 //something went wrong
1682 return PM3_ESOFT;
1685 // load a default pwd file.
1686 int CmdEM4x05Chk(const char *Cmd) {
1688 CLIParserContext *ctx;
1689 CLIParserInit(&ctx, "lf em 4x05 chk",
1690 "This command uses a dictionary attack against EM4205/4305/4469/4569",
1691 "lf em 4x05 chk\n"
1692 "lf em 4x05 chk -e 000022B8 -> check password 000022B8\n"
1693 "lf em 4x05 chk -f t55xx_default_pwds -> use T55xx default dictionary"
1696 void *argtable[] = {
1697 arg_param_begin,
1698 arg_str0("f", "file", "<fn>", "loads a default keys dictionary file <*.dic>"),
1699 arg_str0("e", "em", "<EM4100>", "try the calculated password from some cloners based on EM4100 ID"),
1700 arg_param_end
1702 CLIExecWithReturn(ctx, Cmd, argtable, true);
1703 int fnlen = 0;
1704 char filename[FILE_PATH_SIZE] = {0};
1705 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
1707 uint64_t card_id = 0;
1708 int res = arg_get_u64_hexstr_def_nlen(ctx, 2, 0, &card_id, 5, true);
1709 if (res == 2) {
1710 CLIParserFree(ctx);
1711 PrintAndLogEx(WARNING, "EM4100 ID must be 5 hex bytes");
1712 return PM3_EINVARG;
1714 if (res == 0) {
1715 CLIParserFree(ctx);
1716 return PM3_EINVARG;
1719 CLIParserFree(ctx);
1721 if (strlen(filename) == 0) {
1722 snprintf(filename, sizeof(filename), "t55xx_default_pwds");
1724 PrintAndLogEx(NORMAL, "");
1726 bool found = false;
1727 uint64_t t1 = msclock();
1729 // White cloner password based on EM4100 ID
1730 if (card_id > 0) {
1732 uint32_t pwd = lf_t55xx_white_pwdgen(card_id & 0xFFFFFFFF);
1733 PrintAndLogEx(INFO, "testing %08"PRIX32" generated ", pwd);
1735 int status = em4x05_login_ext(pwd);
1736 if (status == PM3_SUCCESS) {
1737 PrintAndLogEx(SUCCESS, "found valid password [ " _GREEN_("%08"PRIX32) " ]", pwd);
1738 found = true;
1739 } else if (status != PM3_EFAILED) {
1740 PrintAndLogEx(WARNING, "no answer from tag");
1744 // Loop dictionary
1745 uint8_t *keyBlock = NULL;
1746 if (found == false) {
1748 uint32_t keycount = 0;
1750 res = loadFileDICTIONARY_safe(filename, (void **) &keyBlock, 4, &keycount);
1751 if (res != PM3_SUCCESS || keycount == 0 || keyBlock == NULL) {
1752 PrintAndLogEx(WARNING, "no keys found in file");
1753 if (keyBlock != NULL) {
1754 free(keyBlock);
1756 return PM3_ESOFT;
1759 PrintAndLogEx(INFO, "Press " _GREEN_("<Enter>") " to exit");
1761 for (uint32_t c = 0; c < keycount; ++c) {
1763 if (!g_session.pm3_present) {
1764 PrintAndLogEx(WARNING, "device offline\n");
1765 free(keyBlock);
1766 return PM3_ENODATA;
1769 if (is_cancelled()) {
1770 free(keyBlock);
1771 return PM3_EOPABORTED;
1774 uint32_t curr_password = bytes_to_num(keyBlock + 4 * c, 4);
1776 PrintAndLogEx(INFO, "testing %08"PRIX32, curr_password);
1778 int status = em4x05_login_ext(curr_password);
1779 if (status == PM3_SUCCESS) {
1780 PrintAndLogEx(SUCCESS, "found valid password [ " _GREEN_("%08"PRIX32) " ]", curr_password);
1781 found = true;
1782 break;
1783 } else if (status != PM3_EFAILED) {
1784 PrintAndLogEx(WARNING, "no answer from tag");
1789 if (found == false)
1790 PrintAndLogEx(WARNING, "check pwd failed");
1792 free(keyBlock);
1794 t1 = msclock() - t1;
1795 PrintAndLogEx(SUCCESS, "\ntime in check pwd " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0);
1796 return PM3_SUCCESS;
1799 int CmdEM4x05Brute(const char *Cmd) {
1800 CLIParserContext *ctx;
1801 CLIParserInit(&ctx, "lf em 4x05 brute",
1802 "This command tries to bruteforce the password of a EM4205/4305/4469/4569\n"
1803 "The loop is running on device side, press Proxmark3 button to abort\n",
1804 "Note: if you get many false positives, change position on the antenna"
1805 "lf em 4x05 brute\n"
1806 "lf em 4x05 brute -n 1 -> stop after first candidate found\n"
1807 "lf em 4x05 brute -s 000022AA -> start at 000022AA"
1810 void *argtable[] = {
1811 arg_param_begin,
1812 arg_str0("s", "start", "<hex>", "Start bruteforce enumeration from this password value"),
1813 arg_u64_0("n", NULL, "<dec>", "Stop after having found n candidates. Default: 0 (infinite)"),
1814 arg_param_end
1816 CLIExecWithReturn(ctx, Cmd, argtable, true);
1817 uint32_t start_pwd = 0;
1818 int res = arg_get_u32_hexstr_def(ctx, 1, 0, &start_pwd);
1819 if (res != 1) {
1820 CLIParserFree(ctx);
1821 PrintAndLogEx(WARNING, "check `start_pwd` parameter");
1822 return PM3_EINVARG;
1825 uint32_t n = arg_get_u32_def(ctx, 2, 0);
1826 CLIParserFree(ctx);
1828 PrintAndLogEx(NORMAL, "");
1830 struct {
1831 uint32_t start_pwd;
1832 uint32_t n;
1833 } PACKED payload;
1835 payload.start_pwd = start_pwd;
1836 payload.n = n;
1838 clearCommandBuffer();
1839 SendCommandNG(CMD_LF_EM4X_BF, (uint8_t *)&payload, sizeof(payload));
1840 PacketResponseNG resp;
1841 if (WaitForResponseTimeout(CMD_LF_EM4X_BF, &resp, 1000) == false) {
1842 PrintAndLogEx(WARNING, "(EM4x05 Bruteforce) timeout while waiting for reply.");
1843 return PM3_ETIMEOUT;
1845 PrintAndLogEx(INFO, "Bruteforce is running on device side, press button to interrupt");
1846 return PM3_SUCCESS;
1849 static int unlock_write_protect(bool use_pwd, uint32_t pwd, uint32_t data, bool verbose) {
1851 struct {
1852 uint32_t password;
1853 uint32_t data;
1854 uint8_t usepwd;
1855 } PACKED payload;
1857 payload.password = pwd;
1858 payload.data = data;
1859 payload.usepwd = use_pwd;
1861 clearCommandBuffer();
1862 SendCommandNG(CMD_LF_EM4X_PROTECTWORD, (uint8_t *)&payload, sizeof(payload));
1863 PacketResponseNG resp;
1864 if (WaitForResponseTimeout(CMD_LF_EM4X_PROTECTWORD, &resp, 2000) == false) {
1865 PrintAndLogEx(ERR, "Error occurred, device did not respond during write operation.");
1866 return PM3_ETIMEOUT;
1869 if (em4x05_download_samples() == false) {
1870 return PM3_ENODATA;
1873 uint32_t dummy = 0;
1874 int status = em4x05_demod_resp(&dummy, true);
1875 if (status == PM3_SUCCESS && verbose) {
1876 PrintAndLogEx(SUCCESS, "Data written and verified");
1877 } else if (status == PM3_EFAILED) {
1878 PrintAndLogEx(ERR, "Tag denied PROTECT operation");
1879 } else {
1880 PrintAndLogEx(DEBUG, "No answer from tag");
1883 return status;
1886 static int unlock_reset(bool use_pwd, uint32_t pwd, uint32_t data, bool verbose) {
1887 if (verbose) {
1888 PrintAndLogEx(INFO, "resetting the " _RED_("active") " lock block");
1890 return unlock_write_protect(use_pwd, pwd, data, false);
1893 static void unlock_add_item(em4x05_unlock_item_t *array, uint8_t len, uint32_t value) {
1895 uint8_t i = 0;
1896 for (; i < len; i++) {
1897 if (array[i].value == value) {
1898 array[i].cnt++;
1899 break;
1901 if (array[i].cnt == 0) {
1902 array[i].cnt++;
1903 array[i].value = value;
1904 break;
1909 int CmdEM4x05Unlock(const char *Cmd) {
1911 CLIParserContext *ctx;
1912 CLIParserInit(&ctx, "lf em 4x05 unlock",
1913 "execute tear off against EM4205/4305/4469/4569",
1914 "lf em 4x05 unlock\n"
1915 "lf em 4x05 unlock -s 4100 -e 4100 -> lock on and autotune at 4100us\n"
1916 "lf em 4x05 unlock -n 10 -s 3000 -e 4400 -> scan delays 3000us -> 4400us"
1919 void *argtable[] = {
1920 arg_param_begin,
1921 arg_int0("n", NULL, NULL, "steps to skip"),
1922 arg_int0("s", "start", "<us>", "start scan from delay (us)"),
1923 arg_int0("e", "end", "<us>", "end scan at delay (us)"),
1924 arg_str0("p", "pwd", "<hex>", "password (def 00000000)"),
1925 arg_lit0("v", "verbose", "verbose output"),
1926 arg_param_end
1928 CLIExecWithReturn(ctx, Cmd, argtable, true);
1929 double n = (double)arg_get_int_def(ctx, 1, 0);
1930 double start = (double)arg_get_int_def(ctx, 2, 2000);
1931 double end = (double)arg_get_int_def(ctx, 3, 6000);
1932 uint64_t inputpwd = arg_get_u64_hexstr_def(ctx, 4, 0xFFFFFFFFFFFFFFFF);
1933 bool verbose = arg_get_lit(ctx, 5);
1934 CLIParserFree(ctx);
1936 if (start > end) {
1937 PrintAndLogEx(FAILED, "start delay can\'t be larger than end delay %.0lf vs %.0lf", start, end);
1938 return PM3_EINVARG;
1941 if (g_session.pm3_present == false) {
1942 PrintAndLogEx(WARNING, "device offline\n");
1943 return PM3_ENODATA;
1946 bool use_pwd = false;
1947 uint32_t pwd = 0;
1948 if (inputpwd != 0xFFFFFFFFFFFFFFFF) {
1949 use_pwd = true;
1950 pwd = inputpwd & 0xFFFFFFFF;
1953 uint32_t search_value = 0;
1954 uint32_t write_value = 0;
1956 // initial phase
1958 // read word 14
1959 uint32_t init_14 = 0;
1960 int res = em4x05_read_word_ext(14, pwd, use_pwd, &init_14);
1961 if (res != PM3_SUCCESS) {
1962 PrintAndLogEx(FAILED, "failed to read word 14\n");
1963 return PM3_ENODATA;
1967 // read 15
1968 uint32_t init_15 = 0;
1969 res = em4x05_read_word_ext(15, pwd, use_pwd, &init_15);
1970 if (res != PM3_SUCCESS) {
1971 PrintAndLogEx(FAILED, "failed to read word 15\n");
1972 return PM3_ENODATA;
1975 #define ACTIVE_MASK 0x00008000
1976 if ((init_15 & ACTIVE_MASK) == ACTIVE_MASK) {
1977 search_value = init_15;
1978 } else {
1979 search_value = init_14;
1982 if (search_value == ACTIVE_MASK) {
1983 PrintAndLogEx(SUCCESS, "Tag already fully unlocked, nothing to do");
1984 return PM3_SUCCESS;
1987 bool my_auto = false;
1988 if (n == 0) {
1989 my_auto = true;
1990 n = (end - start) / 2;
1993 // fix at one specific delay
1994 if (start == end) {
1995 n = 0;
1998 PrintAndLogEx(INFO, "--------------- " _CYAN_("EM4x05 tear-off : target PROTECT") " -----------------------\n");
2000 PrintAndLogEx(INFO, "initial prot 14&15 [ " _GREEN_("%08X") ", " _GREEN_("%08X") " ]", init_14, init_15);
2002 if (use_pwd) {
2003 PrintAndLogEx(INFO, " target password [ " _GREEN_("%08X") " ]", pwd);
2005 if (my_auto) {
2006 PrintAndLogEx(INFO, " automatic mode [ " _GREEN_("enabled") " ]");
2009 PrintAndLogEx(INFO, " target stepping [ " _GREEN_("%.0lf") " ]", n);
2010 PrintAndLogEx(INFO, "target delay range [ " _GREEN_("%.0lf") " ... " _GREEN_("%.0lf") " ]", start, end);
2011 PrintAndLogEx(INFO, " search value [ " _GREEN_("%08X") " ]", search_value);
2012 PrintAndLogEx(INFO, " write value [ " _GREEN_("%08X") " ]", write_value);
2014 PrintAndLogEx(INFO, "----------------------------------------------------------------------------\n");
2015 PrintAndLogEx(NORMAL, "");
2016 PrintAndLogEx(INFO, "Press " _GREEN_("<Enter>'") " to exit");
2017 PrintAndLogEx(NORMAL, "");
2018 PrintAndLogEx(INFO, "--------------- " _CYAN_("start") " -----------------------\n");
2020 int exit_code = PM3_SUCCESS;
2021 uint32_t word14 = 0, word15 = 0;
2022 uint32_t word14b = 0, word15b = 0;
2023 uint32_t tries = 0;
2024 uint32_t soon = 0;
2025 uint32_t late = 0;
2027 em4x05_unlock_item_t flipped[64] = {{0, 0}};
2030 // main loop
2032 bool success = false;
2033 uint64_t t1 = msclock();
2034 while (start <= end) {
2036 if (my_auto && n < 1) {
2037 PrintAndLogEx(INFO, "Reached n < 1 => " _YELLOW_("disabling automatic mode"));
2038 end = start;
2039 my_auto = false;
2040 n = 0;
2043 if (my_auto == false) {
2044 start += n;
2047 if (tries >= 5 && n == 0 && soon != late) {
2049 if (soon > late) {
2050 start++;
2051 end++;
2052 PrintAndLogEx(INFO, "Tried %d times, soon:%i late:%i => " _CYAN_("adjust +1 us >> %.0lf us"), tries, soon, late, start);
2053 } else {
2054 start--;
2055 end--;
2056 PrintAndLogEx(INFO, "Tried %d times, soon:%i late:%i => " _CYAN_("adjust -1 us >> %.0lf us"), tries, soon, late, start);
2058 tries = 0;
2059 soon = 0;
2060 late = 0;
2063 if (is_cancelled()) {
2064 exit_code = PM3_EOPABORTED;
2065 break;
2068 // set tear off trigger
2069 clearCommandBuffer();
2070 tearoff_params_t params = {
2071 .delay_us = start,
2072 .on = true,
2073 .off = false
2075 res = handle_tearoff(&params, verbose);
2076 if (res != PM3_SUCCESS) {
2077 PrintAndLogEx(WARNING, "failed to configure tear off");
2078 return PM3_ESOFT;
2081 // write
2082 // don't check the return value. As a tear-off occurred, the write failed.
2083 unlock_write_protect(use_pwd, pwd, write_value, verbose);
2085 // read after trigger
2086 res = em4x05_read_word_ext(14, pwd, use_pwd, &word14);
2087 if (res != PM3_SUCCESS) {
2088 PrintAndLogEx(WARNING, "failed to read 14");
2089 return PM3_ESOFT;
2092 // read after trigger
2093 res = em4x05_read_word_ext(15, pwd, use_pwd, &word15);
2094 if (res != PM3_SUCCESS) {
2095 PrintAndLogEx(WARNING, "failed to read 15");
2096 return PM3_ESOFT;
2099 if (verbose)
2100 PrintAndLogEx(INFO, "ref:%08X 14:%08X 15:%08X ", search_value, word14, word15);
2102 if (word14 == search_value && word15 == 0) {
2103 PrintAndLogEx(INFO, "Status: Nothing happened => " _GREEN_("tearing too soon"));
2105 if (my_auto) {
2106 start += n;
2107 PrintAndLogEx(INFO, " => " _CYAN_("adjust +%.0lf us >> %.0lf us"), n, start);
2108 n = (int)(n / 2);
2109 } else {
2110 soon++;
2112 } else {
2114 if (word15 == search_value) {
2116 if (word14 == 0) {
2117 PrintAndLogEx(INFO, "Status: Protect succeeded => " _GREEN_("tearing too late"));
2118 } else {
2119 if (word14 == search_value) {
2120 PrintAndLogEx(INFO, "Status: 15 ok, 14 not yet erased => " _GREEN_("tearing too late"));
2121 } else {
2122 PrintAndLogEx(INFO, "Status: 15 ok, 14 partially erased => " _GREEN_("tearing too late"));
2126 unlock_reset(use_pwd, pwd, write_value, verbose);
2128 // read after reset
2129 res = em4x05_read_word_ext(14, pwd, use_pwd, &word14b);
2130 if (res != PM3_SUCCESS) {
2131 PrintAndLogEx(WARNING, "failed to read 14");
2132 return PM3_ESOFT;
2135 if (word14b == 0) {
2137 unlock_reset(use_pwd, pwd, write_value, verbose);
2139 res = em4x05_read_word_ext(14, pwd, use_pwd, &word14b);
2140 if (res != PM3_SUCCESS) {
2141 PrintAndLogEx(WARNING, "failed to read 14");
2142 return PM3_ESOFT;
2146 if (word14b != search_value) {
2148 res = em4x05_read_word_ext(15, pwd, use_pwd, &word15b);
2149 if (res == PM3_SUCCESS) {
2150 PrintAndLogEx(INFO, "Status: new definitive value! => " _RED_("SUCCESS:") " 14: " _CYAN_("%08X") " 15: %08X", word14b, word15b);
2151 success = true;
2152 break;
2153 } else {
2154 PrintAndLogEx(WARNING, "failed to read 15");
2155 return PM3_ESOFT;
2158 if (my_auto) {
2159 end = start;
2160 start -= n;
2161 PrintAndLogEx(INFO, " => " _CYAN_("adjust -%.0lf us >> %.0lf us"), n, start);
2162 n = (int)(n / 2);
2163 } else {
2164 late++;
2167 } else {
2169 if ((word15 & ACTIVE_MASK) == ACTIVE_MASK) {
2171 PrintAndLogEx(INFO, "Status: 15 bitflipped and active => " _RED_("SUCCESS?: ") "14: %08X 15: " _CYAN_("%08X"), word14, word15);
2172 PrintAndLogEx(INFO, "Committing results...");
2174 unlock_reset(use_pwd, pwd, write_value, verbose);
2176 // read after reset
2177 res = em4x05_read_word_ext(14, pwd, use_pwd, &word14b);
2178 if (res != PM3_SUCCESS) {
2179 PrintAndLogEx(WARNING, "failed to read 14");
2180 return PM3_ESOFT;
2183 res = em4x05_read_word_ext(15, pwd, use_pwd, &word15b);
2184 if (res != PM3_SUCCESS) {
2185 PrintAndLogEx(WARNING, "failed to read 15");
2186 return PM3_ESOFT;
2189 if (verbose)
2190 PrintAndLogEx(INFO, "ref:%08x 14:%08X 15:%08X", search_value, word14b, word15b);
2192 if ((word14b & ACTIVE_MASK) == ACTIVE_MASK) {
2194 if (word14b == word15) {
2195 PrintAndLogEx(INFO, "Status: confirmed => " _GREEN_("SUCCESS: ") "14: " _GREEN_("%08X") " 15: %08X", word14b, word15b);
2197 unlock_add_item(flipped, 64, word14b);
2198 success = true;
2199 break;
2202 if (word14b != search_value) {
2203 PrintAndLogEx(INFO, "Status: new definitive value! => " _RED_("SUCCESS: ") "14: " _CYAN_("%08X") " 15: %08X", word14b, word15b);
2205 unlock_add_item(flipped, 64, word14b);
2206 success = true;
2207 break;
2210 PrintAndLogEx(INFO, "Status: failed to commit bitflip => " _RED_("FAIL: ") "14: %08X 15: %08X", word14b, word15b);
2212 if (my_auto) {
2213 n = 0;
2214 end = start;
2215 } else {
2216 tries = 0;
2217 soon = 0;
2218 late = 0;
2220 } else {
2221 PrintAndLogEx(INFO, "Status: 15 bitflipped but inactive => " _YELLOW_("PROMISING: ") "14: %08X 15: " _CYAN_("%08X"), word14, word15);
2223 unlock_add_item(flipped, 64, word15);
2225 soon ++;
2230 if (my_auto == false) {
2231 tries++;
2235 PrintAndLogEx(INFO, "----------------------------- " _CYAN_("exit") " ----------------------------------\n");
2236 t1 = msclock() - t1;
2237 PrintAndLogEx(SUCCESS, "\ntime in unlock " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0);
2238 if (success) {
2239 uint32_t bitflips = search_value ^ word14b;
2240 PrintAndLogEx(INFO, "Old protection word => " _YELLOW_("%08X"), search_value);
2241 char bitstring[9] = {0};
2242 for (int i = 0; i < 8; i++) {
2243 bitstring[i] = (bitflips & (0xFU << ((7 - i) * 4))) ? 'x' : '.';
2245 // compute number of bits flipped
2246 PrintAndLogEx(INFO, "Bitflips: %2u events => %s", bitcount32(bitflips), bitstring);
2247 PrintAndLogEx(INFO, "New protection word => " _CYAN_("%08X") "\n", word14b);
2248 PrintAndLogEx(INFO, "Try " _YELLOW_("`lf em 4x05 dump --ns`"));
2251 if (verbose) {
2252 PrintAndLogEx(NORMAL, "Stats:");
2253 PrintAndLogEx(INFO, " idx | value | cnt | flipped bits");
2254 PrintAndLogEx(INFO, "-----+----------+-----+------");
2255 for (uint8_t i = 0; i < 64; i++) {
2256 if (flipped[i].cnt == 0) {
2257 break;
2260 PrintAndLogEx(INFO, " %3u | %08X | %3u | %u", i, flipped[i].value, flipped[i].cnt, bitcount32(search_value ^ flipped[i].value));
2263 PrintAndLogEx(NORMAL, "");
2264 return exit_code;
2267 static size_t em4x05_Sniff_GetNextBitStart(size_t idx, size_t sc, const int *data, size_t *pulsesamples) {
2268 while ((idx < sc) && (data[idx] <= 10)) // find a going high
2269 idx++;
2271 while ((idx < sc) && (data[idx] > -10)) // find going low may need to add something here it SHOULD be a small clk around 0, but white seems to extend a bit.
2272 idx++;
2274 (*pulsesamples) = 0;
2275 while ((idx < sc) && ((data[idx + 1] - data[idx]) < 10)) { // find "sharp rise"
2276 (*pulsesamples)++;
2277 idx++;
2280 return idx;
2283 static uint32_t em4x05_Sniff_GetBlock(const char *bits, bool fwd) {
2284 uint32_t value = 0;
2285 uint8_t idx;
2286 bool parityerror = false;
2287 uint8_t parity;
2289 parity = 0;
2290 for (idx = 0; idx < 8; idx++) {
2291 value <<= 1;
2292 value += (bits[idx] - '0');
2293 parity += (bits[idx] - '0');
2296 parity = parity % 2;
2297 if (parity != (bits[8] - '0'))
2298 parityerror = true;
2300 parity = 0;
2301 for (idx = 9; idx < 17; idx++) {
2302 value <<= 1;
2303 value += (bits[idx] - '0');
2304 parity += (bits[idx] - '0');
2307 parity = parity % 2;
2308 if (parity != (bits[17] - '0'))
2309 parityerror = true;
2311 parity = 0;
2313 for (idx = 18; idx < 26; idx++) {
2314 value <<= 1;
2315 value += (bits[idx] - '0');
2316 parity += (bits[idx] - '0');
2319 parity = parity % 2;
2320 if (parity != (bits[26] - '0'))
2321 parityerror = true;
2323 parity = 0;
2324 for (idx = 27; idx < 35; idx++) {
2325 value <<= 1;
2326 value += (bits[idx] - '0');
2327 parity += (bits[idx] - '0');
2330 parity = parity % 2;
2331 if (parity != (bits[35] - '0'))
2332 parityerror = true;
2334 if (parityerror)
2335 PrintAndLogEx(ERR, "parity error : ");
2337 if (fwd == false) {
2338 uint32_t t1 = value;
2339 value = 0;
2340 for (idx = 0; idx < 32; idx++) {
2341 value |= (((t1 >> idx) & 1) << (31 - idx));
2344 return value;
2347 int CmdEM4x05Sniff(const char *Cmd) {
2349 CLIParserContext *ctx;
2350 CLIParserInit(&ctx, "lf em 4x05 sniff",
2351 "Sniff EM4x05 commands sent from a programmer",
2352 "lf em 4x05 sniff --> sniff via lf sniff\n"
2353 "lf em 4x05 sniff -1 --> sniff from data loaded into the buffer\n"
2354 "lf em 4x05 sniff -r --> reverse the bit order when showing block data"
2357 void *argtable[] = {
2358 arg_param_begin,
2359 arg_lit0("1", "buf", "Use the data in the buffer"),
2360 arg_lit0("r", "rev", "Reverse the bit order for data blocks"),
2361 arg_param_end
2363 CLIExecWithReturn(ctx, Cmd, argtable, true);
2364 bool sampleData = (arg_get_lit(ctx, 1) == false);
2365 bool fwd = arg_get_lit(ctx, 2);
2366 CLIParserFree(ctx);
2368 const char *cmdText;
2369 char dataText[100] = {0};
2370 char blkAddr[4] = {0};
2371 int i;
2372 int ZeroWidth; // 32-42 "1" is 32
2373 int CycleWidth;
2374 size_t pulseSamples;
2376 // setup and sample data from Proxmark
2377 // if not directed to existing sample/graphbuffer
2378 if (sampleData) {
2379 if (IfPm3Lf() == false) {
2380 PrintAndLogEx(WARNING, "Only offline mode is available");
2381 return PM3_EINVARG;
2383 CmdLFSniff("");
2386 // Headings
2387 PrintAndLogEx(NORMAL, "");
2388 PrintAndLogEx(INFO, _CYAN_("EM4x05 command detection"));
2389 PrintAndLogEx(SUCCESS, "offset | Command | Data | blk | raw");
2390 PrintAndLogEx(SUCCESS, "-------+-------------+----------+-----+------------------------------------------------------------");
2392 smartbuf bits = { 0 };
2393 bits.ptr = calloc(EM4X05_BITS_BUFSIZE, sizeof(uint8_t));
2394 bits.size = EM4X05_BITS_BUFSIZE;
2395 bits.idx = 0;
2396 size_t idx = 0;
2397 // loop though sample buffer
2398 while (idx < g_GraphTraceLen) {
2399 bool haveData = false;
2400 bool pwd = false;
2402 idx = em4x05_Sniff_GetNextBitStart(idx, g_GraphTraceLen, g_GraphBuffer, &pulseSamples);
2403 size_t pktOffset = idx;
2404 if (pulseSamples >= 10) { // Should be 18 so a bit less to allow for processing
2406 // Use first bit to get "0" bit samples as a reference
2407 ZeroWidth = idx;
2408 idx = em4x05_Sniff_GetNextBitStart(idx, g_GraphTraceLen, g_GraphBuffer, &pulseSamples);
2409 ZeroWidth = idx - ZeroWidth;
2411 if (ZeroWidth <= 50) {
2412 pktOffset -= ZeroWidth;
2413 memset(bits.ptr, 0, bits.size);
2414 bits.idx = 0;
2416 bool eop = false;
2417 while ((idx < g_GraphTraceLen) && !eop) {
2418 CycleWidth = idx;
2419 idx = em4x05_Sniff_GetNextBitStart(idx, g_GraphTraceLen, g_GraphBuffer, &pulseSamples);
2421 CycleWidth = idx - CycleWidth;
2422 if ((CycleWidth > 300) || (CycleWidth < (ZeroWidth - 5))) { // to long or too short
2423 eop = true;
2424 sb_append_char(&bits, '0'); // Append last zero from the last bit find
2425 cmdText = "";
2427 // EM4305 command lengths
2428 // Login 0011 <pwd> => 4 + 45 => 49
2429 // Write Word 0101 <adr> <data> => 4 + 7 + 45 => 56
2430 // Read Word 1001 <adr> => 4 + 7 => 11
2431 // Protect 1100 <data> => 4 + 45 => 49
2432 // Disable 1010 <data> => 4 + 45 => 49
2433 // -> disable 1010 11111111 0 11111111 0 11111111 0 11111111 0 00000000 0
2435 // Check to see if we got the leading 0
2436 if (((strncmp(bits.ptr, "00011", 5) == 0) && (bits.idx == 50)) ||
2437 ((strncmp(bits.ptr, "00101", 5) == 0) && (bits.idx == 57)) ||
2438 ((strncmp(bits.ptr, "01001", 5) == 0) && (bits.idx == 12)) ||
2439 ((strncmp(bits.ptr, "01100", 5) == 0) && (bits.idx == 50)) ||
2440 ((strncmp(bits.ptr, "01010", 5) == 0) && (bits.idx == 50))) {
2441 memmove(bits.ptr, &bits.ptr[1], bits.idx - 1);
2442 bits.idx--;
2443 PrintAndLogEx(INFO, "Trim leading 0");
2445 sb_append_char(&bits, 0);
2446 bits.idx--;
2448 // logon
2449 if ((strncmp(bits.ptr, "0011", 4) == 0) && (bits.idx == 49)) {
2450 haveData = true;
2451 pwd = true;
2452 cmdText = "Logon";
2453 strncpy(blkAddr, " ", sizeof(blkAddr));
2454 uint32_t tmpValue = em4x05_Sniff_GetBlock(&bits.ptr[4], fwd);
2455 snprintf(dataText, sizeof(dataText), "%08X", tmpValue);
2458 // write
2459 if ((strncmp(bits.ptr, "0101", 4) == 0) && (bits.idx == 56)) {
2460 haveData = true;
2461 cmdText = "Write";
2462 uint32_t tmpValue = (bits.ptr[4] - '0') + ((bits.ptr[5] - '0') << 1) + ((bits.ptr[6] - '0') << 2) + ((bits.ptr[7] - '0') << 3);
2463 snprintf(blkAddr, sizeof(blkAddr), "%u", tmpValue);
2464 if (tmpValue == 2) {
2465 pwd = true;
2467 tmpValue = em4x05_Sniff_GetBlock(&bits.ptr[11], fwd);
2468 snprintf(dataText, sizeof(dataText), "%08X", tmpValue);
2471 // read
2472 if ((strncmp(bits.ptr, "1001", 4) == 0) && (bits.idx == 11)) {
2473 haveData = true;
2474 pwd = false;
2475 cmdText = "Read";
2476 uint32_t tmpValue = (bits.ptr[4] - '0') + ((bits.ptr[5] - '0') << 1) + ((bits.ptr[6] - '0') << 2) + ((bits.ptr[7] - '0') << 3);
2477 snprintf(blkAddr, sizeof(blkAddr), "%u", tmpValue);
2478 strncpy(dataText, " ", sizeof(dataText));
2481 // protect
2482 if ((strncmp(bits.ptr, "1100", 4) == 0) && (bits.idx == 49)) {
2483 haveData = true;
2484 pwd = false;
2485 cmdText = "Protect";
2486 strncpy(blkAddr, " ", sizeof(blkAddr));
2487 uint32_t tmpValue = em4x05_Sniff_GetBlock(&bits.ptr[11], fwd);
2488 snprintf(dataText, sizeof(dataText), "%08X", tmpValue);
2491 // disable
2492 if ((strncmp(bits.ptr, "1010", 4) == 0) && (bits.idx == 49)) {
2493 haveData = true;
2494 pwd = false;
2495 cmdText = "Disable";
2496 strncpy(blkAddr, " ", sizeof(blkAddr));
2497 uint32_t tmpValue = em4x05_Sniff_GetBlock(&bits.ptr[11], fwd);
2498 snprintf(dataText, sizeof(dataText), "%08X", tmpValue);
2501 // bits[bitidx] = 0;
2502 } else {
2503 i = (CycleWidth - ZeroWidth) / 28;
2504 sb_append_char(&bits, '0');
2505 for (int ii = 0; ii < i; ii++) {
2506 sb_append_char(&bits, '1');
2512 idx++;
2514 // Print results
2515 if (haveData) { //&& (minWidth > 1) && (maxWidth > minWidth)){
2516 if (pwd)
2517 PrintAndLogEx(SUCCESS, "%6zu | %-10s | " _YELLOW_("%8s")" | " _YELLOW_("%3s")" | %s", pktOffset, cmdText, dataText, blkAddr, bits.ptr);
2518 else
2519 PrintAndLogEx(SUCCESS, "%6zu | %-10s | " _GREEN_("%8s")" | " _GREEN_("%3s")" | %s", pktOffset, cmdText, dataText, blkAddr, bits.ptr);
2522 free(bits.ptr);
2523 bits.ptr = NULL;
2525 // footer
2526 PrintAndLogEx(SUCCESS, "---------------------------------------------------------------------------------------------------");
2527 PrintAndLogEx(NORMAL, "");
2528 return PM3_SUCCESS;
2531 static int CmdEM4x05View(const char *Cmd) {
2532 CLIParserContext *ctx;
2533 CLIParserInit(&ctx, "lf em 4x05 view",
2534 "Print a EM4205/4305/4369/4469 dump file\n"
2535 "note:\n"
2536 "We don't track if password is known in current dump file formats.\n"
2537 "All zeros password block might be filler data",
2538 "lf em 4x05 view -f lf-4x05-01020304-dump.json"
2540 void *argtable[] = {
2541 arg_param_begin,
2542 arg_str1("f", "file", "<fn>", "Specify a filename for dump file"),
2543 arg_litn("v", "verbose", 0, 2, "Verbose output"),
2544 arg_param_end
2546 CLIExecWithReturn(ctx, Cmd, argtable, false);
2547 int fnlen = 0;
2548 char filename[FILE_PATH_SIZE];
2549 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
2550 bool verbose = arg_get_lit(ctx, 2);
2551 bool verbose2 = arg_get_lit(ctx, 2) > 1;
2552 CLIParserFree(ctx);
2554 // read dump file
2555 uint8_t *dump = NULL;
2556 size_t bytes_read = 0;
2557 int res = pm3_load_dump(filename, (void **)&dump, &bytes_read, (MFU_MAX_BYTES + MFU_DUMP_PREFIX_LENGTH));
2558 if (res != PM3_SUCCESS) {
2559 return res;
2562 uint32_t block0 = bytes_to_num(dump, EM4X05_BLOCK_SIZE);
2563 em_tech_type_t cardtype = em_get_card_type(block0);
2564 em4x05_print_type(cardtype);
2566 if (verbose) {
2567 uint32_t serial = bytes_to_num(dump + EM4X05_BLOCK_SIZE, EM4X05_BLOCK_SIZE);
2568 uint32_t config = bytes_to_num(dump + (EM_CONFIG_BLOCK * EM4X05_BLOCK_SIZE), EM4X05_BLOCK_SIZE);
2569 printEM4x05info(block0, serial);
2571 if (verbose2) {
2572 printEM4x05config(cardtype, config);
2576 em4x05_print_hdr();
2577 em4x05_print_blocks(cardtype, dump, bytes_read);
2578 em4x05_print_footer();
2579 free(dump);
2581 PrintAndLogEx(INFO, "Note:");
2582 PrintAndLogEx(INFO, "All ZEROS password block might be filler data");
2583 return PM3_SUCCESS;
2586 static int CmdEM4x05Config(const char *Cmd) {
2588 CLIParserContext *ctx;
2589 CLIParserInit(&ctx, "lf em 4x05 config",
2590 "Create common configuration blocks",
2591 "lf em 4x05 config"
2593 void *argtable[] = {
2594 arg_param_begin,
2595 arg_param_end
2597 CLIExecWithReturn(ctx, Cmd, argtable, true);
2598 CLIParserFree(ctx);
2600 PrintAndLogEx(INFO, "Default....... %08X", EM4305_DEFAULT_CONFIG_BLOCK);
2601 PrintAndLogEx(INFO, "EM / UNIQUE... %08X", EM4305_EM_UNIQUE_CONFIG_BLOCK);
2602 PrintAndLogEx(INFO, "PAXTON........ %08X", EM4305_PAXTON_CONFIG_BLOCK);
2603 PrintAndLogEx(INFO, "VISA2000...... %08X", EM4305_VISA2000_CONFIG_BLOCK);
2604 PrintAndLogEx(INFO, "VIKING........ %08X", EM4305_VIKING_CONFIG_BLOCK);
2605 PrintAndLogEx(INFO, "NORALSY....... %08X", EM4305_NORALSY_CONFIG_BLOCK);
2606 PrintAndLogEx(INFO, "PRESCO........ %08X", EM4305_PRESCO_CONFIG_BLOCK);
2607 PrintAndLogEx(INFO, "SECURA KEY.... %08X", EM4305_SECURAKEY_CONFIG_BLOCK);
2608 PrintAndLogEx(INFO, "GALLAGHER..... %08X", EM4305_GALLAGHER_CONFIG_BLOCK);
2609 PrintAndLogEx(INFO, "DESTRON....... %08X", EM4305_DESTRON_CONFIG_BLOCK);
2610 PrintAndLogEx(INFO, "HID-26........ %08X", EM4305_HID_26_CONFIG_BLOCK);
2611 PrintAndLogEx(INFO, "PARADOX....... %08X", EM4305_PARADOX_CONFIG_BLOCK);
2612 PrintAndLogEx(INFO, "AWID.......... %08X", EM4305_AWID_CONFIG_BLOCK);
2613 PrintAndLogEx(INFO, "PYRAMID....... %08X", EM4305_PYRAMID_CONFIG_BLOCK);
2614 PrintAndLogEx(INFO, "IO PROX....... %08X", EM4305_IOPROX_CONFIG_BLOCK);
2615 PrintAndLogEx(INFO, "INDALA 64..... %08X", EM4305_INDALA_64_CONFIG_BLOCK);
2616 PrintAndLogEx(INFO, "INDALA 224.... %08X", EM4305_INDALA_224_CONFIG_BLOCK);
2617 PrintAndLogEx(INFO, "MOTOROLA...... %08X", EM4305_MOTOROLA_CONFIG_BLOCK);
2618 PrintAndLogEx(INFO, "NEXWATCH...... %08X", EM4305_NEXWATCH_CONFIG_BLOCK);
2619 PrintAndLogEx(INFO, "KERI.......... %08X", EM4305_KERI_CONFIG_BLOCK);
2620 PrintAndLogEx(INFO, "IDTECK........ %08X", EM4305_IDTECK_CONFIG_BLOCK);
2621 PrintAndLogEx(INFO, "JABLOTRON..... %08X", EM4305_JABLOTRON_CONFIG_BLOCK);
2622 PrintAndLogEx(INFO, "G-PROX II..... %08X", EM4305_GUARDPROXII_CONFIG_BLOCK);
2623 PrintAndLogEx(INFO, "NEDAP 64...... %08X", EM4305_NEDAP_64_CONFIG_BLOCK);
2624 PrintAndLogEx(INFO, "NEDAP 128..... %08X", EM4305_NEDAP_128_CONFIG_BLOCK);
2625 PrintAndLogEx(INFO, "FDXB.......... %08X", EM4305_FDXB_CONFIG_BLOCK);
2626 PrintAndLogEx(INFO, "PAC........... %08X", EM4305_PAC_CONFIG_BLOCK);
2627 PrintAndLogEx(INFO, "VERICHIP...... %08X", EM4305_VERICHIP_CONFIG_BLOCK);
2628 return PM3_SUCCESS;
2631 static command_t CommandTable[] = {
2632 {"-----------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("General") " -----------------------"},
2633 {"help", CmdHelp, AlwaysAvailable, "This help"},
2634 {"-----------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("Operations") " -----------------------"},
2635 {"clonehelp", CmdEM4x05CloneHelp, IfPm3Lf, "Shows the available clone commands"},
2636 {"brute", CmdEM4x05Brute, IfPm3Lf, "Bruteforce password"},
2637 {"chk", CmdEM4x05Chk, IfPm3Lf, "Check passwords"},
2638 {"config", CmdEM4x05Config, AlwaysAvailable, "Create common configuration words"},
2639 {"demod", CmdEM4x05Demod, AlwaysAvailable, "Demodulate a EM4x05/EM4x69 tag from the GraphBuffer"},
2640 {"dump", CmdEM4x05Dump, IfPm3Lf, "Dump EM4x05/EM4x69 tag"},
2641 {"info", CmdEM4x05Info, IfPm3Lf, "Tag information"},
2642 {"read", CmdEM4x05Read, IfPm3Lf, "Read word data from EM4x05/EM4x69"},
2643 {"sniff", CmdEM4x05Sniff, AlwaysAvailable, "Attempt to recover em4x05 commands from sample buffer"},
2644 {"unlock", CmdEM4x05Unlock, IfPm3Lf, "Execute tear off against EM4x05/EM4x69"},
2645 {"view", CmdEM4x05View, AlwaysAvailable, "Display content from tag dump file"},
2646 {"wipe", CmdEM4x05Wipe, IfPm3Lf, "Wipe EM4x05/EM4x69 tag"},
2647 {"write", CmdEM4x05Write, IfPm3Lf, "Write word data to EM4x05/EM4x69"},
2648 {NULL, NULL, NULL, NULL}
2651 static int CmdHelp(const char *Cmd) {
2652 (void)Cmd; // Cmd is not used so far
2653 CmdsHelp(CommandTable);
2654 return PM3_SUCCESS;
2657 int CmdLFEM4X05(const char *Cmd) {
2658 clearCommandBuffer();
2659 return CmdsParse(CommandTable, Cmd);