From 7094994b574d1f58fed1e6780c6ae03989fc11b8 Mon Sep 17 00:00:00 2001 From: Marcos Del Sol Vives Date: Fri, 22 Jan 2021 16:05:45 +0100 Subject: [PATCH 01/76] Fix nonce acquisition --- armsrc/mifarecmd.c | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 7faa0c268..a4f1d3d83 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -696,7 +696,7 @@ void MifareAcquireNonces(uint32_t arg0, uint32_t flags) { LED_C_ON(); - for (uint16_t i = 0; i <= PM3_CMD_DATA_SIZE - 4; i += 4) { + while (num_nonces < PM3_CMD_DATA_SIZE / 4) { // Test if the action was cancelled if (BUTTON_PRESS()) { @@ -746,18 +746,14 @@ void MifareAcquireNonces(uint32_t arg0, uint32_t flags) { continue; } - num_nonces++; - // Save the tag nonce (nt) - buf[i] = answer[0]; - buf[i + 1] = answer[1]; - buf[i + 2] = answer[2]; - buf[i + 3] = answer[3]; + memcpy(buf + num_nonces * 4, answer, 4); + num_nonces++; } LED_C_OFF(); LED_B_ON(); - reply_old(CMD_ACK, isOK, cuid, num_nonces - 1, buf, sizeof(buf)); + reply_old(CMD_ACK, isOK, cuid, num_nonces, buf, sizeof(buf)); LED_B_OFF(); if (DBGLEVEL >= 3) DbpString("AcquireNonces finished"); From 8bf89436f86a600a8707b8433426f4f2aa1f00d2 Mon Sep 17 00:00:00 2001 From: Marcos Del Sol Vives Date: Fri, 22 Jan 2021 16:06:39 +0100 Subject: [PATCH 02/76] Improve error messages on encrypted nonce acquisition --- armsrc/mifarecmd.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index a4f1d3d83..4880d01e9 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -822,7 +822,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, if (!have_uid) { // need a full select cycle to get the uid first iso14a_card_select_t card_info; if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { - if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireNonces: Can't select card (ALL)"); + if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Can't select card (ALL)"); continue; } switch (card_info.uidlen) { @@ -841,7 +841,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, have_uid = true; } else { // no need for anticollision. We can directly select the card if (!iso14443a_fast_select_card(uid, cascade_levels)) { - if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireNonces: Can't select card (UID)"); + if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Can't select card (UID)"); continue; } } @@ -851,7 +851,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint32_t nt1; if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) { - if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireNonces: Auth1 error"); + if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Auth1 error"); continue; } @@ -862,7 +862,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, CHK_TIMEOUT(); if (len != 4) { - if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireNonces: Auth2 error len=%d", len); + if (DBGLEVEL >= DBG_ERROR) Dbprintf("AcquireEncryptedNonces: Auth2 error len=%d", len); continue; } From 37f4dee7277c62e5be0ec22c330c5f14273d117b Mon Sep 17 00:00:00 2001 From: Marcos Del Sol Vives Date: Fri, 22 Jan 2021 22:21:08 +0100 Subject: [PATCH 03/76] Fix out of bounds read --- client/src/ui.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/ui.c b/client/src/ui.c index 3b85f4e94..293a98c58 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -474,7 +474,7 @@ static bool emojify_token(const char *token, uint8_t token_length, const char ** case EMO_ALTTEXT: { int j = 0; *emojified_token_length = 0; - while (EmojiAltTable[j].alias && EmojiAltTable[i].alttext) { + while (EmojiAltTable[j].alias && EmojiAltTable[j].alttext) { if ((strlen(EmojiAltTable[j].alias) == token_length) && (0 == memcmp(EmojiAltTable[j].alias, token, token_length))) { *emojified_token = EmojiAltTable[j].alttext; *emojified_token_length = strlen(EmojiAltTable[j].alttext); From 4d2d65a0c6d5a498dbf329287c5ce1e9453f5eef Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 22 Jan 2021 22:58:50 +0100 Subject: [PATCH 04/76] lf fdx reader - check both 125 / 134 freqs. --- client/src/cmdlffdxb.c | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/client/src/cmdlffdxb.c b/client/src/cmdlffdxb.c index 529f63019..fdead8ea9 100644 --- a/client/src/cmdlffdxb.c +++ b/client/src/cmdlffdxb.c @@ -653,16 +653,10 @@ static int CmdFdxBReader(const char *Cmd) { return res; } - int16_t tmp_div = config.divisor; - if (tmp_div != LF_DIVISOR_134) { - config.divisor = LF_DIVISOR_134; - config.verbose = false; - res = lf_config(&config); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "failed to change LF configuration"); - return res; - } - } + config.verbose = false; + + int16_t old_div = config.divisor; + int16_t curr_div = config.divisor; if (cm) { PrintAndLogEx(INFO, "Press " _GREEN_("") " to exit"); @@ -670,13 +664,32 @@ static int CmdFdxBReader(const char *Cmd) { int ret = PM3_SUCCESS; do { + + if (curr_div == LF_DIVISOR_125) { + config.divisor = LF_DIVISOR_134; + res = lf_config(&config); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to change to 134 KHz LF configuration"); + return res; + } + } else { + config.divisor = LF_DIVISOR_125; + res = lf_config(&config); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to change to 125 KHz LF configuration"); + return res; + } + } + curr_div = config.divisor; + lf_read(false, 10000); ret = demodFDXB(!cm); // be verbose only if not in continuous mode - //PrintAndLogEx(INPLACE, ""); + } while (cm && !kbd_enter_pressed()); - if (tmp_div != LF_DIVISOR_134) { - config.divisor = tmp_div; + + if (old_div != curr_div) { + config.divisor = old_div; res = lf_config(&config); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "failed to restore LF configuration"); From 2987fdb18734fc0bb012b36f0a2000815d39e991 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 23 Jan 2021 19:08:45 +0100 Subject: [PATCH 05/76] added warning prefix --- client/deps/cliparser/argtable3.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/client/deps/cliparser/argtable3.c b/client/deps/cliparser/argtable3.c index 2fe32b082..43701d735 100644 --- a/client/deps/cliparser/argtable3.c +++ b/client/deps/cliparser/argtable3.c @@ -2554,18 +2554,18 @@ static void arg_lit_errorfn( switch (errorcode) { case EMINCOUNT: - fprintf(fp, "%s: missing option ", progname); + fprintf(fp, "[!] %s: missing option ", progname); arg_print_option(fp, shortopts, longopts, datatype, "\n"); fprintf(fp, "\n"); break; case EMAXCOUNT: - fprintf(fp, "%s: extraneous option ", progname); + fprintf(fp, "[!] %s: extraneous option ", progname); arg_print_option(fp, shortopts, longopts, datatype, "\n"); break; } - ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, fp, + ARG_TRACE(("[!] %s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, fp, errorcode, argval, progname)); } @@ -2859,7 +2859,7 @@ static void arg_rex_errorfn(struct arg_rex *parent, /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); @@ -3790,7 +3790,7 @@ static void arg_str_errorfn( /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); From b2ba09b8b4d21429647d9b9be6bae4db1cbaa3d7 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 23 Jan 2021 22:37:25 +0100 Subject: [PATCH 06/76] changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 323774a34..868fe6877 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Added support for bidirectional communication for `lf em 4x50 sim` (@tharexde) + - Change `PLATFORM=PM3OTHER` to `PLATFORM=PM3GENERIC` (@iceman1001) - Added `tools/hitag2crack/crack5opencl`, an optimized version of `crack5gpu` (@matrix) - Fixed Makefile to account for changes when running on Apple Silicon (@tcprst) - Added support for debugging ARM with JTAG & VSCode (@Gator96100) From 0fee0c97cb7526f58f279e43a91dc0a06e450738 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 23 Jan 2021 22:38:07 +0100 Subject: [PATCH 07/76] make style --- armsrc/em4x50.c | 80 +++++------ client/src/cmdlfem4x50.c | 6 +- doc/commands.md | 27 ++-- .../crack5opencl/ht2crack5opencl.c | 19 ++- tools/hitag2crack/crack5opencl/opencl.c | 134 +++++++++--------- tools/hitag2crack/crack5opencl/opencl.h | 2 +- tools/hitag2crack/crack5opencl/threads.c | 5 +- 7 files changed, 135 insertions(+), 138 deletions(-) diff --git a/armsrc/em4x50.c b/armsrc/em4x50.c index f27a21367..a9eea7ad2 100644 --- a/armsrc/em4x50.c +++ b/armsrc/em4x50.c @@ -185,7 +185,7 @@ static void em4x50_setup_sim(void) { AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT | GPIO_SSC_CLK; AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK; - + AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0); AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; @@ -194,7 +194,7 @@ static void em4x50_setup_sim(void) { // Watchdog hit WDT_HIT(); - + LEDsoff(); } @@ -1118,7 +1118,7 @@ static void em4x50_sim_send_bit(uint8_t bit) { // wait until SSC_CLK goes HIGH // used as a simple detection of a reader field? while ((timeout--) && !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)); - + if (timeout <= 0) { return; } @@ -1194,19 +1194,19 @@ static void wait_cycles(int maxperiods) { int period = 0, timeout = EM4X50_T_SIMULATION_TIMEOUT_WAIT; while (period < maxperiods) { - + while ((timeout--) && !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)); if (timeout <= 0) { return; } timeout = EM4X50_T_SIMULATION_TIMEOUT_WAIT; - + while ((timeout--) && (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)); if (timeout <= 0) { return; } timeout = EM4X50_T_SIMULATION_TIMEOUT_WAIT; - + period++; } } @@ -1232,7 +1232,7 @@ static int em4x50_sim_read_bit(void) { // gap detected; wait until reader field is switched on again while ((timeout--) && (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)); - + if (timeout <= 0) { return PM3_ETIMEOUT; } @@ -1259,12 +1259,12 @@ static int em4x50_sim_read_bit(void) { // read byte in simulation mode either with or without parity check (even) static bool em4x50_sim_read_byte(uint8_t *byte, bool paritycheck) { - + for (int i = 0; i < 8; i++) { *byte <<= 1; *byte |= em4x50_sim_read_bit(); } - + if (paritycheck) { int pval = em4x50_sim_read_bit(); @@ -1280,12 +1280,12 @@ static bool em4x50_sim_read_byte(uint8_t *byte, bool paritycheck) { } return true; - + } // read complete word in simulation mode static bool em4x50_sim_read_word(uint32_t *word) { - + uint8_t stop_bit = 0; uint8_t parities = 0, parities_calculated = 0; uint8_t bytes[4] = {0}; @@ -1306,20 +1306,20 @@ static bool em4x50_sim_read_word(uint32_t *word) { parities_calculated ^= (bytes[j] >> (7 - i)) & 1; } } - + *word = BYTES2UINT32(bytes); - + // check parities if ((parities == parities_calculated) && (stop_bit == 0)) { return true; } - + return false; } // check if reader requests receive mode (rm) by sending two zeros static int check_rm_request(uint32_t *tag) { - + // look for first zero int bit = em4x50_sim_read_bit(); if (bit == 0) { @@ -1340,13 +1340,13 @@ static int check_rm_request(uint32_t *tag) { } } } - + return (bit != PM3_ETIMEOUT) ? PM3_SUCCESS : PM3_ETIMEOUT; } // send single listen window in simulation mode static int em4x50_sim_send_listen_window(uint32_t *tag) { - + SHORT_COIL(); wait_cycles(EM4X50_T_TAG_HALF_PERIOD); @@ -1388,7 +1388,7 @@ static void em4x50_sim_send_ack(void) { OPEN_COIL(); wait_cycles(EM4X50_T_TAG_HALF_PERIOD); - + SHORT_COIL(); } @@ -1419,7 +1419,7 @@ static void em4x50_sim_send_nak(void) { // standard read mode process (simulation mode) static int em4x50_sim_handle_standard_read_command(uint32_t *tag) { - + int command = 0; // extract control data @@ -1462,11 +1462,11 @@ static int em4x50_sim_handle_standard_read_command(uint32_t *tag) { static int em4x50_sim_handle_selective_read_command(uint32_t *tag) { int command = 0; - + // read password uint32_t address = 0; bool addr = em4x50_sim_read_word(&address); - + // processing pause time (corresponds to a "1" bit) em4x50_sim_send_bit(1); @@ -1486,7 +1486,7 @@ static int em4x50_sim_handle_selective_read_command(uint32_t *tag) { int fwrp = reflect32(tag[EM4X50_PROTECTION]) & 0xFF; // last word read protected int lwrp = (reflect32(tag[EM4X50_PROTECTION]) >> 8) & 0xFF; - + while ((BUTTON_PRESS() == false) && (data_available() == false)) { WDT_HIT(); @@ -1521,7 +1521,7 @@ static int em4x50_sim_handle_login_command(uint32_t *tag) { // read password uint32_t password = 0; bool pwd = em4x50_sim_read_word(&password); - + // processing pause time (corresponds to a "1" bit) em4x50_sim_send_bit(1); @@ -1548,10 +1548,10 @@ static int em4x50_sim_handle_reset_command(uint32_t *tag) { em4x50_sim_send_ack(); gLogin = false; LED_A_OFF(); - + // wait for initialization (tinit) wait_cycles(EM4X50_T_TAG_TINIT); - + // continue with standard read mode return EM4X50_COMMAND_STANDARD_READ; } @@ -1565,7 +1565,7 @@ static int em4x50_sim_handle_write_command(uint32_t *tag) { // read data uint32_t data = 0; bool word = em4x50_sim_read_word(&data); - + // write access time wait_cycles(EM4X50_T_TAG_TWA); @@ -1634,7 +1634,7 @@ static int em4x50_sim_handle_write_command(uint32_t *tag) { } break; } - + // EEPROM write time // strange: need some sort of 'waveform correction', otherwise ack signal // will not be detected; sending a single "1" as last "bit" of Twee @@ -1666,18 +1666,18 @@ static int em4x50_sim_handle_write_command(uint32_t *tag) { static int em4x50_sim_handle_writepwd_command(uint32_t *tag) { bool pwd = false; - + if (gWritePasswordProcess == false) { - + gWritePasswordProcess = true; // read password uint32_t act_password = 0; pwd = em4x50_sim_read_word(&act_password); - + // processing pause time (corresponds to a "1" bit) em4x50_sim_send_bit(1); - + if (pwd && (act_password == reflect32(tag[EM4X50_DEVICE_PASSWORD]))) { em4x50_sim_send_ack(); gLogin = true; @@ -1710,7 +1710,7 @@ static int em4x50_sim_handle_writepwd_command(uint32_t *tag) { em4x50_sim_send_ack(); return EM4X50_COMMAND_STANDARD_READ; } - + // EEPROM write time // strange: need some sort of 'waveform correction', otherwise ack signal // will not be detected; sending a single "1" as last part of Twee @@ -1722,7 +1722,7 @@ static int em4x50_sim_handle_writepwd_command(uint32_t *tag) { // continue with standard read mode return EM4X50_COMMAND_STANDARD_READ; } - + // call writepwd function again for else branch return EM4X50_COMMAND_WRITE_PASSWORD; } @@ -1732,15 +1732,15 @@ static int em4x50_sim_handle_writepwd_command(uint32_t *tag) { // LED B -> standard read mode is active // LED C -> command has been transmitted by reader void em4x50_sim(uint32_t *password) { - + int command = PM3_ENODATA; - + uint8_t *em4x50_mem = BigBuf_get_EM_addr(); uint32_t tag[EM4X50_NO_WORDS] = {0x0}; for (int i = 0; i < EM4X50_NO_WORDS; i++) tag[i] = bytes_to_num(em4x50_mem + (i * 4), 4); - + // via eload uploaded dump usually does not contain a password if (tag[EM4X50_DEVICE_PASSWORD] == 0) { tag[EM4X50_DEVICE_PASSWORD] = reflect32(*password); @@ -1790,25 +1790,25 @@ void em4x50_sim(uint32_t *password) { LED_C_ON(); command = em4x50_sim_handle_selective_read_command(tag); break; - + case EM4X50_COMMAND_STANDARD_READ: LED_B_ON(); LED_C_OFF(); command = em4x50_sim_handle_standard_read_command(tag); break; - + // bit errors during reading may lead to unknown commands // -> continue with standard read mode default: command = EM4X50_COMMAND_STANDARD_READ; break; } - + // stop if key (pm3 button or enter key) has been pressed if (command == PM3_EOPABORTED) { break; } - + // if timeout (e.g. no reader field) continue with standard read // mode and reset former authentication if (command == PM3_ETIMEOUT) { diff --git a/client/src/cmdlfem4x50.c b/client/src/cmdlfem4x50.c index 84c331337..ae99bd8a6 100644 --- a/client/src/cmdlfem4x50.c +++ b/client/src/cmdlfem4x50.c @@ -1129,10 +1129,10 @@ int CmdEM4x50Restore(const char *Cmd) { } int CmdEM4x50Sim(const char *Cmd) { - + int status = PM3_EFAILED; uint32_t password = 0; - + CLIParserContext *ctx; CLIParserInit(&ctx, "lf em 4x50 sim", "Simulates a EM4x50 tag.\n" @@ -1168,7 +1168,7 @@ int CmdEM4x50Sim(const char *Cmd) { clearCommandBuffer(); SendCommandNG(CMD_LF_EM4X50_SIM, (uint8_t *)&password, sizeof(password)); PacketResponseNG resp; - + PrintAndLogEx(INFO, "Press pm3-button to abort simulation"); bool keypress = kbd_enter_pressed(); while (keypress == false) { diff --git a/doc/commands.md b/doc/commands.md index 33b47f975..3c55c5368 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -38,6 +38,7 @@ Check column "offline" for their availability. |`analyse nuid `|Y |`create NUID from 7byte UID` |`analyse demodbuff `|Y |`Load binary string to demodbuffer` |`analyse freq `|Y |`Calc wave lengths` +|`analyse foo `|Y |`muxer` ### data @@ -883,25 +884,25 @@ Check column "offline" for their availability. |`lf t55xx help `|Y |`This help` |`lf t55xx clonehelp `|N |`Shows the available clone commands` |`lf t55xx config `|Y |`Set/Get T55XX configuration (modulation, inverted, offset, rate)` -|`lf t55xx dangerraw `|N |`Sends raw bitstream. Dangerous, do not use!! b t ` -|`lf t55xx detect `|Y |`[1] Try detecting the tag modulation from reading the configuration block.` -|`lf t55xx deviceconfig `|N |`Set/Get T55XX device configuration (startgap, writegap, write0, write1, readgap` -|`lf t55xx dump `|N |`[password] [o] Dump T55xx card Page 0 block 0-7. Optional [password], [override]` -|`lf t55xx info `|Y |`[1] Show T55x7 configuration data (page 0/ blk 0)` -|`lf t55xx p1detect `|N |`[1] Try detecting if this is a t55xx tag by reading page 1` -|`lf t55xx read `|N |`b p [password] [o] [1] -- Read T55xx block data. Optional [p password], [override], [page1]` +|`lf t55xx dangerraw `|N |`Sends raw bitstream. Dangerous, do not use!!` +|`lf t55xx detect `|Y |`Try detecting the tag modulation from reading the configuration block` +|`lf t55xx deviceconfig `|N |`Set/Get T55XX device configuration` +|`lf t55xx dump `|N |`Dump T55xx card Page 0 block 0-7` +|`lf t55xx info `|Y |`Show T55x7 configuration data (page 0/ blk 0)` +|`lf t55xx p1detect `|N |`Try detecting if this is a t55xx tag by reading page 1` +|`lf t55xx read `|N |`Read T55xx block data` |`lf t55xx resetread `|N |`Send Reset Cmd then lf read the stream to attempt to identify the start of it (needs a demod and/or plot after)` -|`lf t55xx restore `|N |`f [p ] Restore T55xx card Page 0 / Page 1 blocks` -|`lf t55xx trace `|Y |`[1] Show T55x7 traceability data (page 1/ blk 0-1)` +|`lf t55xx restore `|N |`Restore T55xx card Page 0 / Page 1 blocks` +|`lf t55xx trace `|Y |`Show T55x7 traceability data (page 1/ blk 0-1)` |`lf t55xx wakeup `|N |`Send AOR wakeup command` -|`lf t55xx write `|N |`b d p [password] [1] -- Write T55xx block data. Optional [p password], [page1]` -|`lf t55xx bruteforce `|N |` Simple bruteforce attack to find password` +|`lf t55xx write `|N |`Write T55xx block data` +|`lf t55xx bruteforce `|N |`Simple bruteforce attack to find password` |`lf t55xx chk `|N |`Check passwords from dictionary/flash` |`lf t55xx protect `|N |`Password protect tag` -|`lf t55xx recoverpw `|N |`[password] Try to recover from bad password write from a cloner. Only use on PW protected chips!` +|`lf t55xx recoverpw `|N |`Try to recover from bad password write from a cloner` |`lf t55xx sniff `|Y |`Attempt to recover T55xx commands from sample buffer` |`lf t55xx special `|N |`Show block changes with 64 different offsets` -|`lf t55xx wipe `|N |`[q] Wipe a T55xx tag and set defaults (will destroy any data on tag)` +|`lf t55xx wipe `|N |`Wipe a T55xx tag and set defaults (will destroy any data on tag)` ### lf viking diff --git a/tools/hitag2crack/crack5opencl/ht2crack5opencl.c b/tools/hitag2crack/crack5opencl/ht2crack5opencl.c index 87fb2c765..924932b2c 100644 --- a/tools/hitag2crack/crack5opencl/ht2crack5opencl.c +++ b/tools/hitag2crack/crack5opencl/ht2crack5opencl.c @@ -454,12 +454,11 @@ int main(int argc, char **argv) { if (show) verbose = true; // now discover and set up compute device(s) - if ((err = discoverDevices(profile_selected, device_types_selected, &ocl_platform_cnt, &selected_platforms_cnt, &selected_devices_cnt, &cd_ctx, plat_sel, plat_cnt, dev_sel, dev_cnt, verbose, show)) != 0) - { - printf ("Error: discoverDevices() failed\n"); - if (err < -5) free (cd_ctx); - MEMORY_FREE_ALL - exit (2); + if ((err = discoverDevices(profile_selected, device_types_selected, &ocl_platform_cnt, &selected_platforms_cnt, &selected_devices_cnt, &cd_ctx, plat_sel, plat_cnt, dev_sel, dev_cnt, verbose, show)) != 0) { + printf("Error: discoverDevices() failed\n"); + if (err < -5) free(cd_ctx); + MEMORY_FREE_ALL + exit(2); } if (verbose) printf("\n"); @@ -776,7 +775,7 @@ int main(int argc, char **argv) { err = clGetProgramBuildInfo(ctx.programs[z], cd_ctx[w].device[q].device_id, CL_PROGRAM_BUILD_LOG, len, buffer, 0); if (err != CL_SUCCESS) { printf("[%zu] clGetProgramBuildInfo() failed (%d)\n", z, err); - free (buffer); + free(buffer); continue; } @@ -787,7 +786,7 @@ int main(int argc, char **argv) { printf("[%zu] Build log (len %zu):\n--------\n%s\n--------\n", z, len, buffer); } - free (buffer); + free(buffer); build_logs++; #if DEBUGME == 0 @@ -832,7 +831,7 @@ int main(int argc, char **argv) { } // setup, phase 2 (select lower profile) - unsigned int profile = get_smallest_profile (cd_ctx, ocl_platform_cnt); + unsigned int profile = get_smallest_profile(cd_ctx, ocl_platform_cnt); // setup, phase 3 (finis him) @@ -1126,7 +1125,7 @@ int main(int argc, char **argv) { } // Hokuto Hyakuretsu Ken - ret = thread_start_scheduler (&th_ctx, t_arg, &ctx.queue_ctx); + ret = thread_start_scheduler(&th_ctx, t_arg, &ctx.queue_ctx); if (ret < 0) { printf("Error: thread_start_scheduler() failed (%d): %s\n", ret, thread_strerror(ret)); error = true; diff --git a/tools/hitag2crack/crack5opencl/opencl.c b/tools/hitag2crack/crack5opencl/opencl.c index ecee691b7..98b85714e 100644 --- a/tools/hitag2crack/crack5opencl/opencl.c +++ b/tools/hitag2crack/crack5opencl/opencl.c @@ -40,8 +40,7 @@ bool plat_dev_enabled(unsigned int id, unsigned int *sel, unsigned int cnt, unsi return false; } -unsigned int get_smallest_profile (compute_platform_ctx_t *cd_ctx, size_t ocl_platform_cnt) -{ +unsigned int get_smallest_profile(compute_platform_ctx_t *cd_ctx, size_t ocl_platform_cnt) { unsigned int profile = 0xff; size_t x = 0, y = 0; @@ -68,8 +67,7 @@ unsigned int get_smallest_profile (compute_platform_ctx_t *cd_ctx, size_t ocl_pl return profile; } -int discoverDevices(unsigned int profile_selected, uint32_t device_types_selected, cl_uint *platform_detected_cnt, size_t *selected_platforms_cnt, size_t *selected_devices_cnt, compute_platform_ctx_t **cd_ctx, unsigned int *plat_sel, unsigned int plat_cnt, unsigned int *dev_sel, unsigned int dev_cnt, bool verbose, bool show) -{ +int discoverDevices(unsigned int profile_selected, uint32_t device_types_selected, cl_uint *platform_detected_cnt, size_t *selected_platforms_cnt, size_t *selected_devices_cnt, compute_platform_ctx_t **cd_ctx, unsigned int *plat_sel, unsigned int plat_cnt, unsigned int *dev_sel, unsigned int dev_cnt, bool verbose, bool show) { int err = 0; unsigned int ocl_platform_max = MAX_OPENCL_DEVICES; // 16 cl_uint ocl_platform_cnt; @@ -84,13 +82,13 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetPlatformIDs(ocl_platform_max, ocl_platforms, &ocl_platform_cnt); if (err != CL_SUCCESS) { printf("Error: clGetPlatformIDs() failed (%d)\n", err); - free (ocl_platforms); + free(ocl_platforms); return -3; } if (ocl_platform_cnt == 0) { printf("No platforms found, exit\n"); - free (ocl_platforms); + free(ocl_platforms); return -4; } @@ -98,7 +96,7 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte *cd_ctx = (compute_platform_ctx_t *) calloc(ocl_platform_cnt, sizeof(compute_platform_ctx_t)); if (*cd_ctx == NULL) { printf("Error: calloc (compute_platform_ctx_t) failed (%d): %s\n", errno, strerror(errno)); - free (ocl_platforms); + free(ocl_platforms); return -5; } @@ -120,7 +118,7 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte (*cd_ctx)[platform_idx].platform_id = ocl_platforms[platform_idx]; (*cd_ctx)[platform_idx].selected = plat_dev_enabled(platform_idx, plat_sel, plat_cnt, 0, 0); - if ((*cd_ctx)[platform_idx].selected) (*selected_platforms_cnt)++; + if ((*cd_ctx)[platform_idx].selected)(*selected_platforms_cnt)++; if (verbose) printf("\n-- Platform ID: %d\n", platform_idx + 1); @@ -130,33 +128,33 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetPlatformInfo((*cd_ctx)[platform_idx].platform_id, ocl_info, 0, NULL, &tmp_len); if (err != CL_SUCCESS) { printf("Error: clGetPlatformInfo(param size) failed (%d)\n", err); - free (*cd_ctx); - free (ocl_platforms); + free(*cd_ctx); + free(ocl_platforms); return -6; } if (tmp_len > 0) { if (!(tmp_buf = (char *) calloc(tmp_len, sizeof(char)))) { printf("Error: calloc (ocl_info %u) failed (%d): %s\n", info_idx, errno, strerror(errno)); - free (*cd_ctx); - free (ocl_platforms); + free(*cd_ctx); + free(ocl_platforms); return -7; } err = clGetPlatformInfo((*cd_ctx)[platform_idx].platform_id, ocl_info, tmp_len, tmp_buf, 0); if (err != CL_SUCCESS) { printf("Error: clGetPlatformInfo(param) failed (%d)\n", err); - free (tmp_buf); - free (*cd_ctx); - free (ocl_platforms); + free(tmp_buf); + free(*cd_ctx); + free(ocl_platforms); return -8; } } else { tmp_len = 4; if (!(tmp_buf = (char *) calloc(tmp_len, sizeof(char)))) { printf("Error: calloc (ocl_info %u) failed (%d): %s\n", info_idx, errno, strerror(errno)); - free (*cd_ctx); - free (ocl_platforms); + free(*cd_ctx); + free(ocl_platforms); return -7; } @@ -182,13 +180,13 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte } if (info_idx == 1) { - if (!strncmp(tmp_buf, "NVIDIA", 6)) (*cd_ctx)[platform_idx].is_nv = true; + if (!strncmp(tmp_buf, "NVIDIA", 6))(*cd_ctx)[platform_idx].is_nv = true; else if (!strncmp(tmp_buf, "Apple", 5)) { (*cd_ctx)[platform_idx].is_apple = true; (*cd_ctx)[platform_idx].warning = true; } - else if (!strncmp(tmp_buf, "Intel", 5)) (*cd_ctx)[platform_idx].is_intel = true; - else if (!strncmp(tmp_buf, "The pocl project", 16)) (*cd_ctx)[platform_idx].is_pocl = true; + else if (!strncmp(tmp_buf, "Intel", 5))(*cd_ctx)[platform_idx].is_intel = true; + else if (!strncmp(tmp_buf, "The pocl project", 16))(*cd_ctx)[platform_idx].is_pocl = true; } - free (tmp_buf); + free(tmp_buf); } if (!show && verbose) { @@ -203,8 +201,8 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte cl_device_id *ocl_devices = (cl_device_id *) calloc(ocl_device_max, sizeof(cl_device_id)); if (!ocl_devices) { printf("Error: calloc (ocl_devices) failed (%d): %s\n", errno, strerror(errno)); - free (*cd_ctx); - free (ocl_platforms); + free(*cd_ctx); + free(ocl_platforms); return -7; } @@ -217,9 +215,9 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte if (err != CL_SUCCESS) { printf("Error: clGetDeviceIDs(cnt) failed (%d)\n", err); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -9; } @@ -243,13 +241,13 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetDeviceInfo(ocl_device, ocl_dev_info, sizeof(cl_device_type), &device_type, 0); if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(device_type) failed (%d)\n", err); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } - if (device_type & CL_DEVICE_TYPE_GPU) (*cd_ctx)[platform_idx].device[device_idx].is_gpu = 1; + if (device_type & CL_DEVICE_TYPE_GPU)(*cd_ctx)[platform_idx].device[device_idx].is_gpu = 1; else if ((device_type & CL_DEVICE_TYPE_CPU) && (*cd_ctx)[platform_idx].is_pocl) { (*cd_ctx)[platform_idx].device[device_idx].profile = (profile_selected > 1) ? 0 : profile_selected; } @@ -258,7 +256,7 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte (*cd_ctx)[platform_idx].device[device_idx].selected = plat_dev_enabled(global_device_id, dev_sel, dev_cnt, (unsigned int) device_type, device_types_selected); global_device_id++; - if ((*cd_ctx)[platform_idx].device[device_idx].selected) (*selected_devices_cnt)++; + if ((*cd_ctx)[platform_idx].device[device_idx].selected)(*selected_devices_cnt)++; continue; } else if (info_idx == 5) { cl_device_local_mem_type local_mem_type; @@ -266,9 +264,9 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetDeviceInfo(ocl_device, ocl_dev_info, sizeof(cl_device_local_mem_type), &local_mem_type, 0); if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(local_mem_type) failed (%d)\n", err); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } @@ -279,9 +277,9 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte (*cd_ctx)[platform_idx].device[device_idx].have_local_memory = true; if ((*cd_ctx)[platform_idx].device[device_idx].is_gpu) { - if (profile_selected > 2) (*cd_ctx)[platform_idx].device[device_idx].profile = PROFILE_DEFAULT; // Apple-Intel GPU's + if (profile_selected > 2)(*cd_ctx)[platform_idx].device[device_idx].profile = PROFILE_DEFAULT; // Apple-Intel GPU's } else { - if (profile_selected > 3) (*cd_ctx)[platform_idx].device[device_idx].profile = PROFILE_DEFAULT; // Apple-Intel CPU's + if (profile_selected > 3)(*cd_ctx)[platform_idx].device[device_idx].profile = PROFILE_DEFAULT; // Apple-Intel CPU's } } } else if ((*cd_ctx)[platform_idx].is_nv) { @@ -299,9 +297,9 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetDeviceInfo(ocl_device, ocl_dev_info, sizeof(size_t) * 3, wis, 0); if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(work_items_size) failed (%d)\n", err); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } @@ -318,9 +316,9 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetDeviceInfo(ocl_device, ocl_dev_info, sizeof(cl_uint), &cores, 0); if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(compute_units) failed (%d)\n", err); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } @@ -336,37 +334,37 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte err = clGetDeviceInfo(ocl_device, ocl_dev_info, 0, NULL, &tmp_len); if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(param size) failed (%d)\n", err); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } if (tmp_len > 0) { if (!(tmp_buf = (char *) calloc(tmp_len, sizeof(char)))) { printf("Error: calloc (ocl_dev_info %u) failed (%d): %s\n", info_idx, errno, strerror(errno)); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -7; } err = clGetDeviceInfo(ocl_device, ocl_dev_info, tmp_len, tmp_buf, 0); if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(param) failed (%d)\n", err); - free (tmp_buf); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(tmp_buf); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } } else { tmp_len = 4; if (!(tmp_buf = (char *) calloc(tmp_len, sizeof(char)))) { printf("Error: calloc (ocl_dev_info %u) failed (%d): %s\n", info_idx, errno, strerror(errno)); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -7; } @@ -395,10 +393,10 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte } if (info_idx == 1) { - // force profile to 0-1 with Jetson Nano - if (strstr(tmp_buf, "Tegra") && (*cd_ctx)[platform_idx].is_pocl) { - (*cd_ctx)[platform_idx].device[device_idx].profile = (profile_selected > 1) ? 0 : profile_selected; - } + // force profile to 0-1 with Jetson Nano + if (strstr(tmp_buf, "Tegra") && (*cd_ctx)[platform_idx].is_pocl) { + (*cd_ctx)[platform_idx].device[device_idx].profile = (profile_selected > 1) ? 0 : profile_selected; + } } else if (info_idx == 4) { if (!strncmp(tmp_buf, "Intel", 5)) { if ((*cd_ctx)[platform_idx].is_apple) { @@ -410,7 +408,7 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte if ((*cd_ctx)[platform_idx].device[device_idx].is_gpu) { (*cd_ctx)[platform_idx].device[device_idx].profile = 0; // Intel GPU's, work better with a very slow profile } else { - (*cd_ctx)[platform_idx].device[device_idx].profile = (profile_selected > 2) ? PROFILE_DEFAULT : profile_selected; // Intel CPU's + (*cd_ctx)[platform_idx].device[device_idx].profile = (profile_selected > 2) ? PROFILE_DEFAULT : profile_selected; // Intel CPU's } } } @@ -423,10 +421,10 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte if (err != CL_SUCCESS) { printf("Error: clGetDeviceInfo(sm_maj/sm_min) failed (%d)\n", err); - free (tmp_buf); - free (ocl_devices); - free (*cd_ctx); - free (ocl_platforms); + free(tmp_buf); + free(ocl_devices); + free(*cd_ctx); + free(ocl_platforms); return -10; } @@ -456,7 +454,7 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte } } - free (tmp_buf); + free(tmp_buf); } if (!show && verbose) printf("%14s: %s\n", "Selected", ((*cd_ctx)[platform_idx].device[device_idx].selected) ? "yes" : "no"); @@ -472,16 +470,16 @@ int discoverDevices(unsigned int profile_selected, uint32_t device_types_selecte (*cd_ctx)[platform_idx].device[device_idx].device_id = ocl_device; } - free (ocl_devices); + free(ocl_devices); ocl_devices = NULL; } - free (ocl_platforms); + free(ocl_platforms); ocl_platforms = NULL; *platform_detected_cnt = ocl_platform_cnt; - if (show) free (*cd_ctx); + if (show) free(*cd_ctx); return 0; } diff --git a/tools/hitag2crack/crack5opencl/opencl.h b/tools/hitag2crack/crack5opencl/opencl.h index 462dbbb4f..76e9857bc 100644 --- a/tools/hitag2crack/crack5opencl/opencl.h +++ b/tools/hitag2crack/crack5opencl/opencl.h @@ -122,7 +122,7 @@ typedef struct opencl_ctx { } opencl_ctx_t; bool plat_dev_enabled(unsigned int id, unsigned int *sel, unsigned int cnt, unsigned int cur_type, unsigned int allow_type); -unsigned int get_smallest_profile (compute_platform_ctx_t *cd_ctx, size_t ocl_platform_cnt); +unsigned int get_smallest_profile(compute_platform_ctx_t *cd_ctx, size_t ocl_platform_cnt); int discoverDevices(unsigned int profile_selected, uint32_t device_types_selected, cl_uint *ocl_platform_cnt, size_t *selected_platforms_cnt, size_t *selected_devices_cnt, compute_platform_ctx_t **cd_ctx, unsigned int *plat_sel, unsigned int plat_cnt, unsigned int *dev_sel, unsigned int dev_cnt, bool verbose, bool show); int runKernel(opencl_ctx_t *ctx, uint32_t cand_base, uint64_t *matches, uint32_t *matches_found, size_t id); diff --git a/tools/hitag2crack/crack5opencl/threads.c b/tools/hitag2crack/crack5opencl/threads.c index ff79a4c74..963425cff 100644 --- a/tools/hitag2crack/crack5opencl/threads.c +++ b/tools/hitag2crack/crack5opencl/threads.c @@ -176,8 +176,7 @@ int thread_init(thread_ctx_t *ctx, short type, size_t thread_count) { return 0; } -int thread_start_scheduler (thread_ctx_t *ctx, thread_args_t *t_arg, wu_queue_ctx_t *queue_ctx) -{ +int thread_start_scheduler(thread_ctx_t *ctx, thread_args_t *t_arg, wu_queue_ctx_t *queue_ctx) { size_t z = 0; bool found = false; bool done = false; @@ -775,7 +774,7 @@ void *computing_process_async(void *arg) { pthread_cond_signal(&a->thread_ctx->thread_cond_usleep); // unlock master/TH_PROCESSING cond #if TDEBUG >= 1 printf("[%s][%zu] after pthread_cond_signal TH_END\n", __func__, z); - fflush (stdout); + fflush(stdout); #endif pthread_mutex_unlock(&a->thread_ctx->thread_mutex_usleep); } From 078a28550f458972401a7dd10f9f350687ec84e8 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 25 Jan 2021 14:28:47 +0100 Subject: [PATCH 08/76] hf mf hardnested - these are called with u16 in the source --- client/deps/hardnested/hardnested_bruteforce.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/deps/hardnested/hardnested_bruteforce.h b/client/deps/hardnested/hardnested_bruteforce.h index 8766362d7..a8e6786d5 100644 --- a/client/deps/hardnested/hardnested_bruteforce.h +++ b/client/deps/hardnested/hardnested_bruteforce.h @@ -25,7 +25,7 @@ typedef struct guess_sum_a8 { float prob; uint64_t num_states; - uint8_t sum_a8_idx; + uint16_t sum_a8_idx; } guess_sum_a8_t; typedef struct noncelistentry { @@ -40,7 +40,7 @@ typedef struct noncelist { guess_sum_a8_t sum_a8_guess[NUM_SUMS]; bool sum_a8_guess_dirty; float expected_num_brute_force; - uint8_t BitFlips[0x400]; + uint16_t BitFlips[0x400]; uint32_t *states_bitarray[2]; uint32_t num_states_bitarray[2]; bool all_bitflips_dirty[2]; From ba8cd6894265bf2095a604d86df0278fb37fff11 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 25 Jan 2021 14:31:17 +0100 Subject: [PATCH 09/76] hf mf hardnested - NUM_SUMS is 19, making loop iterator smaller --- client/src/cmdhfmfhard.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index d75e6b0a3..9061868eb 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -575,7 +575,7 @@ static void init_nonce_memory(void) { nonces[i].num = 0; nonces[i].Sum = 0; nonces[i].first = NULL; - for (uint16_t j = 0; j < NUM_SUMS; j++) { + for (uint8_t j = 0; j < NUM_SUMS; j++) { nonces[i].sum_a8_guess[j].sum_a8_idx = j; nonces[i].sum_a8_guess[j].prob = 0.0; } @@ -679,7 +679,7 @@ static float sum_probability(uint16_t i_K, uint16_t n, uint16_t k) { double p_T_is_k_when_S_is_K = p_hypergeometric(i_K, n, k); double p_S_is_K = p_K[i_K]; double p_T_is_k = 0; - for (uint16_t i = 0; i < NUM_SUMS; i++) { + for (uint8_t i = 0; i < NUM_SUMS; i++) { p_T_is_k += p_K[i] * p_hypergeometric(i, n, k); } return (p_T_is_k_when_S_is_K * p_S_is_K / p_T_is_k); @@ -1044,7 +1044,7 @@ static void estimate_sum_a8(void) { if (first_byte_num == 256) { for (uint16_t i = 0; i < 256; i++) { if (nonces[i].sum_a8_guess_dirty) { - for (uint16_t j = 0; j < NUM_SUMS; j++) { + for (uint8_t j = 0; j < NUM_SUMS; j++) { uint16_t sum_a8_idx = nonces[i].sum_a8_guess[j].sum_a8_idx; nonces[i].sum_a8_guess[j].prob = sum_probability(sum_a8_idx, nonces[i].num, nonces[i].Sum); } @@ -1102,7 +1102,7 @@ static int read_nonce_file(char *filename) { sprintf(progress_string, "Target Block=%d, Keytype=%c", trgBlockNo, trgKeyType == 0 ? 'A' : 'B'); hardnested_print_progress(num_acquired_nonces, progress_string, (float)(1LL << 47), 0); - for (uint16_t i = 0; i < NUM_SUMS; i++) { + for (uint8_t i = 0; i < NUM_SUMS; i++) { if (first_byte_Sum == sums[i]) { first_byte_Sum = i; break; @@ -1152,14 +1152,20 @@ __attribute__((force_align_arg_pointer)) return NULL; } for (uint16_t i = first_byte; i <= last_byte; i++) { + if (nonces[i].BitFlips[bitflip] == 0 && nonces[i].BitFlips[bitflip ^ 0x100] == 0 && nonces[i].first != NULL && nonces[i ^ (bitflip & 0xff)].first != NULL) { + uint8_t parity1 = (nonces[i].first->par_enc) >> 3; // parity of first byte uint8_t parity2 = (nonces[i ^ (bitflip & 0xff)].first->par_enc) >> 3; // parity of nonce with bits flipped + if ((parity1 == parity2 && !(bitflip & 0x100)) // bitflip || (parity1 != parity2 && (bitflip & 0x100))) { // not bitflip + nonces[i].BitFlips[bitflip] = 1; + for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { + if (bitflip_bitarrays[odd_even][bitflip] != NULL) { uint32_t old_count = nonces[i].num_states_bitarray[odd_even]; nonces[i].num_states_bitarray[odd_even] = count_bitarray_AND(nonces[i].states_bitarray[odd_even], bitflip_bitarrays[odd_even][bitflip]); @@ -1344,7 +1350,7 @@ static void simulate_acquire_nonces(void) { if (first_byte_num == 256) { if (hardnested_stage == CHECK_1ST_BYTES) { - for (uint16_t i = 0; i < NUM_SUMS; i++) { + for (uint8_t i = 0; i < NUM_SUMS; i++) { if (first_byte_Sum == sums[i]) { first_byte_Sum = i; break; @@ -1471,7 +1477,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ if (first_byte_num == 256) { if (hardnested_stage == CHECK_1ST_BYTES) { - for (uint16_t i = 0; i < NUM_SUMS; i++) { + for (uint8_t i = 0; i < NUM_SUMS; i++) { if (first_byte_Sum == sums[i]) { first_byte_Sum = i; break; From 134ddf631382e9ed1062801efc4aa40c8ad63a25 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Mon, 25 Jan 2021 17:31:25 +0100 Subject: [PATCH 10/76] hardnested offline: avoid reaching out for pm3 --- client/src/cmdhfmf.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index e9b87add6..9e0b2ba3e 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -576,6 +576,9 @@ static int GetHFMF14AUID(uint8_t *uid, int *uidlen) { } static char *GenerateFilename(const char *prefix, const char *suffix) { + if (! IfPm3Iso14443a()) { + return NULL; + } uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int uidlen = 0; char *fptr = calloc(sizeof(char) * (strlen(prefix) + strlen(suffix)) + sizeof(uid) * 2 + 1, sizeof(uint8_t)); @@ -1972,8 +1975,9 @@ static int CmdHF14AMfNestedHard(const char *Cmd) { uint64_t foundkey = 0; int16_t isOK = mfnestedhard(blockNo, keyType, key, trgBlockNo, trgKeyType, know_target_key ? trgkey : NULL, nonce_file_read, nonce_file_write, slow, tests, &foundkey, filename); - if (tests == 0) + if ((tests == 0) && IfPm3Iso14443a()) { DropField(); + } if (isOK) { switch (isOK) { From 2305411a1d600be5a0fbcb1dd296f5e3fe00d6be Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 25 Jan 2021 19:38:47 +0100 Subject: [PATCH 11/76] hf mf hardnested - added missing init --- client/deps/hardnested/hardnested_bf_core.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/client/deps/hardnested/hardnested_bf_core.c b/client/deps/hardnested/hardnested_bf_core.c index 719578331..feb08997b 100644 --- a/client/deps/hardnested/hardnested_bf_core.c +++ b/client/deps/hardnested/hardnested_bf_core.c @@ -143,7 +143,7 @@ bitslice_test_nonces_t bitslice_test_nonces_NOSIMD; bitslice_test_nonces_t bitslice_test_nonces_dispatch; #if defined (_WIN32) -#define malloc_bitslice(x) __builtin_assume_aligned(_aligned_malloc((x), MAX_BITSLICES/8), MAX_BITSLICES/8) +#define malloc_bitslice(x) __builtin_assume_aligned(_aligned_malloc((x), MAX_BITSLICES / 8), MAX_BITSLICES / 8) #define free_bitslice(x) _aligned_free(x) #elif defined (__APPLE__) static void *malloc_bitslice(size_t x) { @@ -156,7 +156,7 @@ static void *malloc_bitslice(size_t x) { } #define free_bitslice(x) free(x) #else -#define malloc_bitslice(x) memalign(MAX_BITSLICES/8, (x)) +#define malloc_bitslice(x) memalign(MAX_BITSLICES / 8, (x)) #define free_bitslice(x) free(x) #endif @@ -559,6 +559,7 @@ void SetSIMDInstr(SIMDExecInstr instr) { static SIMDExecInstr GetSIMDInstr(void) { SIMDExecInstr instr; + __builtin_cpu_init(); #if defined(COMPILER_HAS_SIMD_AVX512) if (__builtin_cpu_supports("avx512f")) instr = SIMD_AVX512; @@ -575,7 +576,7 @@ static SIMDExecInstr GetSIMDInstr(void) { instr = SIMD_MMX; else #endif - instr = SIMD_NONE; + instr = SIMD_NONE; return instr; } From 77d51cae384172e2a81526108f23ce62f6e71d8e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 25 Jan 2021 20:55:28 +0100 Subject: [PATCH 12/76] hf mf hardnested - just making sure its cleared --- client/src/cmdhfmfhard.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 9061868eb..052353d5a 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -2079,6 +2079,8 @@ static void free_candidates_memory(statelist_t *sl) { return; free_candidates_memory(sl->next); + sl->len[0] = 0; + sl->len[1] = 0; free(sl); } From c571b1e0ad35e55e4c6cb7b76064addaba509027 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 25 Jan 2021 20:59:32 +0100 Subject: [PATCH 13/76] hf mf hardnested - clear these too --- client/deps/hardnested/hardnested_bruteforce.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/deps/hardnested/hardnested_bruteforce.c b/client/deps/hardnested/hardnested_bruteforce.c index 0c768f400..a589040ac 100644 --- a/client/deps/hardnested/hardnested_bruteforce.c +++ b/client/deps/hardnested/hardnested_bruteforce.c @@ -465,7 +465,8 @@ float brute_force_benchmark(void) { free(test_candidates[0].states[ODD_STATE]); free(test_candidates[0].states[EVEN_STATE]); - + test_candidates[0].len[ODD_STATE] = 0; + test_candidates[0].len[EVEN_STATE] = 0; return bf_rate; } From 20fccb16aa487ef4db91965091bafd5df51c193e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 25 Jan 2021 22:12:17 +0100 Subject: [PATCH 14/76] hf mf hardnested - changed to calloc, and some text --- client/src/cmdhfmfhard.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 052353d5a..84b9aaf43 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -1668,7 +1668,7 @@ static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_e if (!possible) { #ifdef DEBUG_KEY_ELIMINATION if (!quiet && known_target_key != -1 && state == test_state[odd_even]) { - PrintAndLogEx(NORMAL, "Initial state lists: %s test state eliminated by bitflip property.\n", odd_even == EVEN_STATE ? "even" : "odd"); + PrintAndLogEx(INFO, "Initial state lists: %s test state eliminated by bitflip property.", odd_even == EVEN_STATE ? "even" : "odd"); sprintf(failstr, "Initial %s Byte Bitflip property", odd_even == EVEN_STATE ? "even" : "odd"); } #endif @@ -1791,14 +1791,14 @@ static void add_matching_states(statelist_t *cands, uint8_t part_sum_a0, uint8_t static statelist_t *add_more_candidates(void) { statelist_t *new_candidates; if (candidates == NULL) { - candidates = (statelist_t *)malloc(sizeof(statelist_t)); + candidates = (statelist_t *)calloc(sizeof(statelist_t), sizeof(uint8_t)); new_candidates = candidates; } else { new_candidates = candidates; while (new_candidates->next != NULL) { new_candidates = new_candidates->next; } - new_candidates = new_candidates->next = (statelist_t *)malloc(sizeof(statelist_t)); + new_candidates = new_candidates->next = (statelist_t *)calloc(sizeof(statelist_t), sizeof(uint8_t)); } new_candidates->next = NULL; new_candidates->len[ODD_STATE] = 0; @@ -1813,14 +1813,15 @@ static void add_bitflip_candidates(uint8_t byte) { for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { uint32_t worstcase_size = nonces[byte].num_states_bitarray[odd_even] + 1; - candidates1->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size); + candidates1->states[odd_even] = (uint32_t *)calloc(worstcase_size, sizeof(uint32_t)); if (candidates1->states[odd_even] == NULL) { - PrintAndLogEx(ERR, "Out of memory error in add_bitflip_candidates().\n"); + PrintAndLogEx(ERR, "Out of memory error in add_bitflip_candidates()"); exit(4); } bitarray_to_list(byte, nonces[byte].states_bitarray[odd_even], candidates1->states[odd_even], &(candidates1->len[odd_even]), odd_even); + // slim down the allocated memory. if (candidates1->len[odd_even] + 1 < worstcase_size) { candidates1->states[odd_even] = realloc(candidates1->states[odd_even], sizeof(uint32_t) * (candidates1->len[odd_even] + 1)); } From 658a62f76157ee02d0ae0182d0fef0c5205e06ef Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Mon, 25 Jan 2021 23:48:15 +0100 Subject: [PATCH 15/76] hardnested: add missing init, fixing some segfault --- client/src/cmdhfmfhard.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 84b9aaf43..6d685ce96 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -2179,6 +2179,9 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc get_SIMD_instruction_set(instr_set); PrintAndLogEx(SUCCESS, "Using %s SIMD core.", instr_set); + // initialize static arrays + memset(part_sum_count, 0, sizeof(part_sum_count)); + srand((unsigned) time(NULL)); brute_force_per_second = brute_force_benchmark(); write_stats = false; From 6a13a0c349cca53c17bc95fad40b414c3941eab3 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 26 Jan 2021 01:07:32 +0100 Subject: [PATCH 16/76] hardnested: one more init --- client/src/cmdhfmfhard.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 6d685ce96..58bd00671 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -2179,8 +2179,8 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc get_SIMD_instruction_set(instr_set); PrintAndLogEx(SUCCESS, "Using %s SIMD core.", instr_set); - // initialize static arrays memset(part_sum_count, 0, sizeof(part_sum_count)); + real_sum_a8 = 0; srand((unsigned) time(NULL)); brute_force_per_second = brute_force_benchmark(); From 05c5985073aef2045d5b84ac707d00480c378802 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 26 Jan 2021 10:47:55 +0100 Subject: [PATCH 17/76] fix #1173 - added guards --- client/deps/hardnested/hardnested_bf_core.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/deps/hardnested/hardnested_bf_core.c b/client/deps/hardnested/hardnested_bf_core.c index feb08997b..e856d26e1 100644 --- a/client/deps/hardnested/hardnested_bf_core.c +++ b/client/deps/hardnested/hardnested_bf_core.c @@ -559,7 +559,10 @@ void SetSIMDInstr(SIMDExecInstr instr) { static SIMDExecInstr GetSIMDInstr(void) { SIMDExecInstr instr; +#if defined(COMPILER_HAS_SIMD) __builtin_cpu_init(); +#endif + #if defined(COMPILER_HAS_SIMD_AVX512) if (__builtin_cpu_supports("avx512f")) instr = SIMD_AVX512; From fad3658604060706e3a77a5224905cd629dda166 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 26 Jan 2021 22:26:19 +0100 Subject: [PATCH 18/76] fix 'lf t55 sniff' input params --- client/src/cmdlft55xx.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index a3e6bc176..675e37af3 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -3883,24 +3883,39 @@ static int CmdT55xxSniff(const char *Cmd) { CLIExecWithReturn(ctx, Cmd, argtable, true); bool use_graphbuf = arg_get_lit(ctx, 1); uint8_t tolerance = arg_get_int_def(ctx, 2, 5); - uint8_t width1 = arg_get_int(ctx, 3); - uint8_t width0 = arg_get_int(ctx, 4); + int opt_width1 = arg_get_int_def(ctx, 3, -1); + int opt_width0 = arg_get_int_def(ctx, 4, -1); CLIParserFree(ctx); - if (width0 && width1 == 0) { + if (opt_width0 > 0 && opt_width1 == -1) { PrintAndLogEx(ERR, _RED_("Missing sample width for ONE")); return PM3_EINVARG; } - if (width1 && width0 == 0) { + if (opt_width1 > 0 && opt_width0 == -1) { PrintAndLogEx(ERR, _RED_("Missing sample width for ZERO")); return PM3_EINVARG; } - if ((width0 == 0) || (width1 == 0)) { - PrintAndLogEx(ERR, "Must call with --one and --zero params"); + if (opt_width0 == 0) { + PrintAndLogEx(ERR, "Must call with --zero larger than 0"); return PM3_EINVARG; } + if ((opt_width0 == 0) || (opt_width1 == 0)) { + PrintAndLogEx(ERR, "Must call with --one larger than 0"); + return PM3_EINVARG; + } + + uint8_t width1 = 0; + uint8_t width0 = 0; + + if (opt_width0 > -1) + width0 = (uint8_t)opt_width0 & 0xFF; + + if (opt_width1 > -1) + width1 = (uint8_t)opt_width1 & 0xFF; + + /* Notes: From 11b94e7748ac561cea9844bfadcf4f9ab18d7ffe Mon Sep 17 00:00:00 2001 From: McEloff Date: Wed, 27 Jan 2021 01:14:20 +0300 Subject: [PATCH 19/76] `trace list -t mf` - now can use external dictionary keys file --- CHANGELOG.md | 1 + client/src/cmdhflist.c | 13 +++++------ client/src/cmdhflist.h | 2 +- client/src/cmdtrace.c | 50 +++++++++++++++++++++++++++++++++++++----- 4 files changed, 53 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 868fe6877..ffd6aa4cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Added `trace list -t mf` - now can use external dictionary keys file - Added support for bidirectional communication for `lf em 4x50 sim` (@tharexde) - Change `PLATFORM=PM3OTHER` to `PLATFORM=PM3GENERIC` (@iceman1001) - Added `tools/hitag2crack/crack5opencl`, an optimized version of `crack5gpu` (@matrix) diff --git a/client/src/cmdhflist.c b/client/src/cmdhflist.c index 945edda06..dbe80ef5a 100644 --- a/client/src/cmdhflist.c +++ b/client/src/cmdhflist.c @@ -17,7 +17,6 @@ #include "commonutil.h" // ARRAYLEN #include "mifare/mifarehost.h" -#include "mifare/mifaredefault.h" #include "parity.h" // oddparity #include "ui.h" #include "crc16.h" @@ -1335,7 +1334,7 @@ void annotateMifare(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize, uint8 } -bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen) { +bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen, const uint64_t *dicKeys, uint32_t dicKeysCount) { static struct Crypto1State *traceCrypto1; *mfDataLen = 0; @@ -1383,12 +1382,12 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes } // check default keys - if (!traceCrypto1) { - for (int i = 0; i < ARRAYLEN(g_mifare_default_keys); i++) { - if (NestedCheckKey(g_mifare_default_keys[i], &AuthData, cmd, cmdsize, parity)) { - PrintAndLogEx(NORMAL, " | | * |%61s " _GREEN_("%012" PRIX64) "| |", "key", g_mifare_default_keys[i]); + if (!traceCrypto1 && dicKeys != NULL && dicKeysCount > 0) { + for (int i = 0; i < dicKeysCount; i++) { + if (NestedCheckKey(dicKeys[i], &AuthData, cmd, cmdsize, parity)) { + PrintAndLogEx(NORMAL, " | | * |%60s " _GREEN_("%012" PRIX64) "| |", "key", dicKeys[i]); - mfLastKey = g_mifare_default_keys[i]; + mfLastKey = dicKeys[i]; traceCrypto1 = lfsr_recovery64(AuthData.ks2, AuthData.ks3); break; }; diff --git a/client/src/cmdhflist.h b/client/src/cmdhflist.h index f12f2a61d..ff7f7f799 100644 --- a/client/src/cmdhflist.h +++ b/client/src/cmdhflist.h @@ -51,7 +51,7 @@ void annotateMifare(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize, uint8 void annotateLTO(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize); void annotateCryptoRF(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize); -bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen); +bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen, const uint64_t *dicKeys, uint32_t dicKeysCount); bool NTParityChk(TAuthData *ad, uint32_t ntx); bool NestedCheckKey(uint64_t key, TAuthData *ad, uint8_t *cmd, uint8_t cmdsize, uint8_t *parity); bool CheckCrypto1Parity(uint8_t *cmd_enc, uint8_t cmdsize, uint8_t *cmd, uint8_t *parity_enc); diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index f934caebe..d53f47883 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -15,6 +15,8 @@ #include "protocols.h" #include "parity.h" // oddparity #include "cmdhflist.h" // annotations +#include "commonutil.h" // ARRAYLEN +#include "mifare/mifaredefault.h" // mifare default key array #include "comms.h" // for sending cmds to device. GetFromBigBuf #include "fileutils.h" // for saveFile #include "cmdlfhitag.h" // annotate hitag @@ -131,7 +133,8 @@ static uint16_t printHexLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trac return ret; } -static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles, bool markCRCBytes, uint32_t *prev_eot, bool use_us) { +static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles, bool markCRCBytes, uint32_t *prev_eot, bool use_us, + const uint64_t *mfDicKeys, uint32_t mfDicKeysCount) { // sanity check if (is_last_record(tracepos, traceLen)) { PrintAndLogEx(DEBUG, "last record triggered. t-pos: %u t-len %u", tracepos, traceLen); @@ -428,7 +431,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr } if (protocol == PROTO_MIFARE) { - if (DecodeMifareData(frame, data_len, parityBytes, hdr->isResponse, mfData, &mfDataLen)) { + if (DecodeMifareData(frame, data_len, parityBytes, hdr->isResponse, mfData, &mfDataLen, mfDicKeys, mfDicKeysCount)) { memset(explanation, 0x00, sizeof(explanation)); if (hdr->isResponse == false) { annotateIso14443a(explanation, sizeof(explanation), mfData, mfDataLen); @@ -612,8 +615,9 @@ int CmdTraceList(const char *Cmd) { "trace list -t hitags -> interpret as " _YELLOW_("HitagS") " communications\n" "trace list -t lto -> interpret as " _YELLOW_("LTO-CM") " communications\n" "trace list -t cryptorf -> interpret as " _YELLOW_("CryptoRF") " communitcations\n" - "trace list -t 14a -f -> show frame delay times\n" - "trace list -t 14a -1 -> use trace buffer " + "trace list -t mf -d -> use dictionary keys file\n" + "trace list -t 14a -f -> show frame delay times\n" + "trace list -t 14a -1 -> use trace buffer " ); void *argtable[] = { @@ -626,6 +630,7 @@ int CmdTraceList(const char *Cmd) { arg_lit0("x", NULL, "show hexdump to convert to pcap(ng)\n" " or to import into Wireshark using encapsulation type \"ISO 14443\""), arg_strx0("t", "type", NULL, "protocol to annotate the trace"), + arg_strx0("d", "dict", NULL, "use dictionary keys file"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -642,6 +647,10 @@ int CmdTraceList(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 7), (uint8_t *)type, sizeof(type), &tlen); str_lower(type); + int diclen = 0; + char dictionary[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)dictionary, sizeof(dictionary), &diclen); + CLIParserFree(ctx); clearCommandBuffer(); @@ -742,6 +751,34 @@ int CmdTraceList(const char *Cmd) { } + const uint64_t *dicKeys = NULL; + uint32_t dicKeysCount = 0; + bool dictionaryLoad = false; + + if (protocol == PROTO_MIFARE) { + if (diclen > 0) { + uint8_t *keyBlock = NULL; + int res = loadFileDICTIONARY_safe(dictionary, (void **) &keyBlock, 6, &dicKeysCount); + if (res != PM3_SUCCESS || dicKeysCount == 0 || keyBlock == NULL) { + PrintAndLogEx(FAILED, "An error occurred while loading the dictionary! (we will use the default keys now)"); + } else { + dicKeys = calloc(dicKeysCount, sizeof(uint64_t)); + for (int i = 0; i < dicKeysCount; i++) { + uint64_t key = bytes_to_num(keyBlock + i * 6, 6); + memcpy((uint8_t *) &dicKeys[i], &key, sizeof(uint64_t)); + } + dictionaryLoad = true; + } + if (keyBlock != NULL) { + free(keyBlock); + } + } + if (dicKeys == NULL) { + dicKeys = g_mifare_default_keys; + dicKeysCount = ARRAYLEN(g_mifare_default_keys); + } + } + PrintAndLogEx(NORMAL, ""); if (use_relative) { PrintAndLogEx(NORMAL, " Gap | Duration | Src | Data (! denotes parity error, ' denotes short bytes) | CRC | Annotation"); @@ -761,11 +798,14 @@ int CmdTraceList(const char *Cmd) { } while (tracepos < g_traceLen) { - tracepos = printTraceLine(tracepos, g_traceLen, g_trace, protocol, show_wait_cycles, mark_crc, prev_EOT, use_us); + tracepos = printTraceLine(tracepos, g_traceLen, g_trace, protocol, show_wait_cycles, mark_crc, prev_EOT, use_us, dicKeys, dicKeysCount); if (kbd_enter_pressed()) break; } + + if (dictionaryLoad) + free((void *) dicKeys); } if (show_hex) From d39e0939b6139d662f8eba63536201800a273d12 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 09:09:42 +0100 Subject: [PATCH 20/76] fix t55xx protect/recoverpw - make param pwd optional --- client/src/cmdlft55xx.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 675e37af3..cd4947b4d 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -3310,7 +3310,7 @@ static int CmdT55xxRecoverPW(const char *Cmd) { // 2 + (5 or 6) void *argtable[8] = { arg_param_begin, - arg_str1("p", "pwd", "", "password (4 hex bytes)"), + arg_str0("p", "pwd", "", "password (4 hex bytes)"), }; uint8_t idx = 2; arg_add_t55xx_downloadlink(argtable, &idx, T55XX_DLMODE_ALL, T55XX_DLMODE_ALL); @@ -3758,7 +3758,7 @@ static int CmdT55xxProtect(const char *Cmd) { void *argtable[4 + 5] = { arg_param_begin, arg_lit0("o", "override", "override safety check"), - arg_str1("p", "pwd", "", "password (4 hex bytes)"), + arg_str0("p", "pwd", "", "password (4 hex bytes)"), arg_str1("n", "new", "", "new password (4 hex bytes)"), }; uint8_t idx = 4; From 2218b4e7db5ecc06b266ee27e033e56daa937f73 Mon Sep 17 00:00:00 2001 From: Eloff Date: Wed, 27 Jan 2021 14:43:50 +0300 Subject: [PATCH 21/76] minor fix --- client/src/cmdtrace.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index d53f47883..a95503813 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -615,7 +615,7 @@ int CmdTraceList(const char *Cmd) { "trace list -t hitags -> interpret as " _YELLOW_("HitagS") " communications\n" "trace list -t lto -> interpret as " _YELLOW_("LTO-CM") " communications\n" "trace list -t cryptorf -> interpret as " _YELLOW_("CryptoRF") " communitcations\n" - "trace list -t mf -d -> use dictionary keys file\n" + "trace list -t mf --dict -> use dictionary keys file\n" "trace list -t 14a -f -> show frame delay times\n" "trace list -t 14a -1 -> use trace buffer " ); @@ -630,7 +630,7 @@ int CmdTraceList(const char *Cmd) { arg_lit0("x", NULL, "show hexdump to convert to pcap(ng)\n" " or to import into Wireshark using encapsulation type \"ISO 14443\""), arg_strx0("t", "type", NULL, "protocol to annotate the trace"), - arg_strx0("d", "dict", NULL, "use dictionary keys file"), + arg_strx0(NULL, "dict", "", "use dictionary keys file"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -648,8 +648,11 @@ int CmdTraceList(const char *Cmd) { str_lower(type); int diclen = 0; - char dictionary[FILE_PATH_SIZE] = {0}; - CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)dictionary, sizeof(dictionary), &diclen); + char dictionary[FILE_PATH_SIZE + 2] = {0}; + if (CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)dictionary, FILE_PATH_SIZE, &diclen)) { + PrintAndLogEx(FAILED, "Dictionary file name too long or invalid."); + diclen = 0; + } CLIParserFree(ctx); From 35cc4125bddebcafae58d68ae057f79da5ad6ba3 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 14:11:36 +0100 Subject: [PATCH 22/76] lf search - now use cliparser --- client/src/cmdlf.c | 60 +++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index 2ee55eebf..4999c4d1e 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -216,20 +216,7 @@ static int usage_lf_simpsk(void) { PrintAndLogEx(NORMAL, " d Data to sim as hex - omit to sim from DemodBuffer"); return PM3_SUCCESS; } -static int usage_lf_find(void) { - PrintAndLogEx(NORMAL, "Usage: lf search [h] <0|1> [u]"); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h This help"); - PrintAndLogEx(NORMAL, " <0|1> Use data from Graphbuffer, if not set, try reading data from tag."); - PrintAndLogEx(NORMAL, " u Search for Unknown tags, if not set, reads only known tags."); - PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, _YELLOW_(" lf search") " - try reading data from tag & search for known tags"); - PrintAndLogEx(NORMAL, _YELLOW_(" lf search 1") " - use data from GraphBuffer & search for known tags"); - PrintAndLogEx(NORMAL, _YELLOW_(" lf search u") " - try reading data from tag & search for known and unknown tags"); - PrintAndLogEx(NORMAL, _YELLOW_(" lf search 1 u") " - use data from GraphBuffer & search for known and unknown tags"); - return PM3_SUCCESS; -} + static int CmdLFTune(const char *Cmd) { @@ -1405,22 +1392,33 @@ out: } int CmdLFfind(const char *Cmd) { - int retval = PM3_SUCCESS; - int ans = 0; - size_t minLength = 2000; - char cmdp = tolower(param_getchar(Cmd, 0)); - char testRaw = param_getchar(Cmd, 1); - if (strlen(Cmd) > 3 || cmdp == 'h') return usage_lf_find(); + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf search", + "Read and search for valid known tag. For offline mode, you can `data load` first then search.", + "lf search -> try reading data from tag & search for known tag\n" + "lf search -1 -> use data from GraphBuffer & search for known tag\n" + "lf search -u -> try reading data from tag & search for known and unknown tag\n" + "lf search -1u -> use data from GraphBuffer & search for known and unknown tag\n" + ); - if (cmdp == 'u') testRaw = 'u'; + void *argtable[] = { + arg_param_begin, + arg_lit0("1", NULL, "Use data from Graphbuffer to search"), + arg_lit0("u", NULL, "Search for unknown tags, if not set, reads only known tags"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool use_gb = arg_get_lit(ctx, 1); + bool search_unk = arg_get_lit(ctx, 2); + CLIParserFree(ctx); - bool isOnline = (session.pm3_present && (cmdp != '1')); - - if (isOnline) + bool is_online = (session.pm3_present && (use_gb == false)); + if (is_online) lf_read(false, 30000); - if (GraphTraceLen < minLength) { + size_t min_length = 2000; + if (GraphTraceLen < min_length) { PrintAndLogEx(FAILED, "Data in Graphbuffer was too small."); return PM3_ESOFT; } @@ -1434,7 +1432,7 @@ int CmdLFfind(const char *Cmd) { PrintAndLogEx(INFO, ""); // only run these tests if device is online - if (isOnline) { + if (is_online) { if (IfPm3Hitag()) { if (readHitagUid()) { @@ -1474,6 +1472,8 @@ int CmdLFfind(const char *Cmd) { } } + int retval = PM3_SUCCESS; + if (demodVisa2k(true) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Visa2000 ID") " found!"); goto out;} if (demodDestron(true) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("FDX-A FECAVA Destron ID") " found!"); goto out;} // to do before HID if (demodHID(true) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("HID Prox ID") " found!"); goto out;} @@ -1502,10 +1502,10 @@ int CmdLFfind(const char *Cmd) { PrintAndLogEx(FAILED, _RED_("No known 125/134 kHz tags found!")); - if (testRaw == 'u') { + if (search_unk) { //test unknown tag formats (raw mode) PrintAndLogEx(INFO, "\nChecking for unknown tags:\n"); - ans = AutoCorrelate(GraphBuffer, GraphBuffer, GraphTraceLen, 8000, false, false); + int ans = AutoCorrelate(GraphBuffer, GraphBuffer, GraphTraceLen, 8000, false, false); if (ans > 0) { PrintAndLogEx(INFO, "Possible auto correlation of %d repeating samples", ans); @@ -1544,7 +1544,7 @@ int CmdLFfind(const char *Cmd) { out: // identify chipset - if (CheckChipType(isOnline) == false) { + if (CheckChipType(is_online) == false) { PrintAndLogEx(DEBUG, "Automatic chip type detection " _RED_("failed")); retval = false; } @@ -1586,7 +1586,7 @@ static command_t CommandTable[] = { {"config", CmdLFConfig, IfPm3Lf, "Get/Set config for LF sampling, bit/sample, decimation, frequency"}, {"cmdread", CmdLFCommandRead, IfPm3Lf, "Modulate LF reader field to send command before read (all periods in microseconds)"}, {"read", CmdLFRead, IfPm3Lf, "Read LF tag"}, - {"search", CmdLFfind, AlwaysAvailable, "Read and Search for valid known tag (in offline mode it you can load first then search)"}, + {"search", CmdLFfind, AlwaysAvailable, "Read and Search for valid known tag"}, {"sim", CmdLFSim, IfPm3Lf, "Simulate LF tag from buffer with optional GAP (in microseconds)"}, {"simask", CmdLFaskSim, IfPm3Lf, "Simulate " _YELLOW_("LF ASK tag") " from demodbuffer or input"}, {"simfsk", CmdLFfskSim, IfPm3Lf, "Simulate " _YELLOW_("LF FSK tag") " from demodbuffer or input"}, From 3176d05a2afba14a835f7b90f6136d92935188b7 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 14:14:59 +0100 Subject: [PATCH 23/76] lf simbidir - now use cliparser --- client/src/cmdlf.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index 4999c4d1e..00f0dea27 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -217,7 +217,6 @@ static int usage_lf_simpsk(void) { return PM3_SUCCESS; } - static int CmdLFTune(const char *Cmd) { CLIParserContext *ctx; @@ -1250,7 +1249,20 @@ int CmdLFpskSim(const char *Cmd) { } int CmdLFSimBidir(const char *Cmd) { - (void)Cmd; // Cmd is not used so far + + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf simbidir", + "Simulate LF tag with bidirectional data transmission between reader and tag", + "lf simbidir" + ); + + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + // Set ADC to twice the carrier for a slight supersampling // HACK: not implemented in ARMSRC. PrintAndLogEx(INFO, "Not implemented yet."); @@ -1591,7 +1603,7 @@ static command_t CommandTable[] = { {"simask", CmdLFaskSim, IfPm3Lf, "Simulate " _YELLOW_("LF ASK tag") " from demodbuffer or input"}, {"simfsk", CmdLFfskSim, IfPm3Lf, "Simulate " _YELLOW_("LF FSK tag") " from demodbuffer or input"}, {"simpsk", CmdLFpskSim, IfPm3Lf, "Simulate " _YELLOW_("LF PSK tag") " from demodbuffer or input"}, -// {"simpsk", CmdLFnrzSim, IfPm3Lf, "Simulate " _YELLOW_("LF NRZ tag") " from demodbuffer or input"}, +// {"simnrz", CmdLFnrzSim, IfPm3Lf, "Simulate " _YELLOW_("LF NRZ tag") " from demodbuffer or input"}, {"simbidir", CmdLFSimBidir, IfPm3Lf, "Simulate LF tag (with bidirectional data transmission between reader and tag)"}, {"sniff", CmdLFSniff, IfPm3Lf, "Sniff LF traffic between reader and tag"}, {"tune", CmdLFTune, IfPm3Lf, "Continuously measure LF antenna tuning"}, From 7f78b0a85dc60394dc00e7048e93e20d695ceba6 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 14:36:43 +0100 Subject: [PATCH 24/76] text and test fix for lf search --- client/luascripts/tests/data_tracetest.lua | 6 +- doc/cliparser_todo.txt | 3 +- tools/pm3_tests.sh | 92 +++++++++++----------- 3 files changed, 50 insertions(+), 51 deletions(-) diff --git a/client/luascripts/tests/data_tracetest.lua b/client/luascripts/tests/data_tracetest.lua index 1e75b707b..5773e0bcf 100644 --- a/client/luascripts/tests/data_tracetest.lua +++ b/client/luascripts/tests/data_tracetest.lua @@ -7,11 +7,11 @@ local ansicolors = require('ansicolors') copyright = '' author = 'Iceman' -version = 'v1.0.3' +version = 'v1.0.4' desc = [[ This script will load several traces files in current working directory/traces/ folder and do "data load" -"lf search 1 u" +"lf search -1u" The following tracefiles will be loaded: em*.pm3 @@ -109,7 +109,7 @@ local function main(args) end p.close(); - local cmdLFSEARCH = 'lf search 1 u' + local cmdLFSEARCH = 'lf search -1u' -- main loop io.write('Starting to test traces > ') diff --git a/doc/cliparser_todo.txt b/doc/cliparser_todo.txt index 335c6491f..0738d589e 100644 --- a/doc/cliparser_todo.txt +++ b/doc/cliparser_todo.txt @@ -1,5 +1,6 @@ clear pref +analyse foo data biphaserawdecode data detectclock data fsktonrz @@ -95,12 +96,10 @@ hf mf ice lf config lf cmdread lf read -lf search lf sim lf simask lf simfsk lf simpsk -lf simbidir lf sniff lf em 410x lf em 4x05 diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index 3c59949ee..0ef81b7c5 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -347,112 +347,112 @@ while true; do if ! CheckExecute "trace load/list x" "$CLIENTBIN -c 'trace load -f traces/hf_14a_mfu.trace; trace list -x1 -t 14a;'" "0.0101840425"; then break; fi echo -e "\n${C_BLUE}Testing LF:${C_NC}" - if ! CheckExecute "lf AWID test" "$CLIENTBIN -c 'data load -f traces/lf_AWID-15-259.pm3;lf search 1'" "AWID ID found"; then break; fi - if ! CheckExecute "lf EM410x test" "$CLIENTBIN -c 'data load -f traces/lf_EM4102-1.pm3;lf search 1'" "EM410x ID found"; then break; fi - if ! CheckExecute "lf EM4x05 test" "$CLIENTBIN -c 'data load -f traces/lf_EM4x05.pm3;lf search 1'" "FDX-B ID found"; then break; fi - if ! CheckExecute "lf FDX-A FECAVA test" "$CLIENTBIN -c 'data load -f traces/lf_EM4305_fdxa_destron.pm3;lf search 1'" "FDX-A FECAVA Destron ID found"; then break; fi - if ! CheckExecute "lf FDX-B test" "$CLIENTBIN -c 'data load -f traces/lf_HomeAgain1600.pm3;lf search 1'" "FDX-B ID found"; then break; fi + if ! CheckExecute "lf AWID test" "$CLIENTBIN -c 'data load -f traces/lf_AWID-15-259.pm3;lf search -1'" "AWID ID found"; then break; fi + if ! CheckExecute "lf EM410x test" "$CLIENTBIN -c 'data load -f traces/lf_EM4102-1.pm3;lf search -1'" "EM410x ID found"; then break; fi + if ! CheckExecute "lf EM4x05 test" "$CLIENTBIN -c 'data load -f traces/lf_EM4x05.pm3;lf search -1'" "FDX-B ID found"; then break; fi + if ! CheckExecute "lf FDX-A FECAVA test" "$CLIENTBIN -c 'data load -f traces/lf_EM4305_fdxa_destron.pm3;lf search -1'" "FDX-A FECAVA Destron ID found"; then break; fi + if ! CheckExecute "lf FDX-B test" "$CLIENTBIN -c 'data load -f traces/lf_HomeAgain1600.pm3;lf search -1'" "FDX-B ID found"; then break; fi if ! CheckExecute "lf FDX/BioThermo test" "$CLIENTBIN -c 'data load -f traces/lf_FDXB_Bio-Thermo.pm3; lf fdxb demod'" "95.2 F / 35.1 C"; then break; fi - if ! CheckExecute "lf GPROXII test" "$CLIENTBIN -c 'data load -f traces/lf_GProx_36_30_14489.pm3; lf search 1'" "Guardall G-Prox II ID found"; then break; fi - if ! CheckExecute "lf HID Prox test" "$CLIENTBIN -c 'data load -f traces/lf_HID-proxCardII-05512-11432784-1.pm3;lf search 1'" "HID Prox ID found"; then break; fi - if ! CheckExecute "lf IDTECK test" "$CLIENTBIN -c 'data load -f traces/lf_IDTECK_4944544BAC40E069.pm3; lf search 1'" "Idteck ID found"; then break; fi - if ! CheckExecute "lf INDALA test" "$CLIENTBIN -c 'data load -f traces/lf_Indala-504278295.pm3;lf search 1'" "Indala ID found"; then break; fi - if ! CheckExecute "lf KERI test" "$CLIENTBIN -c 'data load -f traces/lf_Keri.pm3;lf search 1'" "Pyramid ID found"; then break; fi - if ! CheckExecute "lf NEXWATCH test" "$CLIENTBIN -c 'data load -f traces/lf_NEXWATCH_Quadrakey-521512301.pm3;lf search 1 '" "NexWatch ID found"; then break; fi - if ! CheckExecute "lf SECURAKEY test" "$CLIENTBIN -c 'data load -f traces/lf_NEXWATCH_Securakey-64169.pm3;lf search 1 '" "Securakey ID found"; then break; fi - if ! CheckExecute "lf PAC test" "$CLIENTBIN -c 'data load -f traces/lf_PAC-8E4C058E.pm3;lf search 1'" "PAC/Stanley ID found"; then break; fi - if ! CheckExecute "lf PARADOX test" "$CLIENTBIN -c 'data load -f traces/lf_Paradox-96_40426-APJN08.pm3;lf search 1'" "Paradox ID found"; then break; fi - if ! CheckExecute "lf VIKING test" "$CLIENTBIN -c 'data load -f traces/lf_Transit999-best.pm3;lf search 1'" "Viking ID found"; then break; fi - if ! CheckExecute "lf VISA2000 test" "$CLIENTBIN -c 'data load -f traces/lf_VISA2000.pm3;lf search 1'" "Visa2000 ID found"; then break; fi + if ! CheckExecute "lf GPROXII test" "$CLIENTBIN -c 'data load -f traces/lf_GProx_36_30_14489.pm3; lf search -1'" "Guardall G-Prox II ID found"; then break; fi + if ! CheckExecute "lf HID Prox test" "$CLIENTBIN -c 'data load -f traces/lf_HID-proxCardII-05512-11432784-1.pm3;lf search -1'" "HID Prox ID found"; then break; fi + if ! CheckExecute "lf IDTECK test" "$CLIENTBIN -c 'data load -f traces/lf_IDTECK_4944544BAC40E069.pm3; lf search -1'" "Idteck ID found"; then break; fi + if ! CheckExecute "lf INDALA test" "$CLIENTBIN -c 'data load -f traces/lf_Indala-504278295.pm3;lf search -1'" "Indala ID found"; then break; fi + if ! CheckExecute "lf KERI test" "$CLIENTBIN -c 'data load -f traces/lf_Keri.pm3;lf search -1'" "Pyramid ID found"; then break; fi + if ! CheckExecute "lf NEXWATCH test" "$CLIENTBIN -c 'data load -f traces/lf_NEXWATCH_Quadrakey-521512301.pm3;lf search -1 '" "NexWatch ID found"; then break; fi + if ! CheckExecute "lf SECURAKEY test" "$CLIENTBIN -c 'data load -f traces/lf_NEXWATCH_Securakey-64169.pm3;lf search -1 '" "Securakey ID found"; then break; fi + if ! CheckExecute "lf PAC test" "$CLIENTBIN -c 'data load -f traces/lf_PAC-8E4C058E.pm3;lf search -1'" "PAC/Stanley ID found"; then break; fi + if ! CheckExecute "lf PARADOX test" "$CLIENTBIN -c 'data load -f traces/lf_Paradox-96_40426-APJN08.pm3;lf search -1'" "Paradox ID found"; then break; fi + if ! CheckExecute "lf VIKING test" "$CLIENTBIN -c 'data load -f traces/lf_Transit999-best.pm3;lf search -1'" "Viking ID found"; then break; fi + if ! CheckExecute "lf VISA2000 test" "$CLIENTBIN -c 'data load -f traces/lf_VISA2000.pm3;lf search -1'" "Visa2000 ID found"; then break; fi - if ! CheckExecute slow "lf T55 awid 26 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_awid_26.pm3; lf search 1'" "AWID ID found"; then break; fi + if ! CheckExecute slow "lf T55 awid 26 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_awid_26.pm3; lf search -1'" "AWID ID found"; then break; fi if ! CheckExecute slow "lf T55 awid 26 test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_awid_26.pm3; lf awid demod'" \ "AWID - len: 26 FC: 224 Card: 1337 - Wiegand: 3c00a73"; then break; fi - if ! CheckExecute slow "lf T55 awid 50 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_awid_50.pm3; lf search 1'" "AWID ID found"; then break; fi + if ! CheckExecute slow "lf T55 awid 50 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_awid_50.pm3; lf search -1'" "AWID ID found"; then break; fi if ! CheckExecute slow "lf T55 awid 50 test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_awid_50.pm3; lf awid demod'" \ "AWID - len: 50 FC: 2001 Card: 13371337 - Wiegand: 20fa201980f92, Raw: 0128b12eb1811d7117e22111"; then break; fi - if ! CheckExecute slow "lf T55 em410x test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_em410x.pm3; lf search 1'" "EM410x ID found"; then break; fi + if ! CheckExecute slow "lf T55 em410x test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_em410x.pm3; lf search -1'" "EM410x ID found"; then break; fi if ! CheckExecute slow "lf T55 em410x test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_em410x.pm3; lf em 410x demod'" \ "EM 410x ID 0F0368568B"; then break; fi - if ! CheckExecute slow "lf T55 fdxb_animal test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_fdxb_animal.pm3; lf search 1'" "FDX-B ID found"; then break; fi + if ! CheckExecute slow "lf T55 fdxb_animal test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_fdxb_animal.pm3; lf search -1'" "FDX-B ID found"; then break; fi if ! CheckExecute slow "lf T55 fdxb_animal test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_fdxb_animal.pm3; lf fdxb demod'" \ "Animal ID 999-000000112233"; then break; fi - if ! CheckExecute slow "lf T55 fdxb_extended test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_fdxb_extended.pm3; lf search 1'" "FDX-B ID found"; then break; fi + if ! CheckExecute slow "lf T55 fdxb_extended test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_fdxb_extended.pm3; lf search -1'" "FDX-B ID found"; then break; fi if ! CheckExecute slow "lf T55 fdxb_extended test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_fdxb_extended.pm3; lf fdxb demod'" \ "temperature 95.2 F / 35.1 C"; then break; fi - if ! CheckExecute slow "lf T55 gallagher test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_gallagher.pm3; lf search 1'" "GALLAGHER ID found"; then break; fi + if ! CheckExecute slow "lf T55 gallagher test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_gallagher.pm3; lf search -1'" "GALLAGHER ID found"; then break; fi if ! CheckExecute slow "lf T55 gallagher test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_gallagher.pm3; lf gallagher demod'" \ "GALLAGHER - Region: 0 FC: 27865 CN: 682758 Issue Level: 13"; then break; fi - if ! CheckExecute slow "lf T55 gproxii test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_gproxii.pm3; lf search 1'" "Guardall G-Prox II ID found"; then break; fi + if ! CheckExecute slow "lf T55 gproxii test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_gproxii.pm3; lf search -1'" "Guardall G-Prox II ID found"; then break; fi if ! CheckExecute slow "lf T55 gproxii test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_gproxii.pm3; lf gproxii demod'" \ "G-Prox-II - len: 26 FC: 123 Card: 11223, Raw: f98c7038c63356c7ac26398c"; then break; fi - if ! CheckExecute slow "lf T55 hid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_hid.pm3; lf search 1'" "HID Prox ID found"; then break; fi + if ! CheckExecute slow "lf T55 hid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_hid.pm3; lf search -1'" "HID Prox ID found"; then break; fi if ! CheckExecute slow "lf T55 hid test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_hid.pm3; lf hid demod'" \ "HID H10301 26-bit; FC: 118 CN: 1603"; then break; fi - if ! CheckExecute slow "lf T55 hid_48 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_hid_48.pm3; lf search 1'" "HID Prox ID found"; then break; fi + if ! CheckExecute slow "lf T55 hid_48 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_hid_48.pm3; lf search -1'" "HID Prox ID found"; then break; fi if ! CheckExecute slow "lf T55 hid_48 test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_hid_48.pm3; lf hid demod'" \ "HID Corporate 1000 48-bit"; then break; fi - if ! CheckExecute slow "lf T55 indala_hedem test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala_hedem.pm3; lf search 1'" "Indala ID found"; then break; fi + if ! CheckExecute slow "lf T55 indala_hedem test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala_hedem.pm3; lf search -1'" "Indala ID found"; then break; fi if ! CheckExecute slow "lf T55 indala_hedem test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala_hedem.pm3; lf indala demod'" \ "Heden-2L \| 888"; then break; fi - if ! CheckExecute slow "lf T55 indala test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala.pm3; lf search 1'" "Indala ID found"; then break; fi + if ! CheckExecute slow "lf T55 indala test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala.pm3; lf search -1'" "Indala ID found"; then break; fi if ! CheckExecute slow "lf T55 indala test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala.pm3; lf indala demod'" \ "Fmt 26 FC: 123 Card: 1337 checksum: 10"; then break; fi - if ! CheckExecute slow "lf T55 indala_224 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala_224.pm3; lf search 1'" "Indala ID found"; then break; fi + if ! CheckExecute slow "lf T55 indala_224 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala_224.pm3; lf search -1'" "Indala ID found"; then break; fi if ! CheckExecute slow "lf T55 indala_224 test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_indala_224.pm3; lf indala demod'" \ "Indala (len 224) Raw: 80000001b23523a6c2e31eba3cbee4afb3c6ad1fcf649393928c14e5"; then break; fi - if ! CheckExecute slow "lf T55 io test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_io.pm3; lf search 1'" "IO Prox ID found"; then break; fi + if ! CheckExecute slow "lf T55 io test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_io.pm3; lf search -1'" "IO Prox ID found"; then break; fi if ! CheckExecute slow "lf T55 io test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_io.pm3; lf io demod'" \ "IO Prox - XSF(01)01:01337, Raw: 007840603059cf3f (ok)"; then break; fi - if ! CheckExecute slow "lf T55 jablotron test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_jablotron.pm3; lf search 1'" "Jablotron ID found"; then break; fi + if ! CheckExecute slow "lf T55 jablotron test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_jablotron.pm3; lf search -1'" "Jablotron ID found"; then break; fi if ! CheckExecute slow "lf T55 jablotron test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_jablotron.pm3; lf jablotron demod'" \ "Printed: 1410-00-0011-2233"; then break; fi - if ! CheckExecute slow "lf T55 keri test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri.pm3; lf search 1'" "KERI ID found"; then break; fi + if ! CheckExecute slow "lf T55 keri test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri.pm3; lf search -1'" "KERI ID found"; then break; fi if ! CheckExecute slow "lf T55 keri test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri.pm3; lf keri demod'" \ "KERI - Internal ID: 112233, Raw: E00000008001B669"; then break; fi - if ! CheckExecute slow "lf T55 keri_internalid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri_internalid.pm3; lf search 1'" "KERI ID found"; then break; fi + if ! CheckExecute slow "lf T55 keri_internalid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri_internalid.pm3; lf search -1'" "KERI ID found"; then break; fi if ! CheckExecute slow "lf T55 keri_internalid test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri_internalid.pm3; lf keri demod'" \ "KERI - Internal ID: 12345, Raw: E000000080003039"; then break; fi - if ! CheckExecute slow "lf T55 keri_msid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri_msid.pm3; lf search 1'" "KERI ID found"; then break; fi + if ! CheckExecute slow "lf T55 keri_msid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri_msid.pm3; lf search -1'" "KERI ID found"; then break; fi if ! CheckExecute slow "lf T55 keri_msid test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_keri_msid.pm3; lf keri demod'" \ "Descrambled MS - FC: 6 Card: 12345"; then break; fi -# if ! CheckExecute slow "lf T55 motorola test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_motorola.pm3; lf search 1'" "Indala ID found"; then break; fi +# if ! CheckExecute slow "lf T55 motorola test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_motorola.pm3; lf search -1'" "Indala ID found"; then break; fi if ! CheckExecute slow "lf T55 motorola test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_motorola.pm3; lf motorola demod'" \ "Motorola - fmt: 26 FC: 258 Card: 2, Raw: A0000000A0002021"; then break; fi - if ! CheckExecute slow "lf T55 nedap test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nedap.pm3; lf search 1'" "NEDAP ID found"; then break; fi + if ! CheckExecute slow "lf T55 nedap test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nedap.pm3; lf search -1'" "NEDAP ID found"; then break; fi if ! CheckExecute slow "lf T55 nedap test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nedap.pm3; lf nedap demod'" \ "NEDAP (64b) - ID: 12345 subtype: 1 customer code: 291 / 0x123 Raw: FF82246508209953"; then break; fi - if ! CheckExecute slow "lf T55 nexwatch test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch.pm3; lf search 1'" "NexWatch ID found"; then break; fi + if ! CheckExecute slow "lf T55 nexwatch test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch.pm3; lf search -1'" "NexWatch ID found"; then break; fi if ! CheckExecute slow "lf T55 nexwatch test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch.pm3; lf nexwatch demod'" \ "Raw : 5600000000213C9F8F150C00"; then break; fi - if ! CheckExecute slow "lf T55 nexwatch_nexkey test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch_nexkey.pm3; lf search 1'" "NexWatch ID found"; then break; fi + if ! CheckExecute slow "lf T55 nexwatch_nexkey test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch_nexkey.pm3; lf search -1'" "NexWatch ID found"; then break; fi if ! CheckExecute slow "lf T55 nexwatch_nexkey test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch_nexkey.pm3; lf nexwatch demod'" \ "88bit id : 521512301 (0x1f15a56d)"; then break; fi - if ! CheckExecute slow "lf T55 nexwatch_quadrakey test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch_quadrakey.pm3; lf search 1'" "NexWatch ID found"; then break; fi + if ! CheckExecute slow "lf T55 nexwatch_quadrakey test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch_quadrakey.pm3; lf search -1'" "NexWatch ID found"; then break; fi if ! CheckExecute slow "lf T55 nexwatch_quadrakey test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_nexwatch_quadrakey.pm3; lf nexwatch demod'" \ "88bit id : 521512301 (0x1f15a56d)"; then break; fi - if ! CheckExecute slow "lf T55 noralsy test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_noralsy.pm3; lf search 1'" "Noralsy ID found"; then break; fi + if ! CheckExecute slow "lf T55 noralsy test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_noralsy.pm3; lf search -1'" "Noralsy ID found"; then break; fi if ! CheckExecute slow "lf T55 noralsy test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_noralsy.pm3; lf noralsy demod'" \ "Noralsy - Card: 112233, Year: 2000, Raw: BB0214FF0110002233070000"; then break; fi - if ! CheckExecute slow "lf T55 pac test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_pac.pm3; lf search 1'" "PAC/Stanley ID found"; then break; fi + if ! CheckExecute slow "lf T55 pac test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_pac.pm3; lf search -1'" "PAC/Stanley ID found"; then break; fi if ! CheckExecute slow "lf T55 pac test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_pac.pm3; lf pac demod'" \ "PAC/Stanley - Card: CD4F5552, Raw: FF2049906D8511C593155B56D5B2649F"; then break; fi - if ! CheckExecute slow "lf T55 paradox test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_paradox.pm3; lf search 1'" "Paradox ID found"; then break; fi + if ! CheckExecute slow "lf T55 paradox test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_paradox.pm3; lf search -1'" "Paradox ID found"; then break; fi if ! CheckExecute slow "lf T55 paradox test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_paradox.pm3; lf paradox demod'" \ "Paradox - ID: 004209dea FC: 96 Card: 40426, Checksum: b2, Raw: 0f55555695596a6a9999a59a"; then break; fi - if ! CheckExecute slow "lf T55 presco test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_presco.pm3; lf search 1'" "Presco ID found"; then break; fi + if ! CheckExecute slow "lf T55 presco test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_presco.pm3; lf search -1'" "Presco ID found"; then break; fi if ! CheckExecute slow "lf T55 presco test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_presco.pm3; lf presco demod'" \ "Presco Site code: 30 User code: 8665 Full code: 1E8021D9 Raw: 10D0000000000000000000001E8021D9"; then break; fi - if ! CheckExecute slow "lf T55 pyramid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_pyramid.pm3; lf search 1'" "Pyramid ID found"; then break; fi + if ! CheckExecute slow "lf T55 pyramid test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_pyramid.pm3; lf search -1'" "Pyramid ID found"; then break; fi if ! CheckExecute slow "lf T55 pyramid test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_pyramid.pm3; lf pyramid demod'" \ "Pyramid - len: 26, FC: 123 Card: 11223 - Wiegand: 2f657ae, Raw: 00010101010101010101016eb35e5da4"; then break; fi - if ! CheckExecute slow "lf T55 securakey test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_securakey.pm3; lf search 1'" "Securakey ID found"; then break; fi + if ! CheckExecute slow "lf T55 securakey test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_securakey.pm3; lf search -1'" "Securakey ID found"; then break; fi if ! CheckExecute slow "lf T55 securakey test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_securakey.pm3; lf securakey demod'" \ "Securakey - len: 26 FC: 0x35 Card: 64169, Raw: 7FCB400001ADEA5344300000"; then break; fi - if ! CheckExecute slow "lf T55 viking test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_viking.pm3; lf search 1'" "Viking ID found"; then break; fi + if ! CheckExecute slow "lf T55 viking test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_viking.pm3; lf search -1'" "Viking ID found"; then break; fi if ! CheckExecute slow "lf T55 viking test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_viking.pm3; lf viking demod'" \ "Viking - Card 0001A337, Raw: F200000001A337CF"; then break; fi - if ! CheckExecute slow "lf T55 visa2000 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_visa2000.pm3; lf search 1'" "Visa2000 ID found"; then break; fi + if ! CheckExecute slow "lf T55 visa2000 test" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_visa2000.pm3; lf search -1'" "Visa2000 ID found"; then break; fi if ! CheckExecute slow "lf T55 visa2000 test2" "$CLIENTBIN -c 'data load -f traces/lf_ATA5577_visa2000.pm3; lf visa2000 demod'" \ "Visa2000 - Card 112233, Raw: 564953320001B66900000183"; then break; fi From fdcc4b741c0f6debb621fe7d981a8336dff8a50f Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 22:52:08 +0100 Subject: [PATCH 25/76] fix lf em 4x05 write - pwd/data. t55xx chk - now uses cliparser, and color to cliparser empty message --- client/deps/cliparser/cliparser.c | 54 +++++++-- client/deps/cliparser/cliparser.h | 9 +- client/src/cmdanalyse.c | 18 ++- client/src/cmdlfem4x05.c | 48 +++++--- client/src/cmdlft55xx.c | 192 +++++++++++++++--------------- 5 files changed, 197 insertions(+), 124 deletions(-) diff --git a/client/deps/cliparser/cliparser.c b/client/deps/cliparser/cliparser.c index 6c249e9cb..f3f3c581e 100644 --- a/client/deps/cliparser/cliparser.c +++ b/client/deps/cliparser/cliparser.c @@ -118,7 +118,7 @@ int CLIParserParseArg(CLIParserContext *ctx, int argc, char **argv, void *vargta if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout, ((struct arg_end *)(ctx->argtable)[vargtableLen - 1]), ctx->programName); - PrintAndLogEx(WARNING, "Try '%s --help' for more information.\n", ctx->programName); + PrintAndLogEx(WARNING, "Try " _YELLOW_("'%s --help'") " for more information.\n", ctx->programName); fflush(stdout); return 3; } @@ -269,15 +269,19 @@ int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int return 0; } +// hexstr -> u64, w optional len input and default value fallback. +// 0 = failed +// 1 = OK +// 3 = optional param - not set uint64_t arg_get_u64_hexstr_def(CLIParserContext *ctx, uint8_t paramnum, uint64_t def) { uint64_t rv = 0; - uint8_t data[8]; - int datalen = 0; - int res = CLIParamHexToBuf(arg_get_str(ctx, paramnum), data, sizeof(data), &datalen); - if (res == 0 && datalen > 0) { - for (uint8_t i = 0; i < datalen; i++) { + uint8_t d[8]; + int dlen = 0; + int res = CLIParamHexToBuf(arg_get_str(ctx, paramnum), d, sizeof(d), &dlen); + if (res == 0 && dlen > 0) { + for (uint8_t i = 0; i < dlen; i++) { rv <<= 8; - rv |= data[i]; + rv |= d[i]; } } else { rv = def; @@ -285,11 +289,38 @@ uint64_t arg_get_u64_hexstr_def(CLIParserContext *ctx, uint8_t paramnum, uint64_ return rv; } -int arg_get_u32_hexstr_def(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out) { - return arg_get_u32_hexstr_def_nlen(ctx, paramnum, def, out, 4); +// hexstr -> u64, w optional len input and default value fallback. +// 0 = failed +// 1 = OK +// 2 = wrong len param, use default +// 3 = optional param, if fail, use default. +int arg_get_u64_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint64_t def, uint64_t *out, uint8_t nlen, bool optional) { + int n = 0; + uint8_t d[nlen]; + int res = CLIParamHexToBuf(arg_get_str(ctx, paramnum), d, sizeof(d), &n); + if (res == 0 && n == nlen) { + uint64_t rv = 0; + for (uint8_t i = 0; i < n; i++) { + rv <<= 8; + rv |= d[i]; + } + *out = rv; + return 1; + } else if (res == 0 && n) { + *out = def; + return 2; + } else if (res == 0 && n == 0 && optional) { + *out = def; + return 3; + } + return 0; } -int arg_get_u32_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out, uint8_t nlen) { +int arg_get_u32_hexstr_def(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out) { + return arg_get_u32_hexstr_def_nlen(ctx, paramnum, def, out, 4, false); +} + +int arg_get_u32_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out, uint8_t nlen, bool optional) { int n = 0; uint8_t d[nlen]; int res = CLIParamHexToBuf(arg_get_str(ctx, paramnum), d, sizeof(d), &n); @@ -304,6 +335,9 @@ int arg_get_u32_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint32_ } else if (res == 0 && n) { *out = def; return 2; + } else if (res == 0 && n == 0 && optional) { + *out = def; + return 3; } return 0; } diff --git a/client/deps/cliparser/cliparser.h b/client/deps/cliparser/cliparser.h index 40fd5c2f7..78bb59f32 100644 --- a/client/deps/cliparser/cliparser.h +++ b/client/deps/cliparser/cliparser.h @@ -68,6 +68,13 @@ int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen); uint64_t arg_get_u64_hexstr_def(CLIParserContext *ctx, uint8_t paramnum, uint64_t def); +int arg_get_u64_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint64_t def, uint64_t *out, uint8_t nlen, bool optional); int arg_get_u32_hexstr_def(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out); -int arg_get_u32_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out, uint8_t nlen); +int arg_get_u32_hexstr_def_nlen(CLIParserContext *ctx, uint8_t paramnum, uint32_t def, uint32_t *out, uint8_t nlen, bool optional); + +#define CP_SUCCESS_OPTIONAL 1 +#define CP_SUCCESS 0 +#define CP_ENOPARAM -1 +#define CP_WRONGLEN -2 + #endif diff --git a/client/src/cmdanalyse.c b/client/src/cmdanalyse.c index 02ad3fcd0..4cdd35e68 100644 --- a/client/src/cmdanalyse.c +++ b/client/src/cmdanalyse.c @@ -170,6 +170,14 @@ static uint16_t calcBSDchecksum4(uint8_t *bytes, uint8_t len, uint32_t mask) { return sum; } +// 0xFF - ( n1 ^ n... ) +static uint16_t calcXORchecksum(uint8_t *bytes, uint8_t len, uint32_t mask) { + return 0xFF - calcSumByteXor(bytes, len, mask); +} + + +//2148050707DB0A0E000001C4000000 + // measuring LFSR maximum length static int CmdAnalyseLfsr(const char *Cmd) { CLIParserContext *ctx; @@ -421,11 +429,12 @@ static int CmdAnalyseCHKSUM(const char *Cmd) { PrintAndLogEx(INFO, "Mask value 0x%x", mask); if (verbose) { - PrintAndLogEx(INFO, " add | sub | add 1's compl | sub 1's compl | xor"); - PrintAndLogEx(INFO, "byte nibble crumb | byte nibble | byte nibble cumb | byte nibble | byte nibble cumb | BSD |"); - PrintAndLogEx(INFO, "------------------+-------------+------------------+-----------------+--------------------"); + PrintAndLogEx(INFO, "------------------+-------------+------------------+-----------------+------------------+-----------+-------------"); + PrintAndLogEx(INFO, " add | sub | add 1's compl | sub 1's compl | xor | |"); + PrintAndLogEx(INFO, "byte nibble crumb | byte nibble | byte nibble cumb | byte nibble | byte nibble cumb | BSD | 0xFF - (n^n)"); + PrintAndLogEx(INFO, "------------------+-------------+------------------+-----------------+------------------+-----------+-------------"); } - PrintAndLogEx(INFO, "0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X |\n", + PrintAndLogEx(INFO, "0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X\n", calcSumByteAdd(data, dlen, mask) , calcSumNibbleAdd(data, dlen, mask) , calcSumCrumbAdd(data, dlen, mask) @@ -441,6 +450,7 @@ static int CmdAnalyseCHKSUM(const char *Cmd) { , calcSumCrumbXor(data, dlen, mask) , calcBSDchecksum8(data, dlen, mask) , calcBSDchecksum4(data, dlen, mask) + , calcXORchecksum(data, dlen, mask) ); return PM3_SUCCESS; } diff --git a/client/src/cmdlfem4x05.c b/client/src/cmdlfem4x05.c index c0dc8c2ee..87303124b 100644 --- a/client/src/cmdlfem4x05.c +++ b/client/src/cmdlfem4x05.c @@ -773,15 +773,38 @@ int CmdEM4x05Write(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_int0("a", "addr", "", "memory address to write to. (0-13)"), - arg_str1("d", "data", "", "data to write, 4 bytes hex"), - arg_str0("p", "pwd", "", "optional - password, 4 bytes hex"), + arg_str1("d", "data", "", "data to write (4 hex bytes)"), + arg_str0("p", "pwd", "", "password (4 hex bytes)"), arg_lit0(NULL, "po", "protect operation"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); uint8_t addr = (uint8_t)arg_get_int_def(ctx, 1, 50); - uint32_t data = arg_get_u32(ctx, 2); - uint64_t inputpwd = arg_get_u64_hexstr_def(ctx, 3, 0xFFFFFFFFFFFFFFFF); + uint32_t data = 0; + int res = arg_get_u32_hexstr_def(ctx, 2, 0, &data); + if (res == 2) { + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "Data must be 4 hex bytes"); + return PM3_EINVARG; + } else if (res == 0) { + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "Data must be 4 hex bytes"); + return PM3_EINVARG; + } + + bool use_pwd = false; + uint32_t pwd = 0; + res = arg_get_u32_hexstr_def_nlen(ctx, 3, 0, &pwd, 4, true); + if (res == 2) { + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "Password must be 4 hex bytes"); + return PM3_EINVARG; + } else if (res == 3) { + use_pwd = false; + } else if (res == 1) { + use_pwd = true; + } + bool protect_operation = arg_get_lit(ctx, 4); CLIParserFree(ctx); @@ -790,22 +813,19 @@ int CmdEM4x05Write(const char *Cmd) { return PM3_EINVARG; } - bool use_pwd = false; - uint32_t pwd = (inputpwd != 0xFFFFFFFFFFFFFFFF) ? (inputpwd & 0xFFFFFFFF) : 0; - if (pwd == 0xFFFFFFFF) { - if (protect_operation) - PrintAndLogEx(INFO, "Writing protection words data %08X", data); - else - PrintAndLogEx(INFO, "Writing address %d data %08X", addr, data); - } else { - use_pwd = true; + if (use_pwd) { if (protect_operation) PrintAndLogEx(INFO, "Writing protection words data %08X using password %08X", data, pwd); else PrintAndLogEx(INFO, "Writing address %d data %08X using password %08X", addr, data, pwd); + } else { + if (protect_operation) + PrintAndLogEx(INFO, "Writing protection words data %08X", data); + else + PrintAndLogEx(INFO, "Writing address %d data %08X", addr, data); } - int res = PM3_SUCCESS; + res = PM3_SUCCESS; // set Protect Words if (protect_operation) { res = em4x05_protect(pwd, use_pwd, data); diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index cd4947b4d..d98347342 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -262,26 +262,7 @@ static int usage_t55xx_wakup(void) { PrintAndLogEx(NORMAL, _YELLOW_(" lf t55xx wakeup p 11223344") " - send wakeup password"); return PM3_SUCCESS; } -static int usage_t55xx_chk(void) { - PrintAndLogEx(NORMAL, "This command uses a dictionary attack"); - PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command"); - PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!"); - PrintAndLogEx(NORMAL, "Try to reading block 7 before\n"); - PrintAndLogEx(NORMAL, "Usage: lf t55xx chk [h] [m] [r ] [f <*.dic>] [e ]"); - PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h - this help"); - PrintAndLogEx(NORMAL, " m - use dictionary from flashmemory\n"); - print_usage_t55xx_downloadlink(T55XX_DLMODE_ALL, T55XX_DLMODE_ALL); - PrintAndLogEx(NORMAL, " f <*.dic> - loads a default keys dictionary file <*.dic>"); - PrintAndLogEx(NORMAL, " e - will try the calculated password from some cloners based on EM4100 ID"); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, _YELLOW_(" lf t55xx chk m")); - PrintAndLogEx(NORMAL, _YELLOW_(" lf t55xx chk f t55xx_default_pwds")); - PrintAndLogEx(NORMAL, _YELLOW_(" lf t55xx chk e aa11223344")); - PrintAndLogEx(NORMAL, ""); - return PM3_SUCCESS; -} + static int usage_t55xx_dangerraw(void) { PrintAndLogEx(NORMAL, "This command allows to emit arbitrary raw commands on T5577 and cut the field after arbitrary duration."); PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may lock definitively the tag in an unusable state!"); @@ -2974,68 +2955,83 @@ static bool IsCancelled(void) { // load a default pwd file. static int CmdT55xxChkPwds(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf t55xx chk", + "This command uses a dictionary attack.\n" + "For some cloners, try '--em' for known pwdgen algo.\n" + "Try to reading Page 0 block 7 before.\n" + _RED_("WARNING:") _CYAN_(" this may brick non-password protected chips!"), + "lf t55xx chk -m -> use dictionary from flash memory (RDV4)\n" + "lf t55xx chk -f my_dictionary_pwds -> loads a default keys dictionary file\n" + "lf t55xx chk --em aa11223344 -> try known pwdgen algo from some cloners based on EM4100 ID" + ); + // 4 + (5 or 6) + void *argtable[9] = { + arg_param_begin, + arg_lit0("m", "fm", "use dictionary from flash memory (RDV4)"), + arg_str0("f", "file", "", "file name"), + arg_str0(NULL, "em", "", "EM4100 ID (5 hex bytes)"), + }; + uint8_t idx = 4; + arg_add_t55xx_downloadlink(argtable, &idx, T55XX_DLMODE_ALL, T55XX_DLMODE_ALL); + CLIExecWithReturn(ctx, Cmd, argtable, true); + + bool from_flash = arg_get_lit(ctx, 1); + + int fnlen = 0; char filename[FILE_PATH_SIZE] = {0}; - bool found = false; - uint8_t timeout = 0; - uint8_t *keyBlock = NULL; - bool from_flash = false; - bool try_all_dl_modes = false; - uint8_t downlink_mode = 0; - bool use_pwd_file = false; - int dl_mode; // to try each downlink mode for each password - uint8_t cmdp = 0; - bool errors = false; - bool useCardPassword = false; - uint32_t cardPassword = 0x00; - uint64_t cardID = 0x00; + CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)filename, sizeof(filename), &fnlen); - while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { - switch (tolower(param_getchar(Cmd, cmdp))) { - case 'h': - return usage_t55xx_chk(); - case 'r': - downlink_mode = param_get8ex(Cmd, cmdp + 1, 0, 10); - if (downlink_mode >= 4) { - try_all_dl_modes = true; - downlink_mode = 0; - } - cmdp += 2; - break; - case 'm': - from_flash = true; - cmdp++; - break; - case 'f': - if (param_getstr(Cmd, cmdp + 1, filename, sizeof(filename)) == 0) { - PrintAndLogEx(ERR, "Error, no filename after 'f' was found"); - errors = true; - } - use_pwd_file = true; - cmdp += 2; - break; - case 'e': // White cloner password based on EM4100 ID - useCardPassword = true; - cardID = param_get64ex(Cmd, cmdp + 1, 0, 16); - uint32_t card32Bit = cardID & 0xFFFFFFFF; - cardPassword = lf_t55xx_white_pwdgen(card32Bit); - cmdp += 2; - break; - default: - PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); - errors = true; - break; - } + bool use_calc_password = false; + uint32_t card_password = 0x00; + uint64_t cardid = 0; + int res = arg_get_u64_hexstr_def_nlen(ctx, 3, 0x00, &cardid, 5, true); + if (res == 1) { + use_calc_password = true; + uint32_t calc = cardid & 0xFFFFFFFF; + card_password = lf_t55xx_white_pwdgen(calc); + } + if (res == 2) { + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "EM4100 ID must be 5 hex bytes"); + return PM3_EINVARG; + } + if (res == 0) { + CLIParserFree(ctx); + return PM3_EINVARG; } - if (errors) return usage_t55xx_chk(); + bool r0 = arg_get_lit(ctx, 4); + bool r1 = arg_get_lit(ctx, 5); + bool r2 = arg_get_lit(ctx, 6); + bool r3 = arg_get_lit(ctx, 7); + bool ra = arg_get_lit(ctx, 8); + CLIParserFree(ctx); + if ((r0 + r1 + r2 + r3 + ra) > 1) { + PrintAndLogEx(FAILED, "Error multiple downlink encoding"); + return PM3_EINVARG; + } + + uint8_t downlink_mode = config.downlink_mode; + if (r0) + downlink_mode = refFixedBit; + else if (r1) + downlink_mode = refLongLeading; + else if (r2) + downlink_mode = refLeading0; + else if (r3) + downlink_mode = ref1of4; + + bool use_pwd_file = false; if (strlen(filename) == 0) { snprintf(filename, sizeof(filename), "t55xx_default_pwds"); use_pwd_file = true; } + PrintAndLogEx(INFO, "press " _GREEN_("'enter'") " to cancel the command"); PrintAndLogEx(NORMAL, ""); /* // block 7, page1 = false, usepwd = false, override = false, pwd = 00000000 @@ -3047,6 +3043,8 @@ static int CmdT55xxChkPwds(const char *Cmd) { } */ + bool found = false; + uint64_t t1 = msclock(); uint8_t flags = downlink_mode << 3; @@ -3055,6 +3053,7 @@ static int CmdT55xxChkPwds(const char *Cmd) { SendCommandNG(CMD_LF_T55XX_CHK_PWDS, &flags, sizeof(flags)); PacketResponseNG resp; + uint8_t timeout = 0; while (!WaitForResponseTimeout(CMD_LF_T55XX_CHK_PWDS, &resp, 2000)) { timeout++; PrintAndLogEx(NORMAL, "." NOLF); @@ -3090,55 +3089,59 @@ static int CmdT55xxChkPwds(const char *Cmd) { goto out; } - // try calculated password - if (useCardPassword) { + // to try each downlink mode for each password + int dl_mode; - PrintAndLogEx(INFO, "testing %08"PRIX32" generated ", cardPassword); + // try calculated password + if (use_calc_password) { + + PrintAndLogEx(INFO, "testing %08"PRIX32" generated ", card_password); for (dl_mode = downlink_mode; dl_mode <= 3; dl_mode++) { - if (!AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, cardPassword, dl_mode)) { + if (!AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, card_password, dl_mode)) { continue; } - found = t55xxTryDetectModulationEx(dl_mode, T55XX_PrintConfig, 0, cardPassword); + found = t55xxTryDetectModulationEx(dl_mode, T55XX_PrintConfig, 0, card_password); if (found) { - PrintAndLogEx(SUCCESS, "found valid password : [ " _GREEN_("%08"PRIX32) " ]", cardPassword); - dl_mode = 4; // Exit other downlink mode checks + PrintAndLogEx(SUCCESS, "found valid password : [ " _GREEN_("%08"PRIX32) " ]", card_password); + break; } - if (!try_all_dl_modes) // Exit loop if not trying all downlink modes - dl_mode = 4; + if (ra == false) + break; } } if ((found == false) && use_pwd_file) { uint32_t keycount = 0; + uint8_t *keyblock = NULL; - int res = loadFileDICTIONARY_safe(filename, (void **) &keyBlock, 4, &keycount); - if (res != PM3_SUCCESS || keycount == 0 || keyBlock == NULL) { + res = loadFileDICTIONARY_safe(filename, (void **) &keyblock, 4, &keycount); + if (res != PM3_SUCCESS || keycount == 0 || keyblock == NULL) { PrintAndLogEx(WARNING, "no keys found in file"); - if (keyBlock != NULL) - free(keyBlock); + if (keyblock != NULL) + free(keyblock); return PM3_ESOFT; } - PrintAndLogEx(INFO, "press " _YELLOW_("'enter'") " to cancel the command"); + PrintAndLogEx(INFO, "press " _GREEN_("'enter'") " to cancel the command"); - for (uint32_t c = 0; c < keycount; ++c) { + for (uint32_t c = 0; c < keycount && found == false; ++c) { if (!session.pm3_present) { PrintAndLogEx(WARNING, "device offline\n"); - free(keyBlock); + free(keyblock); return PM3_ENODATA; } if (IsCancelled()) { - free(keyBlock); + free(keyblock); return PM3_EOPABORTED; } - uint32_t curr_password = bytes_to_num(keyBlock + 4 * c, 4); + uint32_t curr_password = bytes_to_num(keyblock + 4 * c, 4); PrintAndLogEx(INFO, "testing %08"PRIX32, curr_password); for (dl_mode = downlink_mode; dl_mode <= 3; dl_mode++) { @@ -3150,20 +3153,19 @@ static int CmdT55xxChkPwds(const char *Cmd) { found = t55xxTryDetectModulationEx(dl_mode, T55XX_PrintConfig, 0, curr_password); if (found) { PrintAndLogEx(SUCCESS, "found valid password: [ " _GREEN_("%08"PRIX32) " ]", curr_password); - dl_mode = 4; // Exit other downlink mode checks - c = keycount; // Exit loop + break; } - if (!try_all_dl_modes) // Exit loop if not trying all downlink modes - dl_mode = 4; + if (ra == false) // Exit loop if not trying all downlink modes + break; } } + + free(keyblock); } if (found == false) - PrintAndLogEx(WARNING, "check pwd failed"); - - free(keyBlock); + PrintAndLogEx(WARNING, "failed to find password"); out: t1 = msclock() - t1; From f6462137cfe10c9100e9bb659a1359867771b0df Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 23:18:01 +0100 Subject: [PATCH 26/76] standalone mode LF_EM4100RWC, LF_EM4100RSWB - odd big buff static pointer usage --- armsrc/Standalone/lf_em4100rswb.c | 19 +++++++++++-------- armsrc/Standalone/lf_em4100rwc.c | 8 ++++---- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/armsrc/Standalone/lf_em4100rswb.c b/armsrc/Standalone/lf_em4100rswb.c index 14bab8357..e6e55f340 100644 --- a/armsrc/Standalone/lf_em4100rswb.c +++ b/armsrc/Standalone/lf_em4100rswb.c @@ -76,14 +76,13 @@ static int bruteforceSpeed[] = {10, 12, 14, 16}; // In high[] must be nulls static uint64_t low[] = {0, 0, 0, 0}; static uint32_t high[] = {0, 0, 0, 0}; -static uint8_t *bba; static int buflen; void ModInfo(void) { DbpString(" LF EM4100 read/sim/write/brute mode"); } -static uint64_t ReversQuads(uint64_t bits) { +static uint64_t rev_quads(uint64_t bits) { uint64_t result = 0; for (int i = 0; i < 16; i++) { result += ((bits >> (60 - 4 * i)) & 0xf) << (4 * i); @@ -92,6 +91,7 @@ static uint64_t ReversQuads(uint64_t bits) { } static void FillBuff(uint8_t bit) { + uint8_t *bba = BigBuf_get_addr(); memset(bba + buflen, bit, LF_CLOCK / 2); buflen += (LF_CLOCK / 2); memset(bba + buflen, bit ^ 1, LF_CLOCK / 2); @@ -99,24 +99,29 @@ static void FillBuff(uint8_t bit) { } static void ConstructEM410xEmulBuf(uint64_t id) { - bba = BigBuf_get_addr(); - int i, j, binary[4], parity[4]; buflen = 0; + for (i = 0; i < 9; i++) FillBuff(1); + parity[0] = parity[1] = parity[2] = parity[3] = 0; + for (i = 0; i < 10; i++) { for (j = 3; j >= 0; j--, id /= 2) binary[j] = id % 2; + for (j = 0; j < 4; j++) FillBuff(binary[j]); + FillBuff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); for (j = 0; j < 4; j++) parity[j] ^= binary[j]; } + for (j = 0; j < 4; j++) FillBuff(parity[j]); + FillBuff(0); } @@ -197,7 +202,6 @@ static uint64_t PackEmID(uint64_t original, int newCardNum) { return buf; } - static void PrintFcAndCardNum(uint64_t lowData) { // Calculate Facility Code and Card Number from high and low uint32_t fc = (lowData >> 17) & 0xFF; @@ -222,7 +226,7 @@ static int BruteEMTag(uint64_t originalCard, int slot) { cardnum = cardnum + direction; uint64_t currentCard = PackEmID(originalCard, cardnum); Dbprintf("[=] >> Simulating card id %"PRIx64" <<", currentCard); - ConstructEM410xEmulBuf(ReversQuads(currentCard)); + ConstructEM410xEmulBuf(rev_quads(currentCard)); SimulateTagLowFrequencyEx(buflen, 0, 1, bruteforceSpeed[bruteforceSpeedCurrent] * 10000); int button_pressed = BUTTON_CLICKED(1000); @@ -267,7 +271,7 @@ static int ExecuteMode(int mode, int slot) { return LF_RWSB_UNKNOWN_RESULT; case LF_RWSB_MODE_SIM: Dbprintf("[=] >> Sim mode started <<"); - ConstructEM410xEmulBuf(ReversQuads(low[slot])); + ConstructEM410xEmulBuf(rev_quads(low[slot])); SimulateTagLowFrequency(buflen, 0, 1); return LF_RWSB_UNKNOWN_RESULT; case LF_RWSB_MODE_WRITE: @@ -310,7 +314,6 @@ void RunMod() { int slot = 0; mode = SwitchMode(mode, slot); - bba = BigBuf_get_addr(); for (;;) { WDT_HIT(); if (data_available()) break; diff --git a/armsrc/Standalone/lf_em4100rwc.c b/armsrc/Standalone/lf_em4100rwc.c index d095b944b..911f97f0e 100644 --- a/armsrc/Standalone/lf_em4100rwc.c +++ b/armsrc/Standalone/lf_em4100rwc.c @@ -41,7 +41,7 @@ // In high[] must be nulls static uint64_t low[] = {0x565AF781C7, 0x540053E4E2, 0x1234567890, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static uint32_t high[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; -static uint8_t *bba, slots_count; +static uint8_t slots_count; static int buflen; void ModInfo(void) { @@ -57,6 +57,7 @@ static uint64_t rev_quads(uint64_t bits) { } static void fillbuff(uint8_t bit) { + uint8_t *bba = BigBuf_get_addr(); memset(bba + buflen, bit, LF_CLOCK / 2); buflen += (LF_CLOCK / 2); memset(bba + buflen, bit ^ 1, LF_CLOCK / 2); @@ -66,8 +67,8 @@ static void fillbuff(uint8_t bit) { static void construct_EM410x_emul(uint64_t id) { int i, j; - int binary[4] = {0}; - int parity[4] = {0}; + int binary[4] = {0,0,0,0}; + int parity[4] = {0,0,0,0}; buflen = 0; for (i = 0; i < 9; i++) @@ -138,7 +139,6 @@ void RunMod(void) { // 3 - write to T5555 tag uint8_t state = 0; slots_count = ARRAYLEN(low); - bba = BigBuf_get_addr(); led_slot(selected); for (;;) { From a5c40fa07b475db11db688304df6e5bddfeb7646 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 23:30:37 +0100 Subject: [PATCH 27/76] minor renaming --- armsrc/Standalone/lf_em4100emul.c | 41 ++++++++++++++++++------------- armsrc/Standalone/lf_em4100rswb.c | 22 ++++++++--------- armsrc/Standalone/lf_em4100rwc.c | 12 ++++----- 3 files changed, 41 insertions(+), 34 deletions(-) diff --git a/armsrc/Standalone/lf_em4100emul.c b/armsrc/Standalone/lf_em4100emul.c index e6ac2f6ff..dd44c843e 100644 --- a/armsrc/Standalone/lf_em4100emul.c +++ b/armsrc/Standalone/lf_em4100emul.c @@ -21,19 +21,19 @@ #include "commonutil.h" #define MAX_IND 16 // 4 LEDs - 2^4 combinations -#define CLOCK 64 //for 125kHz +#define LF_CLOCK 64 // for 125kHz // low & high - array for storage IDs. Its length must be equal. // Predefined IDs must be stored in low[]. static uint64_t low[] = {0x565A1140BE, 0x365A398149, 0x5555555555, 0xFFFFFFFFFF}; -static uint8_t *bba, slots_count; +static uint8_t slots_count; static int buflen; void ModInfo(void) { DbpString(" LF EM4100 simulator standalone mode"); } -static uint64_t ReversQuads(uint64_t bits) { +static uint64_t rev_quads(uint64_t bits) { uint64_t result = 0; for (int i = 0; i < 16; i++) { result += ((bits >> (60 - 4 * i)) & 0xf) << (4 * i); @@ -41,32 +41,40 @@ static uint64_t ReversQuads(uint64_t bits) { return result >> 24; } -static void FillBuff(uint8_t bit) { - memset(bba + buflen, bit, CLOCK / 2); - buflen += (CLOCK / 2); - memset(bba + buflen, bit ^ 1, CLOCK / 2); - buflen += (CLOCK / 2); +static void fill_buff(uint8_t bit) { + uint8_t *bba = BigBuf_get_addr(); + memset(bba + buflen, bit, LF_CLOCK / 2); + buflen += (LF_CLOCK / 2); + memset(bba + buflen, bit ^ 1, LF_CLOCK / 2); + buflen += (LF_CLOCK / 2); } static void ConstructEM410xEmulBuf(uint64_t id) { - int i, j, binary[4], parity[4]; + int i, j; + int binary[4] = {0,0,0,0}; + int parity[4] = {0,0,0,0}; buflen = 0; + for (i = 0; i < 9; i++) - FillBuff(1); - parity[0] = parity[1] = parity[2] = parity[3] = 0; + fill_buff(1); + for (i = 0; i < 10; i++) { for (j = 3; j >= 0; j--, id /= 2) binary[j] = id % 2; + for (j = 0; j < 4; j++) - FillBuff(binary[j]); - FillBuff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); + fill_buff(binary[j]); + + fill_buff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); for (j = 0; j < 4; j++) parity[j] ^= binary[j]; } + for (j = 0; j < 4; j++) - FillBuff(parity[j]); - FillBuff(0); + fill_buff(parity[j]); + + fill_buff(0); } static void LED_Slot(int i) { @@ -85,14 +93,13 @@ void RunMod(void) { int selected = 0; //selected slot after start slots_count = ARRAYLEN(low); - bba = BigBuf_get_addr(); for (;;) { WDT_HIT(); if (data_available()) break; SpinDelay(100); SpinUp(100); LED_Slot(selected); - ConstructEM410xEmulBuf(ReversQuads(low[selected])); + ConstructEM410xEmulBuf(rev_quads(low[selected])); SimulateTagLowFrequency(buflen, 0, true); selected = (selected + 1) % slots_count; } diff --git a/armsrc/Standalone/lf_em4100rswb.c b/armsrc/Standalone/lf_em4100rswb.c index e6e55f340..8e723185f 100644 --- a/armsrc/Standalone/lf_em4100rswb.c +++ b/armsrc/Standalone/lf_em4100rswb.c @@ -53,8 +53,8 @@ #include "flashmem.h" #endif -#define LF_CLOCK 64 //for 125kHz -#define LF_RWSB_T55XX_TYPE 1 //Tag type: 0 - T5555, 1-T55x7 +#define LF_CLOCK 64 // for 125kHz +#define LF_RWSB_T55XX_TYPE 1 // Tag type: 0 - T5555, 1-T55x7 #define LF_RWSB_UNKNOWN_RESULT 0 #define LF_RWSB_BRUTE_STOPED 1 @@ -90,7 +90,7 @@ static uint64_t rev_quads(uint64_t bits) { return result >> 24; } -static void FillBuff(uint8_t bit) { +static void fill_buff(uint8_t bit) { uint8_t *bba = BigBuf_get_addr(); memset(bba + buflen, bit, LF_CLOCK / 2); buflen += (LF_CLOCK / 2); @@ -99,30 +99,30 @@ static void FillBuff(uint8_t bit) { } static void ConstructEM410xEmulBuf(uint64_t id) { - int i, j, binary[4], parity[4]; + int i, j; + int binary[4] = {0,0,0,0}; + int parity[4] = {0,0,0,0}; buflen = 0; for (i = 0; i < 9; i++) - FillBuff(1); - - parity[0] = parity[1] = parity[2] = parity[3] = 0; + fill_buff(1); for (i = 0; i < 10; i++) { for (j = 3; j >= 0; j--, id /= 2) binary[j] = id % 2; for (j = 0; j < 4; j++) - FillBuff(binary[j]); + fill_buff(binary[j]); - FillBuff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); + fill_buff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); for (j = 0; j < 4; j++) parity[j] ^= binary[j]; } for (j = 0; j < 4; j++) - FillBuff(parity[j]); + fill_buff(parity[j]); - FillBuff(0); + fill_buff(0); } static void LED_Update(int mode, int slot) { diff --git a/armsrc/Standalone/lf_em4100rwc.c b/armsrc/Standalone/lf_em4100rwc.c index 911f97f0e..9240feb47 100644 --- a/armsrc/Standalone/lf_em4100rwc.c +++ b/armsrc/Standalone/lf_em4100rwc.c @@ -56,7 +56,7 @@ static uint64_t rev_quads(uint64_t bits) { return result >> 24; } -static void fillbuff(uint8_t bit) { +static void fill_buff(uint8_t bit) { uint8_t *bba = BigBuf_get_addr(); memset(bba + buflen, bit, LF_CLOCK / 2); buflen += (LF_CLOCK / 2); @@ -72,24 +72,24 @@ static void construct_EM410x_emul(uint64_t id) { buflen = 0; for (i = 0; i < 9; i++) - fillbuff(1); + fill_buff(1); for (i = 0; i < 10; i++) { for (j = 3; j >= 0; j--, id /= 2) binary[j] = id % 2; for (j = 0; j < 4; j++) - fillbuff(binary[j]); + fill_buff(binary[j]); - fillbuff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); + fill_buff(binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); for (j = 0; j < 4; j++) parity[j] ^= binary[j]; } for (j = 0; j < 4; j++) - fillbuff(parity[j]); + fill_buff(parity[j]); - fillbuff(0); + fill_buff(0); } static void led_slot(int i) { From f8925aa5f3e1d0f66b9353e6f8c04246b692b3dd Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 27 Jan 2021 23:45:32 +0100 Subject: [PATCH 28/76] added more links --- doc/jtag_notes.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/doc/jtag_notes.md b/doc/jtag_notes.md index 01b964365..f7392d53f 100644 --- a/doc/jtag_notes.md +++ b/doc/jtag_notes.md @@ -60,6 +60,9 @@ TCK | 23 GND | 6 3.3 | 1 +# Where to find more information? +There has been lots of articles and blogposts about recoving, debricking, JTAG your Proxmark3 and you find here below a sortiment of resources that will be of help. + ## Third party notes on using a BusPirate * https://github.com/Proxmark/proxmark3/wiki/Debricking-Proxmark3-with-buspirate @@ -84,3 +87,6 @@ GND | 6 ## Stack Overflow write up article. https://stackoverflow.com/questions/48794076/error-halt-timed-out-wake-up-gdb/64291913#64291913 +## Old original doc, +Describes the SEGGER JLINK, JTAG process but be warned, this document is old. +https://github.com/RfidResearchGroup/proxmark3/blob/master/doc/original_proxmark3/Compiling%20Proxmark%20source%20and%20firmware%20upgrading%20v1.pdf \ No newline at end of file From 02c1034caa9080ea13bf3146f808241baed459f5 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 00:35:14 +0100 Subject: [PATCH 29/76] fix #1175 - biphase demod identification of value clocks now fails if no changes detected --- common/lfdemod.c | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/common/lfdemod.c b/common/lfdemod.c index 171417143..221dba8d6 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -41,6 +41,8 @@ #include // qsort #include "parity.h" // for parity test #include "pm3_cmd.h" // error codes +#include "commonutil.h" // Arraylen + // ********************************************************************************************** // ---------------------------------Utilities Section-------------------------------------------- // ********************************************************************************************** @@ -770,6 +772,22 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { //if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, # Errors %d, Current Best Clk %d, bestStart %d", clk[k], bestErr[k], clk[best], bestStart[best]); } + bool chg = false; + for (i = 0; i < ARRAYLEN(bestErr); i++) { + chg = (bestErr[i] != 1000); + if (chg) + break; + chg = (bestStart[i] != 0); + if (chg) + break; + } + + // just noise - no super good detection. good enough + if (chg == false) { + if (g_debugMode == 2) prnt("DEBUG DetectASKClock: no good values detected - aborting"); + return -2; + } + if (!found_clk) *clock = clk[best]; @@ -1671,12 +1689,12 @@ int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, *startIdx = start - (*clk / 2); if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Weak wave detected: startIdx %i", *startIdx); - int lastBit; //set first clock check - can go negative - size_t i, bitnum = 0; //output counter + int lastBit; // set first clock check - can go negative + size_t i, bitnum = 0; // output counter uint8_t midBit = 0; - uint8_t tol = 0; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave - if (*clk <= 32) tol = 1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely - size_t MaxBits = 3072; //max bits to collect + uint8_t tol = 0; // clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave + if (*clk <= 32) tol = 1; // clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely + size_t MaxBits = 3072; // max bits to collect lastBit = start - *clk; for (i = start; i < *size; ++i) { From 58cbe90469c7e0c720afab426f9b22219f0f9d9d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 01:21:52 +0100 Subject: [PATCH 30/76] rename --- client/src/cmddata.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 7c6fd4785..d2d28d0f0 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -769,22 +769,22 @@ static int CmdBiphaseDecodeRaw(const char *Cmd) { int ASKbiphaseDemod(int offset, int clk, int invert, int maxErr, bool verbose) { //ask raw demod GraphBuffer first - uint8_t BitStream[MAX_DEMOD_BUF_LEN]; - size_t size = getFromGraphBuf(BitStream); + uint8_t bs[MAX_DEMOD_BUF_LEN]; + size_t size = getFromGraphBuf(bs); if (size == 0) { PrintAndLogEx(DEBUG, "DEBUG: no data in graphbuf"); return PM3_ESOFT; } int startIdx = 0; //invert here inverts the ask raw demoded bits which has no effect on the demod, but we need the pointer - int errCnt = askdemod_ext(BitStream, &size, &clk, &invert, maxErr, 0, 0, &startIdx); + int errCnt = askdemod_ext(bs, &size, &clk, &invert, maxErr, 0, 0, &startIdx); if (errCnt < 0 || errCnt > maxErr) { PrintAndLogEx(DEBUG, "DEBUG: no data or error found %d, clock: %d", errCnt, clk); return PM3_ESOFT; } //attempt to Biphase decode BitStream - errCnt = BiphaseRawDecode(BitStream, &size, &offset, invert); + errCnt = BiphaseRawDecode(bs, &size, &offset, invert); if (errCnt < 0) { if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: Error BiphaseRawDecode: %d", errCnt); return PM3_ESOFT; @@ -795,7 +795,7 @@ int ASKbiphaseDemod(int offset, int clk, int invert, int maxErr, bool verbose) { } //success set DemodBuffer and return - setDemodBuff(BitStream, size, 0); + setDemodBuff(bs, size, 0); setClockGrid(clk, startIdx + clk * offset / 2); if (g_debugMode || verbose) { PrintAndLogEx(DEBUG, "Biphase Decoded using offset %d | clock %d | #errors %d | start index %d\ndata\n", offset, clk, errCnt, (startIdx + clk * offset / 2)); From 65c11ee0e4f971b688836e985ebb847d3f1543a2 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 11:49:25 +0100 Subject: [PATCH 31/76] litte rename --- armsrc/Standalone/lf_em4100emul.c | 5 +++-- armsrc/Standalone/lf_em4100rswb.c | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/armsrc/Standalone/lf_em4100emul.c b/armsrc/Standalone/lf_em4100emul.c index dd44c843e..e23986ab7 100644 --- a/armsrc/Standalone/lf_em4100emul.c +++ b/armsrc/Standalone/lf_em4100emul.c @@ -49,7 +49,7 @@ static void fill_buff(uint8_t bit) { buflen += (LF_CLOCK / 2); } -static void ConstructEM410xEmulBuf(uint64_t id) { +static void construct_EM410x_emul(uint64_t id) { int i, j; int binary[4] = {0,0,0,0}; @@ -96,10 +96,11 @@ void RunMod(void) { for (;;) { WDT_HIT(); if (data_available()) break; + SpinDelay(100); SpinUp(100); LED_Slot(selected); - ConstructEM410xEmulBuf(rev_quads(low[selected])); + construct_EM410x_emul(rev_quads(low[selected])); SimulateTagLowFrequency(buflen, 0, true); selected = (selected + 1) % slots_count; } diff --git a/armsrc/Standalone/lf_em4100rswb.c b/armsrc/Standalone/lf_em4100rswb.c index 8e723185f..060795bd1 100644 --- a/armsrc/Standalone/lf_em4100rswb.c +++ b/armsrc/Standalone/lf_em4100rswb.c @@ -98,7 +98,7 @@ static void fill_buff(uint8_t bit) { buflen += (LF_CLOCK / 2); } -static void ConstructEM410xEmulBuf(uint64_t id) { +static void construct_EM410x_emul(uint64_t id) { int i, j; int binary[4] = {0,0,0,0}; int parity[4] = {0,0,0,0}; @@ -226,7 +226,7 @@ static int BruteEMTag(uint64_t originalCard, int slot) { cardnum = cardnum + direction; uint64_t currentCard = PackEmID(originalCard, cardnum); Dbprintf("[=] >> Simulating card id %"PRIx64" <<", currentCard); - ConstructEM410xEmulBuf(rev_quads(currentCard)); + construct_EM410x_emul(rev_quads(currentCard)); SimulateTagLowFrequencyEx(buflen, 0, 1, bruteforceSpeed[bruteforceSpeedCurrent] * 10000); int button_pressed = BUTTON_CLICKED(1000); @@ -271,7 +271,7 @@ static int ExecuteMode(int mode, int slot) { return LF_RWSB_UNKNOWN_RESULT; case LF_RWSB_MODE_SIM: Dbprintf("[=] >> Sim mode started <<"); - ConstructEM410xEmulBuf(rev_quads(low[slot])); + construct_EM410x_emul(rev_quads(low[slot])); SimulateTagLowFrequency(buflen, 0, 1); return LF_RWSB_UNKNOWN_RESULT; case LF_RWSB_MODE_WRITE: From 6e0673fd02ad381c457f3dc5aeb5969ee7ccbde4 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:05:32 +0100 Subject: [PATCH 32/76] cppchecker fixes --- armsrc/iclass.c | 28 ++++++++++++---------------- armsrc/iclass.h | 3 +-- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 5cb5d71ae..f31f17204 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -408,9 +408,9 @@ int do_iclass_simulation(int simulationMode, uint8_t *reader_mac_buf) { // Tag CSN uint8_t *modulated_response = NULL; - int modulated_response_size = 0; + int modulated_response_size; uint8_t *trace_data = NULL; - int trace_data_size = 0; + int trace_data_size; // Respond SOF -- takes 1 bytes uint8_t *resp_sof = BigBuf_malloc(1); @@ -498,10 +498,9 @@ int do_iclass_simulation(int simulationMode, uint8_t *reader_mac_buf) { bool button_pressed = false; uint8_t cmd, options, block; - int len = 0; + int len, kc_attempt = 0; bool exit_loop = false; bool using_kc = false; - int kc_attempt = 0; while (exit_loop == false) { WDT_HIT(); @@ -1364,7 +1363,9 @@ static bool select_iclass_tag_ex(picopass_hdr *hdr, bool use_credit_key, uint32_ return false; memcpy(hdr->epurse, resp, sizeof(hdr->epurse)); - *status |= FLAG_ICLASS_CC; + + if (status) + *status |= FLAG_ICLASS_CC; } else { @@ -1469,16 +1470,9 @@ void ReaderIClass(uint8_t flags) { switch_off(); } -// used with function select_and_auth (cmdhficlass.c) -// which needs to authenticate before doing more things like read/write -// selects and authenticate to a card, sends back div_key and mac to client. -void iClass_Authentication(uint8_t *msg) { -} - bool authenticate_iclass_tag(iclass_auth_req_t *payload, picopass_hdr *hdr, uint32_t *start_time, uint32_t *eof_time, uint8_t *mac_out) { uint8_t cmd_check[9] = { ICLASS_CMD_CHECK }; - uint8_t div_key[8] = {0}; uint8_t mac[4] = {0}; uint8_t resp_auth[4] = {0}; uint8_t ccnr[12] = {0}; @@ -1495,6 +1489,8 @@ bool authenticate_iclass_tag(iclass_auth_req_t *payload, picopass_hdr *hdr, uint memcpy(cmd_check + 1, payload->key, 8); } else { + + uint8_t div_key[8] = {0}; if (payload->use_raw) memcpy(div_key, payload->key, 8); else @@ -1792,7 +1788,7 @@ static bool iclass_writeblock_ext(uint8_t blockno, uint8_t *data, uint8_t *mac, uint8_t resp[10] = {0}; uint32_t eof_time = 0, start_time = 0; - bool isOK = iclass_send_cmd_with_retries(write, sizeof(write), resp, sizeof(resp), 10, 3, &start_time, ICLASS_READER_TIMEOUT_UPDATE, &eof_time); + bool isOK = iclass_send_cmd_with_retries(write, write_len, resp, sizeof(resp), 10, 3, &start_time, ICLASS_READER_TIMEOUT_UPDATE, &eof_time); if (isOK == false) { return false; } @@ -1833,7 +1829,7 @@ void iClass_WriteBlock(uint8_t *msg) { // select tag. uint32_t eof_time = 0; picopass_hdr hdr = {0}; - bool res = select_iclass_tag(&hdr, payload->req.use_credit_key, &eof_time); + uint8_t res = select_iclass_tag(&hdr, payload->req.use_credit_key, &eof_time); if (res == false) { goto out; } @@ -1889,7 +1885,7 @@ void iClass_WriteBlock(uint8_t *msg) { res = false; switch_off(); if (payload->req.send_reply) - reply_ng(CMD_HF_ICLASS_WRITEBL, PM3_ETEAROFF, (uint8_t *)&res, sizeof(uint8_t)); + reply_ng(CMD_HF_ICLASS_WRITEBL, PM3_ETEAROFF, (uint8_t*)&res, sizeof(uint8_t)); return; } else { @@ -1931,7 +1927,7 @@ out: switch_off(); if (payload->req.send_reply) - reply_ng(CMD_HF_ICLASS_WRITEBL, PM3_SUCCESS, (uint8_t *)&res, sizeof(uint8_t)); + reply_ng(CMD_HF_ICLASS_WRITEBL, PM3_SUCCESS, (uint8_t*)&res, sizeof(uint8_t)); } void iClass_Restore(iclass_restore_req_t *msg) { diff --git a/armsrc/iclass.h b/armsrc/iclass.h index 1895ebbf6..b41b79ce8 100644 --- a/armsrc/iclass.h +++ b/armsrc/iclass.h @@ -16,7 +16,7 @@ #include "pm3_cmd.h" void SniffIClass(uint8_t jam_search_len, uint8_t *jam_search_string); -void ReaderIClass(uint8_t arg0); +void ReaderIClass(uint8_t flags); void iClass_WriteBlock(uint8_t *msg); void iClass_Dump(uint8_t *msg); @@ -29,7 +29,6 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain void iclass_simulate(uint8_t sim_type, uint8_t num_csns, bool send_reply, uint8_t *datain, uint8_t *dataout, uint16_t *dataoutlen); void iClass_Authentication_fast(uint64_t arg0, uint64_t arg1, uint8_t *datain); -void iClass_Authentication(uint8_t *bytes); bool iclass_auth(iclass_auth_req_t *payload, uint8_t *out); void iClass_ReadBlock(uint8_t *msg); From 3c07e264c95daf0b4e744aa14fdf1e4a2395cfce Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:11:24 +0100 Subject: [PATCH 33/76] cppchecker fixes --- armsrc/em4x50.c | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/armsrc/em4x50.c b/armsrc/em4x50.c index a9eea7ad2..53abff5d3 100644 --- a/armsrc/em4x50.c +++ b/armsrc/em4x50.c @@ -646,7 +646,7 @@ static int get_word_from_bitstream(uint32_t *data) { // simple login to EM4x50, // used in operations that require authentication -static bool login(uint32_t password) { +static int login(uint32_t password) { if (request_receive_mode() == PM3_SUCCESS) { // send login command @@ -722,7 +722,7 @@ static bool brute(uint32_t start, uint32_t stop, uint32_t *pwd) { void em4x50_login(uint32_t *password) { em4x50_setup_read(); - uint8_t status = PM3_EFAILED; + int status = PM3_EFAILED; if (get_signalproperties() && find_em4x50_tag()) status = login(*password); @@ -1111,7 +1111,7 @@ void em4x50_writepwd(em4x50_data_t *etd) { static void em4x50_sim_send_bit(uint8_t bit) { //uint16_t timeout = EM4X50_T_TAG_FULL_PERIOD; - uint16_t timeout = EM4X50_T_SIMULATION_TIMEOUT_READ; + int16_t timeout = EM4X50_T_SIMULATION_TIMEOUT_READ; for (int t = 0; t < EM4X50_T_TAG_FULL_PERIOD; t++) { @@ -1236,7 +1236,7 @@ static int em4x50_sim_read_bit(void) { if (timeout <= 0) { return PM3_ETIMEOUT; } - timeout = EM4X50_T_SIMULATION_TIMEOUT_READ; + // timeout = EM4X50_T_SIMULATION_TIMEOUT_READ; // now we have a reference "position", from here it will take // slightly less than 32 cycles until the end of the bit period @@ -1420,8 +1420,6 @@ static void em4x50_sim_send_nak(void) { // standard read mode process (simulation mode) static int em4x50_sim_handle_standard_read_command(uint32_t *tag) { - int command = 0; - // extract control data int fwr = reflect32(tag[EM4X50_CONTROL]) & 0xFF; // first word read int lwr = (reflect32(tag[EM4X50_CONTROL]) >> 8) & 0xFF; // last word read @@ -1435,7 +1433,7 @@ static int em4x50_sim_handle_standard_read_command(uint32_t *tag) { WDT_HIT(); - command = em4x50_sim_send_listen_window(tag); + int command = em4x50_sim_send_listen_window(tag); if (command != PM3_SUCCESS) { return command; } @@ -1461,8 +1459,6 @@ static int em4x50_sim_handle_standard_read_command(uint32_t *tag) { // selective read mode process (simulation mode) static int em4x50_sim_handle_selective_read_command(uint32_t *tag) { - int command = 0; - // read password uint32_t address = 0; bool addr = em4x50_sim_read_word(&address); @@ -1491,7 +1487,7 @@ static int em4x50_sim_handle_selective_read_command(uint32_t *tag) { WDT_HIT(); - command = em4x50_sim_send_listen_window(tag); + int command = em4x50_sim_send_listen_window(tag); if (command != PM3_SUCCESS) { return command; } From a9b265ff1b9e3c69d14659b27117ffeaf6b2d3f2 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:16:02 +0100 Subject: [PATCH 34/76] cppcheck fixes call from hf_aveful with NULL --- armsrc/mifareutil.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index 07cf7b098..8fc747a97 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -68,9 +68,12 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) { // send X byte basic commands int mifare_sendcmd(uint8_t cmd, uint8_t *data, uint8_t data_size, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) { + uint8_t dcmd[data_size + 3]; dcmd[0] = cmd; - memcpy(dcmd + 1, data, data_size); + if (data_size > 0) + memcpy(dcmd + 1, data, data_size); + AddCrc14A(dcmd, data_size + 1); ReaderTransmit(dcmd, sizeof(dcmd), timing); int len = ReaderReceive(answer, answer_parity); From 31df889f97ff93de7cae20079dc545d0aca3fd36 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:42:32 +0100 Subject: [PATCH 35/76] cppchecker fix - format string --- tools/fpga_compress/fpga_compress.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tools/fpga_compress/fpga_compress.c b/tools/fpga_compress/fpga_compress.c index 005e66fce..859a2b858 100644 --- a/tools/fpga_compress/fpga_compress.c +++ b/tools/fpga_compress/fpga_compress.c @@ -115,7 +115,7 @@ static int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) { } LZ4_freeStreamHC(lz4_streamhc); - fprintf(stdout, "compressed %u input bytes to %u output bytes\n", total_size, current_out); + fprintf(stdout, "compressed %u input bytes to %d output bytes\n", total_size, current_out); if (current_out == 0) { fprintf(stderr, "Error in lz4"); @@ -399,9 +399,6 @@ int main(int argc, char **argv) { int ret = generate_fpga_version_info(infiles, infile_names, num_input_files, outfile); free(infile_names); free(infiles); - if (ret) { - return (EXIT_FAILURE); - } return (ret); } else { int ret = zlib_compress(infiles, num_input_files, outfile); From 84bc13884135ddc6d142cc7858cbe40d191f2ea4 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:46:26 +0100 Subject: [PATCH 36/76] cppchecker fix - might be called with UID == NULL --- common/iso15693tools.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/common/iso15693tools.c b/common/iso15693tools.c index 725baedb6..aa5119533 100644 --- a/common/iso15693tools.c +++ b/common/iso15693tools.c @@ -15,14 +15,15 @@ // uid[] the UID in transmission order // return: ptr to string char *iso15693_sprintUID(char *dest, uint8_t *uid) { - static char tempbuf[3 * 8 + 1] = {0}; if (dest == NULL) dest = tempbuf; - sprintf(dest, "%02X %02X %02X %02X %02X %02X %02X %02X", - uid[7], uid[6], uid[5], uid[4], - uid[3], uid[2], uid[1], uid[0] - ); + if (uid) { + sprintf(dest, "%02X %02X %02X %02X %02X %02X %02X %02X", + uid[7], uid[6], uid[5], uid[4], + uid[3], uid[2], uid[1], uid[0] + ); + } return dest; } From 3c8cefd8982a5c01407fa8e92129e867d2852e07 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:51:33 +0100 Subject: [PATCH 37/76] forgot to remove --- armsrc/appmain.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index dca2def3b..33ea032de 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1666,10 +1666,6 @@ static void PacketReceived(PacketCommandNG *packet) { iClass_ReadBlock(packet->data.asBytes); break; } - case CMD_HF_ICLASS_AUTH: { //check - iClass_Authentication(packet->data.asBytes); - break; - } case CMD_HF_ICLASS_CHKKEYS: { iClass_Authentication_fast(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes); break; From c0f4abb8d474b6e5778996f17380d9c05de1a9b3 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:52:10 +0100 Subject: [PATCH 38/76] cppchecker fix --- armsrc/iso15693.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index ef4695e20..5050fc117 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -1845,9 +1845,8 @@ void BruteforceIso15693Afi(uint32_t speed) { int datalen = 5; uint32_t eof_time = 0; - uint32_t start_time = GetCountSspClk(); int recvlen = SendDataTag(data, datalen, true, speed, recv, sizeof(recv), 0, ISO15693_READER_TIMEOUT, &eof_time); - start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; + uint32_t start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER; WDT_HIT(); From 6579ca908e731d6a49df0ab2bc547bd51cd407df Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 12:52:43 +0100 Subject: [PATCH 39/76] remove unused usb command --- include/pm3_cmd.h | 1 - 1 file changed, 1 deletion(-) diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index e3dc29aee..6b7f5df07 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -593,7 +593,6 @@ typedef struct { #define CMD_HF_ICLASS_READBL 0x0396 #define CMD_HF_ICLASS_WRITEBL 0x0397 #define CMD_HF_ICLASS_EML_MEMSET 0x0398 -#define CMD_HF_ICLASS_AUTH 0x0399 #define CMD_HF_ICLASS_CHKKEYS 0x039A #define CMD_HF_ICLASS_RESTORE 0x039B From fd7a25beedbb4870a90f87f45362491ecfd957e8 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 13:34:03 +0100 Subject: [PATCH 40/76] cppchecker fix - hf mfu restore and key param --- client/src/cmdhfmfu.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 4d5106437..ac9d44802 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -992,7 +992,6 @@ uint32_t GetHF14AMfU_Type(void) { else if (memcmp(version, "\x00\x04\x04\x05\x02\x01\x15", 7) == 0) { tagtype = NTAG_I2C_2K; break; } else if (memcmp(version, "\x00\x04\x04\x05\x02\x02\x13", 7) == 0) { tagtype = NTAG_I2C_1K_PLUS; break; } else if (memcmp(version, "\x00\x04\x04\x05\x02\x02\x15", 7) == 0) { tagtype = NTAG_I2C_2K_PLUS; break; } - else if (memcmp(version, "\x00\x34\x21\x01\x01\x00\x0E", 7) == 0) { tagtype = UL; break; } else if (version[2] == 0x04) { tagtype = NTAG; break; } else if (version[2] == 0x03) { tagtype = UL_EV1; } break; @@ -2064,7 +2063,16 @@ static int CmdHF14AMfURestore(const char *Cmd) { bool verbose = arg_get_lit(ctx, 7); CLIParserFree(ctx); + bool has_key = false; + if (ak_len > 0) { + if (ak_len != 4 || ak_len != 16) { + PrintAndLogEx(ERR, "Wrong key length. expected 4 or 16, got %d", ak_len); + return PM3_EINVARG; + } else { + has_key = true; + } + } uint8_t *dump = NULL; size_t bytes_read = 0; From 12a28fcd16e5934b8d7bed94ecebf3bbc2ad0121 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 13:38:58 +0100 Subject: [PATCH 41/76] cppchecker fix hf 14b --- client/src/cmdhf14b.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c index 5676aa41f..ff297a4f9 100644 --- a/client/src/cmdhf14b.c +++ b/client/src/cmdhf14b.c @@ -26,7 +26,7 @@ #include "mifare/ndef.h" // NDEFRecordsDecodeAndPrint #include "aidsearch.h" - +#define MAX_14B_TIMEOUT 40542464 // = (2^32-1) * (8*16) / 13560000Hz * 1000ms/s #define TIMEOUT 2000 #define APDU_TIMEOUT 2000 @@ -202,7 +202,6 @@ static bool wait_cmd_14b(bool verbose, bool is_select) { (crc) ? _GREEN_("ok") : _RED_("fail") ); } else if (len == 0) { - if (verbose) PrintAndLogEx(INFO, "no response from tag"); } else { PrintAndLogEx(SUCCESS, "%s", sprint_hex(data, len)); @@ -300,7 +299,7 @@ static int CmdHF14BCmdRaw(const char *Cmd) { arg_lit0(NULL, "sr", "activate field, use SRx ST select"), arg_lit0(NULL, "cts", "activate field, use ASK C-ticket select"), arg_lit0("c", "crc", "calculate and append CRC"), - arg_lit0("r", "noresponse", "do not read response from card"), + arg_lit0(NULL, "noresponse", "do not read response from card"), arg_int0("t", "timeout", "", "timeout in ms"), arg_lit0("v", "verbose", "verbose"), arg_strx0("d", "data", "", "data, bytes to send"), @@ -353,7 +352,7 @@ static int CmdHF14BCmdRaw(const char *Cmd) { user_timeout = MAX_14B_TIMEOUT; PrintAndLogEx(INFO, "set timeout to 40542 seconds (11.26 hours). The max we can wait for response"); } - time_wait = 13560000 / 1000 / (8 * 16) * user_timeout; // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us) + time_wait = (uint32_t)((13560000 / 1000 / (8 * 16)) * user_timeout); // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us) if (verbose) PrintAndLogEx(INFO, "using timeout %u", user_timeout); } @@ -408,8 +407,7 @@ static bool get_14b_UID(iso14b_card_select_t *card) { if (card == NULL) return false; - int status = 0; - + int status; PacketResponseNG resp; clearCommandBuffer(); SendCommandMIX(CMD_HF_ISO14443B_COMMAND, ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT, 0, 0, NULL, 0); @@ -1544,13 +1542,13 @@ static int handle_14b_apdu(bool chainingin, uint8_t *datain, int datainlen, bool uint32_t time_wait = 0; if (user_timeout > 0) { -#define MAX_14B_TIMEOUT 40542464 // = (2^32-1) * (8*16) / 13560000Hz * 1000ms/s + flags |= ISO14B_SET_TIMEOUT; if (user_timeout > MAX_14B_TIMEOUT) { user_timeout = MAX_14B_TIMEOUT; PrintAndLogEx(INFO, "set timeout to 40542 seconds (11.26 hours). The max we can wait for response"); } - time_wait = 13560000 / 1000 / (8 * 16) * user_timeout; // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us) + time_wait = (uint32_t)((13560000 / 1000 / (8 * 16)) * user_timeout); // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us) } // "Command APDU" length should be 5+255+1, but javacard's APDU buffer might be smaller - 133 bytes From 785d790ea0d3e0cd2b4a10f09735e8cd41d3d715 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 13:48:28 +0100 Subject: [PATCH 42/76] cppchecker fix --- client/src/cmdlfem4x05.c | 51 +++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/client/src/cmdlfem4x05.c b/client/src/cmdlfem4x05.c index 87303124b..0a65c1cb2 100644 --- a/client/src/cmdlfem4x05.c +++ b/client/src/cmdlfem4x05.c @@ -125,10 +125,9 @@ static int doPreambleSearch(size_t *startIdx) { // skip first two 0 bits as they might have been missed in the demod uint8_t preamble[EM_PREAMBLE_LEN] = {0, 0, 0, 0, 1, 0, 1, 0}; - uint8_t errpreamble[EM_PREAMBLE_LEN] = {0, 0, 0, 0, 0, 0, 0, 1}; - if (!preambleSearchEx(DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, startIdx, true)) { + uint8_t errpreamble[EM_PREAMBLE_LEN] = {0, 0, 0, 0, 0, 0, 0, 1}; if (!preambleSearchEx(DemodBuffer, errpreamble, EM_PREAMBLE_LEN, &size, startIdx, true)) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 preamble not found :: %zu", *startIdx); return PM3_ESOFT; @@ -258,10 +257,10 @@ static int em4x05_setdemod_buffer(uint32_t *word, size_t idx) { // should cover 90% of known used configs // the rest will need to be manually demoded for now... static int em4x05_demod_resp(uint32_t *word, bool onlyPreamble) { - size_t idx = 0; *word = 0; + int res; + size_t idx = 0; bool found_err = false; - int res = PM3_SUCCESS; do { if (detectASK_MAN()) { res = doPreambleSearch(&idx); @@ -1694,6 +1693,10 @@ int CmdEM4x05Unlock(const char *Cmd) { // write res = unlock_write_protect(use_pwd, pwd, write_value, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "failed unlock write"); + return PM3_ESOFT; + } // read after trigger res = em4x05_read_word_ext(14, pwd, use_pwd, &word14); @@ -1853,7 +1856,7 @@ int CmdEM4x05Unlock(const char *Cmd) { PrintAndLogEx(INFO, "Old protection word => " _YELLOW_("%08X"), search_value); char bitstring[9] = {0}; for (int i = 0; i < 8; i++) { - bitstring[i] = bitflips & (0xF << ((7 - i) * 4)) ? 'x' : '.'; + bitstring[i] = (bitflips & (0xF << ((7 - i) * 4))) ? 'x' : '.'; } // compute number of bits flipped @@ -1955,23 +1958,8 @@ uint32_t static em4x05_Sniff_GetBlock(char *bits, bool fwd) { int CmdEM4x05Sniff(const char *Cmd) { - bool sampleData = true; - bool haveData = false; - size_t idx = 0; - char cmdText [100]; - char dataText [100]; - char blkAddr[4]; - char bits[80]; - int bitidx; - int ZeroWidth; // 32-42 "1" is 32 - int CycleWidth; - size_t pulseSamples; - size_t pktOffset; - int i; - bool eop = false; - uint32_t tmpValue; - bool pwd = false; - bool fwd = false; + bool pwd = false, fwd = false; + bool haveData, sampleData = true; CLIParserContext *ctx; CLIParserInit(&ctx, "lf em 4x05_sniff", @@ -1988,12 +1976,21 @@ int CmdEM4x05Sniff(const char *Cmd) { arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); - - sampleData = !arg_get_lit(ctx, 1); + sampleData = (arg_get_lit(ctx, 1) == false); fwd = arg_get_lit(ctx, 2); - CLIParserFree(ctx); + char cmdText[100]; + char dataText[100]; + char blkAddr[4]; + char bits[80]; + int i, bitidx; + int ZeroWidth; // 32-42 "1" is 32 + int CycleWidth; + size_t idx = 0, pulseSamples, pktOffset; + uint32_t tmpValue; + bool eop = false; + // setup and sample data from Proxmark // if not directed to existing sample/graphbuffer if (sampleData) { @@ -2076,7 +2073,7 @@ int CmdEM4x05Sniff(const char *Cmd) { haveData = true; sprintf(cmdText, "Write"); tmpValue = (bits[4] - '0') + ((bits[5] - '0') << 1) + ((bits[6] - '0') << 2) + ((bits[7] - '0') << 3); - sprintf(blkAddr, "%d", tmpValue); + sprintf(blkAddr, "%u", tmpValue); if (tmpValue == 2) { pwd = true; } @@ -2090,7 +2087,7 @@ int CmdEM4x05Sniff(const char *Cmd) { pwd = false; sprintf(cmdText, "Read"); tmpValue = (bits[4] - '0') + ((bits[5] - '0') << 1) + ((bits[6] - '0') << 2) + ((bits[7] - '0') << 3); - sprintf(blkAddr, "%d", tmpValue); + sprintf(blkAddr, "%u", tmpValue); sprintf(dataText, " "); } From 46767a07e7bc365d2127d392d8eff1a4876a7fab Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 13:50:27 +0100 Subject: [PATCH 43/76] cppchecker --- client/src/graph.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/graph.c b/client/src/graph.c index 21b77e427..eac2048be 100644 --- a/client/src/graph.c +++ b/client/src/graph.c @@ -149,7 +149,7 @@ void convertGraphFromBitstreamEx(int hi, int low) { } // Get or auto-detect ask clock rate -int GetAskClock(const char *str, bool printAns) { +int GetAskClock(const char *str, bool verbose) { if (getSignalProperties()->isnoise) return -1; From 3fead5b93c641e61ca5336e39566c7c325cad789 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 13:53:37 +0100 Subject: [PATCH 44/76] cppchecker... --- client/src/graph.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/graph.c b/client/src/graph.c index eac2048be..5c3221716 100644 --- a/client/src/graph.c +++ b/client/src/graph.c @@ -183,7 +183,7 @@ int GetAskClock(const char *str, bool verbose) { setClockGrid(clock1, idx); } // Only print this message if we're not looping something - if (printAns || g_debugMode) + if (verbose || g_debugMode) PrintAndLogEx(SUCCESS, "Auto-detected clock rate: %d, Best Starting Position: %d", clock1, idx); free(bits); From 3ad822844f4a0f83de26cfb67808fc13d795cabd Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:08:47 +0100 Subject: [PATCH 45/76] cppchecker ... --- client/src/cmdhf14b.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c index ff297a4f9..4de6ddd12 100644 --- a/client/src/cmdhf14b.c +++ b/client/src/cmdhf14b.c @@ -26,7 +26,7 @@ #include "mifare/ndef.h" // NDEFRecordsDecodeAndPrint #include "aidsearch.h" -#define MAX_14B_TIMEOUT 40542464 // = (2^32-1) * (8*16) / 13560000Hz * 1000ms/s +#define MAX_14B_TIMEOUT (uint32_t)40542464 // = (2^32-1) * (8*16) / 13560000Hz * 1000ms/s #define TIMEOUT 2000 #define APDU_TIMEOUT 2000 @@ -346,7 +346,6 @@ static int CmdHF14BCmdRaw(const char *Cmd) { uint32_t time_wait = 0; if (user_timeout > 0) { -#define MAX_14B_TIMEOUT 40542464 // = (2^32-1) * (8*16) / 13560000Hz * 1000ms/s flags |= ISO14B_SET_TIMEOUT; if (user_timeout > MAX_14B_TIMEOUT) { user_timeout = MAX_14B_TIMEOUT; From beb6a8bf110e5323a40684b195e459f323c525e2 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:09:25 +0100 Subject: [PATCH 46/76] cppchecker --- client/src/cmddata.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmddata.c b/client/src/cmddata.c index d2d28d0f0..82f05bb59 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -1576,7 +1576,7 @@ int getSamplesEx(uint32_t start, uint32_t end, bool verbose) { uint32_t n = end - start; - if (n <= 0 || n > pm3_capabilities.bigbuf_size - 1) + if (n == 0 || n > pm3_capabilities.bigbuf_size - 1) n = pm3_capabilities.bigbuf_size - 1; if (verbose) From 10e28291236f3de530ad12c06874bbef1ecd3492 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:11:33 +0100 Subject: [PATCH 47/76] cppchecker fix UID might be NULL --- client/src/cmdhf15.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/client/src/cmdhf15.c b/client/src/cmdhf15.c index 3eebbce74..04ffbae45 100644 --- a/client/src/cmdhf15.c +++ b/client/src/cmdhf15.c @@ -459,6 +459,10 @@ static int nxp_15693_print_signature(uint8_t *uid, uint8_t *signature) { // uid[8] tag uid // returns description of the best match static const char *getTagInfo_15(uint8_t *uid) { + if (uid == NULL) { + return ""; + } + uint64_t myuid, mask; int i = 0, best = -1; memcpy(&myuid, uid, sizeof(uint64_t)); From 11a95d73510ddee705e85a0c64f017f186bfd35d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:16:42 +0100 Subject: [PATCH 48/76] cppchecker fix --- client/src/cmdhfemrtd.c | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/client/src/cmdhfemrtd.c b/client/src/cmdhfemrtd.c index afe5b6b6f..255939ab0 100644 --- a/client/src/cmdhfemrtd.c +++ b/client/src/cmdhfemrtd.c @@ -191,12 +191,10 @@ static int emrtd_exchange_commands_noout(const char *cmd, bool activate_field, b static char emrtd_calculate_check_digit(char *data) { int mrz_weight[] = {7, 3, 1}; - int cd = 0; - int value = 0; - char d; + int value, cd = 0; for (int i = 0; i < strlen(data); i++) { - d = data[i]; + char d = data[i]; if ('A' <= d && d <= 'Z') { value = d - 55; } else if ('a' <= d && d <= 'z') { @@ -652,19 +650,16 @@ static bool emrtd_lds_get_data_by_tag(uint8_t *datain, size_t datainlen, uint8_t offset += emrtd_get_asn1_field_length(datain, datainlen, offset); } - int e_idlen = 0; - int e_datalen = 0; - int e_fieldlen = 0; while (offset < datainlen) { PrintAndLogEx(DEBUG, "emrtd_lds_get_data_by_tag, offset: %i, data: %X", offset, *(datain + offset)); // Determine element ID length to set as offset on asn1datalength - e_idlen = emrtd_lds_determine_tag_length(*(datain + offset)); + int e_idlen = emrtd_lds_determine_tag_length(*(datain + offset)); // Get the length of the element - e_datalen = emrtd_get_asn1_data_length(datain + offset, datainlen - offset, e_idlen); + int e_datalen = emrtd_get_asn1_data_length(datain + offset, datainlen - offset, e_idlen); // Get the length of the element's length - e_fieldlen = emrtd_get_asn1_field_length(datain + offset, datainlen - offset, e_idlen); + int e_fieldlen = emrtd_get_asn1_field_length(datain + offset, datainlen - offset, e_idlen); PrintAndLogEx(DEBUG, "emrtd_lds_get_data_by_tag, e_idlen: %02X, e_datalen: %02X, e_fieldlen: %02X", e_idlen, e_datalen, e_fieldlen); @@ -828,7 +823,8 @@ static bool emrtd_dump_file(uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, cons char *filepath = calloc(strlen(path) + 100, sizeof(char)); if (filepath == NULL) - return PM3_EMALLOC; + return false; + strcpy(filepath, path); strncat(filepath, PATHSEP, 2); strcat(filepath, name); @@ -1649,8 +1645,6 @@ static int emrtd_parse_ef_sod_hashes(uint8_t *data, size_t datalen, uint8_t *has size_t emrtdsiglen = 0; size_t hashlistlen = 0; - size_t e_datalen = 0; - size_t e_fieldlen = 0; size_t offset = 0; if (emrtd_ef_sod_extract_signatures(data, datalen, emrtdsig, &emrtdsiglen) != PM3_SUCCESS) { @@ -1670,10 +1664,10 @@ static int emrtd_parse_ef_sod_hashes(uint8_t *data, size_t datalen, uint8_t *has while (offset < hashlistlen) { // Get the length of the element - e_datalen = emrtd_get_asn1_data_length(hashlist + offset, hashlistlen - offset, 1); + int e_datalen = emrtd_get_asn1_data_length(hashlist + offset, hashlistlen - offset, 1); // Get the length of the element's length - e_fieldlen = emrtd_get_asn1_field_length(hashlist + offset, hashlistlen - offset, 1); + int e_fieldlen = emrtd_get_asn1_field_length(hashlist + offset, hashlistlen - offset, 1); switch (hashlist[offset]) { case 0x30: @@ -1703,11 +1697,10 @@ static int emrtd_print_ef_sod_info(uint8_t *dg_hashes_calc, uint8_t *dg_hashes_s PrintAndLogEx(SUCCESS, "Hash algorithm: " _YELLOW_("%s"), hashalg_table[hash_algo].name); uint8_t all_zeroes[64] = { 0x00 }; - bool calc_all_zero, sod_all_zero, hash_matches; for (int i = 1; i <= 16; i++) { - calc_all_zero = (memcmp(dg_hashes_calc + (i * 64), all_zeroes, hashalg_table[hash_algo].hashlen) == 0); - sod_all_zero = (memcmp(dg_hashes_sod + (i * 64), all_zeroes, hashalg_table[hash_algo].hashlen) == 0); - hash_matches = (memcmp(dg_hashes_sod + (i * 64), dg_hashes_calc + (i * 64), hashalg_table[hash_algo].hashlen) == 0); + bool calc_all_zero = (memcmp(dg_hashes_calc + (i * 64), all_zeroes, hashalg_table[hash_algo].hashlen) == 0); + bool sod_all_zero = (memcmp(dg_hashes_sod + (i * 64), all_zeroes, hashalg_table[hash_algo].hashlen) == 0); + bool hash_matches = (memcmp(dg_hashes_sod + (i * 64), dg_hashes_calc + (i * 64), hashalg_table[hash_algo].hashlen) == 0); // Ignore files we don't haven't read and lack hashes to if (calc_all_zero == true && sod_all_zero == true) { continue; From a5f42128099ce68bf2d765f31edcf71baeb1476e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:18:44 +0100 Subject: [PATCH 49/76] cppchecker fix --- client/src/cmdhficlass.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 7b90a5bbf..2a0e678c6 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -68,7 +68,7 @@ bool check_known_default(uint8_t *csn, uint8_t *epurse, uint8_t *rmac, uint8_t * iclass_prekey_t *prekey = calloc(ICLASS_KEYS_MAX, sizeof(iclass_prekey_t)); if (prekey == false) { - return PM3_EMALLOC; + return false; } uint8_t ccnr[12]; @@ -1075,10 +1075,8 @@ static int CmdHFiClassDecrypt(const char *Cmd) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "Block 9 decoder"); - uint8_t pinsize = 0; if (use_sc) { - pinsize = GetPinSize(decrypted + (8 * 6)); - + uint8_t pinsize = GetPinSize(decrypted + (8 * 6)); if (pinsize > 0) { uint64_t pin = bytes_to_num(decrypted + (8 * 9), 5); From 12c0eb97fb111def689e761d53beef33f94c277b Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:20:33 +0100 Subject: [PATCH 50/76] cppchecker fix --- client/src/cmdhfmfu.c | 2 +- client/src/cmdhfwaveshare.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index ac9d44802..9af773420 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -2066,7 +2066,7 @@ static int CmdHF14AMfURestore(const char *Cmd) { bool has_key = false; if (ak_len > 0) { - if (ak_len != 4 || ak_len != 16) { + if (ak_len != 4 && ak_len != 16) { PrintAndLogEx(ERR, "Wrong key length. expected 4 or 16, got %d", ak_len); return PM3_EINVARG; } else { diff --git a/client/src/cmdhfwaveshare.c b/client/src/cmdhfwaveshare.c index 932012f98..813795bc5 100644 --- a/client/src/cmdhfwaveshare.c +++ b/client/src/cmdhfwaveshare.c @@ -1004,7 +1004,7 @@ static int CmdHF14AWSLoadBmp(const char *Cmd) { ); char modeldesc[40]; - snprintf(modeldesc, sizeof(modeldesc), "model number [0 - %u] of your tag", MEND - 1); + snprintf(modeldesc, sizeof(modeldesc), "model number [0 - %d] of your tag", MEND - 1); void *argtable[] = { arg_param_begin, From 66332149571dc7bb3f10d5eeaa65d1009ac42d0d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:22:44 +0100 Subject: [PATCH 51/76] cppchecker fix --- client/src/cmdhfwaveshare.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/client/src/cmdhfwaveshare.c b/client/src/cmdhfwaveshare.c index 813795bc5..d2a0e7b6e 100644 --- a/client/src/cmdhfwaveshare.c +++ b/client/src/cmdhfwaveshare.c @@ -183,8 +183,6 @@ static void dither_chan_inplace(int16_t *chan, uint16_t width, uint16_t height) } if (Y < height - 1) { chan[X - 1 + (Y + 1) * width] = chan[X - 1 + (Y + 1) * width] + m[1] / 16 * err; - } - if (Y < height - 1) { chan[X + (Y + 1) * width] = chan[X + (Y + 1) * width] + m[2] / 16 * err; } if ((X < width - 1) && (Y < height - 1)) { @@ -250,8 +248,6 @@ static void dither_rgb_inplace(int16_t *chanR, int16_t *chanG, int16_t *chanB, u chanR[XX - 1 + (Y + 1) * width] = (chanR[XX - 1 + (Y + 1) * width] + m[3] / 16 * errR); chanG[XX - 1 + (Y + 1) * width] = (chanG[XX - 1 + (Y + 1) * width] + m[3] / 16 * errG); chanB[XX - 1 + (Y + 1) * width] = (chanB[XX - 1 + (Y + 1) * width] + m[3] / 16 * errB); - } - if (Y < height - 1) { chanR[XX + (Y + 1) * width] = (chanR[XX + (Y + 1) * width] + m[2] / 16 * errR); chanG[XX + (Y + 1) * width] = (chanG[XX + (Y + 1) * width] + m[2] / 16 * errG); chanB[XX + (Y + 1) * width] = (chanB[XX + (Y + 1) * width] + m[2] / 16 * errB); @@ -271,8 +267,6 @@ static void dither_rgb_inplace(int16_t *chanR, int16_t *chanG, int16_t *chanB, u chanR[XX - 1 + (Y + 1) * width] = (chanR[XX - 1 + (Y + 1) * width] + m[1] / 16 * errR); chanG[XX - 1 + (Y + 1) * width] = (chanG[XX - 1 + (Y + 1) * width] + m[1] / 16 * errG); chanB[XX - 1 + (Y + 1) * width] = (chanB[XX - 1 + (Y + 1) * width] + m[1] / 16 * errB); - } - if (Y < height - 1) { chanR[XX + (Y + 1) * width] = (chanR[XX + (Y + 1) * width] + m[2] / 16 * errR); chanG[XX + (Y + 1) * width] = (chanG[XX + (Y + 1) * width] + m[2] / 16 * errG); chanB[XX + (Y + 1) * width] = (chanB[XX + (Y + 1) * width] + m[2] / 16 * errB); From 2c73337bde37e2271534b621d454c85e2fe6e364 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:32:57 +0100 Subject: [PATCH 52/76] cppchecker ,, silence a warning --- client/src/preferences.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/client/src/preferences.c b/client/src/preferences.c index b133dd428..92a91e54a 100644 --- a/client/src/preferences.c +++ b/client/src/preferences.c @@ -834,7 +834,7 @@ static int setCmdSavePaths(const char *Cmd) { CLIParserFree(ctx); if (deflen == 0 && dulen == 0 && tlen == 0) { - PrintAndLogEx(FAILED, "Must give atleast one path"); + PrintAndLogEx(FAILED, "Must give at least one path"); return PM3_EINVARG; } @@ -853,6 +853,11 @@ static int setCmdSavePaths(const char *Cmd) { path = trace_path; } + if (path == NULL) { + PrintAndLogEx(FAILED, "Must give at least one path"); + return PM3_EINVARG; + } + // remove trailing slash. size_t nplen = strlen(path); if ((path[nplen - 1] == '/') || (path[nplen - 1] == '\\')) { From 56b4a480cdb4efd6b63e242f3f234b0aee9fe4f4 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 14:33:30 +0100 Subject: [PATCH 53/76] cppchecker fix, realloc should already freed it --- client/src/ui.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/ui.c b/client/src/ui.c index 293a98c58..99c2cdde5 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -106,7 +106,7 @@ int searchHomeFilePath(char **foundpath, const char *subdir, const char *filenam pathlen += strlen(subdir); char *tmp = realloc(path, pathlen * sizeof(char)); if (tmp == NULL) { - free(path); + //free(path); return PM3_EMALLOC; } path = tmp; @@ -146,7 +146,7 @@ int searchHomeFilePath(char **foundpath, const char *subdir, const char *filenam pathlen += strlen(filename); char *tmp = realloc(path, pathlen * sizeof(char)); if (tmp == NULL) { - free(path); + //free(path); return PM3_EMALLOC; } path = tmp; From 405b93f1099a22d3aa56eda82755d3296009c89d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 15:29:52 +0100 Subject: [PATCH 54/76] coverity fix 309975 --- client/src/cmdlft55xx.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index d98347342..3903a9547 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -2966,8 +2966,11 @@ static int CmdT55xxChkPwds(const char *Cmd) { "lf t55xx chk --em aa11223344 -> try known pwdgen algo from some cloners based on EM4100 ID" ); - // 4 + (5 or 6) - void *argtable[9] = { + // Calculate size of argtable accordingly: + // 1 (help) + 3 (three user specified params) + ( 5 or 6 T55XX_DLMODE) + // 4 + (T55XX_DLMODE_xxx 5) + // 4 + (T55XX_DLMODE_ALL 6) == 10 + void *argtable[10] = { arg_param_begin, arg_lit0("m", "fm", "use dictionary from flash memory (RDV4)"), arg_str0("f", "file", "", "file name"), From 6737f6f3cde8455a8692c8460b7dca8c7bb130a0 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 20:31:39 +0100 Subject: [PATCH 55/76] sanitize fix - lf/hf tune heap overflow --- client/src/cmdlfgallagher.c | 1 - client/src/cmdtrace.c | 9 ++++----- client/src/ui.c | 31 +++++++++++++++++-------------- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/client/src/cmdlfgallagher.c b/client/src/cmdlfgallagher.c index 12b6b9b49..3e13aadf3 100644 --- a/client/src/cmdlfgallagher.c +++ b/client/src/cmdlfgallagher.c @@ -277,7 +277,6 @@ static int CmdGallagherSim(const char *Cmd) { return resp.status; return PM3_SUCCESS; - return PM3_SUCCESS; } static command_t CommandTable[] = { diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index a95503813..c47eff9d3 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -582,11 +582,10 @@ static int CmdTraceSave(const char *Cmd) { if (g_traceLen == 0) { download_trace(); - } - - if (g_traceLen == 0) { - PrintAndLogEx(WARNING, "trace is empty, nothing to save"); - return PM3_SUCCESS; + if (g_traceLen == 0) { + PrintAndLogEx(WARNING, "trace is empty, nothing to save"); + return PM3_SUCCESS; + } } saveFile(filename, ".trace", g_trace, g_traceLen); diff --git a/client/src/ui.c b/client/src/ui.c index 99c2cdde5..3c4069f5b 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -642,9 +642,12 @@ void print_progress(size_t count, uint64_t max, barMode_t style) { prev_cols = cols; #endif int width = cols - 35; + if (width < 1) + return; + #define PERCENTAGE(V, T) ((V * width) / T) // x/8 fractional part of the percentage -#define PERCENTAGEFRAC(V, T) ((int)(((((float)V * width) / T) - ((V * width) / T)) * 8)) +#define PERCENTAGEFRAC(V, T) ((uint8_t)(((((float)V * width) / T) - ((V * width) / T)) * 8)) const char *smoothtable[] = { "\xe2\x80\x80", @@ -658,14 +661,15 @@ void print_progress(size_t count, uint64_t max, barMode_t style) { "\xe2\x96\x88", }; - uint8_t mode = (session.emoji_mode == EMO_EMOJI); + int mode = (session.emoji_mode == EMO_EMOJI); const char *block[] = {"#", "\xe2\x96\x88"}; // use a 3-byte space in emoji mode to ease computations const char *space[] = {" ", "\xe2\x80\x80"}; - uint8_t unit = strlen(block[mode]); + + size_t unit = strlen(block[mode]); // +1 for \0 - char *bar = calloc(unit * width + 1, sizeof(uint8_t)); + char *bar = (char *)calloc(unit * width + 1, sizeof(uint8_t)); uint8_t value = PERCENTAGE(count, max); @@ -687,7 +691,7 @@ void print_progress(size_t count, uint64_t max, barMode_t style) { } // color buffer size_t collen = strlen(bar) + 40; - char *cbar = calloc(collen, sizeof(uint8_t)); + char *cbar = (char *)calloc(collen, sizeof(uint8_t)); // Add colors if (session.supports_colors) { @@ -695,23 +699,23 @@ void print_progress(size_t count, uint64_t max, barMode_t style) { int p20 = unit * (width * 20 / 100); snprintf(cbar, collen, _GREEN_("%.*s"), p60, bar); snprintf(cbar + strlen(cbar), collen - strlen(cbar), _CYAN_("%.*s"), p20, bar + p60); - snprintf(cbar + strlen(cbar), collen - strlen(cbar), _YELLOW_("%.*s"), unit * width - p60 - p20, bar + p60 + p20); + snprintf(cbar + strlen(cbar), collen - strlen(cbar), _YELLOW_("%.*s"), (int)(unit * width - p60 - p20), bar + p60 + p20); } else { snprintf(cbar, collen, "%s", bar); } - size_t len = strlen(cbar) + 32; - char *buffer = calloc(len, sizeof(uint8_t)); + size_t olen = strlen(cbar) + 40; + char *out = (char *)calloc(olen, sizeof(uint8_t)); switch (style) { case STYLE_BAR: { - sprintf(buffer, "%s", cbar); - printf("\b%c[2K\r[" _YELLOW_("=")"] %s", 27, buffer); + sprintf(out, "%s", cbar); + printf("\b%c[2K\r[" _YELLOW_("=")"] %s", 27, out); break; } case STYLE_MIXED: { - sprintf(buffer, "%s [ %zu mV / %2u V / %2u Vmax ] ", cbar, count, (uint32_t)(count / 1000), (uint32_t)(max / 1000)); - printf("\b%c[2K\r[" _YELLOW_("=")"] %s ", 27, buffer); + sprintf(out, "%s [ %zu mV / %2u V / %2u Vmax ]", cbar, count, (uint32_t)(count / 1000), (uint32_t)(max / 1000)); + printf("\b%c[2K\r[" _YELLOW_("=")"] %s", 27, out); break; } case STYLE_VALUE: { @@ -719,9 +723,8 @@ void print_progress(size_t count, uint64_t max, barMode_t style) { break; } } - fflush(stdout); - free(buffer); + free(out); free(bar); free(cbar); } From 90fb78ff1b5bbbd0559ff45fcb642a8b0be52790 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 21:38:30 +0100 Subject: [PATCH 56/76] cppchecker fix --- client/src/loclass/ikeys.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/src/loclass/ikeys.c b/client/src/loclass/ikeys.c index d2798a14e..c311e93b1 100644 --- a/client/src/loclass/ikeys.c +++ b/client/src/loclass/ikeys.c @@ -91,12 +91,12 @@ uint8_t pi[35] = { * @param n bitnumber * @return */ -#define getSixBitByte(c, n) ((uint8_t)(((c) >> (42 - 6 * (n))) & 0x3F)) -/* +//#define getSixBitByte(c, n) ((uint8_t)(((c) >> (42 - 6 * (n))) & 0x3F)) + static inline uint8_t getSixBitByte(uint64_t c, int n) { return (c >> (42 - 6 * n)) & 0x3F; } -*/ + /** * @brief Puts back a six-bit 'byte' into a uint64_t. * @param c buffer From 165ceb122f7a905fa8d7f063a405dd2cec47dd56 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 28 Jan 2021 21:41:57 +0100 Subject: [PATCH 57/76] update to correct filename for the sample file --- client/src/cmdhficlass.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 2a0e678c6..45268b4da 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -2074,7 +2074,7 @@ static int CmdHFiClass_loclass(const char *Cmd) { " <8 byte CSN><8 byte CC><4 byte NR><4 byte MAC>\n" " <8 byte CSN><8 byte CC><4 byte NR><4 byte MAC>\n" " ... totalling N*24 bytes", - "hf iclass loclass -f iclass-dump.bin\n" + "hf iclass loclass -f iclass_dump.bin\n" "hf iclass loclass --test"); void *argtable[] = { From b3c0e00174903f6a69b54782dd31bfc61c46b7dd Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 11:56:31 +0100 Subject: [PATCH 58/76] wiegand encode - now "-w" format param is optional, if excluded it tries to convert to all known formats and output --- client/src/cmdwiegand.c | 50 +++++++++--------------- client/src/wiegand_formats.c | 74 +++++++++++++++++++++++++++++++++--- client/src/wiegand_formats.h | 4 +- 3 files changed, 91 insertions(+), 37 deletions(-) diff --git a/client/src/cmdwiegand.c b/client/src/cmdwiegand.c index 8e154e300..e3b0418ac 100644 --- a/client/src/cmdwiegand.c +++ b/client/src/cmdwiegand.c @@ -25,24 +25,6 @@ static int CmdHelp(const char *Cmd); -static void print_wiegand_code(wiegand_message_t *packed) { - const char *s = "Encoded wiegand: "; - if (packed->Top != 0) { - PrintAndLogEx(SUCCESS, "%s" _GREEN_("%X%08X%08X"), - s, - (uint32_t)packed->Top, - (uint32_t)packed->Mid, - (uint32_t)packed->Bot - ); - } else { - PrintAndLogEx(SUCCESS, "%s" _YELLOW_("%X%08X"), - s, - (uint32_t)packed->Mid, - (uint32_t)packed->Bot - ); - } -} - int CmdWiegandList(const char *Cmd) { CLIParserContext *ctx; @@ -76,7 +58,7 @@ int CmdWiegandEncode(const char *Cmd) { arg_u64_1(NULL, "cn", "", "card number"), arg_u64_0(NULL, "issue", "", "issue level"), arg_u64_0(NULL, "oem", "", "OEM code"), - arg_str1("w", "wiegand", "", "see `wiegand list` for available formats"), + arg_str0("w", "wiegand", "", "see `wiegand list` for available formats"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -94,21 +76,27 @@ int CmdWiegandEncode(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 5), (uint8_t *)format, sizeof(format), &len); CLIParserFree(ctx); - int idx = HIDFindCardFormat(format); - if (idx == -1) { - PrintAndLogEx(WARNING, "Unknown format: %s", format); - return PM3_EINVARG; + int idx = -1; + if (len) { + idx = HIDFindCardFormat(format); + if (idx == -1) { + PrintAndLogEx(WARNING, "Unknown format: %s", format); + return PM3_EINVARG; + } } - wiegand_message_t packed; - memset(&packed, 0, sizeof(wiegand_message_t)); - - if (HIDPack(idx, &data, &packed) == false) { - PrintAndLogEx(WARNING, "The card data could not be encoded in the selected format."); - return PM3_ESOFT; + if (idx != -1) { + wiegand_message_t packed; + memset(&packed, 0, sizeof(wiegand_message_t)); + if (HIDPack(idx, &data, &packed) == false) { + PrintAndLogEx(WARNING, "The card data could not be encoded in the selected format."); + return PM3_ESOFT; + } + print_wiegand_code(&packed); + } else { + // try all formats and print only the ones that work. + HIDPackTryAll(&data); } - - print_wiegand_code(&packed); return PM3_SUCCESS; } diff --git a/client/src/wiegand_formats.c b/client/src/wiegand_formats.c index 78d0bf828..ba8169d37 100644 --- a/client/src/wiegand_formats.c +++ b/client/src/wiegand_formats.c @@ -8,8 +8,10 @@ // HID card format packing/unpacking routines //----------------------------------------------------------------------------- #include "wiegand_formats.h" +#include #include "commonutil.h" + static bool Pack_H10301(wiegand_card_t *card, wiegand_message_t *packed) { memset(packed, 0, sizeof(wiegand_message_t)); @@ -823,7 +825,7 @@ static const cardformat_t FormatTable[] = { {"Optus34", Pack_Optus, Unpack_Optus, "Indala Optus 34-bit", {1, 1, 0, 0, 0}}, // from cardinfo.barkweb.com.au {"Smartpass", Pack_Smartpass, Unpack_Smartpass, "Cardkey Smartpass 34-bit", {1, 1, 1, 0, 0}}, // from cardinfo.barkweb.com.au {"BQT", Pack_bqt, Unpack_bqt, "BQT 34-bit", {1, 1, 0, 0, 1}}, // from cardinfo.barkweb.com.au - {"C1k35s", Pack_C1k35s, Unpack_C1k35s, "HID Corporate 1000 35-bit standard layout", {1, 1, 0, 0, 1}}, // imported from old pack/unpack + {"C1k35s", Pack_C1k35s, Unpack_C1k35s, "HID Corporate 1000 35-bit std", {1, 1, 0, 0, 1}}, // imported from old pack/unpack {"C15001", Pack_C15001, Unpack_C15001, "HID KeyScan 36-bit", {1, 1, 0, 1, 1}}, // from Proxmark forums {"S12906", Pack_S12906, Unpack_S12906, "HID Simplex 36-bit", {1, 1, 1, 0, 1}}, // from cardinfo.barkweb.com.au {"Sie36", Pack_Sie36, Unpack_Sie36, "HID 36-bit Siemens", {1, 1, 0, 0, 1}}, // from cardinfo.barkweb.com.au @@ -834,7 +836,7 @@ static const cardformat_t FormatTable[] = { {"MDI37", Pack_MDI37, Unpack_MDI37, "PointGuard MDI 37-bit", {1, 1, 0, 0, 1}}, // from cardinfo.barkweb.com.au {"P10001", Pack_P10001, Unpack_P10001, "HID P10001 Honeywell 40-bit", {1, 1, 0, 1, 0}}, // from cardinfo.barkweb.com.au {"Casi40", Pack_CasiRusco40, Unpack_CasiRusco40, "Casi-Rusco 40-bit", {1, 0, 0, 0, 0}}, // from cardinfo.barkweb.com.au - {"C1k48s", Pack_C1k48s, Unpack_C1k48s, "HID Corporate 1000 48-bit standard layout", {1, 1, 0, 0, 1}}, // imported from old pack/unpack + {"C1k48s", Pack_C1k48s, Unpack_C1k48s, "HID Corporate 1000 48-bit std", {1, 1, 0, 0, 1}}, // imported from old pack/unpack {NULL, NULL, NULL, NULL, {0, 0, 0, 0, 0}} // Must null terminate array }; @@ -842,18 +844,59 @@ void HIDListFormats(void) { if (FormatTable[0].Name == NULL) return; - PrintAndLogEx(NORMAL, "%-10s %s", "Name", "Description"); - PrintAndLogEx(NORMAL, "------------------------------------------------------------"); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "%-10s %s", "Name", "Description"); + PrintAndLogEx(INFO, "------------------------------------------------------------"); int i = 0; while (FormatTable[i].Name) { - PrintAndLogEx(NORMAL, _YELLOW_("%-10s")" %-30s", FormatTable[i].Name, FormatTable[i].Descrp); + PrintAndLogEx(INFO, _YELLOW_("%-10s")" %-30s", FormatTable[i].Name, FormatTable[i].Descrp); ++i; } PrintAndLogEx(NORMAL, ""); return; } +void print_desc_wiegand(cardformat_t *fmt, wiegand_message_t *packed) { + + char *s = calloc(128, sizeof(uint8_t)); + sprintf(s, _YELLOW_("%-10s")" %-30s", fmt->Name, fmt->Descrp); + + if (packed->Top != 0) { + PrintAndLogEx(SUCCESS, "%s --> " _GREEN_("%X%08X%08X"), + s, + (uint32_t)packed->Top, + (uint32_t)packed->Mid, + (uint32_t)packed->Bot + ); + } else { + PrintAndLogEx(SUCCESS, "%s --> " _YELLOW_("%X%08X"), + s, + (uint32_t)packed->Mid, + (uint32_t)packed->Bot + ); + } + free(s); +} + +void print_wiegand_code(wiegand_message_t *packed) { + const char *s = "Encoded wiegand: "; + if (packed->Top != 0) { + PrintAndLogEx(SUCCESS, "%s" _GREEN_("%X%08X%08X"), + s, + (uint32_t)packed->Top, + (uint32_t)packed->Mid, + (uint32_t)packed->Bot + ); + } else { + PrintAndLogEx(SUCCESS, "%s" _YELLOW_("%X%08X"), + s, + (uint32_t)packed->Mid, + (uint32_t)packed->Bot + ); + } +} + cardformat_t HIDGetCardFormat(int idx) { return FormatTable[idx]; } @@ -886,6 +929,26 @@ bool HIDPack(int format_idx, wiegand_card_t *card, wiegand_message_t *packed) { return FormatTable[format_idx].Pack(card, packed); } +void HIDPackTryAll(wiegand_card_t *card) { + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "%-10s %-30s --> Encoded wiegand", "Name", "Description"); + PrintAndLogEx(INFO, "----------------------------------------------------------------------"); + + wiegand_message_t packed; + int i = 0; + while (FormatTable[i].Name) { + memset(&packed, 0, sizeof(wiegand_message_t)); + bool res = FormatTable[i].Pack(card, &packed); + if (res) { + cardformat_t fmt = HIDGetCardFormat(i); + print_desc_wiegand(&fmt, &packed); + } + i++; + } + PrintAndLogEx(NORMAL, ""); +} + static void HIDDisplayUnpackedCard(wiegand_card_t *card, const cardformat_t format) { /* @@ -951,3 +1014,4 @@ bool HIDTryUnpack(wiegand_message_t *packed, bool ignore_parity) { return result; } + diff --git a/client/src/wiegand_formats.h b/client/src/wiegand_formats.h index 4ac36fdcf..531de1e12 100644 --- a/client/src/wiegand_formats.h +++ b/client/src/wiegand_formats.h @@ -44,5 +44,7 @@ int HIDFindCardFormat(const char *format); cardformat_t HIDGetCardFormat(int idx); bool HIDPack(int format_idx, wiegand_card_t *card, wiegand_message_t *packed); bool HIDTryUnpack(wiegand_message_t *packed, bool ignore_parity); - +void HIDPackTryAll(wiegand_card_t *card); +void print_wiegand_code(wiegand_message_t *packed); +void print_desc_wiegand(cardformat_t *fmt, wiegand_message_t *packed); #endif From dc01b63d4999f37c22518d98264539d26c6c6b0f Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 11:59:32 +0100 Subject: [PATCH 59/76] analyse demodbuff - bad reference to string pointer after free --- client/src/cmdanalyse.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/client/src/cmdanalyse.c b/client/src/cmdanalyse.c index 4cdd35e68..87c989618 100644 --- a/client/src/cmdanalyse.c +++ b/client/src/cmdanalyse.c @@ -931,19 +931,14 @@ static int CmdAnalyseDemodBuffer(const char *Cmd) { }; CLIExecWithReturn(ctx, Cmd, argtable, true); const char *s = arg_get_str(ctx, 1)->sval[0]; - CLIParserFree(ctx); - - if (s == NULL) { - PrintAndLogEx(FAILED, "Must provide a binary string"); - return PM3_EINVARG; - } - int len = MIN(strlen(s), MAX_DEMOD_BUF_LEN); // add 1 for null terminator. uint8_t *data = calloc(len + 1, sizeof(uint8_t)); - if (data == NULL) + if (data == NULL) { + CLIParserFree(ctx); return PM3_EMALLOC; + } for (int i = 0; i <= strlen(s); i++) { char c = s[i]; @@ -954,6 +949,9 @@ static int CmdAnalyseDemodBuffer(const char *Cmd) { PrintAndLogEx(NORMAL, "%c" NOLF, c); } + + CLIParserFree(ctx); + PrintAndLogEx(NORMAL, ""); DemodBufferLen = len; free(data); From 249d3e7d1e6ffa6018e1984536394040dc2e786c Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 12:04:19 +0100 Subject: [PATCH 60/76] text --- CHANGELOG.md | 2 ++ client/src/wiegand_formatutils.c | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd6aa4cc..13743da0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Changed `wiegand encode` - format param is now optional, w/o it will try encode all formats (@iceman1001) + - Fix cppchecker warnings (@iceman1001) - Added `trace list -t mf` - now can use external dictionary keys file - Added support for bidirectional communication for `lf em 4x50 sim` (@tharexde) - Change `PLATFORM=PM3OTHER` to `PLATFORM=PM3GENERIC` (@iceman1001) diff --git a/client/src/wiegand_formatutils.c b/client/src/wiegand_formatutils.c index 3879e616e..212a30151 100644 --- a/client/src/wiegand_formatutils.c +++ b/client/src/wiegand_formatutils.c @@ -121,6 +121,12 @@ bool set_nonlinear_field(wiegand_message_t *data, uint64_t value, uint8_t numBit } static uint8_t get_length_from_header(wiegand_message_t *data) { +/** + * detect if message has "preamble" / "sentinel bit" + * + */ + + uint8_t len = 0; uint32_t hfmt = 0; // for calculating card length From 831a3ad2fa7f7c140de63435ab3e3248153fd9b6 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 12:13:54 +0100 Subject: [PATCH 61/76] hw dbg - fix wrong param --- client/src/cmdhw.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhw.c b/client/src/cmdhw.c index 5c61d2cf4..274dc31b3 100644 --- a/client/src/cmdhw.c +++ b/client/src/cmdhw.c @@ -332,8 +332,8 @@ static int CmdDbg(const char *Cmd) { bool lv0 = arg_get_lit(ctx, 1); bool lv1 = arg_get_lit(ctx, 2); bool lv2 = arg_get_lit(ctx, 3); - bool lv3 = arg_get_lit(ctx, 3); - bool lv4 = arg_get_lit(ctx, 4); + bool lv3 = arg_get_lit(ctx, 4); + bool lv4 = arg_get_lit(ctx, 5); CLIParserFree(ctx); if ((lv0 + lv1 + lv2 + lv3 + lv4) > 1) { From ead26ec3c3f0bb453c80c60a23b1303366e68a48 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:06:26 +0100 Subject: [PATCH 62/76] lf t55xx special - now uses cliparser --- client/src/cmdlft55xx.c | 18 +++++++++++++++--- client/src/cmdlft55xx.h | 2 +- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 3903a9547..788d4ad91 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -1504,8 +1504,20 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5) return false; } -int special(const char *Cmd) { - (void)Cmd; // Cmd is not used so far +int CmdT55xxSpecial(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf t55xx special", + "Show block changes with 64 different offsets, data taken from Demod buffer.", + "lf t55xx special\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); uint8_t bits[32] = {0x00}; @@ -4216,7 +4228,7 @@ static command_t CommandTable[] = { {"protect", CmdT55xxProtect, IfPm3Lf, "Password protect tag"}, {"recoverpw", CmdT55xxRecoverPW, IfPm3Lf, "Try to recover from bad password write from a cloner"}, {"sniff", CmdT55xxSniff, AlwaysAvailable, "Attempt to recover T55xx commands from sample buffer"}, - {"special", special, IfPm3Lf, "Show block changes with 64 different offsets"}, + {"special", CmdT55xxSpecial, IfPm3Lf, "Show block changes with 64 different offsets"}, {"wipe", CmdT55xxWipe, IfPm3Lf, "Wipe a T55xx tag and set defaults (will destroy any data on tag)"}, {NULL, NULL, NULL, NULL} }; diff --git a/client/src/cmdlft55xx.h b/client/src/cmdlft55xx.h index 336dbfc76..83a35b848 100644 --- a/client/src/cmdlft55xx.h +++ b/client/src/cmdlft55xx.h @@ -196,7 +196,7 @@ bool testKnownConfigBlock(uint32_t block0); bool tryDetectP1(bool getData); bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5); -int special(const char *Cmd); +int CmdT55xxSpecial(const char *Cmd); bool AcquireData(uint8_t page, uint8_t block, bool pwdmode, uint32_t password, uint8_t downlink_mode); uint8_t t55xx_try_one_password(uint32_t password, uint8_t downlink_mode, bool try_all_dl_modes); From 3b37ca1d4c0e7978e728e0b6b9bd56cb5e7f5cb8 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:06:45 +0100 Subject: [PATCH 63/76] coverity fix #308455 --- client/src/cmdlft55xx.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 788d4ad91..89204952d 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -3581,6 +3581,7 @@ static int CmdT55xxDetectPage1(const char *Cmd) { int res = arg_get_u32_hexstr_def(ctx, 2, 0, &password); if (res == 2) { PrintAndLogEx(INFO, "Password should be 4 hex bytes"); + CLIParserFree(ctx); return PM3_EINVARG; } else if (res == 1) { usepwd = true; From f65b5eb96da91c3ad948f29fb878707a73347837 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:10:33 +0100 Subject: [PATCH 64/76] coverity fix #308194 --- armsrc/em4x70.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/armsrc/em4x70.c b/armsrc/em4x70.c index 77cfbb2dd..bc9d467cc 100644 --- a/armsrc/em4x70.c +++ b/armsrc/em4x70.c @@ -662,9 +662,10 @@ void em4x70_write(em4x70_data_t *etd) { if (status) { // Read Tag after writing - em4x70_read_id(); - em4x70_read_um1(); - em4x70_read_um2(); + if (em4x70_read_id()) { + em4x70_read_um1(); + em4x70_read_um2(); + } } } From 145a0319229903d7c09d8b390166ee6a27e4792b Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:16:46 +0100 Subject: [PATCH 65/76] coverity fix #308205 --- armsrc/Standalone/hf_iceclass.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/armsrc/Standalone/hf_iceclass.c b/armsrc/Standalone/hf_iceclass.c index 88ccfaa47..27e1bf5ab 100644 --- a/armsrc/Standalone/hf_iceclass.c +++ b/armsrc/Standalone/hf_iceclass.c @@ -170,12 +170,9 @@ static void save_to_flash(uint8_t *data, uint16_t datalen, char *filename) { data[4], data[5], data[6], data[7] ); } else { - int name_len = SPIFFS_OBJ_NAME_LEN; - int filename_len = strlen(filename); - + int fnlen = MIN(strlen(filename), SPIFFS_OBJ_NAME_LEN); // if the given name len longer than buffer allows, cut it down to size - name_len = (name_len >= SPIFFS_OBJ_NAME_LEN) ? SPIFFS_OBJ_NAME_LEN : filename_len; - memcpy(fn, filename, name_len); + memcpy(fn, filename, fnlen); } int res; From a6e4b03c28be37000354c0cd845c145e0a5aebe6 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:18:09 +0100 Subject: [PATCH 66/76] coverty finds this a deadcode, cppchecker complains... --- client/src/preferences.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/client/src/preferences.c b/client/src/preferences.c index 92a91e54a..d961d2c6f 100644 --- a/client/src/preferences.c +++ b/client/src/preferences.c @@ -853,11 +853,6 @@ static int setCmdSavePaths(const char *Cmd) { path = trace_path; } - if (path == NULL) { - PrintAndLogEx(FAILED, "Must give at least one path"); - return PM3_EINVARG; - } - // remove trailing slash. size_t nplen = strlen(path); if ((path[nplen - 1] == '/') || (path[nplen - 1] == '\\')) { From 33a17fcd6706e6e27cf7f1b15984d55996762b73 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:47:02 +0100 Subject: [PATCH 67/76] cppchecker fixes --- armsrc/Standalone/hf_tcprst.c | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/armsrc/Standalone/hf_tcprst.c b/armsrc/Standalone/hf_tcprst.c index 11b2b1935..f9d8b0b59 100644 --- a/armsrc/Standalone/hf_tcprst.c +++ b/armsrc/Standalone/hf_tcprst.c @@ -248,11 +248,9 @@ void RunMod(void) { dynamic_response_info.response[0] = receivedCmd[0]; if (memcmp("\x02\xa2\xb0\x00\x00\x1d\x51\x69", receivedCmd, 8) == 0) { - dynamic_response_info.response[0] = receivedCmd[0]; memcpy(dynamic_response_info.response + 1, ndef, 31); dynamic_response_info.response_n = 32; } else if (memcmp("\x02\x00\x20\x00\x01\x00\x6e\xa9", receivedCmd, 8) == 0) { - dynamic_response_info.response[0] = receivedCmd[0]; dynamic_response_info.response[1] = 0x63; dynamic_response_info.response[2] = 0x00; dynamic_response_info.response_n = 3; @@ -260,14 +258,12 @@ void RunMod(void) { memcpy(verify_pwd + 5, receivedCmd + 6, 16); DbpString("Reader sent password: "); Dbhexdump(16, verify_pwd + 5, 0); - dynamic_response_info.response[0] = receivedCmd[0]; dynamic_response_info.response[1] = 0x90; dynamic_response_info.response[2] = 0x00; dynamic_response_info.response_n = 3; gotkey = true; state = STATE_DUMP; } else { - dynamic_response_info.response[0] = receivedCmd[0]; dynamic_response_info.response[1] = 0x90; dynamic_response_info.response[2] = 0x00; dynamic_response_info.response_n = 3; @@ -321,7 +317,7 @@ void RunMod(void) { LED_B_ON(); uint8_t apdulen = iso14_apdu(apdus[i], (uint16_t) apdusLen[i], false, apdubuffer, NULL); - if (apdulen > 0) { + if (apdulen > 2) { DbpString(_YELLOW_("[ ") "Proxmark command" _YELLOW_(" ]")); Dbhexdump(apdusLen[i], apdus[i], false); DbpString(_GREEN_("[ ") "Card answer" _GREEN_(" ]")); @@ -429,11 +425,9 @@ void RunMod(void) { dynamic_response_info.response[0] = receivedCmd[0]; if (memcmp("\x02\xa2\xb0\x00\x00\x1d\x51\x69", receivedCmd, 8) == 0) { - dynamic_response_info.response[0] = receivedCmd[0]; memcpy(dynamic_response_info.response + 1, ndef, 31); dynamic_response_info.response_n = 32; } else if (memcmp("\x02\x00\x20\x00\x01\x00\x6e\xa9", receivedCmd, 8) == 0) { - dynamic_response_info.response[0] = receivedCmd[0]; dynamic_response_info.response[1] = 0x63; dynamic_response_info.response[2] = 0x00; dynamic_response_info.response_n = 3; @@ -441,12 +435,10 @@ void RunMod(void) { memcpy(verify_pwd + 5, receivedCmd + 6, 16); DbpString("Reader sent password: "); Dbhexdump(16, verify_pwd + 5, 0); - dynamic_response_info.response[0] = receivedCmd[0]; dynamic_response_info.response[1] = 0x90; dynamic_response_info.response[2] = 0x00; dynamic_response_info.response_n = 3; } else { - dynamic_response_info.response[0] = receivedCmd[0]; dynamic_response_info.response[1] = 0x90; dynamic_response_info.response[2] = 0x00; dynamic_response_info.response_n = 3; From 76f2c2c95e8d8551bc0df3232cc46fa283b4875c Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 16:51:06 +0100 Subject: [PATCH 68/76] cppchecker fix --- client/src/cmdhfmf.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 9e0b2ba3e..475c687fb 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -3546,8 +3546,6 @@ static int CmdHF14AMfSim(const char *Cmd) { } showSectorTable(k_sector, k_sectorsCount); } - - k_sectorsCount = MIFARE_4K_MAXSECTOR; return PM3_SUCCESS; } From 3f370438e5b9ed4ad5abee230e9f1efc7a43380e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 18:59:50 +0100 Subject: [PATCH 69/76] cppchecker noticed ct vs pt is swapped. Question is where was the error introduced? pt (plaintext) ct (cryptotext) --- common/cryptorf/cryptolib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/cryptorf/cryptolib.c b/common/cryptorf/cryptolib.c index bf597317b..a59f4109a 100644 --- a/common/cryptorf/cryptolib.c +++ b/common/cryptorf/cryptolib.c @@ -307,7 +307,7 @@ static void cm_crypt(const CryptoAction ca, const uint8_t offset, const uint8_t } } -void cm_encrypt(const uint8_t offset, const uint8_t len, const uint8_t *ct, uint8_t *pt, crypto_state s) { +void cm_encrypt(const uint8_t offset, const uint8_t len, const uint8_t *pt, uint8_t *ct, crypto_state s) { next_n(true, 5, 0, s); next(true, 0, s); cm_crypt(CA_ENCRYPT, offset, len, ct, pt, s); From 4320486a3bf7250a77edb7762662aa55fbc51fdc Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 19:04:35 +0100 Subject: [PATCH 70/76] cppchecker fixes --- common/cryptorf/cryptolib.c | 2 +- tools/cryptorf/sma.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/common/cryptorf/cryptolib.c b/common/cryptorf/cryptolib.c index a59f4109a..ec6ab7468 100644 --- a/common/cryptorf/cryptolib.c +++ b/common/cryptorf/cryptolib.c @@ -310,7 +310,7 @@ static void cm_crypt(const CryptoAction ca, const uint8_t offset, const uint8_t void cm_encrypt(const uint8_t offset, const uint8_t len, const uint8_t *pt, uint8_t *ct, crypto_state s) { next_n(true, 5, 0, s); next(true, 0, s); - cm_crypt(CA_ENCRYPT, offset, len, ct, pt, s); + cm_crypt(CA_ENCRYPT, offset, len, pt, ct, s); } void cm_decrypt(const uint8_t offset, const uint8_t len, const uint8_t *ct, uint8_t *pt, crypto_state s) { diff --git a/tools/cryptorf/sma.cpp b/tools/cryptorf/sma.cpp index 05b9f344f..a51281ad8 100644 --- a/tools/cryptorf/sma.cpp +++ b/tools/cryptorf/sma.cpp @@ -701,7 +701,7 @@ void combine_valid_left_right_states(vector *plcstates, vector *prcs } } printf("Found a total of " _YELLOW_("%llu")" combinations, ", ((unsigned long long)plcstates->size()) * prcstates->size()); - printf("but only " _GREEN_("%lu")" were valid!\n", pgc_candidates->size()); + printf("but only " _GREEN_("%zu")" were valid!\n", pgc_candidates->size()); } int main(int argc, const char *argv[]) { @@ -814,7 +814,7 @@ int main(int argc, const char *argv[]) { printf("Determing the right states that correspond to the keystream\n"); rbits = sm_right(ks, mask, &rstates); - printf("Top-bin for the right state contains " _GREEN_("%d")" correct bits\n", rbits); + printf("Top-bin for the right state contains " _GREEN_("%u")" correct bits\n", rbits); printf("Total count of right bins: " _YELLOW_("%lu") "\n", (unsigned long)rstates.size()); if (rbits < 96) { @@ -827,16 +827,16 @@ int main(int argc, const char *argv[]) { printf("Using the state from the top-right bin: " _YELLOW_("0x%07" PRIx64)"\n", rstate_after_gc); search_gc_candidates_right(rstate_before_gc, rstate_after_gc, Q, &crstates); - printf("Found " _YELLOW_("%lu")" right candidates using the meet-in-the-middle attack\n", crstates.size()); + printf("Found " _YELLOW_("%zu")" right candidates using the meet-in-the-middle attack\n", crstates.size()); if (crstates.size() == 0) continue; printf("Calculating left states using the (unknown bits) mask from the top-right state\n"); sm_left(ks, mask, &clstates); - printf("Found a total of " _YELLOW_("%lu")" left cipher states, recovering left candidates...\n", clstates.size()); + printf("Found a total of " _YELLOW_("%zu")" left cipher states, recovering left candidates...\n", clstates.size()); if (clstates.size() == 0) continue; search_gc_candidates_left(lstate_before_gc, Q, &clstates); - printf("The meet-in-the-middle attack returned " _YELLOW_("%lu")" left cipher candidates\n", clstates.size()); + printf("The meet-in-the-middle attack returned " _YELLOW_("%zu")" left cipher candidates\n", clstates.size()); if (clstates.size() == 0) continue; printf("Combining left and right states, disposing invalid combinations\n"); From 7750e60ac39193abfaa0d51a7028eade1c8ed107 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 19:12:36 +0100 Subject: [PATCH 71/76] cppchecker fixes. wrong format string. shadows outer... --- tools/cryptorf/sma_multi.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tools/cryptorf/sma_multi.cpp b/tools/cryptorf/sma_multi.cpp index 390c98495..bb1676aad 100644 --- a/tools/cryptorf/sma_multi.cpp +++ b/tools/cryptorf/sma_multi.cpp @@ -371,7 +371,7 @@ static inline void sm_left_mask(const uint8_t *ks, uint8_t *mask, uint64_t rstat std::atomic key_found{0}; std::atomic key{0}; -std::atomic topbits{0}; +std::atomic g_topbits{0}; std::mutex g_ice_mtx; static uint32_t g_num_cpus = std::thread::hardware_concurrency(); @@ -421,9 +421,9 @@ static void ice_sm_right_thread( } g_ice_mtx.lock(); - if (bits > topbits.load(std::memory_order_relaxed)) { + if (bits > g_topbits.load(std::memory_order_relaxed)) { // Copy the winning mask - topbits = bits; + g_topbits = bits; memcpy(mask, tmp_mask, 16); } g_ice_mtx.unlock(); @@ -450,7 +450,7 @@ static void ice_sm_right_thread( static uint32_t ice_sm_right(const uint8_t *ks, uint8_t *mask, vector *pcrstates) { map bincstates; - topbits = ATOMIC_VAR_INIT(0); + g_topbits = ATOMIC_VAR_INIT(0); std::vector threads(g_num_cpus); for (uint8_t m = 0; m < g_num_cpus; m++) { @@ -474,7 +474,7 @@ static uint32_t ice_sm_right(const uint8_t *ks, uint8_t *mask, vector // Reverse the vector order (so the higest bin comes first) reverse(pcrstates->begin(), pcrstates->end()); - return topbits; + return g_topbits; } static void ice_sm_left_thread( @@ -899,7 +899,7 @@ void combine_valid_left_right_states(vector *plcstates, vector *prcs inner = *plcstates; } - printf("Outer " _YELLOW_("%lu")" , inner " _YELLOW_("%lu") "\n", outer.size(), inner.size()); + printf("Outer " _YELLOW_("%zu")" , inner " _YELLOW_("%zu") "\n", outer.size(), inner.size()); // Clean up the candidate list pgc_candidates->clear(); @@ -928,7 +928,7 @@ void combine_valid_left_right_states(vector *plcstates, vector *prcs } } printf("Found a total of " _YELLOW_("%llu")" combinations, ", ((unsigned long long)plcstates->size()) * prcstates->size()); - printf("but only " _GREEN_("%lu")" were valid!\n", pgc_candidates->size()); + printf("but only " _GREEN_("%zu")" were valid!\n", pgc_candidates->size()); } static void ice_compare( @@ -1080,8 +1080,8 @@ int main(int argc, const char *argv[]) { //rbits = sm_right(ks, mask, &rstates); rbits = ice_sm_right(ks, mask, &rstates); - printf("Top-bin for the right state contains " _GREEN_("%d")" correct bits\n", rbits); - printf("Total count of right bins: " _YELLOW_("%lu") "\n", (unsigned long)rstates.size()); + printf("Top-bin for the right state contains " _GREEN_("%u")" correct bits\n", rbits); + printf("Total count of right bins: " _YELLOW_("%zu") "\n", (unsigned long)rstates.size()); if (rbits < 96) { printf(_RED_("\n WARNING!!! Better find another trace, the right top-bin is < 96 bits\n\n")); @@ -1093,19 +1093,19 @@ int main(int argc, const char *argv[]) { printf("Using the state from the top-right bin: " _YELLOW_("0x%07" PRIx64)"\n", rstate_after_gc); search_gc_candidates_right(rstate_before_gc, rstate_after_gc, Q, &crstates); - printf("Found " _YELLOW_("%lu")" right candidates using the meet-in-the-middle attack\n", crstates.size()); + printf("Found " _YELLOW_("%zu")" right candidates using the meet-in-the-middle attack\n", crstates.size()); if (crstates.size() == 0) continue; printf("Calculating left states using the (unknown bits) mask from the top-right state\n"); //sm_left(ks, mask, &clstates); ice_sm_left(ks, mask, &clstates); - printf("Found a total of " _YELLOW_("%lu")" left cipher states, recovering left candidates...\n", clstates.size()); + printf("Found a total of " _YELLOW_("%zu")" left cipher states, recovering left candidates...\n", clstates.size()); if (clstates.size() == 0) continue; search_gc_candidates_left(lstate_before_gc, Q, &clstates); - printf("The meet-in-the-middle attack returned " _YELLOW_("%lu")" left cipher candidates\n", clstates.size()); + printf("The meet-in-the-middle attack returned " _YELLOW_("%zu")" left cipher candidates\n", clstates.size()); if (clstates.size() == 0) continue; printf("Combining left and right states, disposing invalid combinations\n"); From c50c0f1630bc104717c12556f89fffe2d55e33cb Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 19:28:13 +0100 Subject: [PATCH 72/76] cppchecker fix, removed odd loop --- common/crc32.c | 21 +++++++++++---------- common/crc32.h | 4 ++-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/common/crc32.c b/common/crc32.c index baf6ddd28..574d499b2 100644 --- a/common/crc32.c +++ b/common/crc32.c @@ -18,17 +18,18 @@ static void crc32_byte(uint32_t *crc, const uint8_t value) { } } -void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc) { - uint32_t desfire_crc = CRC32_PRESET; - for (size_t i = 0; i < len; i++) { - crc32_byte(&desfire_crc, data[i]); - } - uint32_t crctmp = htole32(desfire_crc); - for (size_t i = 0; i < sizeof(uint32_t); i++) { - crc[i] = ((uint8_t *) &crctmp)[i]; +void crc32_ex(const uint8_t *d, const size_t n, uint8_t *crc) { + uint32_t c = CRC32_PRESET; + for (size_t i = 0; i < n; i++) { + crc32_byte(&c, d[i]); } + crc[0] = (uint8_t) c; + crc[1] = (uint8_t)(c >> 8); + crc[2] = (uint8_t)(c >> 16); + crc[3] = (uint8_t)(c >> 24); } -void crc32_append(uint8_t *data, const size_t len) { - crc32_ex(data, len, data + len); + +void crc32_append(uint8_t *d, const size_t n) { + crc32_ex(d, n, d + n); } diff --git a/common/crc32.h b/common/crc32.h index a6bbee16a..2cbe45e6c 100644 --- a/common/crc32.h +++ b/common/crc32.h @@ -11,7 +11,7 @@ #include "common.h" -void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc); -void crc32_append(uint8_t *data, const size_t len); +void crc32_ex(const uint8_t *d, const size_t n, uint8_t *crc); +void crc32_append(uint8_t *d, const size_t n); #endif From e42985b65ca4e7084f26bbfdb0135cca7f391614 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 19:28:45 +0100 Subject: [PATCH 73/76] testing crc32 --- client/src/cmdanalyse.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/client/src/cmdanalyse.c b/client/src/cmdanalyse.c index 87c989618..5f6860e95 100644 --- a/client/src/cmdanalyse.c +++ b/client/src/cmdanalyse.c @@ -19,6 +19,7 @@ #include "ui.h" // PrintAndLog #include "crc.h" #include "crc16.h" // crc16 ccitt +#include "crc32.h" // crc32_ex #include "tea.h" #include "legic_prng.h" #include "cmddata.h" // demodbuffer @@ -361,6 +362,12 @@ static int CmdAnalyseCRC(const char *Cmd) { uint16_t crcEE = b1 << 8 | b2; PrintAndLogEx(INFO, "FeliCa | %04x or %04x (31C3 expected)\n", crcEE, Crc16ex(CRC_FELICA, dataStr, sizeof(dataStr))); + + uint32_t crc32 = 0; + crc32_ex(dataStr, sizeof(dataStr), (uint8_t *)&crc32); + PrintAndLogEx(INFO, "CRC32 (desfire) | %08x ( expected)", crc32); + PrintAndLogEx(INFO, "---------------------------------------------------------------\n\n\n"); + return PM3_SUCCESS; } From ea5625c304d07ca8655db218e1b3013645170bfe Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 20:35:18 +0100 Subject: [PATCH 74/76] chg: cliparse error message unified to pm3 style --- client/deps/cliparser/argtable3.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/client/deps/cliparser/argtable3.c b/client/deps/cliparser/argtable3.c index 43701d735..783bd303b 100644 --- a/client/deps/cliparser/argtable3.c +++ b/client/deps/cliparser/argtable3.c @@ -830,7 +830,7 @@ static void arg_date_errorfn( /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); @@ -846,11 +846,11 @@ static void arg_date_errorfn( struct tm tm; char buff[200]; - fprintf(fp, "illegal timestamp format \"%s\"\n", argval); + fprintf(fp, "[!] illegal timestamp format \"%s\"\n", argval); memset(&tm, 0, sizeof(tm)); arg_strptime("1999-12-31 23:59:59", "%F %H:%M:%S", &tm); strftime(buff, sizeof(buff), parent->format, &tm); - printf("correct format is \"%s\"\n", buff); + printf("[+] correct format is \"%s\"\n", buff); break; } } @@ -1442,7 +1442,7 @@ static void arg_dbl_errorfn( /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); @@ -1455,7 +1455,7 @@ static void arg_dbl_errorfn( break; case EBADDOUBLE: - fprintf(fp, "invalid argument \"%s\" to option ", argval); + fprintf(fp, "[!] invalid argument \"%s\" to option ", argval); arg_print_option(fp, shortopts, longopts, datatype, "\n"); break; } @@ -1805,7 +1805,7 @@ static void arg_file_errorfn( /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); @@ -1818,7 +1818,7 @@ static void arg_file_errorfn( break; default: - fprintf(fp, "unknown error at \"%s\"\n", argval); + fprintf(fp, "[!] unknown error at \"%s\"\n", argval); } } @@ -2136,7 +2136,7 @@ static void arg_int_errorfn( /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); @@ -2149,7 +2149,7 @@ static void arg_int_errorfn( break; case EBADINT: - fprintf(fp, "invalid argument \"%s\" to option ", argval); + fprintf(fp, "[!] invalid argument \"%s\" to option ", argval); arg_print_option(fp, shortopts, longopts, datatype, "\n"); break; @@ -2394,7 +2394,7 @@ static void arg_u64_errorfn( /* make argval NULL safe */ argval = argval ? argval : ""; - fprintf(fp, "%s: ", progname); + fprintf(fp, "[!] %s: ", progname); switch (errorcode) { case EMINCOUNT: fputs("missing option ", fp); @@ -2407,7 +2407,7 @@ static void arg_u64_errorfn( break; case EBADINT: - fprintf(fp, "invalid argument \"%s\" to option ", argval); + fprintf(fp, "[!] invalid argument \"%s\" to option ", argval); arg_print_option(fp, shortopts, longopts, datatype, "\n"); break; From e29bbcf6c374582816cca1406c897e68dd135d9b Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 29 Jan 2021 20:35:36 +0100 Subject: [PATCH 75/76] text --- client/src/cmdwiegand.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/src/cmdwiegand.c b/client/src/cmdwiegand.c index e3b0418ac..3fcce3214 100644 --- a/client/src/cmdwiegand.c +++ b/client/src/cmdwiegand.c @@ -49,7 +49,8 @@ int CmdWiegandEncode(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "wiegand encode", "Encode wiegand formatted number to raw hex", - "wiegand encode -w H10301 --fc 101 --cn 1337" + "wiegand encode --fc 101 --cn 1337 -> show all formats\n" + "wiegand encode -w H10301 --fc 101 --cn 1337 -> H10301 format " ); void *argtable[] = { From 8f8263ae59df4a8faab33b37cb144a81f74309e2 Mon Sep 17 00:00:00 2001 From: Ave Date: Fri, 29 Jan 2021 23:27:33 +0300 Subject: [PATCH 76/76] emrtd: Fix EF_DG2 image dumping --- client/src/cmdhfemrtd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhfemrtd.c b/client/src/cmdhfemrtd.c index 255939ab0..604beb68c 100644 --- a/client/src/cmdhfemrtd.c +++ b/client/src/cmdhfemrtd.c @@ -713,8 +713,8 @@ static int emrtd_dump_ef_dg2(uint8_t *file_contents, size_t file_length, const c // Note: Doing file_length - 6 to account for the longest data we're checking. // Checks first byte before the rest to reduce overhead for (offset = 0; offset < file_length - 6; offset++) { - if ((file_contents[offset] == 0xFF && memcmp(jpeg_header, file_contents + offset, 4) != 0) || - (file_contents[offset] == 0x00 && memcmp(jpeg2k_header, file_contents + offset, 6) != 0)) { + if ((file_contents[offset] == 0xFF && memcmp(jpeg_header, file_contents + offset, 4) == 0) || + (file_contents[offset] == 0x00 && memcmp(jpeg2k_header, file_contents + offset, 6) == 0)) { datalen = file_length - offset; break; }