From ff04e1ea9ad594b739b2f997d4df5696c4250834 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sun, 7 Jun 2026 20:23:28 +0200 Subject: [PATCH] hf mfu cauth: add -c to collect nonces --- armsrc/appmain.c | 4 + armsrc/mifarecmd.c | 65 +++++++++ armsrc/mifarecmd.h | 1 + .../pyscripts/mfulc_counterfeit_recovery.py | 26 +++- client/src/cmdhfmfu.c | 126 ++++++++++++++++++ include/pm3_cmd.h | 2 +- 6 files changed, 217 insertions(+), 7 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 2a6d999da..b59b15018 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -2049,6 +2049,10 @@ static void PacketReceived(PacketCommandNG *packet) { MifareAcquireNonces(packet->oldarg[0], packet->oldarg[2]); break; } + case CMD_HF_MIFAREU3P_ACQ_ENCRYPTED_NONCES: { + MifareU3PAcquireEncryptedNonces(packet->oldarg[0], packet->oldarg[1]); + break; + } case CMD_HF_MIFARE_NESTED: { struct p { uint8_t block; diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index c44a616cd..c80bb89bc 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -320,6 +320,71 @@ static uint8_t chkKey3Pass(uint8_t keyno, uint8_t *keybytes, uint32_t *auths, bo return res; } +//----------------------------------------------------------------------------- +// acquire encrypted nonces of Ultralight C or Ultralight AES +//----------------------------------------------------------------------------- +void MifareU3PAcquireEncryptedNonces(uint8_t keyno, uint8_t num_nonces_to_acquire) { + uint8_t i = 0; + int res = PM3_SUCCESS; + bool selected = false; + // Buf first byte is nr of nonces in the buffer, uint8_t + uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + uint8_t nonce_size = keyno == MIFAREULC_KEY_INDEX ? 8 : 16; + uint8_t max_nonces_per_response = (PM3_CMD_DATA_SIZE - sizeof(uint8_t)) / nonce_size; + uint8_t acquired_nonces = 0; + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + set_tracing(false); + set_tracing(true); + LED_A_ON(); + LED_C_ON(); + if (num_nonces_to_acquire > max_nonces_per_response) { + Dbprintf("Limiting number of nonces to acquire to %u per response", max_nonces_per_response); + num_nonces_to_acquire = max_nonces_per_response; + } + for (acquired_nonces = 0; acquired_nonces < num_nonces_to_acquire; acquired_nonces++) { + + // Needed for USCUID-UL + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelayUsPrecision(500); + + selected = false; + while (i < 5 && selected == false) { + if (MifareUFastRead0() == 0) { + ++i; + continue; + } + selected = true; + } + if (selected == false) { + Dbprintf("acquire nonces: Failed at fast selecting the card!"); + res = PM3_ESOFT; + break; + } + uint16_t len = 0; + uint8_t resp[19] = {0x00}; + if (keyno == MIFAREULC_KEY_INDEX) { + len = mifare_sendcmd_short(NULL, CRYPT_NONE, MIFARE_ULC_AUTH_1, 0x00, resp, sizeof(resp), NULL, NULL); + if (len != 1 + nonce_size + 2) { + res = PM3_ESOFT; + break; + } + } else { + len = mifare_sendcmd_short(NULL, CRYPT_NONE, MIFARE_ULAES_AUTH_1, keyno, resp, sizeof(resp), NULL, NULL); + if (len != 1 + nonce_size + 2) { + res = PM3_ESOFT; + break; + } + } + memcpy(buf + 1 + acquired_nonces * nonce_size, resp + 1, nonce_size); + } + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LED_B_ON(); + buf[0] = acquired_nonces; + reply_ng(CMD_HF_MIFAREU3P_ACQ_ENCRYPTED_NONCES, res, buf, sizeof(uint8_t) + acquired_nonces * nonce_size); + LEDsoff(); +} + void MifareU3PassAuth(mful_3passauth_t *packet) { LED_A_ON(); diff --git a/armsrc/mifarecmd.h b/armsrc/mifarecmd.h index 09bbd4f08..6362a3c16 100644 --- a/armsrc/mifarecmd.h +++ b/armsrc/mifarecmd.h @@ -33,6 +33,7 @@ void MifareUWriteBlock(mful_writeblock_t *packet); void MifareU3PassAuth(mful_3passauth_t *packet); void MifareU3PassChkKeys(mful_3passchk_t *packet); +void MifareU3PAcquireEncryptedNonces(uint8_t keyno, uint8_t num_nonces_to_acquire); void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, bool calibrate, uint8_t *key); void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, uint8_t *key, uint8_t forceDetectDist); diff --git a/client/pyscripts/mfulc_counterfeit_recovery.py b/client/pyscripts/mfulc_counterfeit_recovery.py index 30e60d400..3decfe64c 100755 --- a/client/pyscripts/mfulc_counterfeit_recovery.py +++ b/client/pyscripts/mfulc_counterfeit_recovery.py @@ -389,7 +389,8 @@ def is_known_counterfeit(p) -> bool: return False -def collect(num_challenges: int, p, debug: bool, force: bool = False, erndarndb: Optional[str] = None) -> Optional[dict]: +def collect(num_challenges: int, p, debug: bool, force: bool = False, + erndarndb: Optional[str] = None) -> Optional[dict]: """ Collect challenges from the card and check if it is vulnerable. @@ -568,11 +569,24 @@ def main(): uid = get_ulc_uid(p) if uid is None: return - max_occurrence, challenges = collect_100(num_challenges, p, early_stop=False) - print(f"[+] Most frequent challenge: \033[1;34m{challenges['challenge_100']}\033[0m" - f" (occurrences: {max_occurrence}/{num_challenges})") - print("[+] Get the corresponding reader response with") - print(f"[+] \033[1;33mhf mfu sim -t 13 -u {uid} --1a1 {challenges['challenge_100']}\033[0m") + common_nonces = [] + legacy_collect = False + if legacy_collect: + max_occurrence, challenges = collect_100(num_challenges, p, early_stop=False) + if max_occurrence <= 1: + return + common_nonces.append((challenges["challenge_100"], max_occurrence)) + else: + p.console(f"hf mfu cauth -c {num_challenges}") + for line in p.grabbed_output.splitlines(): + match = re.search(r"\[=\]\s+([0-9a-fA-F]{16})\s+\(count:\s*(\d+)\)", line) + if match: + common_nonces.append((match.group(1), int(match.group(2)))) + for i in range(len(common_nonces)): + challenge_hex = common_nonces[i][0] + occurrence = common_nonces[i][1] + print(f"E(RndB): {challenge_hex} Count: {occurrence:3d} Cmd:" + f" \033[1;33mhf mfu sim -t 13 -u {uid} --1a1 {challenge_hex}\033[0m") return if use_cuda: diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index d2867999d..262b1139f 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -4473,6 +4473,122 @@ static int mfu_3pass_check_keys(uint8_t key_index, uint8_t firstChunk, uint8_t l // Ultralight C Methods //------------------------------------------------------------------------------- +static uint32_t acquire_ul3p_nonces(uint8_t keytype, uint32_t num_nonces_to_acquire, uint64_t *nonces) { + + uint32_t num_acquired_nonces = 0; + uint8_t nonce_size = keytype == 1 ? 8 : 16; + uint8_t max_nonces_per_response = (PM3_CMD_DATA_SIZE - sizeof(uint8_t)) / nonce_size; + PacketResponseNG resp; + memset(&resp, 0, sizeof(resp)); + + if (keytype != 1) { + PrintAndLogEx(ERR, "Currently, only supported keytype for acquiring nonces is ULC"); + return PM3_ENOTIMPL; + } + + do { + clearCommandBuffer(); + SendCommandMIX(CMD_HF_MIFAREU3P_ACQ_ENCRYPTED_NONCES, MIFAREULC_KEY_INDEX, MIN(num_nonces_to_acquire - num_acquired_nonces, max_nonces_per_response), 0, NULL, 0); + if (WaitForResponseTimeout(CMD_HF_MIFAREU3P_ACQ_ENCRYPTED_NONCES, &resp, 1500 + num_nonces_to_acquire * 15) == false) { + PrintAndLogEx(WARNING, "Timeout"); + return num_acquired_nonces; + } + + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Failure to collect tag nonces"); + return num_acquired_nonces; + } + + uint8_t num_sampled_nonces = resp.data.asBytes[0]; + uint8_t *bufp = resp.data.asBytes + 1; + + for (uint16_t i = 0; i < num_sampled_nonces; i++) { + uint64_t nt_enc = bytes_to_num(bufp + i * nonce_size, nonce_size); + if (nonces != NULL) { + nonces[num_acquired_nonces] = nt_enc; + } + num_acquired_nonces++; + } + + } while (num_acquired_nonces < num_nonces_to_acquire); + return num_acquired_nonces; +} + +static int collect_and_stat_nonces(uint32_t collect_nonces) { + PrintAndLogEx(INFO, "Collecting %d nonces...", collect_nonces); + uint64_t *nonces = calloc(collect_nonces, sizeof(uint64_t)); + if (nonces == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + uint32_t num_sampled_nonces = acquire_ul3p_nonces(1, collect_nonces, nonces); + for (uint16_t i = 0; i < num_sampled_nonces; i++) { + PrintAndLogEx(DEBUG, "Encrypted nonce: %016" PRIx64 "\n", nonces[i]); + } + + if (num_sampled_nonces != collect_nonces) { + PrintAndLogEx(WARNING, "Failed to acquire all nonces"); + } + + // Count nonce frequencies + typedef struct { + uint64_t nonce; + uint32_t count; + } nonce_count_t; + + nonce_count_t *counts = calloc(num_sampled_nonces, sizeof(nonce_count_t)); + if (counts == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory for counts"); + free(nonces); + return PM3_EMALLOC; + } + uint32_t unique_count = 0; + + for (uint32_t i = 0; i < num_sampled_nonces; i++) { + bool found = false; + for (uint32_t j = 0; j < unique_count; j++) { + if (counts[j].nonce == nonces[i]) { + counts[j].count++; + found = true; + break; + } + } + if (!found && unique_count < num_sampled_nonces) { + counts[unique_count].nonce = nonces[i]; + counts[unique_count].count = 1; + unique_count++; + } + } + + // Sort by count (descending) + for (uint32_t i = 0; i < unique_count - 1; i++) { + for (uint32_t j = i + 1; j < unique_count; j++) { + if (counts[j].count > counts[i].count) { + nonce_count_t temp = counts[i]; + counts[i] = counts[j]; + counts[j] = temp; + } + } + } + + // Show top 10 + uint32_t show_count = unique_count < 10 ? unique_count : 10; + if (counts[0].count == 1) { + PrintAndLogEx(INFO, "All %u collected nonces are unique.", num_sampled_nonces); + free(nonces); + free(counts); + return PM3_SUCCESS; + } + PrintAndLogEx(INFO, "Top %u most common nonces:", show_count); + for (uint32_t i = 0; i < show_count; i++) { + PrintAndLogEx(INFO, " %016" PRIx64 " (count: %u)", counts[i].nonce, counts[i].count); + } + free(nonces); + free(counts); + return PM3_SUCCESS; +} + // Ultralight C Authentication // static int CmdHF14AMfUCAuth(const char *Cmd) { @@ -4492,6 +4608,7 @@ static int CmdHF14AMfUCAuth(const char *Cmd) { arg_int0("r", "retries", "", "Number of retries with provided key (def: 0)"), arg_lit0("n", "nocheck", "Skip checking tag answer correctness (only if a key is provided)"), arg_lit0("0", "read0", "Use fast READ0 (skip anticol)"), + arg_int0("c", "collect", "", "Collect nonces and show top 10 (def: 0, no collection)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -4505,6 +4622,7 @@ static int CmdHF14AMfUCAuth(const char *Cmd) { int retries = arg_get_int_def(ctx, 4, 0); bool check_answer = !arg_get_lit(ctx, 5); bool use_fastread0 = arg_get_lit(ctx, 6); + int collect_nonces = arg_get_int_def(ctx, 7, 0); CLIParserFree(ctx); if (ak_len != 16 && ak_len != 0) { @@ -4524,6 +4642,14 @@ static int CmdHF14AMfUCAuth(const char *Cmd) { return PM3_EINVARG; } + if (collect_nonces > 0) { + if (ak_len != 0 || keep_field_on || retries > 0 || check_answer == false) { + PrintAndLogEx(WARNING, "ERROR: Nonce collection incompatible with other options"); + return PM3_EINVARG; + } + return collect_and_stat_nonces(collect_nonces); + } + // Swap endianness if (swap_endian && ak_len) { auth_key_ptr = SwapEndian64(authenticationkey, 16, 8); diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 6efe9f339..645e13dc1 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -835,7 +835,7 @@ typedef struct { // ultralight-C & AES #define CMD_HF_MIFAREU3P_AUTH 0x0724 -// 0x0725 is free +#define CMD_HF_MIFAREU3P_ACQ_ENCRYPTED_NONCES 0x0725 #define CMD_HF_MIFAREU3P_CHKKEY 0x0726 #define CMD_HF_MIFAREU_SETKEY 0x0727