phase 1 simulation and desfire fixes...

This commit is contained in:
iceman1001 committed 2026-09-14 21:13:10 +02:00
1 parent e5a44e1874
commit a7b1276781
13 files changed
+840 -20

No files matched your search

+1 -1
View File
@@ -1071,7 +1071,7 @@ int CmdHF14ASim(const char *Cmd) {
"Use type 7 for Mifare Ultralight EV1, Amiibo (NTAG215 pack 0x8080)",
"hf 14a sim -t 1 --uid 11223344 -> MIFARE Classic 1k\n"
"hf 14a sim -t 2 -> MIFARE Ultralight\n"
"hf 14a sim -t 3 -> MIFARE Desfire\n"
"hf 14a sim -t 3 -> MIFARE DESFire (card image from `hf mfdes eload`)\n"
"hf 14a sim -t 4 -> ISO/IEC 14443-4\n"
"hf 14a sim -t 5 -> MIFARE Tnp3xxx\n"
"hf 14a sim -t 6 -> MIFARE Mini\n"
+125 -6
View File
@@ -661,7 +661,14 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE
size_t prepare_resp_len = 0;
uint8_t respcode = 0xFF;
res = DesfireExchangeEx(activate_field, dctx, MFDES_PREPARE_PC, NULL, 0, &respcode, prepare_resp, &prepare_resp_len, true, 0);
if (res != PM3_SUCCESS) {
if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) {
// DesfireExchangeEx reports the transport result; the card's own status
// comes back in respcode and an error there still reads as success. It
// also ends the authentication, so drop our side of the session.
if (res == PM3_SUCCESS) {
res = PM3_EAPDU_FAIL;
}
DesfireClearSession(dctx);
uint16_t sw = status(respcode);
PrintAndLogEx(ERR, "Prepare proximity check command failed. Result: %d %s", res, DesfireGetErrorString(res, &sw));
goto out;
@@ -715,7 +722,11 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE
respcode = 0xFF;
res = DesfireExchange(dctx, MFDES_PROXIMITY_CHECK, round_payload, challenge_part_len + 1, &respcode, round_resp, &round_resp_len);
if (res != PM3_SUCCESS) {
if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) {
if (res == PM3_SUCCESS) {
res = PM3_EAPDU_FAIL;
}
DesfireClearSession(dctx);
uint16_t sw = status(respcode);
PrintAndLogEx(ERR, "Proximity check round %u command failed. Result: %d %s", (unsigned int)round + 1, res, DesfireGetErrorString(res, &sw));
goto out;
@@ -767,7 +778,11 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE
size_t verify_resp_len = 0;
respcode = 0xFF;
res = DesfireExchange(dctx, MFDES_VERIFY_PC, verify_cmd_mac, sizeof(verify_cmd_mac), &respcode, verify_resp, &verify_resp_len);
if (res != PM3_SUCCESS) {
if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) {
if (res == PM3_SUCCESS) {
res = PM3_EAPDU_FAIL;
}
DesfireClearSession(dctx);
uint16_t sw = status(respcode);
PrintAndLogEx(ERR, "Verify proximity check command failed. Result: %d %s", res, DesfireGetErrorString(res, &sw));
goto out;
@@ -1468,6 +1483,13 @@ static int AuthCheckDesfire(DesfireContext_t *dctx,
if (res == PM3_SUCCESS) {
if (filescount > 0) {
for (int i = 0; i < filescount; i++) {
if (fileList[i].fileSettingsRead == false) {
// settings we could not read tell us nothing about which
// keys the file uses, so keep every key in the search
for (int k = 0; k < DESFIRE_MAX_KEY_COUNT; k++)
usedkeys[k] = 1;
break;
}
if (fileList[i].fileSettings.rAccess < 0x0e)
usedkeys[fileList[i].fileSettings.rAccess] = 1;
if (fileList[i].fileSettings.wAccess < 0x0e)
@@ -3128,6 +3150,7 @@ static int DesfireGetDelegatedInfoNoFieldOn(DesfireContext_t *dctx, uint16_t dam
}
if (respcode != MFDES_S_OPERATION_OK) {
DesfireClearSession(dctx);
return PM3_EAPDU_FAIL;
}
@@ -8156,8 +8179,13 @@ static int CmdHF14ADesLsFiles(const char *Cmd) {
}
PrintAndLogEx(INFO, "------------------------------------------ " _CYAN_("File list") " -----------------------------------------------------");
for (int i = 0; i < filescount; i++)
for (int i = 0; i < filescount; i++) {
if (FileList[i].fileSettingsRead == false) {
PrintAndLogEx(WARNING, "File " _YELLOW_("0x%02x") " settings could not be read", FileList[i].fileNum);
continue;
}
DesfirePrintFileSettingsTable((i == 0), FileList[i].fileNum, isopresent, FileList[i].fileISONum, &FileList[i].fileSettings);
}
DropField();
return PM3_SUCCESS;
@@ -8343,7 +8371,15 @@ static int DesfireDumpFindApp(const AppListS appList, size_t appcount, const Des
return -1;
}
static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f) {
static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f, bool settings_ok) {
// Settings we never read are not a 0 byte standard data file. Leave the
// whole record at its defaults and say so, the same way read_ok does for
// contents -- a simulator built from this image must not invent a file.
if (settings_ok == false) {
f->settings_ok = false;
return;
}
f->type = fs->fileType;
f->commmode = fs->fileCommMode;
@@ -8583,9 +8619,16 @@ static int DesfireDumpCollectApp(DesfireContext_t *dctx, desfire_dump_app_t *app
desfire_dump_file_t *f = &app->files[app->filecount];
f->num = FileList[i].fileNum;
f->isofid = FileList[i].fileISONum;
DesfireDumpFillFileSettings(&FileList[i].fileSettings, f);
DesfireDumpFillFileSettings(&FileList[i].fileSettings, f, FileList[i].fileSettingsRead);
app->filecount++;
if (FileList[i].fileSettingsRead == false) {
// without the settings we do not know the file's type, so there is
// no sensible read command to send
PrintAndLogEx(WARNING, "File " _YELLOW_("0x%02x") " settings could not be read, contents skipped", f->num);
continue;
}
session_lost = (DesfireDumpReadFile(dctx, &FileList[i].fileSettings, f, maxlength, verbose) == PM3_ESOFT);
DesfireDumpPrintFile(f, isopresent);
@@ -9043,6 +9086,81 @@ static void DesfireViewPrintApp(const desfire_dump_app_t *app) {
}
}
static int CmdHF14ADesSim(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes sim",
"Simulate the DESFire card image currently in emulator memory.\n"
"Load one first with `hf mfdes eload`, and read back what a reader\n"
"changed with `hf mfdes esave`.\n"
"\n"
"This is `hf 14a sim -t 3` with the DESFire command set behind it:\n"
"UID, ATQA, SAK and ATS all come out of the loaded image",
"hf mfdes sim\n"
"hf mfdes sim -n 1 -> stop after the first reader session\n");
void *argtable[] = {
arg_param_begin,
arg_int0("n", "num", "<dec>", "Exit after <num> commands have been answered. 0 = infinite"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint8_t exit_after = arg_get_int_def(ctx, 1, 0);
CLIParserFree(ctx);
// Same payload the 14a simulation takes -- there is one 14443a tag loop on
// the device and this is it. Tag type 3 is MIFARE DESFire; the UID is left
// for the device to lift out of the card image header, which is why no UID
// is supplied here.
struct {
uint8_t tagtype;
uint16_t flags;
uint8_t uid[10];
uint8_t exitAfter;
uint8_t rats[20];
uint8_t ulauth_1a1_len;
uint8_t ulauth_1a2_len;
uint8_t ulauth_1a1[16];
uint8_t ulauth_1a2[16];
bool ulauth_1a2_mirror;
} PACKED payload;
memset(&payload, 0x00, sizeof(payload));
payload.tagtype = 3;
payload.exitAfter = exit_after;
FLAG_SET_UID_IN_EMUL(payload.flags);
clearCommandBuffer();
SendCommandNG(CMD_HF_ISO14443A_SIMULATE, (uint8_t *)&payload, sizeof(payload));
PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("<Enter>") " to abort simulation");
PacketResponseNG resp;
bool keypress = kbd_enter_pressed();
while (keypress == false) {
keypress = kbd_enter_pressed();
if (WaitForResponseTimeout(CMD_HF_MIFARE_SIMULATE, &resp, 1500) == false) {
continue;
}
if (resp.status != PM3_SUCCESS) {
PrintAndLogEx(WARNING, "Simulation stopped");
PrintAndLogEx(HINT, "Hint: load a card image with " _YELLOW_("`hf mfdes eload -f <fn>`"));
return resp.status;
}
break;
}
if (keypress) {
SendCommandNG(CMD_BREAK_LOOP, NULL, 0);
}
PrintAndLogEx(INFO, "Done!");
PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes esave`") " to see what a reader changed");
return PM3_SUCCESS;
}
static int CmdHF14ADesELoad(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes eload",
@@ -11018,6 +11136,7 @@ static command_t CommandTable[] = {
{"eload", CmdHF14ADesELoad, IfPm3Iso14443a, "Upload file into emulator memory"},
{"esave", CmdHF14ADesESave, IfPm3Iso14443a, "Save emulator memory to file"},
{"eview", CmdHF14ADesEView, IfPm3Iso14443a, "View emulator memory"},
{"sim", CmdHF14ADesSim, IfPm3Iso14443a, "Simulate DESFire card from emulator memory"},
{"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"},
{"createvaluefile", CmdHF14ADesCreateValueFile, IfPm3Iso14443a, "Create Value File"},
{"createrecordfile", CmdHF14ADesCreateRecordFile, IfPm3Iso14443a, "Create Linear/Cyclic Record File"},
+96 -9
View File
@@ -437,6 +437,27 @@ void DesfirePrintContext(DesfireContext_t *ctx) {
}
}
// Table 11 of M075031 footnotes five status codes as "not expected to appear
// during normal operation": the card saying it has damaged or disabled itself.
// Those are never noise, so they are reported whether or not APDU logging is on.
// Everything else is an ordinary refusal, and the caller decides what to say.
static void DesfireReportUnrecoverable(uint8_t cmd, uint8_t respcode) {
if (respcode != MFDES_E_PICC_INTEGRITY &&
respcode != MFDES_E_PICC_DISABLED &&
respcode != MFDES_E_APPL_INTEGRITY &&
respcode != MFDES_E_FILE_INTEGRITY &&
respcode != MFDES_E_EEPROM) {
return;
}
uint16_t sw = DESFIRE_GET_ISO_STATUS(respcode);
PrintAndLogEx(WARNING, "Desfire command " _YELLOW_("0x%02X") " -> " _RED_("0x%02X") " %s"
, cmd
, respcode
, DesfireGetErrorString(PM3_EAPDU_FAIL, &sw));
}
static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) {
if (result_len) *result_len = 0;
if (sw) *sw = 0;
@@ -483,6 +504,11 @@ static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uin
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_SIGNATURE) &&
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_ADDITIONAL_FRAME) &&
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_NO_CHANGES)) {
if ((isw >> 8) == 0x91) {
DesfireReportUnrecoverable(apdu.INS, isw & 0xFF);
}
if (GetAPDULogging()) {
if (isw >> 8 == 0x61) {
PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff);
@@ -567,6 +593,8 @@ static int DESFIRESendRaw(bool activate_field, uint8_t *data, size_t datalen, ui
if (!rcode_ok) {
DesfireReportUnrecoverable(data[0], rcode);
if (GetAPDULogging()) {
PrintAndLogEx(ERR, "Command (%02x) ERROR: 0x%02x", data[0], rcode);
}
@@ -2002,7 +2030,18 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap
// result bytes: 3, 2, 1-16. total record size = 24
res = DesfireGetDFList(dctx, buf, &buflen);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, "Desfire GetDFList command " _RED_("error") ". Result: %d", res);
// Same hazard as GetFileISOIDList below: the PICC ends the authentication
// on a command error, so drop our side of the session too. Left alone,
// every following command is still framed as MACed against a session the
// card has already thrown away, and the card sees a run of frames whose
// integrity it cannot verify. Callers that keep using the card
// re-authenticate.
dctx->secureChannel = DACNone;
uint16_t dfsw = DESFIRE_GET_ISO_STATUS(dctx->lastRespCode);
PrintAndLogEx(WARNING, "Desfire GetDFList command " _RED_("error") ". Result: %d, card said " _RED_("0x%02X") " %s. Session dropped by the PICC"
, res
, dctx->lastRespCode
, DesfireGetErrorString(PM3_EAPDU_FAIL, &dfsw));
} else if (buflen > 0) {
for (int i = 0; i < buflen; i++) {
int indx = AppListSearchAID(DesfireAIDByteToUint(&buf[i * 24 + 1]), appList, PICCInfo->appCount);
@@ -2030,7 +2069,7 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap
if (res != PM3_SUCCESS)
continue;
DesfireGetKeySettings(dctx, buf, &buflen);
res = DesfireGetKeySettings(dctx, buf, &buflen);
if (res == PM3_SUCCESS && buflen >= 2) {
appList[i].keySettings = buf[0];
appList[i].numKeysRaw = buf[1];
@@ -2126,7 +2165,11 @@ void DesfirePrintAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS
PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a"));
}
}
DesfirePrintFileSettingsExtended(&appList[i].fileList[fnum].fileSettings);
if (appList[i].fileList[fnum].fileSettingsRead) {
DesfirePrintFileSettingsExtended(&appList[i].fileList[fnum].fileSettings);
} else {
PrintAndLogEx(WARNING, "File settings : " _YELLOW_("could not be read"));
}
}
}
PrintAndLogEx(NORMAL, "");
@@ -2156,6 +2199,24 @@ static int DesfireCommandEx(DesfireContext_t *dctx, uint8_t cmd, uint8_t *data,
}
if (respcode != MFDES_S_OPERATION_OK) {
// Keep and print which status the card returned. Every card error
// collapses to PM3_EAPDU_FAIL on the way out, so without this the
// difference between 0x1C ILLEGAL_COMMAND_CODE, 0xCA COMMAND_ABORTED and
// 0xC1 PICC_INTEGRITY_ERROR -- the card saying it has just disabled
// itself -- never reaches the caller or the log.
dctx->lastRespCode = respcode;
uint16_t sw = DESFIRE_GET_ISO_STATUS(respcode);
PrintAndLogEx(DEBUG, "Desfire command " _YELLOW_("0x%02X") " returned " _RED_("0x%02X") " %s"
, cmd
, respcode
, DesfireGetErrorString(PM3_EAPDU_FAIL, &sw));
// The PICC ends the authentication on a command error, so drop our side
// of the session too. Left set, every following command is still framed
// as MACed against a session the card has thrown away: the plain answer
// gets parsed as a CMAC, and the card sees a run of frames whose
// integrity it cannot verify. Callers that keep going re-authenticate.
DesfireClearSession(dctx);
free(xresp);
return PM3_EAPDU_FAIL;
}
@@ -2230,6 +2291,7 @@ int DesfireReadSignature(DesfireContext_t *dctx, uint8_t sid, uint8_t *resp, siz
}
if (respcode != 0x90) {
DesfireClearSession(dctx);
return PM3_EAPDU_FAIL;
}
@@ -2283,6 +2345,7 @@ int DesfireCreateDelegatedApplication(DesfireContext_t *dctx, uint8_t *appdata,
return res;
}
if (respcode != MFDES_S_OPERATION_OK) {
DesfireClearSession(dctx);
return PM3_EAPDU_FAIL;
}
@@ -2360,7 +2423,8 @@ int DesfireFillFileList(DesfireContext_t *dctx, FileList_t FileList, size_t *fil
for (int i = 0; i < buflen; i++) {
FileList[i].fileNum = buf[i];
DesfireFileSettingsStruct(dctx, FileList[i].fileNum, &FileList[i].fileSettings);
FileList[i].fileSettingsRead =
(DesfireFileSettingsStruct(dctx, FileList[i].fileNum, &FileList[i].fileSettings) == PM3_SUCCESS);
}
*filescount = buflen;
@@ -2378,6 +2442,13 @@ int DesfireFillFileList(DesfireContext_t *dctx, FileList_t FileList, size_t *fil
size_t isoindx = 0;
if (buflen > 0) {
for (int i = 0; i < *filescount; i++) {
if (FileList[i].fileSettingsRead == false) {
// we do not know this file's type, so we cannot tell whether it
// takes an entry. Stop rather than hand out ISO ids that belong
// to other files.
PrintAndLogEx(DEBUG, "File 0x%02x settings unknown, ISO ID mapping stops here", FileList[i].fileNum);
break;
}
if (FileList[i].fileSettings.fileType != 0x02 && FileList[i].fileSettings.fileType != 0x05) {
FileList[i].fileISONum = MemLeToUint2byte(&buf[isoindx * 2]);
isoindx++;
@@ -3190,8 +3261,12 @@ int DesfireISOSelectEx(DesfireContext_t *dctx, bool fieldon, DesfireISOSelectCon
if (res == PM3_EAPDU_FAIL && sw == 0 && xresplen == 0) {
return PM3_ECARDEXCHANGE;
}
if (res == PM3_SUCCESS && sw != ISO7816_OK)
if (res == PM3_SUCCESS && sw != ISO7816_OK) {
// the success path below clears the session because a select ends the
// authentication; a refused select ends it just the same
DesfireClearSession(dctx);
return PM3_ESOFT;
}
if (resp != NULL && resplen != NULL) {
*resplen = xresplen;
@@ -3260,8 +3335,11 @@ int DesfireISOReadBinary(DesfireContext_t *dctx, bool use_file_id, uint8_t filei
uint16_t sw = 0;
int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_READ_BINARY, p1, p2, 0, NULL}, (length == 0) ? APDU_INCLUDE_LE_00 : length, resp, resplen, &sw);
if (res == PM3_SUCCESS && sw != ISO7816_OK)
if (res == PM3_SUCCESS && sw != ISO7816_OK) {
// an error ends the authentication on the card, so drop our side too
DesfireClearSession(dctx);
return PM3_ESOFT;
}
return res;
}
@@ -3279,8 +3357,11 @@ int DesfireISOUpdateBinary(DesfireContext_t *dctx, bool use_file_id, uint8_t fil
uint16_t sw = 0;
int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_UPDATE_BINARY, p1, p2, datalen, data}, 0, resp, &resplen, &sw);
if (res == PM3_SUCCESS && sw != ISO7816_OK)
if (res == PM3_SUCCESS && sw != ISO7816_OK) {
// an error ends the authentication on the card, so drop our side too
DesfireClearSession(dctx);
return PM3_ESOFT;
}
return res;
}
@@ -3290,8 +3371,11 @@ int DesfireISOReadRecords(DesfireContext_t *dctx, uint8_t recordnum, bool read_a
uint16_t sw = 0;
int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_READ_RECORDS, recordnum, p2, 0, NULL}, (length == 0) ? APDU_INCLUDE_LE_00 : length, resp, resplen, &sw);
if (res == PM3_SUCCESS && sw != ISO7816_OK)
if (res == PM3_SUCCESS && sw != ISO7816_OK) {
// an error ends the authentication on the card, so drop our side too
DesfireClearSession(dctx);
return PM3_ESOFT;
}
return res;
}
@@ -3304,8 +3388,11 @@ int DesfireISOAppendRecord(DesfireContext_t *dctx, uint8_t fileid, uint8_t *data
uint16_t sw = 0;
int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_APPEND_RECORD, 0x00, p2, datalen, data}, 0, resp, &resplen, &sw);
if (res == PM3_SUCCESS && sw != ISO7816_OK)
if (res == PM3_SUCCESS && sw != ISO7816_OK) {
// an error ends the authentication on the card, so drop our side too
DesfireClearSession(dctx);
return PM3_ESOFT;
}
return res;
}
+4
View File
@@ -95,6 +95,10 @@ typedef struct {
typedef struct {
uint8_t fileNum;
uint16_t fileISONum;
// false means GetFileSettings failed for this file, so fileSettings is
// zeros and not a 0 byte standard data file. Callers must not read
// fileSettings without checking this first
bool fileSettingsRead;
FileSettings_t fileSettings;
} FileListElm_t;
+4
View File
@@ -86,6 +86,10 @@ typedef struct {
uint8_t sessionKeyEnc[DESFIRE_MAX_KEY_SIZE]; // look at mifare4.h - mf4Session_t
uint8_t lastIV[DESFIRE_MAX_KEY_SIZE];
uint8_t lastCommand;
// status byte of the last answer the card gave. Every card error collapses
// to PM3_EAPDU_FAIL on the way out, so this is the only place the caller can
// find out which one it was
uint8_t lastRespCode;
bool lastRequestZeroLen;
uint16_t cmdCntr; // for AES
uint8_t TI[4]; // for AES
+6
View File
@@ -601,6 +601,12 @@ void desfire_em_print(const uint8_t *img, size_t imglen) {
const desfire_em_hdr_t *hdr = (const desfire_em_hdr_t *)img;
if (hdr->magic != DESFIRE_EM_MAGIC) {
PrintAndLogEx(WARNING, "No DESFire card image here, magic is " _YELLOW_("%08X"), hdr->magic);
PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f <fn>`"));
return;
}
PrintAndLogEx(INFO, "--- " _CYAN_("DESFire card image") " -----------------------");
PrintAndLogEx(SUCCESS, "Generation....... %s", desfire_em_gen_str(hdr->generation));
PrintAndLogEx(SUCCESS, "UID.............. %s", sprint_hex_inrow(hdr->uid, hdr->uidlen));