diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 6b471491e..0d5bb38ce 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -354,6 +354,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/loclass/hash1_brute.c ${PM3_ROOT}/client/src/loclass/ikeys.c ${PM3_ROOT}/client/src/mifare/mad.c + ${PM3_ROOT}/client/src/mifare/mad_test.c ${PM3_ROOT}/client/src/mifare/aiddesfire.c ${PM3_ROOT}/client/src/mifare/mfkey.c ${PM3_ROOT}/client/src/mifare/mifare4.c @@ -463,6 +464,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/cmdlfviking.c ${PM3_ROOT}/client/src/cmdlfvisa2000.c ${PM3_ROOT}/client/src/cmdlfzx8211.c + ${PM3_ROOT}/client/src/cmdmad.c ${PM3_ROOT}/client/src/cmdmain.c ${PM3_ROOT}/client/src/cmdmqtt.c ${PM3_ROOT}/client/src/cmdnfc.c diff --git a/client/Makefile b/client/Makefile index 6b24597c0..9b90a0f1c 100644 --- a/client/Makefile +++ b/client/Makefile @@ -805,6 +805,7 @@ SRCS = mifare/aiddesfire.c \ cmdlfviking.c \ cmdlfvisa2000.c \ cmdlfzx8211.c \ + cmdmad.c \ cmdmain.c \ cmdmqtt.c \ cmdnfc.c \ @@ -873,6 +874,7 @@ SRCS = mifare/aiddesfire.c \ mifare/gallaghercore.c \ mifare/gallaghertest.c \ mifare/mad.c \ + mifare/mad_test.c \ mifare/mfkey.c \ mifare/mifare4.c \ mifare/mifaredefault.c \ diff --git a/client/src/cmdhfgallagher.c b/client/src/cmdhfgallagher.c index d8ed2c73f..08ffbec17 100644 --- a/client/src/cmdhfgallagher.c +++ b/client/src/cmdhfgallagher.c @@ -999,19 +999,20 @@ static int hfgal_update_mad(uint8_t cred_sector, uint8_t cad_sector, return res; } - mad1_sector_t *m = (mad1_sector_t *)sector0; - // Set AID for credential sector (0x4812) if (cred_sector >= 1 && cred_sector <= 15) { - mad_aid_set(&m->aid[cred_sector - 1], CLASSIC_CRED_AID); + sector0[16 + 2 + (cred_sector - 1) * 2] = CLASSIC_CRED_AID & 0xFF; + sector0[16 + 2 + (cred_sector - 1) * 2 + 1] = (CLASSIC_CRED_AID >> 8) & 0xFF; } // Set AID for CAD sector (0x4811) if (cad_sector >= 1 && cad_sector <= 15) { - mad_aid_set(&m->aid[cad_sector - 1], CLASSIC_CAD_AID); + sector0[16 + 2 + (cad_sector - 1) * 2] = CLASSIC_CAD_AID & 0xFF; + sector0[16 + 2 + (cad_sector - 1) * 2 + 1] = (CLASSIC_CAD_AID >> 8) & 0xFF; } - m->crc = MADComputeCRC(m); + // Recalculate CRC over bytes 17..47 (info byte + 15 AID entries) + sector0[16] = CRC8Mad(§or0[16 + 1], 15 + 16); // Write blocks 1 and 2 of sector 0 back (block 0 is manufacturer block, don't touch) res = mf_write_block(1, mad_key_type, mad_key, §or0[MFBLOCK_SIZE]); diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index c863021e5..fddfc963c 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -48,6 +48,7 @@ #include "mifare/mifarehost.h" #include "crypto/originality.h" #include "cmdhfmfsen.h" // Mifare Classic Static Nonce +#include "cmdmad.h" // Defines for Saflok parsing #define SAFLOK_YEAR_OFFSET 1980 @@ -703,8 +704,7 @@ void mf_print_blocks(uint16_t n, uint8_t *d, bool verbose) { } // MAD detection - mad_sector_t mad_sec = {d, n * MFBLOCK_SIZE}; - if (HasMADKey(&mad_sec)) { + if (n * MFBLOCK_SIZE >= sizeof(mad1_sector_t) && HasMADKey((const mad1_sector_t *)d)) { PrintAndLogEx(HINT, "Hint: MAD key detected. Try `" _YELLOW_("hf mf mad") "` for more details"); } PrintAndLogEx(NORMAL, ""); @@ -6837,6 +6837,7 @@ static int CmdHF14AMfAuth4(const char *Cmd) { return MifareAuth4(NULL, keyn, key, false, true, false, true, true, false); } + // https://www.nxp.com/docs/en/application-note/AN10787.pdf static int CmdHF14AMfMAD(const char *Cmd) { @@ -6903,18 +6904,30 @@ static int CmdHF14AMfMAD(const char *Cmd) { } // MAD detection - mad_sector_t dump_sec = {dump, bytes_read}; - if ((HasMADKey(&dump_sec) == false) && (force == false)) { + if (bytes_read < sizeof(mad1_sector_t)) { + PrintAndLogEx(FAILED, "Dump file too small for MAD1 (%zu < %zu)", bytes_read, sizeof(mad1_sector_t)); + free(dump); + return PM3_EINVARG; + } + + const mad1_sector_t *s0 = (const mad1_sector_t *)dump; + + if ((HasMADKey(s0) == false) && (force == false)) { PrintAndLogEx(FAILED, "No MAD key was detected in the dump file"); free(dump); return PM3_ESOFT; } + const mad2_sector_t *s16 = NULL; + size_t mad2_off = mfFirstBlockOfSector(MF_MAD2_SECTOR) * MFBLOCK_SIZE; + if (bytes_read >= mad2_off + sizeof(mad2_sector_t)) + s16 = (const mad2_sector_t *)(dump + mad2_off); + MADPrintHeader(); bool haveMAD2 = false; - MAD1DecodeAndPrint(&dump_sec, swapmad, verbose, &haveMAD2); + MAD1DecodeAndPrint(s0, swapmad, verbose, &haveMAD2); - int sector = DetectHID(&dump_sec, 0x484d); + int sector = DetectHID(s0, 0x484d); if (sector > -1) { // decode it @@ -6922,8 +6935,11 @@ static int CmdHF14AMfMAD(const char *Cmd) { PrintAndLogEx(INFO, "------------------------- " _CYAN_("Wiegand") " ---------------------------"); PrintAndLogEx(INFO, _CYAN_("HID PACS detected")); + size_t pacs_off = mfFirstBlockOfSector(sector) * MFBLOCK_SIZE; uint8_t pacs_sector[MFBLOCK_SIZE * 3] = {0}; - memcpy(pacs_sector, dump + (sector * 4 * MFBLOCK_SIZE), sizeof(pacs_sector)); + if (pacs_off + sizeof(pacs_sector) <= bytes_read) { + memcpy(pacs_sector, dump + pacs_off, sizeof(pacs_sector)); + } if (pacs_sector[16] == 0x02) { @@ -6946,26 +6962,20 @@ static int CmdHF14AMfMAD(const char *Cmd) { } } - sector = DetectHID(&dump_sec, 0x4910); + sector = DetectHID(s0, 0x4910); if (sector > -1) { // decode it PrintAndLogEx(INFO, ""); PrintAndLogEx(INFO, _CYAN_("VIGIK PACS detected")); } - if (haveMAD2) { - size_t mad2_off = MIFARE_1K_MAXBLOCK * MF_MAD2_SECTOR; - size_t mad2_len = (bytes_read > mad2_off) ? bytes_read - mad2_off : 0; - mad_sector_t mad2_sec = {dump + mad2_off, mad2_len}; - MAD2DecodeAndPrint(&mad2_sec, swapmad, verbose); + if (haveMAD2 && s16) { + MAD2DecodeAndPrint(s16, swapmad, verbose); } if (aidlen == 2 || decodeholder) { - size_t sector16_off = 0x10 * MIFARE_1K_MAXBLOCK; - size_t sector16_len = (bytes_read > sector16_off) ? bytes_read - sector16_off : 0; - mad_sector_t s16 = {dump + sector16_off, sector16_len}; - mad_t mad = {0}; - if (MADDecode(&dump_sec, &s16, &mad, swapmad, override) != PM3_SUCCESS) { + mad_entry_list_t mad_list = {0}; + if (MADDecode(s0, s16, &mad_list, swapmad, override)) { PrintAndLogEx(ERR, "can't decode MAD"); free(dump); return PM3_ESOFT; @@ -6981,39 +6991,23 @@ static int CmdHF14AMfMAD(const char *Cmd) { uint8_t chdata[MIFARE_4K_MAX_BYTES] = {0}; int chdatalen = 0; - - for (size_t i = 0; i < mad.count; i++) { - if (aaid != mad.entries[i]) + for (size_t i = 0; i < mad_list.len; i++) { + if (aaid != mad_list.entries[i].aid) continue; - - uint8_t sectorNo = i + 1; - size_t sec_off = mfFirstBlockOfSector(sectorNo) * MFBLOCK_SIZE; - uint8_t nblocks = mfNumBlocksPerSector(sectorNo); - size_t sec_size = nblocks * MFBLOCK_SIZE; - - if (sec_off + sec_size > bytes_read) + uint8_t sno = mad_list.entries[i].sector; + size_t sec_off = mfFirstBlockOfSector(sno) * MFBLOCK_SIZE; + size_t data_size = (mfNumBlocksPerSector(sno) - 1) * MFBLOCK_SIZE; + if (sec_off + data_size > bytes_read) continue; - - if (aidlen == 2) { - for (int j = 0; j < (verbose ? nblocks : nblocks - 1); j++) - PrintAndLogEx(INFO, " [%03d] %s", (int)(mfFirstBlockOfSector(sectorNo) + j), sprint_hex(&dump[sec_off + j * MFBLOCK_SIZE], MFBLOCK_SIZE)); - } - - if (decodeholder) { - size_t data_size = (nblocks - 1) * MFBLOCK_SIZE; - if (chdatalen + data_size > sizeof(chdata)) - break; - memcpy(&chdata[chdatalen], dump + sec_off, data_size); - chdatalen += data_size; - } + if ((size_t)chdatalen + data_size > sizeof(chdata)) + break; + memcpy(&chdata[chdatalen], dump + sec_off, data_size); + chdatalen += data_size; } - - if (decodeholder) { - if (chdatalen == 0) { - PrintAndLogEx(WARNING, "no Card Holder Info data"); - } else { - MADCardHolderInfoDecode(chdata, chdatalen, verbose); - } + if (chdatalen > 0) { + MADCardHolderInfoDecode(chdata, chdatalen, verbose); + } else { + PrintAndLogEx(WARNING, "no Card Holder Info data"); } } free(dump); @@ -7024,11 +7018,11 @@ static int CmdHF14AMfMAD(const char *Cmd) { return PM3_ENOTTY; - uint8_t sector0[MFBLOCK_SIZE * 4] = {0}; - uint8_t sector10[MFBLOCK_SIZE * 4] = {0}; + mad1_sector_t sector0 = {0}; + mad2_sector_t mad2_sector = {0}; bool got_first = true; - if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, (uint8_t *)§or0) != PM3_SUCCESS) { PrintAndLogEx(WARNING, "error, read sector 0. card doesn't have MAD or doesn't have MAD on default keys"); got_first = false; } else { @@ -7038,7 +7032,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { // User supplied key if (got_first == false && keylen == 6) { PrintAndLogEx(INFO, "Trying user specified key..."); - if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, userkey, sector0) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, userkey, (uint8_t *)§or0) != PM3_SUCCESS) { PrintAndLogEx(ERR, "error, read sector 0. card doesn't have MAD or the custom key is wrong"); } else { PrintAndLogEx(INFO, "Authentication ( " _GREEN_("ok") " )"); @@ -7052,7 +7046,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { } got_first = true; - if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, (uint8_t *)&mad2_sector) != PM3_SUCCESS) { if (verbose) { PrintAndLogEx(ERR, "error, read sector 0x10. card doesn't have MAD 2 or doesn't have MAD 2 on default keys"); } @@ -7064,7 +7058,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { // User supplied key if (got_first == false && keylen == 6) { PrintAndLogEx(INFO, "Trying user specified key..."); - if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, userkey, sector10) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, userkey, (uint8_t *)&mad2_sector) != PM3_SUCCESS) { if (verbose) { PrintAndLogEx(ERR, "error, read sector 10. card doesn't have MAD 2 or the custom key is wrong"); } @@ -7076,18 +7070,15 @@ static int CmdHF14AMfMAD(const char *Cmd) { MADPrintHeader(); bool haveMAD2 = false; - mad_sector_t s0 = {sector0, sizeof(sector0)}; - MAD1DecodeAndPrint(&s0, swapmad, verbose, &haveMAD2); + MAD1DecodeAndPrint(§or0, swapmad, verbose, &haveMAD2); if (haveMAD2) { - mad_sector_t s10 = {sector10, sizeof(sector10)}; - MAD2DecodeAndPrint(&s10, swapmad, verbose); + MAD2DecodeAndPrint(&mad2_sector, swapmad, verbose); } if (aidlen == 2 || decodeholder) { - mad_sector_t s10 = {sector10, sizeof(sector10)}; - mad_t mad = {0}; - if (MADDecode(&s0, &s10, &mad, swapmad, override) != PM3_SUCCESS) { + mad_entry_list_t mad_list = {0}; + if (MADDecode(§or0, &mad2_sector, &mad_list, swapmad, override)) { PrintAndLogEx(ERR, "can't decode MAD"); return PM3_ESOFT; } @@ -7109,17 +7100,18 @@ static int CmdHF14AMfMAD(const char *Cmd) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "-------------- " _CYAN_("AID 0x%04x") " ---------------", aaid); - for (size_t i = 0; i < mad.count; i++) { - if (aaid == mad.entries[i]) { + for (size_t i = 0; i < mad_list.len; i++) { + if (aaid == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; - if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { + if (mf_read_sector(sno, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(ERR, "error, read sector %d", (int)(i + 1)); + PrintAndLogEx(ERR, "error, read sector %d", sno); return PM3_ESOFT; } for (int j = 0; j < (verbose ? 4 : 3); j ++) - PrintAndLogEx(NORMAL, " [%03d] %s", (int)((i + 1) * 4 + j), sprint_hex(&vsector[j * MFBLOCK_SIZE], MFBLOCK_SIZE)); + PrintAndLogEx(NORMAL, " [%03d] %s", sno * 4 + j, sprint_hex(&vsector[j * MFBLOCK_SIZE], MFBLOCK_SIZE)); } } } @@ -7132,18 +7124,17 @@ static int CmdHF14AMfMAD(const char *Cmd) { uint8_t data[MIFARE_4K_MAX_BYTES] = {0}; int datalen = 0; - for (size_t i = 0; i < mad.count; i++) { - if (aaid == mad.entries[i]) { - + for (size_t i = 0; i < mad_list.len; i++) { + if (aaid == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; - if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { + if (mf_read_sector(sno, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(ERR, "error, read sector %d", (int)(i + 1)); + PrintAndLogEx(ERR, "error, read sector %d", sno); return PM3_ESOFT; } - if (datalen + MFBLOCK_SIZE * 3 > (int)sizeof(data)) - break; + // skip ST block hence only 3 blocks copy memcpy(&data[datalen], vsector, MFBLOCK_SIZE * 3); datalen += MFBLOCK_SIZE * 3; } @@ -7161,13 +7152,13 @@ static int CmdHF14AMfMAD(const char *Cmd) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "------------ " _CYAN_("MAD v1 sector raw") " -------------"); for (int i = 0; i < 4; i ++) { - PrintAndLogEx(INFO, "[%d] %s", i, sprint_hex(§or0[i * MFBLOCK_SIZE], MFBLOCK_SIZE)); + PrintAndLogEx(INFO, "[%d] %s", i, sprint_hex(MF_SECTOR_BLOCK(sector0, i), MFBLOCK_SIZE)); } PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "------------ " _CYAN_("MAD v2 sector raw") " -------------"); for (int i = 0; i < 4; i ++) { - PrintAndLogEx(INFO, "[%d] %s", i, sprint_hex(§or10[i * MFBLOCK_SIZE], MFBLOCK_SIZE)); + PrintAndLogEx(INFO, "[%d] %s", i, sprint_hex(MF_SECTOR_BLOCK(mad2_sector, i), MFBLOCK_SIZE)); } } @@ -7227,8 +7218,8 @@ int CmdHFMFNDEFRead(const char *Cmd) { memcpy(ndefkey, key, 6); } - uint8_t sector0[MFBLOCK_SIZE * 4] = {0}; - uint8_t sector10[MFBLOCK_SIZE * 4] = {0}; + mad1_sector_t sector0 = {0}; + mad2_sector_t mad2_sector = {0}; uint8_t data[4096] = {0}; int datalen = 0; @@ -7236,7 +7227,7 @@ int CmdHFMFNDEFRead(const char *Cmd) { PrintAndLogEx(INFO, "reading MAD v1 sector"); } - if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0)) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, (uint8_t *)§or0)) { PrintAndLogEx(ERR, "error, read sector 0. card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mf ndefread -k `") " with your custom key"); return PM3_ESOFT; @@ -7246,17 +7237,16 @@ int CmdHFMFNDEFRead(const char *Cmd) { PrintAndLogEx(INFO, "reading MAD v2 sector"); } - if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, sector10)) { - if (verbose) { - PrintAndLogEx(ERR, "error, read sector 0x10. card doesn't have MAD 2 or doesn't have MAD 2 on default keys"); - PrintAndLogEx(INFO, "Skipping MAD 2"); - } + const mad2_sector_t *pmad2 = NULL; + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, (uint8_t *)&mad2_sector) == PM3_SUCCESS) { + pmad2 = &mad2_sector; + } else if (verbose) { + PrintAndLogEx(ERR, "error, read sector 0x10. card doesn't have MAD 2 or doesn't have MAD 2 on default keys"); + PrintAndLogEx(INFO, "Skipping MAD 2"); } bool haveMAD2 = false; - mad_sector_t s0 = {sector0, sizeof(sector0)}; - mad_sector_t s10 = {sector10, sizeof(sector10)}; - int res = MADCheck(&s0, &s10, verbose, &haveMAD2); + int res = MADCheck(§or0, pmad2, verbose, &haveMAD2); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "MAD error %d", res); if (override) @@ -7265,19 +7255,20 @@ int CmdHFMFNDEFRead(const char *Cmd) { return res; } - mad_t mad = {0}; - res = MADDecode(&s0, &s10, &mad, false, override); + mad_entry_list_t mad_list = {0}; + res = MADDecode(§or0, pmad2, &mad_list, false, override); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "can't decode MAD"); return res; } PrintAndLogEx(INFO, "reading data from tag"); - for (size_t i = 0; i < mad.count; i++) { - if (ndef_aid == mad.entries[i]) { + for (size_t i = 0; i < mad_list.len; i++) { + if (ndef_aid == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; - if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) { - PrintAndLogEx(ERR, "error, reading sector %d ", i + 1); + if (mf_read_sector(sno, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) { + PrintAndLogEx(ERR, "error, reading sector %d ", sno); return PM3_ESOFT; } @@ -7675,51 +7666,48 @@ int CmdHFMFNDEFWrite(const char *Cmd) { print_buffer(raw, bytes, 0); } - // read MAD Sector 0, block1,2 - uint8_t sector0[MFBLOCK_SIZE * 4] = {0}; - if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0)) { + // read MAD Sector 0 + mad1_sector_t sector0 = {0}; + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, (uint8_t *)§or0)) { PrintAndLogEx(ERR, "error, reading sector 0. Card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mf ndefread -k `") " with your custom key"); return PM3_ESOFT; } - // read MAD Sector 10, block1,2 - uint8_t sector10[MFBLOCK_SIZE * 4] = {0}; + // read MAD Sector 16 + mad2_sector_t mad2_sector = {0}; + const mad2_sector_t *pmad2 = NULL; if (m4) { - if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, sector10)) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, (uint8_t *)&mad2_sector)) { PrintAndLogEx(ERR, "error, reading sector 10. Card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mf ndefread -k `") " with your custom key"); return PM3_ESOFT; } + pmad2 = &mad2_sector; } - // decode MAD v1 - mad_sector_t s0 = {sector0, sizeof(sector0)}; - mad_sector_t s10 = {sector10, sizeof(sector10)}; - mad_t mad = {0}; - res = MADDecode(&s0, &s10, &mad, false, false); + mad_entry_list_t mad_list = {0}; + res = MADDecode(§or0, pmad2, &mad_list, false, false); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "can't decode MAD"); return res; } - // how much memory do I have available ? - // Skip sector 0 since its used for MAD uint8_t freemem[MIFARE_4K_MAXSECTOR] = {0}; uint16_t sum = 0; uint8_t block_no = 0; - for (uint8_t i = 1; i < (mad.count & 0xFF); i++) { + for (size_t i = 0; i < mad_list.len; i++) { + uint8_t sno = mad_list.entries[i].sector; + freemem[sno] = (mad_list.entries[i].aid == NDEF_MFC_AID); - freemem[i] = (mad.entries[i] == NDEF_MFC_AID); - - if (freemem[i]) { + if (freemem[sno]) { if (block_no == 0) { - block_no = mfFirstBlockOfSector(i); + block_no = mfFirstBlockOfSector(sno); } if (verbose) { - PrintAndLogEx(INFO, "Sector %u is NDEF formatted", i); + PrintAndLogEx(INFO, "Sector %u is NDEF formatted", sno); } sum += (MFBLOCK_SIZE * 3); } @@ -8568,16 +8556,17 @@ static int CmdHF14AMfView(const char *Cmd) { mf_save_keys_from_arr(block_cnt, dump); } - mad_sector_t dump_sec = {dump, bytes_read}; - int sector = DetectHID(&dump_sec, 0x4910); + const mad1_sector_t *vigik_s0 = (bytes_read >= sizeof(mad1_sector_t)) + ? (const mad1_sector_t *)dump : NULL; + + int sector = vigik_s0 ? DetectHID(vigik_s0, 0x4910) : -1; if (sector > -1) { // decode it PrintAndLogEx(INFO, ""); PrintAndLogEx(INFO, _CYAN_("VIGIK PACS detected")); - // decode MAD v1 - mad_t mad = {0}; - res = MADDecode(&dump_sec, NULL, &mad, false, true); + mad_entry_list_t mad_list = {0}; + res = MADDecode(vigik_s0, NULL, &mad_list, false, true); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "can't decode MAD"); return res; @@ -8587,7 +8576,6 @@ static int CmdHF14AMfView(const char *Cmd) { uint8_t *bytes; mfc_vigik_t *vigik; } UDATA; - // allocate memory UDATA d; d.bytes = calloc(bytes_read, sizeof(uint8_t)); if (d.bytes == NULL) { @@ -8596,21 +8584,17 @@ static int CmdHF14AMfView(const char *Cmd) { } uint16_t dlen = 0; - // vigik struture sector 0 - uint8_t *pdump = dump; - - memcpy(d.bytes + dlen, pdump, MFBLOCK_SIZE * 3); + // vigik structure sector 0 + memcpy(d.bytes + dlen, dump, MFBLOCK_SIZE * 3); dlen += MFBLOCK_SIZE * 3; - pdump += (MFBLOCK_SIZE * 4); // skip sectortrailer - // extract memory from MAD sectors - for (size_t i = 0; i < mad.count; i++) { - if (0x4910 == mad.entries[i] || 0x4916 == mad.entries[i]) { - memcpy(d.bytes + dlen, pdump, MFBLOCK_SIZE * 3); + for (size_t i = 0; i < mad_list.len; i++) { + if (0x4910 == mad_list.entries[i].aid || 0x4916 == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; + uint32_t offset = sno * MFBLOCK_SIZE * 4; + memcpy(d.bytes + dlen, dump + offset, MFBLOCK_SIZE * 3); dlen += MFBLOCK_SIZE * 3; } - - pdump += (MFBLOCK_SIZE * 4); // skip sectortrailer } // convert_mfc_2_arr(pdump, bytes_read, d, &dlen); @@ -11198,6 +11182,9 @@ static command_t CommandTable[] = { {"info", CmdHF14AMfInfo, IfPm3Iso14443a, "Tag information"}, {"isen", CmdHF14AMfISEN, IfPm3Iso14443a, "Information Static Encrypted Nonces"}, {"mad", CmdHF14AMfMAD, AlwaysAvailable, "Checks and prints MAD"}, + {"madread", CmdMADMFRead, IfPm3Iso14443a, "Read data from MAD AID sectors"}, + {"madwrite", CmdMADMFWrite, IfPm3Iso14443a, "Write data to MAD AID sectors"}, + {"madverify", CmdMADMFVerify, IfPm3Iso14443a, "Verify data in MAD AID sectors"}, {"personalize", CmdHFMFPersonalize, IfPm3Iso14443a, "Personalize UID (MIFARE Classic EV1 only)"}, {"rdbl", CmdHF14AMfRdBl, IfPm3Iso14443a, "Read MIFARE Classic block"}, {"rdsc", CmdHF14AMfRdSc, IfPm3Iso14443a, "Read MIFARE Classic sector"}, diff --git a/client/src/cmdhfmfp.c b/client/src/cmdhfmfp.c index 800b2c404..f4fbc5eca 100644 --- a/client/src/cmdhfmfp.c +++ b/client/src/cmdhfmfp.c @@ -39,6 +39,7 @@ #include "mifare/mifarehost.h" // mf_read_sector (SL1 CRYPTO1) #include "cmdtrace.h" #include "crypto/originality.h" +#include "cmdmad.h" static const uint8_t mfp_default_key[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static uint16_t mfp_card_adresses[] = {0x9000, 0x9001, 0x9002, 0x9003, 0x9004, 0x9006, 0x9007, 0xA000, 0xA001, 0xA080, 0xA081, 0xC000, 0xC001}; @@ -844,9 +845,9 @@ int mfp_data_crypt(mf4Session_t *mf4session, uint8_t *dati, uint8_t *dato, bool } if (rev) { - aes_decode(IV, kenc, dati, dato, MFBLOCK_SIZE * bc); + aes_decode(IV, kenc, dati, dato, MFBLOCK_SIZE*bc); } else { - aes_encode(IV, kenc, dati, dato, MFBLOCK_SIZE * bc); + aes_encode(IV, kenc, dati, dato, MFBLOCK_SIZE*bc); } return PM3_SUCCESS; @@ -2244,10 +2245,10 @@ static int CmdHFMFPDump(const char *Cmd) { int STRead; uint8_t mac[8] = {0}; chunkCycle: - ki_pA[1] = sl3Count * 2; + ki_pA[1] = sl3Count*2; MifareAuth4(&_session, ki_pA, &aesFoundKeys[MF_KEY_A][sl3Count][1], nonfirst, !nonfirst, true, true, verbose, false); nonfirst = true; - MFPReadBlock(&_session, false, false, true, 3 + sl3Count * 4, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, false, false, true, 3+sl3Count*4, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "\nTrailer read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); goto chunkBlank; @@ -2257,17 +2258,17 @@ chunkCycle: } mfp_data_crypt(&_session, &STBuffer[1], &STBuffer[1], true, 1); // Multiblock reads do not allow reading out STs, as such this is the time to save them into the final dump - memcpy(carddata + ((3 + 4 * sl3Count) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); + memcpy(carddata + ((3+4*sl3Count) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); // Check if any block is encrypted only - ki_pB[1] = 0x01+sl3Count * 2; + ki_pB[1] = 0x01+sl3Count*2; MifareAuth4(&_session, ki_pB, &aesFoundKeys[MF_KEY_B][sl3Count][1], true, false, true, true, verbose, false); if (STBuffer[6] & 0xF0) { // At least one bit is set to force enc. only - MFPReadBlock(&_session, false, false, true, sl3Count * 4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, false, false, true, sl3Count*4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { chunkBlank: PrintAndLogEx(ERR, "\nChunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); memcpy(carddata + (sl3Count * 4 * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); - memcpy(carddata + ((3 + 4 * sl3Count) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); + memcpy(carddata + ((3+4*sl3Count) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); PrintAndLogEx(WARNING, "Quick-reading sector %3d / %3d ( " _RED_("fail") " )", sl3Count, numSectors - 1); // Restart auth since a read failure resets it nonfirst = false; @@ -2285,7 +2286,7 @@ chunkBlank: sectorsRead++; sl3Count++; } else { - MFPReadBlock(&_session, true, false, true, sl3Count * 4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, true, false, true, sl3Count*4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Chunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); memcpy(carddata + (sl3Count * 4 * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); @@ -2308,12 +2309,12 @@ chunkCycleClean: - if (numSectors > 32) { + if (numSectors>32){ chunkCycle2: - ki_pA[1] = sl3Count * 2; + ki_pA[1] = sl3Count*2; MifareAuth4(&_session, ki_pA, &aesFoundKeys[MF_KEY_A][sl3Count][1], nonfirst, !nonfirst, true, true, verbose, false); nonfirst = true; - MFPReadBlock(&_session, false, false, true, 128 + (sl3Count - 31) * 16 - 1, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, false, false, true, 128+(sl3Count-31)*16-1, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Trailer read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); goto chunkBlank2; @@ -2324,23 +2325,22 @@ chunkCycle2: } mfp_data_crypt(&_session, &STBuffer[1], &STBuffer[1], true, 1); // Multiblock reads do not allow reading out STs, as such this is the time to save them into the final dump - memcpy(carddata + ((128 + (sl3Count - 31) * 16 - 1) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); + memcpy(carddata + ((128+(sl3Count-31)*16-1) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); int c = 0; // Check if any block is encrypted only - ki_pB[1] = 0x01+sl3Count * 2; + ki_pB[1] = 0x01+sl3Count*2; MifareAuth4(&_session, ki_pB, &aesFoundKeys[MF_KEY_B][sl3Count][1], true, false, true, true, verbose, false); if (STBuffer[6] & 0xF0) { // At least one bit is set to force enc. only chunkBlank2: // Jumping here will start the cycle which will blank out the remaining 5 chunks anyway - for (c = 0; c < 5; ++c) { - MFPReadBlock(&_session, false, false, true, 128 + (sl3Count - 32) * 16 + c * 3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + for (c=0; c<5; ++c) { + MFPReadBlock(&_session, false, false, true, 128+(sl3Count-32)*16+c*3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Chunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); PrintAndLogEx(WARNING, "Quick-reading sector %3d / %3d chunk %d ( " _RED_("fail") " )", sl3Count, numSectors - 1, c); - memcpy(carddata + ((128 + (sl3Count - 31) * 16 - 1) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); - memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); + memcpy(carddata + ((128+(sl3Count-31)*16-1) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); nonfirst = false; - if (c < 5) {continue;} - else {sl3Count++; goto chunkCycleClean2;}; + if (c<5) {continue;} else {sl3Count++; goto chunkCycleClean2;}; } if (STRead != 1 + 48 + 2) { PrintAndLogEx(ERR, "Error return length: %d", STRead); @@ -2349,16 +2349,16 @@ chunkBlank2: // Jumping here will start the cycle which will blank out the remai } mfp_data_crypt(&_session, &STBuffer[1], &STBuffer[1], true, 3); PrintAndLogEx(INPLACE, "Quick-reading sector %3d / %3d ( " _GREEN_("ok") " )", sl3Count, numSectors - 1); - memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); } sectorsRead++; sl3Count++; } else { - for (c = 0; c < 5; ++c) { - MFPReadBlock(&_session, true, false, true, 128 + (sl3Count - 32) * 16 + c * 3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + for (c=0; c<5; ++c) { + MFPReadBlock(&_session, true, false, true, 128+(sl3Count-32)*16+c*3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Chunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); - memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); PrintAndLogEx(WARNING, "Quick-reading sector %3d / %3d ( " _RED_("fail") " )", sl3Count, numSectors - 1); continue; } @@ -2368,8 +2368,8 @@ chunkBlank2: // Jumping here will start the cycle which will blank out the remai return PM3_ESOFT; } PrintAndLogEx(INPLACE, "Quick-reading sector %3d / %3d ( " _GREEN_("ok") " )", sl3Count, numSectors - 1); - memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); - + memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); + } sectorsRead++; sl3Count++; @@ -2446,7 +2446,7 @@ chunkCycleClean2: DropField(); t1 = msclock() - t1; - + // ======================================== // Print sector summary // ======================================== @@ -2547,7 +2547,7 @@ chunkCycleClean2: PrintAndLogEx(HINT, "Partial dump: %d of %d sectors read", sectorsRead, numSectors); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfp chk --dump`") " and/or " _YELLOW_("`hf mf chk`") " to find more keys"); } - + PrintAndLogEx(INFO, "\ntime in dump " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0); free(carddata); return PM3_SUCCESS; @@ -2593,10 +2593,10 @@ static int CmdHFMFPMAD(const char *Cmd) { PrintAndLogEx(WARNING, "Using default MAD keys instead"); } - uint8_t sector0[16 * 4] = {0}; - uint8_t sector16[16 * 4] = {0}; + mad1_sector_t sector0 = {0}; + mad2_sector_t mad2_sector = {0}; - if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector0, verbose)) { + if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, (uint8_t *)§or0, verbose)) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(ERR, "error, read sector 0. card doesn't have MAD or doesn't have MAD on default keys"); return PM3_ESOFT; @@ -2606,29 +2606,28 @@ static int CmdHFMFPMAD(const char *Cmd) { if (verbose) { PrintAndLogEx(SUCCESS, "Raw:"); - for (int i = 0; i < 4; i ++) - PrintAndLogEx(INFO, "[%d] %s", i, sprint_hex(§or0[i * 16], 16)); + for (int i = 0; i < 4; i++) + PrintAndLogEx(INFO, "[%d] %s", i, sprint_hex(MF_SECTOR_BLOCK(sector0, i), MFBLOCK_SIZE)); } bool haveMAD2 = false; - mad_sector_t s0 = {sector0, sizeof(sector0)}; - MAD1DecodeAndPrint(&s0, swapmad, verbose, &haveMAD2); + MAD1DecodeAndPrint(§or0, swapmad, verbose, &haveMAD2); + const mad2_sector_t *pmad2 = NULL; if (haveMAD2) { - if (mfpReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector16, verbose)) { + if (mfpReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, (uint8_t *)&mad2_sector, verbose)) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(ERR, "error, read sector " _YELLOW_("0x10") ". Card doesn't have MAD or doesn't have MAD on default keys"); return PM3_ESOFT; } + pmad2 = &mad2_sector; - mad_sector_t s16 = {sector16, sizeof(sector16)}; - MAD2DecodeAndPrint(&s16, swapmad, verbose); + MAD2DecodeAndPrint(pmad2, swapmad, verbose); } if (aidlen == 2 || decodeholder) { - mad_sector_t s16 = {sector16, sizeof(sector16)}; - mad_t mad = {0}; - if (MADDecode(&s0, &s16, &mad, swapmad, override) != PM3_SUCCESS) { + mad_entry_list_t mad_list = {0}; + if (MADDecode(§or0, pmad2, &mad_list, swapmad, override)) { PrintAndLogEx(ERR, "can't decode MAD"); return PM3_EWRONGANSWER; } @@ -2648,17 +2647,18 @@ static int CmdHFMFPMAD(const char *Cmd) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "-------------- " _CYAN_("AID 0x%04x") " ---------------", aaid); - for (size_t i = 0; i < mad.count; i++) { - if (aaid == mad.entries[i]) { - uint8_t vsector[16 * 4] = {0}; - if (mfpReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector, false)) { + for (size_t i = 0; i < mad_list.len; i++) { + if (aaid == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; + uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; + if (mfpReadSector(sno, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector, false)) { PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(ERR, "error, read sector %d error", (int)(i + 1)); + PrintAndLogEx(ERR, "error, read sector %d error", sno); return PM3_ESOFT; } for (int j = 0; j < (verbose ? 4 : 3); j ++) - PrintAndLogEx(NORMAL, " [%03d] %s", (int)((i + 1) * 4 + j), sprint_hex(&vsector[j * 16], 16)); + PrintAndLogEx(NORMAL, " [%03d] %s", sno * 4 + j, sprint_hex(&vsector[j * 16], 16)); } } } @@ -2671,20 +2671,18 @@ static int CmdHFMFPMAD(const char *Cmd) { uint8_t data[4096] = {0}; int datalen = 0; - for (size_t i = 0; i < mad.count; i++) { - if (aaid == mad.entries[i]) { - - uint8_t vsector[16 * 4] = {0}; - if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { + for (size_t i = 0; i < mad_list.len; i++) { + if (aaid == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; + uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; + if (mf_read_sector(sno, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(ERR, "error, read sector %d", (int)(i + 1)); + PrintAndLogEx(ERR, "error, read sector %d", sno); return PM3_ESOFT; } - if (datalen + MFBLOCK_SIZE * 3 > (int)sizeof(data)) - break; - memcpy(&data[datalen], vsector, MFBLOCK_SIZE * 3); - datalen += MFBLOCK_SIZE * 3; + memcpy(&data[datalen], vsector, 16 * 3); + datalen += 16 * 3; } } @@ -2778,23 +2776,22 @@ int CmdHFMFPNDEFRead(const char *Cmd) { memcpy(ndefkey, key, 16); } - uint8_t sector0[MIFARE_1K_MAXBLOCK] = {0}; - uint8_t sector16[MIFARE_1K_MAXBLOCK] = {0}; + mad1_sector_t sector0 = {0}; + mad2_sector_t mad2_sector = {0}; uint8_t data[MIFARE_4K_MAX_BYTES] = {0}; int datalen = 0; if (verbose) PrintAndLogEx(INFO, "reading MAD v1 sector"); - if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector0, verbose)) { + if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, (uint8_t *)§or0, verbose)) { PrintAndLogEx(ERR, "error, read sector 0. card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfp ndefread -k `") " with your custom key"); return PM3_ESOFT; } bool haveMAD2 = false; - mad_sector_t s0 = {sector0, sizeof(sector0)}; - int res = MADCheck(&s0, NULL, verbose, &haveMAD2); + int res = MADCheck(§or0, NULL, verbose, &haveMAD2); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "MAD error %d", res); if (override) @@ -2803,36 +2800,34 @@ int CmdHFMFPNDEFRead(const char *Cmd) { return res; } + const mad2_sector_t *pmad2 = NULL; if (haveMAD2) { if (verbose) PrintAndLogEx(INFO, "reading MAD v2 sector"); - if (mfpReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector16, verbose)) { + if (mfpReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, (uint8_t *)&mad2_sector, verbose)) { PrintAndLogEx(ERR, "error, read sector 0x10. card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfp ndefread -k `") " with your custom key"); return PM3_ESOFT; } + pmad2 = &mad2_sector; } - mad_sector_t s16 = {0}; - if (haveMAD2) { - s16.data = sector16; - s16.len = sizeof(sector16); - } - mad_t mad = {0}; - res = MADDecode(&s0, haveMAD2 ? &s16 : NULL, &mad, false, override); + mad_entry_list_t mad_list = {0}; + res = MADDecode(§or0, pmad2, &mad_list, false, override); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "can't decode MAD"); return res; } PrintAndLogEx(INFO, "reading data from tag"); - for (size_t i = 0; i < mad.count; i++) { - if (ndefAID == mad.entries[i]) { - uint8_t vsector[MIFARE_1K_MAXBLOCK] = {0}; - if (mfpReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector, false)) { - PrintAndLogEx(ERR, "error, reading sector %d", i + 1); + for (size_t i = 0; i < mad_list.len; i++) { + if (ndefAID == mad_list.entries[i].aid) { + uint8_t sno = mad_list.entries[i].sector; + uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; + if (mfpReadSector(sno, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector, false)) { + PrintAndLogEx(ERR, "error, reading sector %d", sno); return PM3_ESOFT; } @@ -2935,6 +2930,9 @@ static command_t CommandTable[] = { {"dump", CmdHFMFPDump, IfPm3Iso14443a, "Dump MIFARE Plus tag to file"}, {"info", CmdHFMFPInfo, IfPm3Iso14443a, "Tag information"}, {"mad", CmdHFMFPMAD, IfPm3Iso14443a, "Check and print MAD"}, + {"madread", CmdMADMFPRead, IfPm3Iso14443a, "Read data from MAD AID sectors"}, + {"madwrite", CmdMADMFPWrite, IfPm3Iso14443a, "Write data to MAD AID sectors"}, + {"madverify", CmdMADMFPVerify, IfPm3Iso14443a, "Verify data in MAD AID sectors"}, {"rdbl", CmdHFMFPRdbl, IfPm3Iso14443a, "Read blocks from card"}, {"rdsc", CmdHFMFPRdsc, IfPm3Iso14443a, "Read sectors from card"}, {"wrbl", CmdHFMFPWrbl, IfPm3Iso14443a, "Write block to card"}, diff --git a/client/src/cmdmad.c b/client/src/cmdmad.c new file mode 100644 index 000000000..d1898f830 --- /dev/null +++ b/client/src/cmdmad.c @@ -0,0 +1,649 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MAD commands +//----------------------------------------------------------------------------- + +#include "cmdmad.h" +#include +#include "cmdparser.h" +#include "commonutil.h" +#include "comms.h" +#include "ui.h" +#include "cliparser.h" +#include "fileutils.h" +#include "mifare/mad.h" +#include "mifare/mifarehost.h" +#include "mifare/mifare4.h" +#include "mifare/mifaredefault.h" +#include "mifare.h" +#include "crc.h" +#include "util.h" +#include "mifare/mad_test.h" + +// --- Card transport adapters --- + +static int mfc_read_sector(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, uint8_t *buf, bool verbose) { + (void)verbose; + return mf_read_sector(sector_no, key_type, key, buf); +} + +static int mfc_write_sector_data(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, const uint8_t *data, bool verbose) { + (void)verbose; + uint8_t first = mfFirstBlockOfSector(sector_no); + uint8_t ndata = mfNumBlocksPerSector(sector_no) - 1; + for (int i = 0; i < ndata; i++) { + int res = mf_write_block(first + i, key_type, key, data + i * MFBLOCK_SIZE); + if (res != PM3_SUCCESS) + return res; + } + return PM3_SUCCESS; +} + +static int mfp_read_sector(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, uint8_t *buf, bool verbose) { + return mfpReadSector(sector_no, key_type, (uint8_t *)key, buf, verbose); +} + +static int mfp_write_sector_data(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, const uint8_t *data, bool verbose) { + return mfpWriteSector(sector_no, key_type, (uint8_t *)key, data, verbose); +} + +// --- Card type detection --- + +typedef enum { + MAD_CARD_CLASSIC, + MAD_CARD_PLUS, +} mad_card_type_t; + +static int mad_detect_card(mad_card_type_t *out) { + uint8_t sector0[MFBLOCK_SIZE * 4] = {0}; + + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0) == PM3_SUCCESS) { + *out = MAD_CARD_CLASSIC; + return PM3_SUCCESS; + } + + if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector0, false) == PM3_SUCCESS) { + *out = MAD_CARD_PLUS; + return PM3_SUCCESS; + } + + PrintAndLogEx(ERR, "Could not authenticate to MAD sector with default keys (Classic or Plus)"); + return PM3_ESOFT; +} + +static void mad_fill_ops(mad_ops_t *ops, mad_card_type_t card_type, + const uint8_t *mad_key, const uint8_t *app_key, + uint8_t key_type, bool verbose) { + if (card_type == MAD_CARD_CLASSIC) { + ops->read_sector = mfc_read_sector; + ops->write_sector_data = mfc_write_sector_data; + ops->mad_key = mad_key ? mad_key : g_mifare_mad_key; + ops->app_key = app_key ? app_key : g_mifare_ndef_key; + } else { + ops->read_sector = mfp_read_sector; + ops->write_sector_data = mfp_write_sector_data; + ops->mad_key = mad_key ? mad_key : g_mifarep_mad_key; + ops->app_key = app_key ? app_key : g_mifarep_ndef_key; + } + ops->mad_key_type = MF_KEY_A; + ops->app_key_type = key_type; + ops->verbose = verbose; +} + +// Determine card type from key length, or auto-detect +static int mad_resolve_card(int keylen, int madkeylen, mad_card_type_t *out, bool force_classic, bool force_plus) { + if (force_classic) { + *out = MAD_CARD_CLASSIC; + return PM3_SUCCESS; + } + if (force_plus) { + *out = MAD_CARD_PLUS; + return PM3_SUCCESS; + } + if (keylen == AES_KEY_LEN || madkeylen == AES_KEY_LEN) { + *out = MAD_CARD_PLUS; + return PM3_SUCCESS; + } + if (keylen == MIFARE_KEY_SIZE || madkeylen == MIFARE_KEY_SIZE) { + *out = MAD_CARD_CLASSIC; + return PM3_SUCCESS; + } + return mad_detect_card(out); +} + +// --- Shared read/write/verify implementation --- + +static int mad_cmd_read(const char *Cmd, const char *cmd_name, bool force_classic, bool force_plus) { + CLIParserContext *ctx; + CLIParserInit(&ctx, cmd_name, + "Read application data from sectors matching a MAD AID", + "mad read --aid e103 -> read NDEF data (auto-detect card)\n" + "mad read --aid e103 -k ffffffffffff -b -> Classic, key B\n" + "mad read --aid e103 -k d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7 -> Plus\n" + "mad read --aid e103 -v -f mydata.bin -> verbose, save to file"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("v", "verbose", "verbose output"), + arg_str1(NULL, "aid", "", "application ID (2 hex bytes)"), + arg_str0("k", "key", "", "key for data sectors"), + arg_lit0("b", "keyb", "use key B (def: key A)"), + arg_str0(NULL, "mad-key", "", "key for MAD sectors"), + arg_lit0(NULL, "be", "big-endian AID byte swap"), + arg_lit0(NULL, "override", "override failed CRC check"), + arg_str0("f", "file", "", "save raw data to file"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + bool verbose = arg_get_lit(ctx, 1); + uint8_t aid[2] = {0}; + int aidlen = 0; + CLIGetHexWithReturn(ctx, 2, aid, &aidlen); + uint8_t userkey[AES_KEY_LEN] = {0}; + int keylen = 0; + CLIGetHexWithReturn(ctx, 3, userkey, &keylen); + bool keyB = arg_get_lit(ctx, 4); + uint8_t madkey[AES_KEY_LEN] = {0}; + int madkeylen = 0; + CLIGetHexWithReturn(ctx, 5, madkey, &madkeylen); + bool swapmad = arg_get_lit(ctx, 6); + bool override = arg_get_lit(ctx, 7); + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + CLIParserFree(ctx); + + mad_card_type_t card_type; + int res = mad_resolve_card(keylen, madkeylen, &card_type, force_classic, force_plus); + if (res != PM3_SUCCESS) + return res; + + if (verbose) + PrintAndLogEx(INFO, "Using %s transport", card_type == MAD_CARD_CLASSIC ? "MIFARE Classic" : "MIFARE Plus"); + + mad_ops_t ops = {0}; + mad_fill_ops(&ops, card_type, + madkeylen > 0 ? madkey : NULL, + keylen > 0 ? userkey : NULL, + keyB ? MF_KEY_B : MF_KEY_A, verbose); + + uint16_t aaid = (aid[0] << 8) | aid[1]; + uint8_t data[MIFARE_4K_MAX_BYTES] = {0}; + size_t datalen = 0; + res = mad_app_read(&ops, aaid, swapmad, override, data, sizeof(data), &datalen); + if (res != PM3_SUCCESS) + return res; + + PrintAndLogEx(INFO, "read %zu bytes from AID 0x%04X", datalen, aaid); + print_buffer_with_offset(data, datalen, 0, true); + + if (fnlen > 0) + pm3_save_dump(filename, data, datalen, jsfRaw); + + return PM3_SUCCESS; +} + +static int mad_cmd_write(const char *Cmd, const char *cmd_name, bool force_classic, bool force_plus) { + CLIParserContext *ctx; + CLIParserInit(&ctx, cmd_name, + "Write application data to sectors matching a MAD AID", + "mad write --aid e103 -d 0102030405060708 -> write data\n" + "mad write --aid e103 -f mydata.bin -> write from file\n" + "mad write --aid e103 -k ffffffffffff -d 0102030405 -> Classic, custom key"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("v", "verbose", "verbose output"), + arg_str1(NULL, "aid", "", "application ID (2 hex bytes)"), + arg_str0("k", "key", "", "key for data sectors"), + arg_lit0("b", "keyb", "use key B (def: key A)"), + arg_str0(NULL, "mad-key", "", "key for MAD sectors"), + arg_lit0(NULL, "be", "big-endian AID byte swap"), + arg_lit0(NULL, "override", "override failed CRC check"), + arg_str0("d", "data", "", "data to write"), + arg_str0("f", "file", "", "load data from file"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + bool verbose = arg_get_lit(ctx, 1); + uint8_t aid[2] = {0}; + int aidlen = 0; + CLIGetHexWithReturn(ctx, 2, aid, &aidlen); + uint8_t userkey[AES_KEY_LEN] = {0}; + int keylen = 0; + CLIGetHexWithReturn(ctx, 3, userkey, &keylen); + bool keyB = arg_get_lit(ctx, 4); + uint8_t madkey[AES_KEY_LEN] = {0}; + int madkeylen = 0; + CLIGetHexWithReturn(ctx, 5, madkey, &madkeylen); + bool swapmad = arg_get_lit(ctx, 6); + bool override = arg_get_lit(ctx, 7); + uint8_t hexdata[MIFARE_4K_MAX_BYTES] = {0}; + int hexdatalen = 0; + CLIGetHexWithReturn(ctx, 8, hexdata, &hexdatalen); + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 9), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + CLIParserFree(ctx); + + uint8_t *wdata = hexdata; + size_t wdata_len = hexdatalen; + uint8_t *dump = NULL; + + if (fnlen > 0) { + size_t bytes_read = 0; + int res = pm3_load_dump(filename, (void **)&dump, &bytes_read, MIFARE_4K_MAX_BYTES); + if (res != PM3_SUCCESS) + return res; + wdata = dump; + wdata_len = bytes_read; + } + + if (wdata_len == 0) { + PrintAndLogEx(ERR, "no data to write (use -d or -f)"); + free(dump); + return PM3_EINVARG; + } + + mad_card_type_t card_type; + int res = mad_resolve_card(keylen, madkeylen, &card_type, force_classic, force_plus); + if (res != PM3_SUCCESS) { + free(dump); + return res; + } + + if (verbose) + PrintAndLogEx(INFO, "Using %s transport", card_type == MAD_CARD_CLASSIC ? "MIFARE Classic" : "MIFARE Plus"); + + mad_ops_t ops = {0}; + mad_fill_ops(&ops, card_type, + madkeylen > 0 ? madkey : NULL, + keylen > 0 ? userkey : NULL, + keyB ? MF_KEY_B : MF_KEY_A, verbose); + + uint16_t aaid = (aid[0] << 8) | aid[1]; + res = mad_app_write(&ops, aaid, swapmad, override, wdata, wdata_len); + free(dump); + return res; +} + +static int mad_cmd_verify(const char *Cmd, const char *cmd_name, bool force_classic, bool force_plus) { + CLIParserContext *ctx; + CLIParserInit(&ctx, cmd_name, + "Read back and verify application data against expected content", + "mad verify --aid e103 -d 0102030405060708 -> verify data\n" + "mad verify --aid e103 -f mydata.bin -> verify against file"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("v", "verbose", "verbose output"), + arg_str1(NULL, "aid", "", "application ID (2 hex bytes)"), + arg_str0("k", "key", "", "key for data sectors"), + arg_lit0("b", "keyb", "use key B (def: key A)"), + arg_str0(NULL, "mad-key", "", "key for MAD sectors"), + arg_lit0(NULL, "be", "big-endian AID byte swap"), + arg_lit0(NULL, "override", "override failed CRC check"), + arg_str0("d", "data", "", "expected data"), + arg_str0("f", "file", "", "load expected data from file"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + bool verbose = arg_get_lit(ctx, 1); + uint8_t aid[2] = {0}; + int aidlen = 0; + CLIGetHexWithReturn(ctx, 2, aid, &aidlen); + uint8_t userkey[AES_KEY_LEN] = {0}; + int keylen = 0; + CLIGetHexWithReturn(ctx, 3, userkey, &keylen); + bool keyB = arg_get_lit(ctx, 4); + uint8_t madkey[AES_KEY_LEN] = {0}; + int madkeylen = 0; + CLIGetHexWithReturn(ctx, 5, madkey, &madkeylen); + bool swapmad = arg_get_lit(ctx, 6); + bool override = arg_get_lit(ctx, 7); + uint8_t hexdata[MIFARE_4K_MAX_BYTES] = {0}; + int hexdatalen = 0; + CLIGetHexWithReturn(ctx, 8, hexdata, &hexdatalen); + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 9), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + CLIParserFree(ctx); + + uint8_t *edata = hexdata; + size_t edata_len = hexdatalen; + uint8_t *dump = NULL; + + if (fnlen > 0) { + size_t bytes_read = 0; + int res = pm3_load_dump(filename, (void **)&dump, &bytes_read, MIFARE_4K_MAX_BYTES); + if (res != PM3_SUCCESS) + return res; + edata = dump; + edata_len = bytes_read; + } + + if (edata_len == 0) { + PrintAndLogEx(ERR, "no expected data (use -d or -f)"); + free(dump); + return PM3_EINVARG; + } + + mad_card_type_t card_type; + int res = mad_resolve_card(keylen, madkeylen, &card_type, force_classic, force_plus); + if (res != PM3_SUCCESS) { + free(dump); + return res; + } + + if (verbose) + PrintAndLogEx(INFO, "Using %s transport", card_type == MAD_CARD_CLASSIC ? "MIFARE Classic" : "MIFARE Plus"); + + mad_ops_t ops = {0}; + mad_fill_ops(&ops, card_type, + madkeylen > 0 ? madkey : NULL, + keylen > 0 ? userkey : NULL, + keyB ? MF_KEY_B : MF_KEY_A, verbose); + + uint16_t aaid = (aid[0] << 8) | aid[1]; + res = mad_app_verify(&ops, aaid, swapmad, override, edata, edata_len); + free(dump); + return res; +} + +// --- Auto-detect commands (mad read / mad write / mad verify) --- + +static int CmdMADRead(const char *Cmd) { return mad_cmd_read(Cmd, "mad read", false, false); } +static int CmdMADWrite(const char *Cmd) { return mad_cmd_write(Cmd, "mad write", false, false); } +static int CmdMADVerify(const char *Cmd) { return mad_cmd_verify(Cmd, "mad verify", false, false); } + +// --- Card-specific wrappers (for hf mf / hf mfp aliases) --- + +int CmdMADMFRead(const char *Cmd) { return mad_cmd_read(Cmd, "hf mf madread", true, false); } +int CmdMADMFWrite(const char *Cmd) { return mad_cmd_write(Cmd, "hf mf madwrite", true, false); } +int CmdMADMFVerify(const char *Cmd) { return mad_cmd_verify(Cmd, "hf mf madverify", true, false); } +int CmdMADMFPRead(const char *Cmd) { return mad_cmd_read(Cmd, "hf mfp madread", false, true); } +int CmdMADMFPWrite(const char *Cmd) { return mad_cmd_write(Cmd, "hf mfp madwrite", false, true); } +int CmdMADMFPVerify(const char *Cmd) { return mad_cmd_verify(Cmd, "hf mfp madverify", false, true); } + +// --- Decode (offline) --- + +static int CmdMADDecode(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "mad decode", + "Decode a MAD byte array and print the directory", + "mad decode -d -> decode MAD1\n" + "mad decode -d --mad2 -> decode MAD1 + MAD2\n"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("v", "verbose", "verbose output"), + arg_str1("d", "data", "", "MAD1 sector 0 data (64 bytes)"), + arg_str0(NULL, "mad2", "", "MAD2 sector 16 data (64 bytes)"), + arg_lit0(NULL, "be", "big-endian AID byte swap"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + bool verbose = arg_get_lit(ctx, 1); + uint8_t data[MFBLOCK_SIZE * 4] = {0}; + int datalen = 0; + int res = CLIParamHexToBuf(arg_get_str(ctx, 2), data, sizeof(data), &datalen); + uint8_t data2[MFBLOCK_SIZE * 4] = {0}; + int data2len = 0; + int res2 = CLIParamHexToBuf(arg_get_str(ctx, 3), data2, sizeof(data2), &data2len); + bool swapmad = arg_get_lit(ctx, 4); + CLIParserFree(ctx); + if (res) { + PrintAndLogEx(FAILED, "Error parsing MAD1 hex data"); + return PM3_EINVARG; + } + if (data2len > 0 && res2) { + PrintAndLogEx(FAILED, "Error parsing MAD2 hex data"); + return PM3_EINVARG; + } + + if (datalen < (int)sizeof(mad1_sector_t)) { + PrintAndLogEx(ERR, "Need at least %zu bytes for MAD1 (got %d)", sizeof(mad1_sector_t), datalen); + return PM3_EINVARG; + } + + MADPrintHeader(); + bool haveMAD2 = false; + MAD1DecodeAndPrint((const mad1_sector_t *)data, swapmad, verbose, &haveMAD2); + + if (data2len >= (int)sizeof(mad2_sector_t)) { + MAD2DecodeAndPrint((const mad2_sector_t *)data2, swapmad, verbose); + } else if (haveMAD2 && data2len == 0) { + PrintAndLogEx(HINT, "MAD1 indicates v2, use --mad2 to provide sector 16 data"); + } + + return PM3_SUCCESS; +} + +// --- Encode --- + +// parse "1-3,5,7-9" into sector numbers, returns count or -1 on error +static int parse_sector_ranges(const char *str, uint8_t *sectors, int max_sectors) { + int count = 0; + const char *p = str; + + while (*p) { + while (*p == ' ' || *p == '\t') p++; + if (*p == '\0') break; + + char *end = NULL; + long start = strtol(p, &end, 10); + if (end == p || start < 0 || start > 39) + return -1; + + long stop = start; + if (*end == '-') { + p = end + 1; + stop = strtol(p, &end, 10); + if (end == p || stop < start || stop > 39) + return -1; + } + + for (long s = start; s <= stop; s++) { + if (s == 0 || s == 16) { + PrintAndLogEx(ERR, "Sector %ld is reserved for MAD directory", s); + return -1; + } + if (count >= max_sectors) + return -1; + sectors[count++] = (uint8_t)s; + } + + p = end; + if (*p == ',') p++; + } + return count; +} + +static int CmdMADEncode(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "mad encode", + "Encode a MAD byte array from AID-to-sector mappings", + "mad encode --aid E103:1-3 --aid 484D:4 -> MAD1 with NDEF + HID\n" + "mad encode --aid E103:1-3,5 -> non-contiguous sectors\n" + "mad encode --aid E103:1-3,17-18 --aid 484D:4 -> MAD1 + MAD2\n" + "mad encode --aid E103:1-3 -q -> quiet, hex only\n"); + + void *argtable[] = { + arg_param_begin, + arg_strn(NULL, "aid", "", 1, 8, "AID and sector ranges (e.g. E103:1-3,5)"), + arg_lit0("q", "quiet", "quiet output, hex bytes only"), + arg_lit0(NULL, "be", "big-endian AID byte swap"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + int aid_count = 0; + struct arg_str *aid_arg = arg_get_str(ctx, 1); + aid_count = aid_arg->count; + + uint16_t sector_aids[40] = {0}; + bool have_mad2 = false; + + for (int a = 0; a < aid_count; a++) { + const char *val = aid_arg->sval[a]; + + const char *colon = strchr(val, ':'); + if (colon == NULL) { + PrintAndLogEx(ERR, "Invalid format '%s', expected : (e.g. E103:1-3)", val); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + int aid_hex_len = colon - val; + if (aid_hex_len != 4) { + PrintAndLogEx(ERR, "AID must be 4 hex chars, got %d in '%s'", aid_hex_len, val); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + char aid_str[5] = {0}; + memcpy(aid_str, val, 4); + uint16_t aid_val = (uint16_t)strtoul(aid_str, NULL, 16); + + uint8_t sectors[40] = {0}; + int nsectors = parse_sector_ranges(colon + 1, sectors, 40); + if (nsectors <= 0) { + PrintAndLogEx(ERR, "Invalid sector range in '%s'", val); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + for (int s = 0; s < nsectors; s++) { + uint8_t sno = sectors[s]; + if (sector_aids[sno] != 0) { + PrintAndLogEx(ERR, "Sector %d already assigned to AID 0x%04X", sno, sector_aids[sno]); + CLIParserFree(ctx); + return PM3_EINVARG; + } + sector_aids[sno] = aid_val; + if (sno > 15) have_mad2 = true; + } + } + + bool quiet = arg_get_lit(ctx, 2); + bool swapmad = arg_get_lit(ctx, 3); + CLIParserFree(ctx); + + // build MAD1 + mad1_sector_t s0; + memset(&s0, 0, sizeof(s0)); + s0.mad.info = 0x00; + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + uint16_t a = sector_aids[i + 1]; + s0.mad.aid[i] = swapmad ? BSWAP_16(a) : a; + } + s0.mad.crc = CRC8Mad((uint8_t *)&s0.mad.info, sizeof(mad1_t) - 1); + memcpy(s0.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s0.trailer.access[0] = 0x78; + s0.trailer.access[1] = 0x77; + s0.trailer.access[2] = 0x88; + s0.trailer.gpb = have_mad2 ? 0xC2 : 0xC1; // DA=1, MA=1, version + memcpy(s0.trailer.key_b, g_mifare_mad_key_b, MIFARE_KEY_SIZE); + + // build MAD2 if needed + mad2_sector_t s16; + memset(&s16, 0, sizeof(s16)); + if (have_mad2) { + s16.mad.info = 0x00; + for (int i = 0; i < MAD2_NUM_AIDS; i++) { + uint16_t a = sector_aids[i + 17]; + s16.mad.aid[i] = swapmad ? BSWAP_16(a) : a; + } + s16.mad.crc = CRC8Mad((uint8_t *)&s16.mad.info, sizeof(mad2_t) - 1); + memcpy(s16.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s16.trailer.access[0] = 0x78; + s16.trailer.access[1] = 0x77; + s16.trailer.access[2] = 0x88; + s16.trailer.gpb = 0xC2; + memcpy(s16.trailer.key_b, g_mifare_mad_key_b, MIFARE_KEY_SIZE); + } + + if (!quiet) { + MADPrintHeader(); + bool dummy = false; + MAD1DecodeAndPrint(&s0, swapmad, false, &dummy); + if (have_mad2) { + MAD2DecodeAndPrint(&s16, swapmad, false); + } + PrintAndLogEx(NORMAL, ""); + } + + PrintAndLogEx(SUCCESS, "MAD1 sector (64 bytes):"); + PrintAndLogEx(SUCCESS, "%s", sprint_hex_inrow((const uint8_t *)&s0, sizeof(s0))); + + if (have_mad2) { + PrintAndLogEx(SUCCESS, "MAD2 sector (64 bytes):"); + PrintAndLogEx(SUCCESS, "%s", sprint_hex_inrow((const uint8_t *)&s16, sizeof(s16))); + } + + return PM3_SUCCESS; +} + +// --- Command table --- + +static int CmdMADTest(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "mad test", + "Run MAD regression tests (offline, no card needed)", + "mad test\n" + "mad test -v -> verbose output"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("v", "verbose", "verbose output"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool verbose = arg_get_lit(ctx, 1); + CLIParserFree(ctx); + + return exec_mad_test(verbose); +} + +static int CmdHelp(const char *Cmd); + +static command_t CommandTable[] = { + {"--------", CmdHelp, AlwaysAvailable, "--------------- " _CYAN_("MAD") " -----------------"}, + {"read", CmdMADRead, IfPm3Iso14443a, "Read data from MAD AID sectors"}, + {"write", CmdMADWrite, IfPm3Iso14443a, "Write data to MAD AID sectors"}, + {"verify", CmdMADVerify, IfPm3Iso14443a, "Verify data in MAD AID sectors"}, + {"--------", CmdHelp, AlwaysAvailable, "------------- " _CYAN_("General") " ---------------"}, + {"help", CmdHelp, AlwaysAvailable, "This help"}, + {"decode", CmdMADDecode, AlwaysAvailable, "Decode MAD byte array"}, + {"encode", CmdMADEncode, AlwaysAvailable, "Encode MAD byte array from AID mappings"}, + {"test", CmdMADTest, AlwaysAvailable, "Run MAD regression tests"}, + {NULL, NULL, NULL, NULL} +}; + +int CmdMAD(const char *Cmd) { + clearCommandBuffer(); + return CmdsParse(CommandTable, Cmd); +} + +static int CmdHelp(const char *Cmd) { + (void)Cmd; + CmdsHelp(CommandTable); + return PM3_SUCCESS; +} diff --git a/client/src/cmdmad.h b/client/src/cmdmad.h new file mode 100644 index 000000000..a6202c351 --- /dev/null +++ b/client/src/cmdmad.h @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MAD commands +//----------------------------------------------------------------------------- + +#ifndef CMDMAD_H__ +#define CMDMAD_H__ + +#include "common.h" + +int CmdMAD(const char *Cmd); + +int CmdMADMFRead(const char *Cmd); +int CmdMADMFWrite(const char *Cmd); +int CmdMADMFVerify(const char *Cmd); +int CmdMADMFPRead(const char *Cmd); +int CmdMADMFPWrite(const char *Cmd); +int CmdMADMFPVerify(const char *Cmd); + +#endif diff --git a/client/src/cmdmain.c b/client/src/cmdmain.c index 21dd08180..a6e5d5403 100644 --- a/client/src/cmdmain.c +++ b/client/src/cmdmain.c @@ -32,6 +32,7 @@ #include "cmddata.h" #include "cmdhw.h" #include "cmdlf.h" +#include "cmdmad.h" #include "cmdnfc.h" #include "cmdtrace.h" #include "cmdscript.h" @@ -345,6 +346,7 @@ static command_t CommandTable[] = { {"hf", CmdHF, AlwaysAvailable, "{ High frequency commands... }"}, {"hw", CmdHW, AlwaysAvailable, "{ Hardware commands... }"}, {"lf", CmdLF, AlwaysAvailable, "{ Low frequency commands... }"}, + {"mad", CmdMAD, AlwaysAvailable, "{ MAD commands... }"}, {"mem", CmdFlashMem, IfPm3Flash, "{ Flash memory manipulation... }"}, {"mqtt", CmdMqtt, AlwaysAvailable, "{ MQTT commmands... }"}, {"nfc", CmdNFC, AlwaysAvailable, "{ NFC commands... }"}, diff --git a/client/src/cmdnfc.c b/client/src/cmdnfc.c index 53d631c1d..fe58e5aba 100644 --- a/client/src/cmdnfc.c +++ b/client/src/cmdnfc.c @@ -138,13 +138,18 @@ static int CmdNfcDecode(const char *Cmd) { } else { // convert from MFC dump file to a pure NDEF byte array - mad_sector_t s = {tmp, bytes_read}; - if (HasMADKey(&s)) { + if (bytes_read >= sizeof(mad1_sector_t) && HasMADKey((const mad1_sector_t *)tmp)) { PrintAndLogEx(SUCCESS, "MFC dump file detected. Converting..."); uint8_t ndef[4096] = {0}; size_t ndeflen = 0; - if (convert_mad_to_arr(tmp, bytes_read, ndef, &ndeflen, sizeof(ndef), override) != PM3_SUCCESS) { + const mad1_sector_t *s0 = (const mad1_sector_t *)tmp; + const mad2_sector_t *s16 = NULL; + size_t mad2_off = mfFirstBlockOfSector(MF_MAD2_SECTOR) * MFBLOCK_SIZE; + if (bytes_read >= mad2_off + sizeof(mad2_sector_t)) + s16 = (const mad2_sector_t *)(tmp + mad2_off); + + if (convert_mad_to_arr(s0, s16, bytes_read, ndef, sizeof(ndef), &ndeflen, override) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed converting, aborting..."); free(dump); return PM3_ESOFT; diff --git a/client/src/mifare/gallaghertest.c b/client/src/mifare/gallaghertest.c index aff545b41..27508399b 100644 --- a/client/src/mifare/gallaghertest.c +++ b/client/src/mifare/gallaghertest.c @@ -4,7 +4,6 @@ #include // memcpy memset #include "ui.h" #include "crc.h" -#include "mad.h" #include "mifare/gallaghercore.h" @@ -138,9 +137,9 @@ static bool test_mad_crc(void) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x77, 0x88, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; - const mad1_sector_t *m = (const mad1_sector_t *)sector0; - uint8_t expected_crc = m->crc; - uint8_t computed_crc = MADComputeCRC(m); + // MAD v1 CRC: computed over sector0[17..47] (info byte + 15 AID pairs = 31 bytes) + uint8_t expected_crc = sector0[16]; // 0xBD + uint8_t computed_crc = CRC8Mad(§or0[16 + 1], 15 + 16); if (computed_crc != expected_crc) { PrintAndLogEx(INFO, "MAD CRC test failed: expected 0x%02X, got 0x%02X", expected_crc, computed_crc); return false; diff --git a/client/src/mifare/mad.c b/client/src/mifare/mad.c index 29da3c112..1be9fa605 100644 --- a/client/src/mifare/mad.c +++ b/client/src/mifare/mad.c @@ -18,7 +18,7 @@ #include "mad.h" #include "ui.h" -#include "commonutil.h" // ARRAYLEN +#include "commonutil.h" // ARRAYLEN, BSWAP_16 #include "pm3_cmd.h" #include "crc.h" #include "util.h" @@ -26,10 +26,7 @@ #include "jansson.h" #include "mifaredefault.h" #include "mifare4.h" - -// Compile-time size sanity checks (force a build error if the structs don't match a 4-block sector). -typedef char mad_assert_mad1[sizeof(mad1_sector_t) == MFBLOCK_SIZE * 4 ? 1 : -1]; -typedef char mad_assert_mad2[sizeof(mad2_sector_t) == MFBLOCK_SIZE * 4 ? 1 : -1]; +#include "mifare.h" // MF_MAD1_SECTOR, MF_MAD2_SECTOR // https://www.nxp.com/docs/en/application-note/AN10787.pdf static json_t *mad_known_aids = NULL; @@ -50,10 +47,6 @@ static const char *aid_admin[] = { "not applicable" }; -// --------------------------------------------------------------------------- -// JSON helpers -// --------------------------------------------------------------------------- - static int open_mad_file(json_t **root, bool verbose) { char *path; int res = searchFile(&path, RESOURCES_SUBDIR, "mad", ".json", true); @@ -73,6 +66,8 @@ static int open_mad_file(json_t **root, bool verbose) { if (!json_is_array(*root)) { PrintAndLogEx(ERR, "Invalid json (%s) format. root must be an array.", path); + json_decref(*root); + *root = NULL; retval = PM3_ESOFT; goto out; } @@ -111,210 +106,148 @@ static const char *mad_json_get_str(json_t *data, const char *name) { return cstr; } -static int print_aid_description(json_t *root, uint16_t aid, char *fmt, bool verbose) { - if (root == NULL || fmt == NULL) { - return PM3_EINVARG; - } +static uint16_t madGetAID(uint16_t raw, bool swapmad) { + return swapmad ? BSWAP_16(raw) : raw; +} +static json_t *mad_lookup_aid(json_t *root, uint16_t aid) { char lmad[7] = {0}; - snprintf(lmad, sizeof(lmad), "0x%04x", aid); // must be lowercase - - json_t *elm = NULL; + snprintf(lmad, sizeof(lmad), "0x%04x", aid); for (uint32_t idx = 0; idx < json_array_size(root); idx++) { json_t *data = json_array_get(root, idx); if (!json_is_object(data)) { - PrintAndLogEx(ERR, "data [%u] is not an object", idx); + PrintAndLogEx(ERR, "data [%d] is not an object\n", idx); continue; } const char *fmad = mad_json_get_str(data, "mad"); if (fmad == NULL) continue; - char lfmad[16]; - strncpy(lfmad, fmad, sizeof(lfmad) - 1); - lfmad[sizeof(lfmad) - 1] = '\0'; + char lfmad[strlen(fmad) + 1]; + strcpy(lfmad, fmad); str_lower(lfmad); if (strcmp(lmad, lfmad) == 0) { - elm = data; - break; + return data; } } + return NULL; +} - if (elm == NULL) { - PrintAndLogEx(INFO, fmt, " (unknown)"); - return PM3_ENODATA; +static const char *mad_aid_description(json_t *elm) { + static char result[256]; + const char *application = mad_json_get_str(elm, "application"); + const char *company = mad_json_get_str(elm, "company"); + if (application && company) { + snprintf(result, sizeof(result), " %s [%s]", application, company); + } else if (application) { + snprintf(result, sizeof(result), " %s", application); + } else { + snprintf(result, sizeof(result), " (unknown)"); } + return result; +} +static void mad_print_aid_verbose(json_t *elm) { const char *vmad = mad_json_get_str(elm, "mad"); const char *application = mad_json_get_str(elm, "application"); const char *company = mad_json_get_str(elm, "company"); const char *provider = mad_json_get_str(elm, "service_provider"); const char *integrator = mad_json_get_str(elm, "system_integrator"); - if (application && company) { - char result[512]; - snprintf(result, sizeof(result), " %s [%s]", application, company); - PrintAndLogEx(INFO, fmt, result); + PrintAndLogEx(SUCCESS, " MAD................. %s", vmad); + if (application) { + PrintAndLogEx(SUCCESS, " Application......... %s", application); } + if (company) { + PrintAndLogEx(SUCCESS, " Company............. %s", company); + } + if (provider) { + PrintAndLogEx(SUCCESS, " Service provider.... %s", provider); + } + if (integrator) { + PrintAndLogEx(SUCCESS, " System integrator... %s", integrator); + } +} - if (verbose) { - PrintAndLogEx(SUCCESS, " MAD................. %s", vmad ? vmad : "n/a"); - if (application) { - PrintAndLogEx(SUCCESS, " Application......... %s", application); - } - if (company) { - PrintAndLogEx(SUCCESS, " Company............. %s", company); - } - if (provider) { - PrintAndLogEx(SUCCESS, " Service provider.... %s", provider); - } - if (integrator) { - PrintAndLogEx(SUCCESS, " System integrator... %s", integrator); - } +static int mad1CRCCheck(const mad1_t *mad1, bool verbose) { + uint8_t crc = CRC8Mad((uint8_t *)&mad1->info, sizeof(mad1_t) - 1); + if (crc != mad1->crc) { + PrintAndLogEx(WARNING, _RED_("Wrong MAD 1 CRC") " calculated: 0x%02x != 0x%02x", crc, mad1->crc); + return PM3_ESOFT; } return PM3_SUCCESS; } -// --------------------------------------------------------------------------- -// Low-level MAD sector parsing -// --------------------------------------------------------------------------- - -static bool mad_sector_valid(const mad_sector_t *sector) { - return sector != NULL && sector->data != NULL && sector->len >= sizeof(mad1_sector_t); -} - -static int madCRCCheck(const mad_sector_t *sector, int mad_ver) { - if (!mad_sector_valid(sector)) { - return PM3_EINVARG; - } - - if (mad_ver == 1) { - const mad1_sector_t *m = (const mad1_sector_t *)sector->data; - uint8_t crc = MADComputeCRC(m); - if (crc != m->crc) { - PrintAndLogEx(WARNING, _RED_("Wrong MAD %d CRC") " calculated: 0x%02x != 0x%02x", mad_ver, crc, m->crc); - return PM3_ESOFT; - } - } else { - const mad2_sector_t *m = (const mad2_sector_t *)sector->data; - uint8_t crc = MADComputeCRC(m); - if (crc != m->crc) { - PrintAndLogEx(WARNING, _RED_("Wrong MAD %d CRC") " calculated: 0x%02x != 0x%02x", mad_ver, crc, m->crc); - return PM3_ESOFT; - } +static int mad2CRCCheck(const mad2_t *mad2, bool verbose) { + uint8_t crc = CRC8Mad((uint8_t *)&mad2->info, sizeof(mad2_t) - 1); + if (crc != mad2->crc) { + PrintAndLogEx(WARNING, _RED_("Wrong MAD 2 CRC") " calculated: 0x%02x != 0x%02x", crc, mad2->crc); + return PM3_ESOFT; } return PM3_SUCCESS; } -static uint16_t madGetAID(const mad_sector_t *sector, bool swapmad, int mad_ver, int sector_no) { - if (!mad_sector_valid(sector)) { - return 0; - } - - const mad_aid_t *aid = NULL; - - if (mad_ver == 1) { - const mad1_sector_t *m = (const mad1_sector_t *)sector->data; - if (sector_no >= 1 && sector_no <= 15) - aid = &m->aid[sector_no - 1]; - else - return 0; - } else { - const mad2_sector_t *m = (const mad2_sector_t *)sector->data; - if (sector_no >= 1 && sector_no <= 23) - aid = &m->aid[sector_no - 1]; - else - return 0; - } - - uint16_t val = mad_aid_get(aid); - return swapmad ? BSWAP_16(val) : val; -} - -static int MADInfoByteDecode(const mad_sector_t *sector, int mad_ver, bool verbose) { - if (!mad_sector_valid(sector)) { - return PM3_EINVARG; - } - - uint8_t info; - if (mad_ver == 1) { - const mad1_sector_t *m = (const mad1_sector_t *)sector->data; - info = m->info & 0x3f; - if (info >= 0x10) { - PrintAndLogEx(WARNING, "Invalid Info byte (MAD1) value " _YELLOW_("0x%02x"), info); - if (verbose) { - PrintAndLogEx(WARNING, "MAD1 Info byte points outside of MAD1 sector space (0x%02x), report a bug?", info); - } - return PM3_ESOFT; - } - } else { - const mad2_sector_t *m = (const mad2_sector_t *)sector->data; - info = m->info & 0x3f; - if (info == 0x10 || info >= 0x28) { - PrintAndLogEx(WARNING, "Invalid Info byte (MAD2) value " _YELLOW_("0x%02x"), info); - return PM3_ESOFT; +static int MADInfoByteDecode(uint8_t info, int mad_ver, bool verbose) { + info &= MAD_INFO_MASK; + if (mad_ver == 1 && info >= 0xF) { + PrintAndLogEx(WARNING, "Invalid Info byte (MAD1) value " _YELLOW_("0x%02x"), info); + if (verbose) { + PrintAndLogEx(WARNING, "MAD1 Info byte points outside of MAD1 sector space (0x%02x)", info); } + return PM3_ESOFT; + } + if (mad_ver == 2 && (info == 0x10 || info >= 0x28)) { + PrintAndLogEx(WARNING, "Invalid Info byte (MAD2) value " _YELLOW_("0x%02x"), info); + return PM3_ESOFT; } - return info; } -// --------------------------------------------------------------------------- -// Public API -// --------------------------------------------------------------------------- - -int MADCheck(const mad_sector_t *sector0, const mad_sector_t *sector16, bool verbose, bool *haveMAD2) { - if (!mad_sector_valid(sector0)) { +int MADCheck(const mad1_sector_t *sector0, const mad2_sector_t *mad2, bool verbose, bool *haveMAD2) { + if (sector0 == NULL) return PM3_EINVARG; - } - - const mad1_sector_t *m1 = (const mad1_sector_t *)sector0->data; - uint8_t GPB = m1->gpb; + uint8_t GPB = sector0->trailer.gpb; if (verbose) { PrintAndLogEx(SUCCESS, "GPB....... " _GREEN_("0x%02X"), GPB); } - // DA (MAD available) - if ((GPB & 0x80) == 0x00) { + if ((GPB & MAD_GPB_DA_MASK) == 0x00) { PrintAndLogEx(ERR, "DA = 0! MAD not available"); return PM3_ESOFT; } - uint8_t mad_ver = (GPB & 0x03); + uint8_t mad_ver = (GPB & MAD_GPB_VER_MASK); if (verbose) PrintAndLogEx(SUCCESS, "Version... " _GREEN_("%d"), mad_ver); - // MAD version if ((mad_ver != 0x01) && (mad_ver != 0x02)) { PrintAndLogEx(ERR, "Wrong MAD version " _RED_("0x%02X"), mad_ver); return PM3_ESOFT; - } + }; - bool mad2_available = (mad_ver == 2) && mad_sector_valid(sector16); if (haveMAD2) { - *haveMAD2 = mad2_available; + *haveMAD2 = (mad_ver == 2); } - int res = madCRCCheck(sector0, 1); + int res = mad1CRCCheck(§or0->mad, true); if (verbose && res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( %s )", m1->crc, _GREEN_("ok")); + PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( %s )", sector0->mad.crc, _GREEN_("ok")); } - if (mad2_available) { - int res2 = madCRCCheck(sector16, 2); + if (mad_ver == 2 && mad2) { + int res2 = mad2CRCCheck(&mad2->mad, true); if (res == PM3_SUCCESS) { res = res2; } - if (verbose && res2 == PM3_SUCCESS) { - const mad2_sector_t *m2 = (const mad2_sector_t *)sector16->data; - PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( %s )", m2->crc, _GREEN_("ok")); + + if (verbose && !res2) { + PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( %s )", mad2->mad.crc, _GREEN_("ok")); } } - // MA (multi-application card) if (verbose) { - if (GPB & 0x40) + if (GPB & MAD_GPB_MA_MASK) PrintAndLogEx(SUCCESS, "Multi application card"); else PrintAndLogEx(SUCCESS, "Single application card"); @@ -322,21 +255,10 @@ int MADCheck(const mad_sector_t *sector0, const mad_sector_t *sector16, bool ver return res; } -int MADDecode(const mad_sector_t *sector0, const mad_sector_t *sector16, mad_t *out, bool swapmad, bool override) { - if (out == NULL) { - return PM3_EINVARG; - } - - memset(out, 0, sizeof(mad_t)); - +int MADDecode(const mad1_sector_t *sector0, const mad2_sector_t *mad2, mad_entry_list_t *mad_list, bool swapmad, bool override) { + mad_list->len = 0; bool haveMAD2 = false; - int res = MADCheck(sector0, sector16, false, &haveMAD2); - out->has_mad2 = haveMAD2; - - if (mad_sector_valid(sector0)) { - const mad1_sector_t *m1 = (const mad1_sector_t *)sector0->data; - out->gpb = m1->gpb; - } + int res = MADCheck(sector0, mad2, false, &haveMAD2); if (res != PM3_SUCCESS && override == false) { PrintAndLogEx(WARNING, "Not a valid MAD"); @@ -347,41 +269,27 @@ int MADDecode(const mad_sector_t *sector0, const mad_sector_t *sector16, mad_t * PrintAndLogEx(INFO, "overriding crc check"); } - out->crc1_ok = (madCRCCheck(sector0, 1) == PM3_SUCCESS); - - for (int i = 1; i <= MAD1_AID_COUNT; i++) { - if (out->count >= MAD_MAX_AID_ENTRIES) - break; - out->entries[out->count++] = madGetAID(sector0, swapmad, 1, i); + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + mad_list->entries[mad_list->len].sector = i + 1; + mad_list->entries[mad_list->len].aid = madGetAID(sector0->mad.aid[i], swapmad); + mad_list->len++; } - if (haveMAD2) { - out->crc2_ok = (madCRCCheck(sector16, 2) == PM3_SUCCESS); - - if (out->count >= MAD_MAX_AID_ENTRIES) - return PM3_ESOFT; - - // MAD2 sector marker - out->entries[out->count++] = 0x0005; - - for (int i = 1; i <= MAD2_AID_COUNT; i++) { - if (out->count >= MAD_MAX_AID_ENTRIES) - break; - out->entries[out->count++] = madGetAID(sector16, swapmad, 2, i); + if (haveMAD2 && mad2) { + for (int i = 0; i < MAD2_NUM_AIDS; i++) { + mad_list->entries[mad_list->len].sector = i + 17; + mad_list->entries[mad_list->len].aid = madGetAID(mad2->mad.aid[i], swapmad); + mad_list->len++; } } return PM3_SUCCESS; } int MADCardHolderInfoDecode(const uint8_t *data, size_t datalen, bool verbose) { - if (data == NULL) { - return PM3_EINVARG; - } - size_t idx = 0; while (idx < datalen) { - uint8_t len = data[idx] & 0x3f; - uint8_t type = data[idx] >> 6; + uint8_t len = data[idx] & MAD_TLV_LEN_MASK; + uint8_t type = data[idx] >> MAD_TLV_TYPE_SHIFT; idx++; if (len == 0) break; @@ -389,11 +297,8 @@ int MADCardHolderInfoDecode(const uint8_t *data, size_t datalen, bool verbose) { PrintAndLogEx(WARNING, "Card holder info truncated (need %u bytes, %zu available)", len, datalen - idx); break; } - if (type >= ARRAYLEN(holder_info_type)) { - PrintAndLogEx(WARNING, "Unknown card holder info type %u", type); - idx += len; - continue; - } + if (type >= ARRAYLEN(holder_info_type)) + type = ARRAYLEN(holder_info_type) - 1; PrintAndLogEx(INFO, "%14s " _GREEN_("%.*s"), holder_info_type[type], len, &data[idx]); idx += len; } @@ -405,28 +310,17 @@ void MADPrintHeader(void) { PrintAndLogEx(INFO, "--- " _CYAN_("MIFARE App Directory Information") " ----------------"); } -int MAD1DecodeAndPrint(const mad_sector_t *sector, bool swapmad, bool verbose, bool *haveMAD2) { - if (!mad_sector_valid(sector)) { - return PM3_EINVARG; - } - - int res = open_mad_file(&mad_known_aids, verbose); - if (res != PM3_SUCCESS) { - mad_known_aids = NULL; +int MAD1DecodeAndPrint(const mad1_sector_t *sector, bool swapmad, bool verbose, bool *haveMAD2) { + if (open_mad_file(&mad_known_aids, verbose) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Could not load MAD JSON, AID names will not be resolved"); } PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "------------ " _CYAN_("MAD v1 details") " -------------"); - // check MAD1 only MADCheck(sector, NULL, verbose, haveMAD2); - int ibs = MADInfoByteDecode(sector, 1, verbose); - if (ibs < 0) { - close_mad_file(mad_known_aids); - mad_known_aids = NULL; - return ibs; - } + int ibs = MADInfoByteDecode(sector->mad.info, 1, verbose); if (ibs > 0) { PrintAndLogEx(SUCCESS, "Card publisher sector " _MAGENTA_("0x%02X"), ibs); @@ -439,71 +333,59 @@ int MAD1DecodeAndPrint(const mad_sector_t *sector, bool swapmad, bool verbose, b PrintAndLogEx(INFO, " 00 MAD v1"); uint32_t prev_aid = 0xFFFFFFFF; - for (int i = 1; i <= MAD1_AID_COUNT; i++) { - uint16_t aid = madGetAID(sector, swapmad, 1, i); - if (aid < ARRAYLEN(aid_admin)) { + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + int sector_no = i + 1; + uint16_t aid = madGetAID(sector->mad.aid[i], swapmad); + if (aid <= MAD_AID_ADMIN_MAX) { PrintAndLogEx(INFO, - (ibs == i) ? _MAGENTA_(" %02d [%04X] %s") : " %02d [" _GREEN_("%04X") "] %s", - i, + (ibs == sector_no) ? _MAGENTA_(" %02d [%04X] %s") : " %02d [" _GREEN_("%04X") "] %s", + sector_no, aid, aid_admin[aid] ); } else if (prev_aid == aid) { PrintAndLogEx(INFO, - (ibs == i) ? _MAGENTA_(" %02d [%04X] continuation") : " %02d [" _YELLOW_("%04X") "] continuation", - i, + (ibs == sector_no) ? _MAGENTA_(" %02d [%04X] continuation") : " %02d [" _YELLOW_("%04X") "] continuation", + sector_no, aid ); } else { - char fmt[80]; - snprintf(fmt - , sizeof(fmt) - , (ibs == i) ? - _MAGENTA_(" %02d [%04X] %s") : - " %02d [" _GREEN_("%04X") "] %s" - , i - , aid - , "%s" - ); - print_aid_description(mad_known_aids, aid, fmt, verbose); + json_t *elm = mad_lookup_aid(mad_known_aids, aid); + const char *desc = elm ? mad_aid_description(elm) : " (unknown)"; + PrintAndLogEx(INFO, + (ibs == sector_no) ? _MAGENTA_(" %02d [%04X]%s") : " %02d [" _GREEN_("%04X") "]%s", + sector_no, + aid, + desc + ); + if (verbose && elm) { + mad_print_aid_verbose(elm); + } prev_aid = aid; } } close_mad_file(mad_known_aids); - mad_known_aids = NULL; return PM3_SUCCESS; } -int MAD2DecodeAndPrint(const mad_sector_t *sector, bool swapmad, bool verbose) { - if (!mad_sector_valid(sector)) { - return PM3_EINVARG; - } - - int res = open_mad_file(&mad_known_aids, false); - if (res != PM3_SUCCESS) { - mad_known_aids = NULL; +int MAD2DecodeAndPrint(const mad2_sector_t *sector, bool swapmad, bool verbose) { + if (open_mad_file(&mad_known_aids, false) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Could not load MAD JSON, AID names will not be resolved"); } PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "------------ " _CYAN_("MAD v2 details") " -------------"); - int crc_res = madCRCCheck(sector, 2); + int res = mad2CRCCheck(§or->mad, true); if (verbose) { - const mad2_sector_t *m2 = (const mad2_sector_t *)sector->data; - if (crc_res == PM3_SUCCESS) - PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( " _GREEN_("%s") " )", m2->crc, "ok"); + if (res == PM3_SUCCESS) + PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( " _GREEN_("%s") " )", sector->mad.crc, "ok"); else - PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( " _RED_("%s") " )", m2->crc, "fail"); - } - - int ibs = MADInfoByteDecode(sector, 2, verbose); - if (ibs < 0) { - close_mad_file(mad_known_aids); - mad_known_aids = NULL; - return ibs; + PrintAndLogEx(SUCCESS, "CRC8...... 0x%02X ( " _RED_("%s") " )", sector->mad.crc, "fail"); } + int ibs = MADInfoByteDecode(sector->mad.info, 2, verbose); if (ibs > 0) { PrintAndLogEx(SUCCESS, "Card publisher sector " _MAGENTA_("0x%02X"), ibs); } else { @@ -516,142 +398,264 @@ int MAD2DecodeAndPrint(const mad_sector_t *sector, bool swapmad, bool verbose) { PrintAndLogEx(INFO, " 16 MAD v2"); uint32_t prev_aid = 0xFFFFFFFF; - for (int i = 1; i <= MAD2_AID_COUNT; i++) { - uint16_t aid = madGetAID(sector, swapmad, 2, i); - if (aid < ARRAYLEN(aid_admin)) { + for (int i = 0; i < MAD2_NUM_AIDS; i++) { + int sector_no = i + 17; + uint16_t aid = madGetAID(sector->mad.aid[i], swapmad); + if (aid <= MAD_AID_ADMIN_MAX) { PrintAndLogEx(INFO, - (ibs == i + 16) ? _MAGENTA_(" %02d [%04X] %s") : " %02d [" _GREEN_("%04X") "] %s", - i + 16, + (ibs == sector_no) ? _MAGENTA_(" %02d [%04X] %s") : " %02d [" _GREEN_("%04X") "] %s", + sector_no, aid, aid_admin[aid] ); } else if (prev_aid == aid) { PrintAndLogEx(INFO, - (ibs == i + 16) ? _MAGENTA_(" %02d [%04X] continuation") : " %02d [" _YELLOW_("%04X") "] continuation", - i + 16, + (ibs == sector_no) ? _MAGENTA_(" %02d [%04X] continuation") : " %02d [" _YELLOW_("%04X") "] continuation", + sector_no, aid ); } else { - char fmt[80]; - snprintf(fmt - , sizeof(fmt) - , (ibs == i + 16) ? - _MAGENTA_(" %02d [%04X] %s") : - " %02d [" _GREEN_("%04X") "] %s" - , i + 16 - , aid - , "%s" - ); - print_aid_description(mad_known_aids, aid, fmt, verbose); + json_t *elm = mad_lookup_aid(mad_known_aids, aid); + const char *desc = elm ? mad_aid_description(elm) : " (unknown)"; + PrintAndLogEx(INFO, + (ibs == sector_no) ? _MAGENTA_(" %02d [%04X]%s") : " %02d [" _GREEN_("%04X") "]%s", + sector_no, + aid, + desc + ); + if (verbose && elm) { + mad_print_aid_verbose(elm); + } prev_aid = aid; } } close_mad_file(mad_known_aids); - mad_known_aids = NULL; return PM3_SUCCESS; } int MADDFDecodeAndPrint(uint32_t short_aid, bool verbose) { - int res = open_mad_file(&mad_known_aids, false); - if (res != PM3_SUCCESS) { - mad_known_aids = NULL; + if (open_mad_file(&mad_known_aids, false) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Could not load MAD JSON, AID names will not be resolved"); } - char fmt[128]; - snprintf(fmt, sizeof(fmt), " MAD AID Function 0x%04X... " _YELLOW_("%s"), short_aid, "%s"); - print_aid_description(mad_known_aids, short_aid, fmt, verbose); + json_t *elm = mad_lookup_aid(mad_known_aids, short_aid); + const char *desc = elm ? mad_aid_description(elm) : " (unknown)"; + PrintAndLogEx(INFO, " MAD AID Function 0x%04X... " _YELLOW_("%s"), short_aid, desc); + if (verbose && elm) { + mad_print_aid_verbose(elm); + } close_mad_file(mad_known_aids); - mad_known_aids = NULL; return PM3_SUCCESS; } -bool HasMADKey(const mad_sector_t *sector) { - if (sector == NULL || sector->data == NULL) { +bool HasMADKey(const mad1_sector_t *s0) { + if (s0 == NULL) return false; - } - - if (sector->len < sizeof(mad1_sector_t)) { - return false; - } - - const mad1_sector_t *m = (const mad1_sector_t *)sector->data; - return (memcmp(m->key_a, g_mifare_mad_key, sizeof(g_mifare_mad_key)) == 0); + return (memcmp(s0->trailer.key_a, g_mifare_mad_key, sizeof(g_mifare_mad_key)) == 0); } -int DetectHID(const mad_sector_t *sector, uint16_t manufacture) { - if (!mad_sector_valid(sector)) { +int DetectHID(const mad1_sector_t *s0, uint16_t manufacture) { + if (s0 == NULL) return -1; + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + if (madGetAID(s0->mad.aid[i], false) == manufacture) + return i + 1; } - - for (int i = 1; i <= MAD1_AID_COUNT; i++) { - uint16_t aid = madGetAID(sector, false, 1, i); - if (aid == manufacture) { - return i; - } - } - return -1; } -int convert_mad_to_arr(const uint8_t *in, size_t ilen, uint8_t *out, size_t *olen, size_t olen_max, bool override) { - if (in == NULL || out == NULL || olen == NULL || ilen == 0 || olen_max == 0) { +int convert_mad_to_arr(const mad1_sector_t *s0, const mad2_sector_t *s16, + size_t dump_len, + uint8_t *out, size_t omax, size_t *olen, bool override) { + if (s0 == NULL || out == NULL || olen == NULL || dump_len < sizeof(mad1_sector_t) || omax == 0) return PM3_EINVARG; - } *olen = 0; - mad_sector_t dump = { in, ilen }; - if (HasMADKey(&dump) == false) { + if (HasMADKey(s0) == false) { PrintAndLogEx(FAILED, "No MAD key was detected in the dump file"); return PM3_ESOFT; } - uint8_t sector0_buf[MFBLOCK_SIZE * 4] = {0}; - uint8_t sector16_buf[MFBLOCK_SIZE * 4] = {0}; - - memcpy(sector0_buf, in, MIN(sizeof(sector0_buf), ilen)); - - mad_sector_t sector16 = { NULL, 0 }; - size_t sector16_offset = MF_MAD2_SECTOR * 4 * MFBLOCK_SIZE; - if (ilen >= sector16_offset + sizeof(sector16_buf)) { - memcpy(sector16_buf, in + sector16_offset, sizeof(sector16_buf)); - sector16.data = sector16_buf; - sector16.len = sizeof(sector16_buf); - } - - mad_sector_t sector0 = { sector0_buf, sizeof(sector0_buf) }; - mad_t mad = {0}; - int res = MADDecode(§or0, §or16, &mad, false, override); - if (res != PM3_SUCCESS) { + mad_entry_list_t mad_list = {0}; + if (MADDecode(s0, s16, &mad_list, false, override)) { PrintAndLogEx(ERR, "can't decode MAD"); return PM3_ESOFT; } + const uint8_t *dump = (const uint8_t *)s0; uint16_t ndef_aid = 0xE103; - for (size_t i = 0; i < mad.count; i++) { - if (ndef_aid == mad.entries[i]) { - uint8_t sectorNo = i + 1; - uint16_t first_block = mfFirstBlockOfSector(sectorNo); - uint8_t num_blocks = mfNumBlocksPerSector(sectorNo); - uint32_t offset = first_block * MFBLOCK_SIZE; - uint16_t sector_size = num_blocks * MFBLOCK_SIZE; + for (size_t i = 0; i < mad_list.len; i++) { + if (ndef_aid != mad_list.entries[i].aid) + continue; - if (offset + sector_size > ilen) { - PrintAndLogEx(WARNING, "NDEF sector %u exceeds input bounds", sectorNo); - break; - } + uint8_t sector_no = mad_list.entries[i].sector; + size_t offset = mfFirstBlockOfSector(sector_no) * MFBLOCK_SIZE; + size_t sector_size = mfNumBlocksPerSector(sector_no) * MFBLOCK_SIZE; + size_t data_size = sector_size - MFBLOCK_SIZE; - uint16_t data_size = sector_size - MFBLOCK_SIZE; - if (*olen + data_size > olen_max) { - PrintAndLogEx(WARNING, "NDEF output buffer full"); - return PM3_ESOFT; - } + if (offset + sector_size > dump_len) + break; - memcpy(out, in + offset, data_size); - out += data_size; - *olen += data_size; + if (*olen + data_size > omax) { + PrintAndLogEx(WARNING, "NDEF output buffer full"); + return PM3_EOVFLOW; } + + memcpy(out + *olen, dump + offset, data_size); + *olen += data_size; } return PM3_SUCCESS; } + +static int mad_read_directory(const mad_ops_t *ops, bool swapmad, bool override, + mad_entry_list_t *mad_list) { + mad1_sector_t sector0 = {0}; + int res = ops->read_sector(MF_MAD1_SECTOR, ops->mad_key_type, + ops->mad_key, (uint8_t *)§or0, ops->verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "error reading MAD1 sector 0"); + return res; + } + + mad2_sector_t mad2 = {0}; + const mad2_sector_t *pmad2 = NULL; + res = ops->read_sector(MF_MAD2_SECTOR, ops->mad_key_type, + ops->mad_key, (uint8_t *)&mad2, ops->verbose); + if (res == PM3_SUCCESS) { + pmad2 = &mad2; + } else if (ops->verbose) { + PrintAndLogEx(INFO, "MAD2 sector not available, skipping"); + } + + return MADDecode(§or0, pmad2, mad_list, swapmad, override); +} + +int mad_app_read(const mad_ops_t *ops, uint16_t aid, bool swapmad, bool override, + uint8_t *out, size_t max_len, size_t *out_len) { + *out_len = 0; + + mad_entry_list_t mad_list = {0}; + int res = mad_read_directory(ops, swapmad, override, &mad_list); + if (res != PM3_SUCCESS) + return res; + + for (size_t i = 0; i < mad_list.len; i++) { + if (mad_list.entries[i].aid != aid) + continue; + + uint8_t sno = mad_list.entries[i].sector; + uint8_t sector_buf[MFBLOCK_SIZE * 16] = {0}; + res = ops->read_sector(sno, ops->app_key_type, + ops->app_key, sector_buf, ops->verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "error reading sector %u", sno); + return res; + } + + uint8_t num_data_blocks = mfNumBlocksPerSector(sno) - 1; + size_t nbytes = num_data_blocks * MFBLOCK_SIZE; + + if (*out_len + nbytes > max_len) { + PrintAndLogEx(ERR, "output buffer too small"); + return PM3_EOVFLOW; + } + + memcpy(out + *out_len, sector_buf, nbytes); + *out_len += nbytes; + + if (ops->verbose) + PrintAndLogEx(INFO, "read sector %u, %zu data bytes", sno, nbytes); + } + + if (*out_len == 0) + PrintAndLogEx(WARNING, "no sectors found for AID 0x%04X", aid); + + return PM3_SUCCESS; +} + +int mad_app_write(const mad_ops_t *ops, uint16_t aid, bool swapmad, bool override, + const uint8_t *data, size_t data_len) { + mad_entry_list_t mad_list = {0}; + int res = mad_read_directory(ops, swapmad, override, &mad_list); + if (res != PM3_SUCCESS) + return res; + + size_t capacity = 0; + for (size_t i = 0; i < mad_list.len; i++) { + if (mad_list.entries[i].aid == aid) + capacity += (mfNumBlocksPerSector(mad_list.entries[i].sector) - 1) * MFBLOCK_SIZE; + } + + if (data_len > capacity) { + PrintAndLogEx(ERR, "data (%zu bytes) exceeds capacity (%zu bytes) for AID 0x%04X", + data_len, capacity, aid); + return PM3_EINVARG; + } + + size_t offset = 0; + for (size_t i = 0; i < mad_list.len; i++) { + if (mad_list.entries[i].aid != aid) + continue; + if (offset >= data_len) + break; + + uint8_t sno = mad_list.entries[i].sector; + uint8_t num_data_blocks = mfNumBlocksPerSector(sno) - 1; + size_t sector_data_size = num_data_blocks * MFBLOCK_SIZE; + + uint8_t sector_data[MFBLOCK_SIZE * 15] = {0}; + size_t to_copy = sector_data_size; + if (data_len - offset < to_copy) + to_copy = data_len - offset; + memcpy(sector_data, data + offset, to_copy); + + res = ops->write_sector_data(sno, ops->app_key_type, + ops->app_key, sector_data, ops->verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "error writing sector %u", sno); + return res; + } + + if (ops->verbose) + PrintAndLogEx(INFO, "wrote sector %u, %zu bytes", sno, to_copy); + + offset += sector_data_size; + } + + PrintAndLogEx(SUCCESS, "wrote %zu bytes to AID 0x%04X", data_len, aid); + return PM3_SUCCESS; +} + +int mad_app_verify(const mad_ops_t *ops, uint16_t aid, bool swapmad, bool override, + const uint8_t *expected, size_t expected_len) { + uint8_t readback[MIFARE_4K_MAX_BYTES]; + size_t readback_len = 0; + + int res = mad_app_read(ops, aid, swapmad, override, + readback, sizeof(readback), &readback_len); + if (res != PM3_SUCCESS) + return res; + + size_t cmp_len = readback_len < expected_len ? readback_len : expected_len; + if (memcmp(expected, readback, cmp_len) != 0) { + PrintAndLogEx(ERR, "Verify " _RED_("FAILED") ": data mismatch"); + for (size_t j = 0; j < cmp_len; j++) { + if (expected[j] != readback[j]) { + PrintAndLogEx(ERR, "first difference at offset %zu: expected %02X, got %02X", + j, expected[j], readback[j]); + break; + } + } + return PM3_ESOFT; + } + + if (expected_len != readback_len) { + PrintAndLogEx(WARNING, "length mismatch: expected %zu, read %zu (data matches up to shorter)", + expected_len, readback_len); + } + + PrintAndLogEx(SUCCESS, "Verify " _GREEN_("OK") " (%zu bytes)", cmp_len); + return PM3_SUCCESS; +} diff --git a/client/src/mifare/mad.h b/client/src/mifare/mad.h index 82c41b1cf..e309abc76 100644 --- a/client/src/mifare/mad.h +++ b/client/src/mifare/mad.h @@ -20,88 +20,111 @@ #define _MAD_H_ #include "common.h" +#include "mifaredefault.h" -// --------------------------------------------------------------------------- -// On-card layout structures -// --------------------------------------------------------------------------- +// MAD1/MAD2 AID counts per NXP AN10787 +#define MAD1_NUM_AIDS 15 +#define MAD2_NUM_AIDS 23 -// AID as stored on the card: low byte first, then high byte. -typedef struct PACKED { - uint8_t lo; - uint8_t hi; -} mad_aid_t; - -static inline uint16_t mad_aid_get(const mad_aid_t *a) { - return (a->hi << 8) | a->lo; -} - -static inline void mad_aid_set(mad_aid_t *a, uint16_t val) { - a->lo = val & 0xFF; - a->hi = (val >> 8) & 0xFF; -} - -// MAD1 lives in sector 0 (blocks 0-3, 64 bytes total). -typedef struct PACKED { - uint8_t manufacturer[16]; - uint8_t crc; - uint8_t info; - mad_aid_t aid[15]; // sectors 1-15 - uint8_t key_a[6]; - uint8_t access_bits[3]; - uint8_t gpb; - uint8_t key_b[6]; -} mad1_sector_t; - -// MAD2 lives in sector 0x10 (blocks 0-3 of that sector, 64 bytes total). -typedef struct PACKED { - uint8_t crc; - uint8_t info; - mad_aid_t aid[23]; // sectors 17-39 - uint8_t key_a[6]; - uint8_t access_bits[3]; - uint8_t gpb; - uint8_t key_b[6]; -} mad2_sector_t; - -// AID counts per MAD version -#define MAD1_AID_COUNT 15 -#define MAD2_AID_COUNT 23 - -// Maximum decoded AID entries: 15 (MAD1) + 1 (MAD2 marker) + 23 (MAD2) = 39 -#define MAD_MAX_AID_ENTRIES (MAD1_AID_COUNT + 1 + MAD2_AID_COUNT) - -// Wrapper for a raw sector buffer passed with explicit size. +// MAD1: overlays bytes 16-47 of sector 0 (blocks 1-2, skipping manufacturer block 0) typedef struct { - const uint8_t *data; + uint8_t crc; + uint8_t info; + uint16_t aid[MAD1_NUM_AIDS]; +} PACKED mad1_t; + +// MAD2: overlays bytes 0-47 of sector 16 (blocks 0-2) +typedef struct { + uint8_t crc; + uint8_t info; + uint16_t aid[MAD2_NUM_AIDS]; +} PACKED mad2_t; + +// Full MAD1 sector (sector 0): manufacturer block + MAD1 data + trailer +typedef struct { + uint8_t manufacturer[MFBLOCK_SIZE]; + mad1_t mad; + mf_trailer_t trailer; +} PACKED mad1_sector_t; + +_Static_assert(sizeof(mad1_sector_t) == MFBLOCK_SIZE * 4, "mad1_sector_t must be 4 blocks"); + +// Full MAD2 sector (sector 16): MAD2 data + trailer +typedef struct { + mad2_t mad; + mf_trailer_t trailer; +} PACKED mad2_sector_t; + +_Static_assert(sizeof(mad2_sector_t) == MFBLOCK_SIZE * 4, "mad2_sector_t must be 4 blocks"); + +// Access the i-th block of a sector struct as raw bytes +#define MF_SECTOR_BLOCK(sector, i) ((const uint8_t *)&(sector) + (i) * MFBLOCK_SIZE) + +// Single decoded MAD entry: sector number + AID +typedef struct { + uint8_t sector; + uint16_t aid; +} mad_entry_t; + +#define MAD_MAX_ENTRIES (MAD1_NUM_AIDS + MAD2_NUM_AIDS) + +typedef struct { + mad_entry_t entries[MAD_MAX_ENTRIES]; size_t len; -} mad_sector_t; +} mad_entry_list_t; -// Output of MADDecode. +// Card transport ops struct for MAD operations. +// Abstracts over MIFARE Classic (CRYPTO1) and MIFARE Plus (AES). typedef struct { - uint16_t entries[MAD_MAX_AID_ENTRIES]; - size_t count; - bool has_mad2; - uint8_t info_byte; - uint8_t gpb; - bool crc1_ok; - bool crc2_ok; -} mad_t; + // Read a full sector (all blocks including trailer) into buf. + // buf must hold mfNumBlocksPerSector(sector_no) * MFBLOCK_SIZE bytes. + int (*read_sector)(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, uint8_t *buf, bool verbose); -// --------------------------------------------------------------------------- -// API -// --------------------------------------------------------------------------- + // Write the data blocks (non-trailer) of a sector. + // data points to (mfNumBlocksPerSector(sector_no) - 1) * MFBLOCK_SIZE bytes. + int (*write_sector_data)(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, const uint8_t *data, bool verbose); -#define MADComputeCRC(m) CRC8Mad((uint8_t *)&(m)->info, sizeof((m)->info) + sizeof((m)->aid)) + const uint8_t *mad_key; + uint8_t mad_key_type; + const uint8_t *app_key; + uint8_t app_key_type; + bool verbose; +} mad_ops_t; -int MADCheck(const mad_sector_t *sector0, const mad_sector_t *sector16, bool verbose, bool *haveMAD2); -int MADDecode(const mad_sector_t *sector0, const mad_sector_t *sector16, mad_t *out, bool swapmad, bool override); -int MAD1DecodeAndPrint(const mad_sector_t *sector, bool swapmad, bool verbose, bool *haveMAD2); -int MAD2DecodeAndPrint(const mad_sector_t *sector, bool swapmad, bool verbose); +// AID admin codes (0x0000-0x0005) +#define MAD_AID_ADMIN_MAX 5 + +// GPB (General Purpose Byte) bit masks +#define MAD_GPB_DA_MASK 0x80 +#define MAD_GPB_MA_MASK 0x40 +#define MAD_GPB_VER_MASK 0x03 + +// Info byte: lower 6 bits = card publisher sector pointer +#define MAD_INFO_MASK 0x3F + +// Card holder info TLV encoding +#define MAD_TLV_LEN_MASK 0x3F +#define MAD_TLV_TYPE_SHIFT 6 + +int MADCheck(const mad1_sector_t *sector0, const mad2_sector_t *mad2, bool verbose, bool *haveMAD2); +int MADDecode(const mad1_sector_t *sector0, const mad2_sector_t *mad2, mad_entry_list_t *mad_list, bool swapmad, bool override); +int MAD1DecodeAndPrint(const mad1_sector_t *sector, bool swapmad, bool verbose, bool *haveMAD2); +int MAD2DecodeAndPrint(const mad2_sector_t *sector, bool swapmad, bool verbose); int MADDFDecodeAndPrint(uint32_t short_aid, bool verbose); int MADCardHolderInfoDecode(const uint8_t *data, size_t datalen, bool verbose); void MADPrintHeader(void); -bool HasMADKey(const mad_sector_t *sector); -int DetectHID(const mad_sector_t *sector, uint16_t manufacture); -int convert_mad_to_arr(const uint8_t *in, size_t ilen, uint8_t *out, size_t *olen, size_t olen_max, bool override); +bool HasMADKey(const mad1_sector_t *s0); +int DetectHID(const mad1_sector_t *s0, uint16_t manufacture); +int convert_mad_to_arr(const mad1_sector_t *s0, const mad2_sector_t *s16, + size_t dump_len, + uint8_t *out, size_t omax, size_t *olen, bool override); +int mad_app_read(const mad_ops_t *ops, uint16_t aid, bool swapmad, bool override, + uint8_t *out, size_t max_len, size_t *out_len); +int mad_app_write(const mad_ops_t *ops, uint16_t aid, bool swapmad, bool override, + const uint8_t *data, size_t data_len); +int mad_app_verify(const mad_ops_t *ops, uint16_t aid, bool swapmad, bool override, + const uint8_t *expected, size_t expected_len); #endif // _MAD_H_ diff --git a/client/src/mifare/mad_test.c b/client/src/mifare/mad_test.c new file mode 100644 index 000000000..27e594118 --- /dev/null +++ b/client/src/mifare/mad_test.c @@ -0,0 +1,858 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MAD regression tests +//----------------------------------------------------------------------------- + +#include "mad_test.h" +#include "mad.h" +#include "ui.h" +#include "crc.h" +#include "mifare4.h" +#include "mifaredefault.h" +#include "mifare.h" +#include + + +#define ASSERT_EQ(msg, expected, actual) do { \ + if ((expected) != (actual)) { \ + PrintAndLogEx(FAILED, " %s: expected %d, got %d", (msg), (int)(expected), (int)(actual)); \ + return false; \ + } \ +} while (0) + +#define ASSERT_EQ_HEX(msg, expected, actual) do { \ + if ((expected) != (actual)) { \ + PrintAndLogEx(FAILED, " %s: expected 0x%04X, got 0x%04X", (msg), (unsigned)(expected), (unsigned)(actual)); \ + return false; \ + } \ +} while (0) + +#define ASSERT_TRUE(msg, cond) do { \ + if (!(cond)) { \ + PrintAndLogEx(FAILED, " %s", (msg)); \ + return false; \ + } \ +} while (0) + +static void build_test_mad1(mad1_sector_t *s) { + memset(s, 0, sizeof(*s)); + + s->manufacturer[0] = 0x01; + s->manufacturer[1] = 0x02; + s->manufacturer[2] = 0x03; + s->manufacturer[3] = 0x04; + + // AIDs stored as native uint16_t + s->mad.info = 0x01; + s->mad.aid[0] = 0xE103; // sector 1: NDEF + s->mad.aid[1] = 0xE103; // sector 2: NDEF continuation + s->mad.aid[2] = 0xE103; // sector 3: NDEF continuation + s->mad.aid[3] = 0x484D; // sector 4: HID + // sectors 5-15: 0x0000 = free + + s->mad.crc = CRC8Mad((uint8_t *)&s->mad.info, sizeof(mad1_t) - 1); + + memcpy(s->trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s->trailer.access[0] = 0xFF; + s->trailer.access[1] = 0x07; + s->trailer.access[2] = 0x80; + s->trailer.gpb = 0x82; // DA=1, MA=0, version=2 + memset(s->trailer.key_b, 0xFF, MIFARE_KEY_SIZE); +} + +static void build_test_mad2(mad2_sector_t *s) { + memset(s, 0, sizeof(*s)); + + s->mad.info = 0x00; + s->mad.aid[0] = 0xE103; // sector 17: NDEF + s->mad.aid[1] = 0xE103; // sector 18: NDEF continuation + // sectors 19-39: 0x0000 = free + + s->mad.crc = CRC8Mad((uint8_t *)&s->mad.info, sizeof(mad2_t) - 1); + + memcpy(s->trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s->trailer.access[0] = 0xFF; + s->trailer.access[1] = 0x07; + s->trailer.access[2] = 0x80; + s->trailer.gpb = 0x00; + memset(s->trailer.key_b, 0xFF, MIFARE_KEY_SIZE); +} + +// --- Mock card memory --- + +#define MOCK_CARD_SIZE (256 * 16) +static uint8_t g_mock_card[MOCK_CARD_SIZE]; + +static int mock_read_sector(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, uint8_t *buf, bool verbose) { + (void)key_type; (void)key; (void)verbose; + uint8_t first_block = mfFirstBlockOfSector(sector_no); + uint8_t nblocks = mfNumBlocksPerSector(sector_no); + uint32_t offset = first_block * 16; + uint32_t size = nblocks * 16; + if (offset + size > MOCK_CARD_SIZE) + return PM3_ESOFT; + memcpy(buf, &g_mock_card[offset], size); + return PM3_SUCCESS; +} + +static int mock_write_sector_data(uint8_t sector_no, uint8_t key_type, + const uint8_t *key, const uint8_t *data, bool verbose) { + (void)key_type; (void)key; (void)verbose; + uint8_t first_block = mfFirstBlockOfSector(sector_no); + uint8_t ndata = mfNumBlocksPerSector(sector_no) - 1; + uint32_t offset = first_block * 16; + if (offset + ndata * 16 > MOCK_CARD_SIZE) + return PM3_ESOFT; + memcpy(&g_mock_card[offset], data, ndata * 16); + return PM3_SUCCESS; +} + +static void mock_card_init(void) { + memset(g_mock_card, 0, sizeof(g_mock_card)); + + mad1_sector_t s0; + build_test_mad1(&s0); + memcpy(&g_mock_card[0], &s0, sizeof(s0)); + + // fill data sectors with deterministic per-byte pattern: + // byte value = (sector * 0x10) + (block_within_sector * 0x04) + byte_within_block + for (int sec = 1; sec <= 15; sec++) { + uint8_t first = mfFirstBlockOfSector(sec); + for (int b = 0; b < 3; b++) { + uint8_t *block = &g_mock_card[(first + b) * 16]; + for (int i = 0; i < 16; i++) + block[i] = (uint8_t)((sec << 4) | (b << 2) | (i & 0x03)); + } + // trailer + uint8_t *trailer = &g_mock_card[(first + 3) * 16]; + memset(trailer, 0xFF, 16); + } + + // MAD2 at sector 16 + mad2_sector_t s16; + build_test_mad2(&s16); + uint8_t first16 = mfFirstBlockOfSector(16); + memcpy(&g_mock_card[first16 * 16], &s16, sizeof(s16)); + + // fill sectors 17-18 (MAD2 NDEF) with pattern + for (int sec = 17; sec <= 18; sec++) { + uint8_t first = mfFirstBlockOfSector(sec); + for (int b = 0; b < 3; b++) { + uint8_t *block = &g_mock_card[(first + b) * 16]; + for (int i = 0; i < 16; i++) + block[i] = (uint8_t)((sec << 4) | (b << 2) | (i & 0x03)); + } + uint8_t *trailer = &g_mock_card[(first + 3) * 16]; + memset(trailer, 0xFF, 16); + } +} + +static mad_ops_t make_mock_ops(void) { + mad_ops_t ops = { + .read_sector = mock_read_sector, + .write_sector_data = mock_write_sector_data, + .mad_key = g_mifare_mad_key, + .mad_key_type = MF_KEY_A, + .app_key = g_mifare_ndef_key, + .app_key_type = MF_KEY_A, + .verbose = false, + }; + return ops; +} + +// --- Test cases --- + +static bool test_struct_sizes(bool verbose) { + PrintAndLogEx(INFO, " struct sizes..."); + + ASSERT_EQ("mad1_t", 32, sizeof(mad1_t)); + ASSERT_EQ("mad2_t", 48, sizeof(mad2_t)); + ASSERT_EQ("mad1_sector_t", 64, sizeof(mad1_sector_t)); + ASSERT_EQ("mad2_sector_t", 64, sizeof(mad2_sector_t)); + ASSERT_EQ("mf_trailer_t", 16, sizeof(mf_trailer_t)); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_mad1_crc_valid(bool verbose) { + PrintAndLogEx(INFO, " MAD1 CRC valid..."); + mad1_sector_t s; + build_test_mad1(&s); + + bool haveMAD2 = false; + int res = MADCheck(&s, NULL, false, &haveMAD2); + ASSERT_EQ("MADCheck on valid sector", PM3_SUCCESS, res); + ASSERT_EQ("should report MAD2 (v2)", true, haveMAD2); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_mad1_crc_corrupt(bool verbose) { + PrintAndLogEx(INFO, " MAD1 CRC corrupt..."); + mad1_sector_t s; + build_test_mad1(&s); + s.mad.crc ^= 0xFF; + + bool haveMAD2 = false; + + int res = MADCheck(&s, NULL, false, &haveMAD2); + + ASSERT_TRUE("MADCheck should fail on corrupt CRC", res != PM3_SUCCESS); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_mad1_decode_entries(bool verbose) { + PrintAndLogEx(INFO, " MAD1 decode entries..."); + mad1_sector_t s; + build_test_mad1(&s); + + mad_entry_list_t list = {0}; + int res = MADDecode(&s, NULL, &list, false, false); + ASSERT_EQ("MADDecode return", PM3_SUCCESS, res); + ASSERT_EQ("entry count", MAD1_NUM_AIDS, (int)list.len); + + // NDEF sectors 1-3 + for (int i = 0; i < 3; i++) { + ASSERT_EQ_HEX("NDEF AID", 0xE103, list.entries[i].aid); + ASSERT_EQ("NDEF sector", i + 1, list.entries[i].sector); + } + + // HID sector 4 + ASSERT_EQ_HEX("HID AID", 0x484D, list.entries[3].aid); + ASSERT_EQ("HID sector", 4, list.entries[3].sector); + + // free sectors 5-15 + for (int i = 4; i < MAD1_NUM_AIDS; i++) { + ASSERT_EQ_HEX("free AID", 0x0000, list.entries[i].aid); + } + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_mad2_decode(bool verbose) { + PrintAndLogEx(INFO, " MAD2 decode with MAD1 v2..."); + mad1_sector_t s0; + build_test_mad1(&s0); + mad2_sector_t s16; + build_test_mad2(&s16); + + bool haveMAD2 = false; + int res = MADCheck(&s0, &s16, false, &haveMAD2); + ASSERT_EQ("MADCheck return", PM3_SUCCESS, res); + ASSERT_EQ("should report MAD2", true, haveMAD2); + + mad_entry_list_t list = {0}; + res = MADDecode(&s0, &s16, &list, false, false); + ASSERT_EQ("MADDecode return", PM3_SUCCESS, res); + ASSERT_EQ("entry count", MAD1_NUM_AIDS + MAD2_NUM_AIDS, (int)list.len); + + // MAD1 entries: sectors 1-3 NDEF, sector 4 HID, 5-15 free + ASSERT_EQ_HEX("MAD1 sector 1", 0xE103, list.entries[0].aid); + ASSERT_EQ_HEX("MAD1 sector 4", 0x484D, list.entries[3].aid); + + // MAD2 entries start at index 15 (MAD1_NUM_AIDS) + // sector 17 = NDEF, sector 18 = NDEF, rest free + ASSERT_EQ("MAD2 entry 0 sector", 17, list.entries[MAD1_NUM_AIDS].sector); + ASSERT_EQ_HEX("MAD2 entry 0 AID", 0xE103, list.entries[MAD1_NUM_AIDS].aid); + ASSERT_EQ("MAD2 entry 1 sector", 18, list.entries[MAD1_NUM_AIDS + 1].sector); + ASSERT_EQ_HEX("MAD2 entry 1 AID", 0xE103, list.entries[MAD1_NUM_AIDS + 1].aid); + ASSERT_EQ_HEX("MAD2 entry 2 free", 0x0000, list.entries[MAD1_NUM_AIDS + 2].aid); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_read_mad2_sectors(bool verbose) { + PrintAndLogEx(INFO, " read AID spanning MAD1+MAD2..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + uint8_t data[MIFARE_4K_MAX_BYTES] = {0}; + size_t datalen = 0; + int res = mad_app_read(&ops, 0xE103, false, false, data, sizeof(data), &datalen); + ASSERT_EQ("read return", PM3_SUCCESS, res); + + // MAD1: sectors 1-3 (3*48=144), MAD2: sectors 17-18 (2*48=96), total=240 + ASSERT_EQ("read length", 240, (int)datalen); + + // verify first byte of sector 1 + ASSERT_EQ("sector 1 byte 0", (uint8_t)((1 << 4) | 0), data[0]); + // verify first byte of sector 17 (at offset 144) + ASSERT_EQ("sector 17 byte 0", (uint8_t)((17 << 4) | 0), data[144]); + // verify first byte of sector 18 (at offset 144+48=192) + ASSERT_EQ("sector 18 byte 0", (uint8_t)((18 << 4) | 0), data[192]); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_read_full_content(bool verbose) { + PrintAndLogEx(INFO, " read full AID content..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + uint8_t data[MIFARE_4K_MAX_BYTES] = {0}; + size_t datalen = 0; + + int res = mad_app_read(&ops, 0xE103, false, false, data, sizeof(data), &datalen); + + ASSERT_EQ("mad_app_read return", PM3_SUCCESS, res); + + // 5 NDEF sectors (1-3 from MAD1, 17-18 from MAD2) * 3 data blocks * 16 = 240 + ASSERT_EQ("read length", 240, (int)datalen); + + // verify every byte across MAD1 sectors 1-3 + size_t off = 0; + for (int sec = 1; sec <= 3; sec++) { + for (int b = 0; b < 3; b++) { + for (int i = 0; i < 16; i++) { + uint8_t expected = (uint8_t)((sec << 4) | (b << 2) | (i & 0x03)); + if (data[off] != expected) { + PrintAndLogEx(FAILED, " byte %zu: expected 0x%02X, got 0x%02X (sector %d block %d byte %d)", + off, expected, data[off], sec, b, i); + return false; + } + off++; + } + } + } + // verify MAD2 sectors 17-18 + for (int sec = 17; sec <= 18; sec++) { + for (int b = 0; b < 3; b++) { + for (int i = 0; i < 16; i++) { + uint8_t expected = (uint8_t)((sec << 4) | (b << 2) | (i & 0x03)); + if (data[off] != expected) { + PrintAndLogEx(FAILED, " byte %zu: expected 0x%02X, got 0x%02X (sector %d block %d byte %d)", + off, expected, data[off], sec, b, i); + return false; + } + off++; + } + } + } + ASSERT_EQ("total bytes checked", 240, (int)off); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_read_single_sector_aid(bool verbose) { + PrintAndLogEx(INFO, " read single-sector AID..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + uint8_t data[256] = {0}; + size_t datalen = 0; + + int res = mad_app_read(&ops, 0x484D, false, false, data, sizeof(data), &datalen); + + ASSERT_EQ("read return", PM3_SUCCESS, res); + ASSERT_EQ("read length", 48, (int)datalen); + + // sector 4 data: (4 << 4) | (b << 2) | (i & 3) + for (int b = 0; b < 3; b++) { + for (int i = 0; i < 16; i++) { + uint8_t expected = (uint8_t)((4 << 4) | (b << 2) | (i & 0x03)); + size_t off = b * 16 + i; + if (data[off] != expected) { + PrintAndLogEx(FAILED, " byte %zu: expected 0x%02X, got 0x%02X", off, expected, data[off]); + return false; + } + } + } + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_write_full_roundtrip(bool verbose) { + PrintAndLogEx(INFO, " write full round-trip..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + // write exactly 240 bytes (full NDEF capacity: MAD1 + MAD2) + uint8_t wdata[240]; + for (int i = 0; i < 240; i++) + wdata[i] = (uint8_t)(i ^ 0x55); + + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("write return", PM3_SUCCESS, res); + + // read back and compare every byte + uint8_t rdata[MIFARE_4K_MAX_BYTES] = {0}; + size_t rlen = 0; + + res = mad_app_read(&ops, 0xE103, false, false, rdata, sizeof(rdata), &rlen); + + ASSERT_EQ("readback return", PM3_SUCCESS, res); + ASSERT_EQ("readback length", 240, (int)rlen); + + for (int i = 0; i < 240; i++) { + if (rdata[i] != wdata[i]) { + PrintAndLogEx(FAILED, " byte %d: wrote 0x%02X, read 0x%02X", i, wdata[i], rdata[i]); + return false; + } + } + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_write_partial_zero_pads(bool verbose) { + PrintAndLogEx(INFO, " write partial zero-pads remainder..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + // write 50 bytes into 240-byte capacity + // sector 1 gets full 48 bytes, sector 2 gets 2 bytes + zero-pad + // sectors 3, 17, 18 are not touched (write stops after data exhausted) + uint8_t wdata[50]; + memset(wdata, 0xAB, sizeof(wdata)); + + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("write return", PM3_SUCCESS, res); + + uint8_t rdata[MIFARE_4K_MAX_BYTES] = {0xFF}; + size_t rlen = 0; + + res = mad_app_read(&ops, 0xE103, false, false, rdata, sizeof(rdata), &rlen); + + ASSERT_EQ("readback return", PM3_SUCCESS, res); + ASSERT_EQ("readback length", 240, (int)rlen); + + // first 48 bytes (sector 1) should all be 0xAB + for (int i = 0; i < 48; i++) { + if (rdata[i] != 0xAB) { + PrintAndLogEx(FAILED, " byte %d: expected 0xAB, got 0x%02X", i, rdata[i]); + return false; + } + } + // bytes 48-49 should be 0xAB (start of sector 2) + ASSERT_EQ("byte 48", 0xAB, rdata[48]); + ASSERT_EQ("byte 49", 0xAB, rdata[49]); + // bytes 50-95 should be 0x00 (zero-padded remainder of sector 2) + for (int i = 50; i < 96; i++) { + if (rdata[i] != 0x00) { + PrintAndLogEx(FAILED, " byte %d: expected 0x00, got 0x%02X", i, rdata[i]); + return false; + } + } + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_verify_match(bool verbose) { + PrintAndLogEx(INFO, " verify match..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + // write known data, then verify with same data + uint8_t wdata[240]; + for (int i = 0; i < 240; i++) + wdata[i] = (uint8_t)(i * 3); + + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("write return", PM3_SUCCESS, res); + + + res = mad_app_verify(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("verify should pass", PM3_SUCCESS, res); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_verify_mismatch(bool verbose) { + PrintAndLogEx(INFO, " verify mismatch..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + // write known data + uint8_t wdata[240]; + for (int i = 0; i < 240; i++) + wdata[i] = (uint8_t)(i * 3); + + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("write return", PM3_SUCCESS, res); + + // flip one byte and verify should fail + uint8_t bad[240]; + memcpy(bad, wdata, sizeof(bad)); + bad[72] ^= 0xFF; // corrupt byte in sector 2 + + + res = mad_app_verify(&ops, 0xE103, false, false, bad, sizeof(bad)); + + ASSERT_TRUE("verify should detect mismatch", res != PM3_SUCCESS); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_write_overflow(bool verbose) { + PrintAndLogEx(INFO, " write overflow..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + uint8_t wdata[241]; + memset(wdata, 0xAA, sizeof(wdata)); + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_TRUE("should reject 241 bytes into 240-byte capacity", res != PM3_SUCCESS); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_aid_not_found(bool verbose) { + PrintAndLogEx(INFO, " AID not found..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + uint8_t data[256] = {0}; + size_t datalen = 99; + + int res = mad_app_read(&ops, 0xBEEF, false, false, data, sizeof(data), &datalen); + + ASSERT_EQ("should succeed with 0 bytes", PM3_SUCCESS, res); + ASSERT_EQ("datalen should be 0", 0, (int)datalen); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_write_does_not_touch_trailer(bool verbose) { + PrintAndLogEx(INFO, " write does not touch trailer..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + // save trailer block of sector 1 before write + uint8_t first = mfFirstBlockOfSector(1); + uint8_t trailer_before[16]; + memcpy(trailer_before, &g_mock_card[(first + 3) * 16], 16); + + uint8_t wdata[48]; + memset(wdata, 0xCC, sizeof(wdata)); + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("write return", PM3_SUCCESS, res); + + // trailer should be unchanged + ASSERT_TRUE("sector 1 trailer unchanged", + memcmp(trailer_before, &g_mock_card[(first + 3) * 16], 16) == 0); + + // also check sector 2 trailer + uint8_t first2 = mfFirstBlockOfSector(2); + uint8_t trailer2[16]; + memcpy(trailer2, &g_mock_card[(first2 + 3) * 16], 16); + uint8_t expected_trailer[16]; + memset(expected_trailer, 0xFF, 16); + ASSERT_TRUE("sector 2 trailer unchanged", memcmp(trailer2, expected_trailer, 16) == 0); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_mad_sector_untouched_after_write(bool verbose) { + PrintAndLogEx(INFO, " MAD sector untouched after write..."); + mock_card_init(); + mad_ops_t ops = make_mock_ops(); + + // save MAD sector 0 before write + uint8_t mad_before[64]; + memcpy(mad_before, &g_mock_card[0], 64); + + uint8_t wdata[240]; + memset(wdata, 0xDD, sizeof(wdata)); + + int res = mad_app_write(&ops, 0xE103, false, false, wdata, sizeof(wdata)); + + ASSERT_EQ("write return", PM3_SUCCESS, res); + + // MAD sector 0 should be completely unchanged + ASSERT_TRUE("MAD sector 0 unchanged after write", + memcmp(mad_before, &g_mock_card[0], 64) == 0); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_encode_decode_roundtrip(bool verbose) { + PrintAndLogEx(INFO, " encode-decode round-trip..."); + + // simulate CmdMADEncode: fill sector_aids[], build struct, decode + uint16_t sector_aids[40] = {0}; + sector_aids[1] = 0xE103; // NDEF + sector_aids[2] = 0xE103; + sector_aids[3] = 0xE103; + sector_aids[4] = 0x484D; // HID + sector_aids[5] = 0xE103; // NDEF non-contiguous + + // build MAD1 (same logic as CmdMADEncode) + mad1_sector_t s0; + memset(&s0, 0, sizeof(s0)); + s0.mad.info = 0x00; + for (int i = 0; i < MAD1_NUM_AIDS; i++) + s0.mad.aid[i] = sector_aids[i + 1]; + s0.mad.crc = CRC8Mad((uint8_t *)&s0.mad.info, sizeof(mad1_t) - 1); + memcpy(s0.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s0.trailer.access[0] = 0x78; + s0.trailer.access[1] = 0x77; + s0.trailer.access[2] = 0x88; + s0.trailer.gpb = 0xC1; + memcpy(s0.trailer.key_b, g_mifare_mad_key_b, MIFARE_KEY_SIZE); + + // verify CRC is valid + bool haveMAD2 = false; + int res = MADCheck(&s0, NULL, false, &haveMAD2); + ASSERT_EQ("CRC on encoded MAD1", PM3_SUCCESS, res); + + // decode and verify every entry + mad_entry_list_t list = {0}; + res = MADDecode(&s0, NULL, &list, false, false); + ASSERT_EQ("decode return", PM3_SUCCESS, res); + ASSERT_EQ("entry count", MAD1_NUM_AIDS, (int)list.len); + + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + ASSERT_EQ("sector number", i + 1, list.entries[i].sector); + ASSERT_EQ_HEX("AID", sector_aids[i + 1], list.entries[i].aid); + } + + // verify GPB: DA=1, version=1 + ASSERT_TRUE("GPB DA bit set", (s0.trailer.gpb & 0x80) != 0); + ASSERT_EQ("GPB version", 1, s0.trailer.gpb & 0x03); + + // verify trailer keys match MAD defaults + ASSERT_TRUE("key A is MAD key", + memcmp(s0.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE) == 0); + ASSERT_TRUE("key B is MAD key B", + memcmp(s0.trailer.key_b, g_mifare_mad_key_b, MIFARE_KEY_SIZE) == 0); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_encode_decode_mad2_roundtrip(bool verbose) { + PrintAndLogEx(INFO, " encode-decode MAD2 round-trip..."); + + uint16_t sector_aids[40] = {0}; + sector_aids[1] = 0xE103; // MAD1 NDEF + sector_aids[2] = 0xE103; + sector_aids[4] = 0x484D; // MAD1 HID + sector_aids[17] = 0xE103; // MAD2 NDEF + sector_aids[18] = 0xE103; + sector_aids[19] = 0xE103; + sector_aids[20] = 0x4910; // MAD2 VIGIK + + // build MAD1 + mad1_sector_t s0; + memset(&s0, 0, sizeof(s0)); + s0.mad.info = 0x00; + for (int i = 0; i < MAD1_NUM_AIDS; i++) + s0.mad.aid[i] = sector_aids[i + 1]; + s0.mad.crc = CRC8Mad((uint8_t *)&s0.mad.info, sizeof(mad1_t) - 1); + memcpy(s0.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s0.trailer.access[0] = 0x78; + s0.trailer.access[1] = 0x77; + s0.trailer.access[2] = 0x88; + s0.trailer.gpb = 0xC2; // DA=1, MA=1, version=2 + memcpy(s0.trailer.key_b, g_mifare_mad_key_b, MIFARE_KEY_SIZE); + + // build MAD2 + mad2_sector_t s16; + memset(&s16, 0, sizeof(s16)); + s16.mad.info = 0x00; + for (int i = 0; i < MAD2_NUM_AIDS; i++) + s16.mad.aid[i] = sector_aids[i + 17]; + s16.mad.crc = CRC8Mad((uint8_t *)&s16.mad.info, sizeof(mad2_t) - 1); + memcpy(s16.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + s16.trailer.access[0] = 0x78; + s16.trailer.access[1] = 0x77; + s16.trailer.access[2] = 0x88; + s16.trailer.gpb = 0xC2; + memcpy(s16.trailer.key_b, g_mifare_mad_key_b, MIFARE_KEY_SIZE); + + // verify CRC on both + bool haveMAD2 = false; + int res = MADCheck(&s0, &s16, false, &haveMAD2); + ASSERT_EQ("CRC on MAD1+MAD2", PM3_SUCCESS, res); + ASSERT_EQ("should report MAD2", true, haveMAD2); + + // decode and verify all 38 entries + mad_entry_list_t list = {0}; + res = MADDecode(&s0, &s16, &list, false, false); + ASSERT_EQ("decode return", PM3_SUCCESS, res); + ASSERT_EQ("entry count", MAD1_NUM_AIDS + MAD2_NUM_AIDS, (int)list.len); + + // verify MAD1 entries (sectors 1-15) + for (int i = 0; i < MAD1_NUM_AIDS; i++) { + ASSERT_EQ("MAD1 sector", i + 1, list.entries[i].sector); + ASSERT_EQ_HEX("MAD1 AID", sector_aids[i + 1], list.entries[i].aid); + } + + // verify MAD2 entries (sectors 17-39) + for (int i = 0; i < MAD2_NUM_AIDS; i++) { + ASSERT_EQ("MAD2 sector", i + 17, list.entries[MAD1_NUM_AIDS + i].sector); + ASSERT_EQ_HEX("MAD2 AID", sector_aids[i + 17], list.entries[MAD1_NUM_AIDS + i].aid); + } + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_mad2_crc_independent(bool verbose) { + PrintAndLogEx(INFO, " MAD2 CRC independent..."); + + mad1_sector_t s0; + build_test_mad1(&s0); + mad2_sector_t s16; + build_test_mad2(&s16); + + // valid: both CRCs pass + bool haveMAD2 = false; + int res = MADCheck(&s0, &s16, false, &haveMAD2); + ASSERT_EQ("both valid", PM3_SUCCESS, res); + ASSERT_EQ("MAD2 present", true, haveMAD2); + + // corrupt MAD2 CRC only, MAD1 stays valid + mad2_sector_t s16_bad; + memcpy(&s16_bad, &s16, sizeof(s16_bad)); + s16_bad.mad.crc ^= 0xFF; + + res = MADCheck(&s0, &s16_bad, false, &haveMAD2); + ASSERT_TRUE("should fail with corrupt MAD2 CRC", res != PM3_SUCCESS); + + // corrupt MAD1 CRC only, MAD2 stays valid + mad1_sector_t s0_bad; + memcpy(&s0_bad, &s0, sizeof(s0_bad)); + s0_bad.mad.crc ^= 0xFF; + + res = MADCheck(&s0_bad, &s16, false, &haveMAD2); + ASSERT_TRUE("should fail with corrupt MAD1 CRC", res != PM3_SUCCESS); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_encode_gpb_version(bool verbose) { + PrintAndLogEx(INFO, " encode GPB version..."); + + // MAD1-only: GPB should have version=1 + mad1_sector_t s_v1; + memset(&s_v1, 0, sizeof(s_v1)); + s_v1.mad.aid[0] = 0xE103; + s_v1.mad.crc = CRC8Mad((uint8_t *)&s_v1.mad.info, sizeof(mad1_t) - 1); + s_v1.trailer.gpb = 0xC1; // DA=1, MA=1, v1 + memcpy(s_v1.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + + bool haveMAD2 = false; + int res = MADCheck(&s_v1, NULL, false, &haveMAD2); + ASSERT_EQ("v1 check", PM3_SUCCESS, res); + ASSERT_EQ("v1 no MAD2", false, haveMAD2); + ASSERT_EQ("GPB version bits", 1, s_v1.trailer.gpb & 0x03); + + // MAD1+MAD2: GPB should have version=2 + mad1_sector_t s_v2; + memset(&s_v2, 0, sizeof(s_v2)); + s_v2.mad.aid[0] = 0xE103; + s_v2.mad.crc = CRC8Mad((uint8_t *)&s_v2.mad.info, sizeof(mad1_t) - 1); + s_v2.trailer.gpb = 0xC2; // DA=1, MA=1, v2 + memcpy(s_v2.trailer.key_a, g_mifare_mad_key, MIFARE_KEY_SIZE); + + res = MADCheck(&s_v2, NULL, false, &haveMAD2); + ASSERT_EQ("v2 check", PM3_SUCCESS, res); + ASSERT_EQ("v2 has MAD2", true, haveMAD2); + ASSERT_EQ("GPB version bits", 2, s_v2.trailer.gpb & 0x03); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +static bool test_encode_sector_overlap(bool verbose) { + PrintAndLogEx(INFO, " encode sector overlap detection..."); + + // two different AIDs assigned to the same sector + uint16_t sector_aids[40] = {0}; + sector_aids[1] = 0xE103; + sector_aids[2] = 0xE103; + + // simulate assigning sector 2 again to a different AID + // this is what CmdMADEncode checks: sector_aids[sno] != 0 + bool overlap_detected = (sector_aids[2] != 0); + ASSERT_TRUE("overlap on sector 2 detected", overlap_detected); + + // verify non-overlapping case + bool no_overlap = (sector_aids[5] == 0); + ASSERT_TRUE("sector 5 is free", no_overlap); + + if (verbose) PrintAndLogEx(SUCCESS, " " _GREEN_("passed")); + return true; +} + +// --- Aggregator --- + +int exec_mad_test(bool verbose) { + PrintAndLogEx(INFO, "--- " _CYAN_("MAD regression tests") " ---"); + + bool ok = true; + if (!test_struct_sizes(verbose)) ok = false; + if (!test_mad1_crc_valid(verbose)) ok = false; + if (!test_mad1_crc_corrupt(verbose)) ok = false; + if (!test_mad1_decode_entries(verbose)) ok = false; + if (!test_mad2_decode(verbose)) ok = false; + if (!test_read_mad2_sectors(verbose)) ok = false; + if (!test_read_full_content(verbose)) ok = false; + if (!test_read_single_sector_aid(verbose)) ok = false; + if (!test_write_full_roundtrip(verbose)) ok = false; + if (!test_write_partial_zero_pads(verbose)) ok = false; + if (!test_verify_match(verbose)) ok = false; + if (!test_verify_mismatch(verbose)) ok = false; + if (!test_write_overflow(verbose)) ok = false; + if (!test_aid_not_found(verbose)) ok = false; + if (!test_write_does_not_touch_trailer(verbose)) ok = false; + if (!test_mad_sector_untouched_after_write(verbose)) ok = false; + if (!test_encode_decode_roundtrip(verbose)) ok = false; + if (!test_encode_decode_mad2_roundtrip(verbose)) ok = false; + if (!test_mad2_crc_independent(verbose)) ok = false; + if (!test_encode_gpb_version(verbose)) ok = false; + if (!test_encode_sector_overlap(verbose)) ok = false; + + PrintAndLogEx(INFO, "----------------------------"); + if (ok) + PrintAndLogEx(SUCCESS, "Tests ( " _GREEN_("ok") " )"); + else + PrintAndLogEx(FAILED, "Tests ( " _RED_("fail") " )"); + + return ok ? PM3_SUCCESS : PM3_ESOFT; +} diff --git a/client/src/mifare/mad_test.h b/client/src/mifare/mad_test.h new file mode 100644 index 000000000..2ff2e4af0 --- /dev/null +++ b/client/src/mifare/mad_test.h @@ -0,0 +1,26 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MAD regression tests +//----------------------------------------------------------------------------- + +#ifndef __MIFARE_MAD_TEST_H__ +#define __MIFARE_MAD_TEST_H__ + +#include + +int exec_mad_test(bool verbose); + +#endif diff --git a/client/src/mifare/mifare4.c b/client/src/mifare/mifare4.c index d12b3131b..7908f2846 100644 --- a/client/src/mifare/mifare4.c +++ b/client/src/mifare/mifare4.c @@ -224,8 +224,7 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo } uint8_t cmd1[4]; - if (nonfirst) { cmd1[0] = 0x76; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; } - else { cmd1[0] = 0x70; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; cmd1[3] = 0x00; } + if (nonfirst) { cmd1[0] = 0x76; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; } else { cmd1[0] = 0x70; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; cmd1[3] = 0x00; } int res = ExchangeRAW14a(cmd1, nonfirst ? 3 : 4, activateField, true, data, sizeof(data), &datalen, silentMode); if (res != PM3_SUCCESS) { @@ -308,7 +307,7 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo memcpy(&IVW[12], &mf4session->R_Ctr, 2); memcpy(&IVW[14], &mf4session->W_Ctr, 2); memcpy(IVW, mf4session->TI, 4); - + aes_decode(IVR, key, &data[1], RndB, 16); RndB[16] = RndB[0]; if (verbose) { @@ -354,7 +353,7 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo PrintAndLogEx(INFO, "< phase2: %s", sprint_hex(data, datalen)); } - if (data[0] != 0x90) { + if (data[0]!=0x90) { if (silentMode == false) { PrintAndLogEx(ERR, "\nAuthentication FAILED. Card did not ACK response"); } @@ -365,8 +364,7 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo return PM3_EWRONGANSWER; } - if (nonfirst) { aes_decode(IVR, key, &data[1], raw, 16); } - else { aes_decode(NULL, key, &data[1], raw, 32); } + if (nonfirst) { aes_decode(IVR, key, &data[1], raw, 16); } else { aes_decode(NULL, key, &data[1], raw, 32); } if (verbose) { if (nonfirst) { @@ -614,6 +612,59 @@ int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data return PM3_SUCCESS; } +int mfpWriteSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, const uint8_t *datain, bool verbose) { + uint8_t keyn[2] = {0}; + + uint16_t uKeyNum = 0x4000 + sectorNo * 2 + (keyType ? 1 : 0); + keyn[0] = uKeyNum >> 8; + keyn[1] = uKeyNum & 0xff; + if (verbose) { + PrintAndLogEx(INFO, "--sector[%u]:%02x key:%04x", mfNumBlocksPerSector(sectorNo), sectorNo, uKeyNum); + } + + mf4Session_t _session; + int res = MifareAuth4(&_session, keyn, key, false, true, true, true, verbose, false); + if (res) { + PrintAndLogEx(ERR, "Sector %u authentication error: %d", sectorNo, res); + return res; + } + + uint8_t firstBlockNo = mfFirstBlockOfSector(sectorNo); + uint8_t numDataBlocks = mfNumBlocksPerSector(sectorNo) - 1; + + for (int n = 0; n < numDataBlocks; n++) { + uint8_t blockNo = firstBlockNo + n; + + uint8_t block[16]; + memcpy(block, datain + (n * 16), 16); + mfp_data_crypt(&_session, block, block, false, 1); + + uint8_t data[250] = {0}; + int datalen = 0; + uint8_t mac[8] = {0}; + res = MFPWriteBlock(&_session, false, false, blockNo & 0xff, 0x00, block, + false, true, data, sizeof(data), &datalen, mac); + if (res) { + PrintAndLogEx(ERR, "Sector %u block %d write error: %d", sectorNo, blockNo, res); + DropField(); + return res; + } + + if (datalen && data[0] != 0x90) { + PrintAndLogEx(ERR, "Sector %u block %d card write error: %02x %s", + sectorNo, blockNo, data[0], mfpGetErrorDescription(data[0])); + DropField(); + return PM3_ESOFT; + } + + if (verbose) + PrintAndLogEx(INFO, "wrote block %d: %s", blockNo, sprint_hex(datain + (n * 16), 16)); + } + + DropField(); + return PM3_SUCCESS; +} + int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { uint8_t c[] = {0x3c, 0x00}; return intExchangeRAW14aPlus(c, sizeof(c), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); diff --git a/client/src/mifare/mifare4.h b/client/src/mifare/mifare4.h index f510df350..913bd53ef 100644 --- a/client/src/mifare/mifare4.h +++ b/client/src/mifare/mifare4.h @@ -67,6 +67,7 @@ int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int int MFPReadBlock(mf4Session_t *mf4session, bool plain, bool nomaccmd, bool nomacres, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac); int MFPWriteBlock(mf4Session_t *mf4session, bool plain, bool nomacres, uint8_t blockNum, uint8_t blockHdr, const uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac); int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose); +int mfpWriteSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, const uint8_t *datain, bool verbose); int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); diff --git a/client/src/mifare/mifaredefault.h b/client/src/mifare/mifaredefault.h index e13e05963..8d832b22d 100644 --- a/client/src/mifare/mifaredefault.h +++ b/client/src/mifare/mifaredefault.h @@ -56,6 +56,14 @@ #define MIFARE_2K_MAX_KEY_SIZE (MIFARE_2K_MAXSECTOR * 2 * MIFARE_KEY_SIZE) #define MIFARE_4K_MAX_KEY_SIZE (MIFARE_4K_MAXSECTOR * 2 * MIFARE_KEY_SIZE) +typedef struct { + uint8_t key_a[MIFARE_KEY_SIZE]; + uint8_t access[3]; + uint8_t gpb; + uint8_t key_b[MIFARE_KEY_SIZE]; +} PACKED mf_trailer_t; + +_Static_assert(sizeof(mf_trailer_t) == MFBLOCK_SIZE, "mf_trailer_t must be one block"); static const uint64_t g_mifare_default_keys[] = { 0xffffffffffff, // Default key (first key used by program if no user defined key) diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index 8d7a9b183..ccc92ead5 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -500,17 +500,6 @@ while true; do if ! CheckExecute "wiegand decode new no padded bin" "if ! $CLIENTBIN -c 'wiegand decode --new 06BD88EB80' 2>&1 | grep -q 'padded bin'; then echo OK; fi" "OK"; then break; fi if ! CheckExecute "wiegand decode new 96-bit" "$CLIENTBIN -c 'wiegand decode --new 00555555555555555555555555'" "hex\\.{14} 555555555555555555555555"; then break; fi if ! CheckExecute "wiegand decode new 48-bit" "$CLIENTBIN -c 'wiegand decode --new 0000A4550148AB'" "C1k48s.*FC: 42069 CN: 42069 parity \( ok \)"; then break; fi - - if ! CheckFileExist "iCLASS transport key exists" "$RESOURCEPATH/iclass_decryptionkey.bin"; then break; fi - ICLASS_TRANSPORT_KEY="$(od -An -tx1 -v "$RESOURCEPATH/iclass_decryptionkey.bin" | tr -d ' \n')" - if ! CheckExecute "hf iclass encrypt default 2k3des" "$CLIENTBIN -c 'hf iclass encrypt -d 00000000063E02A3 -k $ICLASS_TRANSPORT_KEY'" "encrypted\\.\\.\\. 10A145919ED16F50"; then break; fi - if ! CheckExecute "hf iclass decrypt default 2k3des" "$CLIENTBIN -c 'hf iclass decrypt -d 10A145919ED16F50 -k $ICLASS_TRANSPORT_KEY'" "plain\\.\\.\\.\\.\\.\\.\\. 00000000063E02A3"; then break; fi - if ! CheckExecute "hf iclass encrypt des" "$CLIENTBIN -c 'hf iclass encrypt -d 00000000063E02A3 --enc des -k $ICLASS_TRANSPORT_KEY'" "encrypted\\.\\.\\. D50D3FC66AF7E0F3"; then break; fi - if ! CheckExecute "hf iclass decrypt des" "$CLIENTBIN -c 'hf iclass decrypt -d D50D3FC66AF7E0F3 --enc des -k $ICLASS_TRANSPORT_KEY'" "plain\\.\\.\\.\\.\\.\\.\\. 00000000063E02A3"; then break; fi - if ! CheckExecute "hf iclass view dump" "$CLIENTBIN -c 'hf iclass view -f traces/iclass/hf-iclass-dump.json'" "7/0x07 \\| 78 36 02 A2 28 30 10 E8"; then break; fi - if ! CheckExecute "hf iclass view SE AIA SIO block" "$CLIENTBIN -c 'hf iclass view -f traces/iclass/hf-iclass-se-weird.json'" "SIO / SE"; then break; fi - if ! CheckExecute "hf iclass view SE AIA SIO raw" "$CLIENTBIN -c 'hf iclass view -f traces/iclass/hf-iclass-se-weird.json'" "SIO - RAW"; then break; fi - if ! CheckExecute "hf iclass decrypt dump" "$CLIENTBIN -c 'hf iclass decrypt -f traces/iclass/hf-iclass-dump.json --ns -k $ICLASS_TRANSPORT_KEY'" "C1k48s.*FC: 69 CN: 69420 parity \\( ok \\)"; then break; fi if ! CheckExecute "wiegand Verkada40 encode test 1" "$CLIENTBIN -c 'wiegand encode -w Verkada40 --fc 50 --cn 1001'" "86400007D3"; then break; fi if ! CheckExecute "wiegand Verkada40 decode test 1" "$CLIENTBIN -c 'wiegand decode --raw 86400007D3'" "Verkada40.*FC: 50 CN: 1001 parity \( ok \)"; then break; fi if ! CheckExecute "wiegand Verkada40 encode test 2" "$CLIENTBIN -c 'wiegand encode -w Verkada40 --fc 50 --cn 1004'" "86400007D9"; then break; fi @@ -646,6 +635,7 @@ while true; do if ! CheckExecute "hf cipurse test" "$CLIENTBIN -c 'hf cipurse test'" "Tests \( ok"; then break; fi if ! CheckExecute "hf mfdes test" "$CLIENTBIN -c 'hf mfdes test'" "Tests \( ok"; then break; fi if ! CheckExecute "hf gst test" "$CLIENTBIN -c 'hf gst test'" "Tests \( ok"; then break; fi + if ! CheckExecute "mad test" "$CLIENTBIN -c 'mad test'" "Tests \( ok"; then break; fi if ! CheckExecute "hf waveshare load" "$CLIENTBIN -c 'hf waveshare load -m 6 -f tools/lena.bmp -s dither.bmp' && echo '34ff55fe7257876acf30dae00eb0e439 dither.bmp' | md5sum -c -" "dither.bmp: OK"; then break; fi fi echo -e "\n------------------------------------------------------------"