diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e2c7eaff..cb82e055a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Added `hf mfdes dump` - now walks the whole PICC and saves a `hf-mfdes--dump.json` card image, picking up `hf-mfdes--keys.json` on its own (@iceman1001) +- Added `hf mfdes view` - print a DESFire card dump file, no device needed (@iceman1001) +- Fixed `sprint_hex` - a buffer twice the old size, so printing a long block no longer runs off the end of the static buffer (@iceman1001) - Added `vigik_recover_pk.py` - recover public keys from RSA signatures (@iceman1001) - Fixed `hf mf autopwn` - a sector that cannot be cracked no longer discards the keys already recovered (@iceman1001) - Fixed `hf mf nested` - a NAK from the tag now ends the nonce collection instead of retrying until the client times out (@iceman1001) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 95aa11d35..cf8d95ea9 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -8229,11 +8229,380 @@ static int CmdHF14ADesLsApp(const char *Cmd) { return PM3_SUCCESS; } +//----------------------------------------------------------------------------- +// DESFire card image collection. +// +// `hf mfdes dump` walks the whole PICC into a desfire_dump_t and writes it out +// as a jsfMfDesfire_v1 json file. `hf mfdes view` reads one back. +// See doc/mfdes_dump_format.md for the on-disk schema. +//----------------------------------------------------------------------------- + +// the 14a select answer carries UID/ATQA/SAK/ATS, none of which the DESFire +// layer keeps around +static int DesfireDumpFillCardInfo(iso14a_card_select_t *card_info) { + + DropField(); + SendIso14aReader(ISO14A_CONNECT | ISO14A_CLEARTRACE, NULL, 0); + + PacketResponseNG resp; + uint8_t select_status = 0; + if (WaitForIso14aReply(&resp, 2500, NULL, &select_status) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for card select"); + return PM3_ETIMEOUT; + } + + // 0: couldn't read, 1: OK with ATS, 2: OK no ATS, 3: proprietary anticollision + if (select_status != 1 && select_status != 2) { + return PM3_ESOFT; + } + + memcpy(card_info, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); + return PM3_SUCCESS; +} + +// record a key we authenticated with. The algo is the application's, not the +// key's, so it is not stored here -- see desfire_dump_app_t.keytype +static void DesfireDumpStoreKey(desfire_dump_app_t *app, uint8_t keyno, uint8_t algo, const uint8_t *key) { + + if (keyno >= DESFIRE_MAX_KEY_COUNT) { + return; + } + + app->keytype = algo; + app->keys.present[keyno] = 1; + memcpy(app->keys.key[keyno], key, desfire_get_key_length(algo)); +} + +// pull keyno for `aid` out of a `hf mfdes chk` key file, NULL when we have none +static const uint8_t *DesfireDumpFindKey(const desfire_keys_dump_t *keyfile, uint32_t aid, uint8_t algo, uint8_t keyno) { + + if (keyfile == NULL || keyno >= DESFIRE_MAX_KEY_COUNT || algo >= DESFIRE_MAX_ALGO_COUNT) { + return NULL; + } + + for (uint8_t i = 0; i < keyfile->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + if (keyfile->app[i].aid != aid) { + continue; + } + if (keyfile->app[i].keys[algo][keyno][0] == 0) { + return NULL; + } + return &keyfile->app[i].keys[algo][keyno][1]; + } + return NULL; +} + +static void DesfireDumpFillAppMeta(desfire_dump_app_t *app, const AppListElm_t *src) { + + app->aid = src->appNum; + app->isofid = src->appISONum; + app->keysettings = src->keySettings; + app->numkeysraw = src->numKeysRaw; + app->numkeys = src->numberOfKeys; + app->keytype = src->keyType; + app->settings_ok = (src->numKeysRaw != 0); + + for (uint8_t i = 0; i < src->numberOfKeys && i < DESFIRE_MAX_KEY_COUNT; i++) { + app->keys.version[i] = src->keyVersions[i]; + app->keys.versionknown[i] = 1; + } + + app->dfnamelen = str_nlen((char *)src->appDFName, sizeof(src->appDFName)); + memcpy(app->dfname, src->appDFName, app->dfnamelen); +} + +// find the application the user named on the command line in the PICC's own +// list, so an --isoid or --dfname dump still records the AID and key settings +static int DesfireDumpFindApp(const AppListS appList, size_t appcount, const DesfireContext_t *dctx, + DesfireISOSelectWay selectway, uint32_t id) { + + for (size_t i = 0; i < appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + + switch (selectway) { + case ISW6bAID: + if (appList[i].appNum == id) { + return i; + } + break; + case ISWIsoID: + if (appList[i].appISONum == id) { + return i; + } + break; + case ISWDFName: + if (dctx->selectedDFNameLen > 0 && + memcmp(appList[i].appDFName, dctx->selectedDFName, dctx->selectedDFNameLen) == 0) { + return i; + } + break; + case ISWMF: + break; + } + } + return -1; +} + +static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f) { + + f->type = fs->fileType; + f->commmode = fs->fileCommMode; + f->accessrights = fs->rawAccessRights; + f->size = fs->fileSize; + f->lowerlimit = fs->lowerLimit; + f->upperlimit = fs->upperLimit; + f->limitedcredit = fs->limitedCredit; + f->recordsize = fs->recordSize; + f->maxrecords = fs->maxRecordCount; + f->currecords = fs->curRecordCount; + + f->addrights_len = fs->additionalAccessRightsLength; + if (f->addrights_len > ARRAYLEN(f->addrights)) { + f->addrights_len = ARRAYLEN(f->addrights); + } + for (uint8_t i = 0; i < f->addrights_len; i++) { + f->addrights[i] = fs->additionalAccessRights[i]; + } + + f->settings_ok = true; +} + +// read one file into the image. Leaves f->read_ok false when the contents +// could not be fetched -- the caller must not turn that into zeroed data +static int DesfireDumpReadFile(DesfireContext_t *dctx, const FileSettings_t *fs, desfire_dump_file_t *f, + uint32_t maxdatafilelength, bool verbose) { + + f->read_ok = false; + + int filetype; + switch (fs->fileType) { + case 0x00: + case 0x01: + filetype = RFTData; + break; + case 0x02: + filetype = RFTValue; + break; + case 0x03: + case 0x04: + filetype = RFTRecord; + break; + case 0x05: + filetype = RFTMAC; + break; + default: + // nothing was sent, the session is still good + return PM3_EINVARG; + } + + // iso chaining works in the lrp mode + dctx->isoChaining |= (dctx->secureChannel == DACLRP); + + DesfireCommunicationMode commMode; + if (filetype == RFTValue) { + commMode = DesfireValueOpCommMode(dctx, fs, MFDES_GET_VALUE); + } else { + const uint8_t rrights[] = { fs->rAccess, fs->rwAccess }; + commMode = DesfireEffectiveCommMode(dctx, fs->commMode, rrights, ARRAYLEN(rrights)); + } + + // lrp needs to point exact mode + if (dctx->secureChannel == DACLRP && fs->rAccess == 0x0e) { + commMode = DCMPlain; + } + + if (fs->rAccess == 0x0f && fs->rwAccess == 0x0f) { + if (verbose) { + PrintAndLogEx(INFO, "File 0x%02x read access is denied (0x0F), skipping contents", f->num); + } + // nothing was sent, the session is still good + return PM3_EINVARG; + } + + DesfireSetCommMode(dctx, commMode); + + if (filetype == RFTValue) { + uint32_t value = 0; + if (DesfireValueFileOperations(dctx, f->num, MFDES_GET_VALUE, &value) != PM3_SUCCESS) { + return PM3_ESOFT; + } + f->value = value; + f->read_ok = true; + return PM3_SUCCESS; + } + + uint8_t *resp = calloc(DESFIRE_BUFFER_SIZE, sizeof(uint8_t)); + if (resp == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return PM3_EMALLOC; + } + size_t resplen = 0; + int res; + + if (filetype == RFTRecord) { + + size_t reclen = fs->recordSize; + res = DesfireReadRecords(dctx, f->num, 0, 0, resp, &resplen); + if (res != PM3_SUCCESS) { + free(resp); + return PM3_ESOFT; + } + + if (reclen == 0 && resplen > 0) { + reclen = resplen; + } + f->recordsize = reclen; + + } else { + uint32_t length = 0; + if (filetype == RFTData && maxdatafilelength && (maxdatafilelength < fs->fileSize)) { + length = maxdatafilelength; + } + + res = DesfireReadFile(dctx, f->num, 0, length, resp, &resplen); + if (res != PM3_SUCCESS) { + free(resp); + return PM3_ESOFT; + } + } + + if (resplen == 0) { + // an empty answer is a successful read of nothing, keep read_ok true + // so a reader can tell it apart from "we never got there" + free(resp); + f->read_ok = true; + return PM3_SUCCESS; + } + + f->data = calloc(resplen, sizeof(uint8_t)); + if (f->data == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + free(resp); + return PM3_EMALLOC; + } + + memcpy(f->data, resp, resplen); + f->datalen = resplen; + f->read_ok = true; + free(resp); + return PM3_SUCCESS; +} + +static void DesfireDumpPrintFile(const desfire_dump_file_t *f, bool isopresent) { + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--------------------------------- " _CYAN_("File %02x") " ----------------------------------", f->num); + PrintAndLogEx(SUCCESS, "File ID : " _GREEN_("%02x"), f->num); + if (isopresent) { + if (f->isofid != 0) { + PrintAndLogEx(SUCCESS, "File ISO ID : %04x", f->isofid); + } else { + PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); + } + } + + if (f->read_ok == false) { + PrintAndLogEx(WARNING, "Contents : " _YELLOW_("not read")); + return; + } + + if (f->type == 0x02) { + PrintAndLogEx(SUCCESS, "Value : %u (0x%08x)", f->value, f->value); + return; + } + + if (f->datalen == 0) { + PrintAndLogEx(SUCCESS, "Contents : " _YELLOW_("empty")); + return; + } + + if ((f->type == 0x03 || f->type == 0x04) && f->recordsize > 0 && (f->datalen % f->recordsize) == 0) { + uint32_t reccount = f->datalen / f->recordsize; + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x, %u record(s) of %u bytes", f->datalen, f->num, reccount, f->recordsize); + for (uint32_t i = 0; i < reccount; i++) { + if (i != 0) { + PrintAndLogEx(SUCCESS, "Record %u", i); + } + print_buffer_with_offset(f->data + (i * f->recordsize), f->recordsize, 0, (i == 0)); + } + return; + } + + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x", f->datalen, f->num); + print_buffer_with_offset(f->data, f->datalen, 0, true); +} + +// collect one application. The caller has already selected and authenticated +static int DesfireDumpCollectApp(DesfireContext_t *dctx, desfire_dump_app_t *app, uint32_t maxlength, + DesfireISOSelectWay selectway, uint32_t id, int securechann, + bool noauth, bool verbose) { + + FileList_t FileList = {{0}}; + size_t filescount = 0; + bool isopresent = false; + + int res = DesfireFillFileList(dctx, FileList, &filescount, &isopresent); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Can't get file list for application " _YELLOW_("%06X"), app->aid); + return res; + } + + // the ISO file id probe in DesfireFillFileList makes the PICC end the session on + // applications without ISO file ids, so get it back before reading the files + if (noauth == false && DesfireIsAuthenticated(dctx) == false) { + DesfireSetCommMode(dctx, DCMPlain); + res = DesfireSelectAndAuthenticateAppW(dctx, securechann, selectway, id, noauth, verbose); + if (res != PM3_SUCCESS) { + return res; + } + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, "Application " _CYAN_("%s") " have " _GREEN_("%zu") " files", DesfireWayIDStr(selectway, id), filescount); + + if (selectway == ISW6bAID) { + DesfirePrintAIDFunctions(id); + } + + app->filecount = 0; + bool session_lost = false; + + for (size_t i = 0; i < filescount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + // a refused exchange ends the PICC session, re-open it before the next file. + // a file we chose not to read never reached the card and costs us nothing + if (session_lost) { + DesfireSetCommMode(dctx, DCMPlain); + if (DesfireSelectAndAuthenticateAppW(dctx, securechann, selectway, id, noauth, verbose) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Lost the session on application " _YELLOW_("%06X") ", stopping here", app->aid); + break; + } + session_lost = false; + } + + desfire_dump_file_t *f = &app->files[app->filecount]; + f->num = FileList[i].fileNum; + f->isofid = FileList[i].fileISONum; + DesfireDumpFillFileSettings(&FileList[i].fileSettings, f); + app->filecount++; + + session_lost = (DesfireDumpReadFile(dctx, &FileList[i].fileSettings, f, maxlength, verbose) == PM3_ESOFT); + + DesfireDumpPrintFile(f, isopresent); + DesfirePrintFileSettingsExtended(&FileList[i].fileSettings); + } + + return PM3_SUCCESS; +} + static int CmdHF14ADesDump(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes dump", - "For each application show fil list and then file content. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", - "hf mfdes dump --aid 123456 -> show file dump for: app=123456 with channel defaults from `default` command/n" + "Dump a DESFire card to a json file. Walks every application and every file\n" + "unless an application is named with --aid / --isoid / --dfname.\n" + "Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", + "hf mfdes dump -> dump the whole PICC with channel defaults from `default` command\n" + "hf mfdes dump --aid 123456 -> dump only application 123456\n" + "hf mfdes dump --keys hf-mfdes-0102030405-keys.json -> use recovered keys per application\n" "hf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit"); void *argtable[] = { @@ -8253,6 +8622,9 @@ static int CmdHF14ADesDump(const char *Cmd) { arg_str0(NULL, "dfname", "", "Application ISO DF Name (5-16 hex bytes, big endian)"), arg_str0("l", "length", "", "Maximum length for read data files (3 hex bytes, big endian)"), arg_lit0(NULL, "no-auth", "Execute without authentication"), + arg_str0("f", "file", "", "Save dump to file, if no UID will be used as filename"), + arg_str0(NULL, "keys", "", "Load application keys from a `hf mfdes chk` key file"), + arg_lit0(NULL, "ns", "No save to file"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -8261,6 +8633,21 @@ static int CmdHF14ADesDump(const char *Cmd) { bool verbose = arg_get_lit(ctx, 2); bool noauth = arg_get_lit(ctx, 15); + // an application was named on the command line? then dump only that one + bool single_app = (arg_get_str(ctx, 11)->count > 0) || + (arg_get_str(ctx, 12)->count > 0) || + (arg_get_str(ctx, 13)->count > 0); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 16), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + int keyfnlen = 0; + char keyfilename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 17), (uint8_t *)keyfilename, FILE_PATH_SIZE, &keyfnlen); + + bool nosave = arg_get_lit(ctx, 18); + DesfireContext_t dctx = {0}; int securechann = defaultSecureChannel; uint32_t id = 0x000000; @@ -8280,70 +8667,444 @@ static int CmdHF14ADesDump(const char *Cmd) { SetAPDULogging(APDULogging); CLIParserFree(ctx); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; } - FileList_t FileList = {{0}}; - size_t filescount = 0; - bool isopresent = false; - res = DesfireFillFileList(&dctx, FileList, &filescount, &isopresent); - if (res != PM3_SUCCESS) { - DropField(); - return res; + // UID / ATQA / SAK / ATS come from the 14a layer, grab them before we talk DESFire + DesfireDumpFillCardInfo(&dump->card_info); + DropField(); + + // no --keys given? look for the key file this card would have been saved + // under, the same `hf-mfdes--...` template the dump itself uses + bool autokeys = false; + if (keyfnlen == 0 && dump->card_info.uidlen > 0) { + strcat(keyfilename, "hf-mfdes-"); + FillFileNameByUID(keyfilename, dump->card_info.uid, "-keys", dump->card_info.uidlen); + keyfnlen = strlen(keyfilename); + autokeys = true; } - // the ISO file id probe in DesfireFillFileList makes the PICC end the session on - // applications without ISO file ids, so get it back before reading the files - if (noauth == false && DesfireIsAuthenticated(&dctx) == false) { - DesfireSetCommMode(&dctx, DCMPlain); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; + // optional key file from `hf mfdes chk` + desfire_keys_dump_t *keyfile = NULL; + if (keyfnlen > 0) { + keyfile = calloc(1, sizeof(desfire_keys_dump_t)); + if (keyfile == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + free(dump); + return PM3_EMALLOC; } - } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(SUCCESS, "Application " _CYAN_("%s") " have " _GREEN_("%zu") " files", DesfireWayIDStr(selectway, id), filescount); + // a key file we went looking for on our own is not expected to exist, + // so probe quietly first rather than let loadFileJSON complain + char *found = NULL; + bool exists = (searchFile(&found, RESOURCES_SUBDIR, keyfilename, ".json", autokeys) == PM3_SUCCESS); + free(found); - if (selectway == ISW6bAID) - DesfirePrintAIDFunctions(id); - - if (filescount == 0) { - PrintAndLogEx(INFO, "There is no files in the application %s", DesfireWayIDStr(selectway, id)); - DropField(); - return res; - } - - res = PM3_SUCCESS; - for (int i = 0; i < filescount; i++) { - if (res != PM3_SUCCESS) { - DesfireSetCommMode(&dctx, DCMPlain); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; + size_t klen = 0; + if (exists == false || loadFileJSON(keyfilename, keyfile, sizeof(desfire_keys_dump_t), &klen, NULL) != PM3_SUCCESS) { + if (autokeys == false) { + PrintAndLogEx(WARNING, "Could not load key file `" _YELLOW_("%s") "`, continuing without it", keyfilename); + } else if (verbose) { + PrintAndLogEx(INFO, "No key file `" _YELLOW_("%s") "` found", keyfilename); } + free(keyfile); + keyfile = NULL; + } else { + PrintAndLogEx(INFO, "Loaded keys for " _YELLOW_("%u") " application(s) from `" _YELLOW_("%s") "`", keyfile->appcount, keyfilename); + } + } + + uint8_t buf[255] = {0}; + size_t buflen = 0; + + // GetVersion and the originality signature are answered unauthenticated. + // Asking for them from inside the authenticated session instead would put + // them in the wrong communication mode and every answer would come back + // looking like a MAC failure + DesfireContext_t plainctx = {0}; + plainctx.commMode = DCMPlain; + plainctx.cmdSet = DCCNative; + + if (DesfireAnticollision(verbose) == PM3_SUCCESS) { + + if (DesfireGetVersion(&plainctx, buf, &buflen) == PM3_SUCCESS && buflen <= sizeof(dump->version)) { + memcpy(dump->version, buf, buflen); + dump->versionlen = buflen; } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--------------------------------- " _CYAN_("File %02x") " ----------------------------------", FileList[i].fileNum); - PrintAndLogEx(SUCCESS, "File ID : " _GREEN_("%02x"), FileList[i].fileNum); - if (isopresent) { - if (FileList[i].fileISONum != 0) - PrintAndLogEx(SUCCESS, "File ISO ID : %04x", FileList[i].fileISONum); - else - PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); + buflen = 0; + if (DesfireReadSignature(&plainctx, 0x00, buf, &buflen) == PM3_SUCCESS && buflen <= sizeof(dump->signature)) { + memcpy(dump->signature, buf, buflen); + dump->signaturelen = buflen; } - DesfirePrintFileSettingsExtended(&FileList[i].fileSettings); - - res = DesfileReadFileAndPrint(&dctx, FileList[i].fileNum, RFTAuto, 0, 0, maxlength, noauth, verbose); } DropField(); + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, ISW6bAID, 0x000000, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "PICC level select/auth " _RED_("failed")); + DropField(); + free(keyfile); + free(dump); + return res; + } + + // the PICC level is application 000000 + dump->picc.aid = 0x000000; + dump->picc.auth_ok = (noauth == false); + if (dump->picc.auth_ok) { + DesfireDumpStoreKey(&dump->picc, dctx.keyNum, dctx.keyType, dctx.key); + } + + // DesfireFillAppList() -> DesfireFillPICCInfo() already asks for free memory, + // key settings and key version 0, so don't ask a second time + PICCInfo_t PICCInfo = {0}; + AppListS AppList = {{0}}; + DesfireFillAppList(&dctx, &PICCInfo, AppList, false, false, true); + + // DesfireFillPICCInfo() reports a refused GetFreeMem as 0xffffffff + dump->freemem_ok = (PICCInfo.freemem != 0xffffffff); + if (dump->freemem_ok) { + dump->freemem = PICCInfo.freemem; + } + + dump->picc.keysettings = PICCInfo.keySettings; + dump->picc.numkeysraw = PICCInfo.numKeysRaw; + dump->picc.numkeys = PICCInfo.numberOfKeys; + dump->picc.settings_ok = true; + + // the PICC only hands out the version of key 0 + dump->picc.keys.version[0] = PICCInfo.keyVersion0; + dump->picc.keys.versionknown[0] = 1; + + PrintAndLogEx(NORMAL, ""); + DesfirePrintPICCInfo(&dctx, &PICCInfo); + + if (single_app) { + + // only the application the user named + desfire_dump_app_t *app = &dump->app[0]; + dump->appcount = 1; + + int idx = DesfireDumpFindApp(AppList, PICCInfo.appCount, &dctx, selectway, id); + if (idx >= 0) { + DesfireDumpFillAppMeta(app, &AppList[idx]); + } else { + // not in the PICC's list, record what the selector told us + app->aid = (selectway == ISW6bAID) ? id : 0; + app->isofid = (selectway == ISWIsoID) ? id : 0; + app->dfnamelen = dctx.selectedDFNameLen; + memcpy(app->dfname, dctx.selectedDFName, app->dfnamelen); + } + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Select/auth of %s " _RED_("failed"), DesfireWayIDStr(selectway, id)); + DropField(); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return res; + } + + app->auth_ok = (noauth == false); + if (app->auth_ok) { + DesfireDumpStoreKey(app, dctx.keyNum, dctx.keyType, dctx.key); + } + + DesfireDumpCollectApp(&dctx, app, maxlength, selectway, id, securechann, noauth, verbose); + + } else { + + uint8_t appcount = (PICCInfo.appCount > DESFIRE_MAX_APP_COUNT) ? DESFIRE_MAX_APP_COUNT : PICCInfo.appCount; + if (PICCInfo.appCount > DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "PICC has %zu applications, dumping the first %d", PICCInfo.appCount, DESFIRE_MAX_APP_COUNT); + } + + dump->appcount = appcount; + + // the key we authenticated the PICC with is the fallback for every + // application, so keep a copy -- picking a key out of the key file for + // one application must not carry over into the next + uint8_t basekey[DESFIRE_MAX_KEY_SIZE] = {0}; + memcpy(basekey, dctx.key, sizeof(basekey)); + DesfireCryptoAlgorithm basealgo = dctx.keyType; + + for (uint8_t i = 0; i < appcount; i++) { + + desfire_dump_app_t *app = &dump->app[i]; + DesfireDumpFillAppMeta(app, &AppList[i]); + + // a key from the key file beats the one on the command line + // DesfireSetKey() would clear the whole context -- command set, + // comm mode, KDF and UID all came from the command line and have to + // survive, so only the key itself is swapped + const uint8_t *appkey = DesfireDumpFindKey(keyfile, app->aid, app->keytype, dctx.keyNum); + if (appkey != NULL) { + DesfireSetKeyNoClear(&dctx, dctx.keyNum, app->keytype, (uint8_t *)appkey); + if (verbose) { + PrintAndLogEx(INFO, "Application " _YELLOW_("%06X") " using key %u from the key file", app->aid, dctx.keyNum); + } + } else { + DesfireSetKeyNoClear(&dctx, dctx.keyNum, basealgo, basekey); + } + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, ISW6bAID, app->aid, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Application " _YELLOW_("%06X") " select/auth " _RED_("failed") ", skipping", app->aid); + continue; + } + + app->auth_ok = (noauth == false); + if (app->auth_ok) { + DesfireDumpStoreKey(app, dctx.keyNum, dctx.keyType, dctx.key); + } + + DesfireDumpCollectApp(&dctx, app, maxlength, ISW6bAID, app->aid, securechann, noauth, verbose); + } + } + + DropField(); + + if (nosave) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "Called with no save option"); + PrintAndLogEx(NORMAL, ""); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_SUCCESS; + } + + if (fnlen < 1) { + if (dump->card_info.uidlen == 0) { + PrintAndLogEx(WARNING, "No UID to build a filename from, use " _YELLOW_("-f ")); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_ESOFT; + } + PrintAndLogEx(INFO, "Using UID as filename"); + strcat(filename, "hf-mfdes-"); + FillFileNameByUID(filename, dump->card_info.uid, "-dump", dump->card_info.uidlen); + } + + PrintAndLogEx(NORMAL, ""); + pm3_save_dump_json(filename, (uint8_t *)dump, sizeof(desfire_dump_t), jsfMfDesfire_v1); + + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_SUCCESS; +} + +static void DesfireViewPrintKeys(const desfire_dump_app_t *app) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + const desfire_dump_keys_t *keys = &app->keys; + + if (keys->versionknown[keyno] == 0 && keys->present[keyno] == 0) { + continue; + } + + char ver[16] = "??"; + if (keys->versionknown[keyno]) { + snprintf(ver, sizeof(ver), "%02X", keys->version[keyno]); + } + + if (keys->present[keyno]) { + PrintAndLogEx(SUCCESS, " Key %02u (ver %s). " _GREEN_("%s") + , keyno + , ver + , sprint_hex_inrow(keys->key[keyno], desfire_get_key_length(app->keytype)) + ); + } else { + PrintAndLogEx(SUCCESS, " Key %02u (ver %s). " _YELLOW_("not recovered"), keyno, ver); + } + } +} + +// the PICC is application 000000 and prints the same way as the rest +static void DesfireViewPrintApp(const desfire_dump_app_t *app) { + + PrintAndLogEx(NORMAL, ""); + if (app->aid == 0x000000) { + PrintAndLogEx(INFO, "--- " _CYAN_("AID 000000") " ( PICC level ) ---------------------"); + } else { + PrintAndLogEx(INFO, "--- " _CYAN_("AID %06X") " --------------------------------", app->aid); + } + + if (app->isofid != 0) { + PrintAndLogEx(SUCCESS, " ISO DF ID.... %04X", app->isofid); + } + if (app->dfnamelen > 0) { + // DF names are often plain ascii, show both the way `lsapp` does + PrintAndLogEx(SUCCESS, " DF name...... " _YELLOW_("%s") " ( %s )" + , sprint_ascii(app->dfname, app->dfnamelen) + , sprint_hex_inrow(app->dfname, app->dfnamelen) + ); + } + if (app->settings_ok) { + PrintAndLogEx(SUCCESS, " Key settings. %02X, %u %s key(s)" + , app->keysettings + , app->numkeys + , CLIGetOptionListStr(DesfireAlgoOpts, app->keytype) + ); + } + PrintAndLogEx(SUCCESS, " Authenticated %s", app->auth_ok ? _GREEN_("yes") : _YELLOW_("no")); + + DesfireViewPrintKeys(app); + + PrintAndLogEx(SUCCESS, " Files........ %u", app->filecount); + + for (uint8_t n = 0; n < app->filecount && n < DESFIRE_MAX_FILE_COUNT; n++) { + + const desfire_dump_file_t *f = &app->files[n]; + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, " File " _GREEN_("%02X") " - %s", f->num, GetDesfireFileType(f->type)); + + if (f->isofid != 0) { + PrintAndLogEx(SUCCESS, " ISO file ID.. %04X", f->isofid); + } + + if (f->settings_ok) { + // f->commmode is the raw file comm mode byte, not a DesfireCommunicationMode + PrintAndLogEx(SUCCESS, " Comm mode.... %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, DesfireFileCommModeToCommMode(f->commmode))); + PrintAndLogEx(SUCCESS, " Access rights %04X", f->accessrights); + } + + switch (f->type) { + case 0x00: + case 0x01: + PrintAndLogEx(SUCCESS, " File size.... %u", f->size); + break; + case 0x02: + PrintAndLogEx(SUCCESS, " Limits....... %u ... %u", f->lowerlimit, f->upperlimit); + break; + case 0x03: + case 0x04: + PrintAndLogEx(SUCCESS, " Records...... %u of %u, %u bytes each", f->currecords, f->maxrecords, f->recordsize); + break; + default: + break; + } + + if (f->read_ok == false) { + PrintAndLogEx(WARNING, " Contents..... " _YELLOW_("not read")); + continue; + } + + if (f->type == 0x02) { + PrintAndLogEx(SUCCESS, " Value........ " _GREEN_("%u") " (0x%08X)", f->value, f->value); + continue; + } + + if (f->datalen == 0) { + PrintAndLogEx(SUCCESS, " Contents..... " _YELLOW_("empty")); + continue; + } + + PrintAndLogEx(NORMAL, ""); + if ((f->type == 0x03 || f->type == 0x04) && f->recordsize > 0 && (f->datalen % f->recordsize) == 0) { + for (uint32_t r = 0; r < f->datalen / f->recordsize; r++) { + PrintAndLogEx(SUCCESS, " Record %u", r); + print_buffer_with_offset(f->data + (r * f->recordsize), f->recordsize, 0, (r == 0)); + } + } else { + print_buffer_with_offset(f->data, f->datalen, 0, true); + } + } +} + +static int CmdHF14ADesView(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes view", + "Print a DESFire card dump file (json)", + "hf mfdes view -f hf-mfdes-01020304050607-dump.json"); + + void *argtable[] = { + arg_param_begin, + arg_str1("f", "file", "", "Filename of dump"), + arg_lit0("v", "verbose", "Verbose output"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + bool verbose = arg_get_lit(ctx, 2); + CLIParserFree(ctx); + + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + size_t dlen = 0; + int res = loadFileJSON(filename, dump, sizeof(desfire_dump_t), &dlen, NULL); + if (res != PM3_SUCCESS) { + free(dump); + return res; + } + + if (dlen != sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "`" _YELLOW_("%s") "` is not a DESFire card dump", filename); + desfire_dump_free(dump); + free(dump); + return PM3_EINVARG; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------"); + + if (dump->card_info.uidlen > 0) { + PrintAndLogEx(SUCCESS, "UID.............. " _GREEN_("%s"), sprint_hex_inrow(dump->card_info.uid, dump->card_info.uidlen)); + // the file keeps ATQA in wire order, `hf 14a info` prints it the other way round + PrintAndLogEx(SUCCESS, "ATQA............. %02X %02X", dump->card_info.atqa[1], dump->card_info.atqa[0]); + PrintAndLogEx(SUCCESS, "SAK.............. %02X", dump->card_info.sak); + if (dump->card_info.ats_len > 0) { + PrintAndLogEx(SUCCESS, "ATS.............. %s", sprint_hex_inrow(dump->card_info.ats, dump->card_info.ats_len)); + } + } + + if (dump->versionlen > 0) { + PrintAndLogEx(SUCCESS, "Version.......... %s", sprint_hex_inrow(dump->version, dump->versionlen)); + } + + if (dump->signaturelen > 0) { + PrintAndLogEx(SUCCESS, "Signature........ %s", sprint_hex_inrow(dump->signature, dump->signaturelen)); + } + + if (dump->freemem_ok) { + PrintAndLogEx(SUCCESS, "Free memory...... " _GREEN_("%u") " bytes", dump->freemem); + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Applications") " ------------------------------"); + PrintAndLogEx(SUCCESS, "%u application(s) plus the PICC level", dump->appcount); + + DesfireViewPrintApp(&dump->picc); + + for (uint8_t i = 0; i < dump->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + DesfireViewPrintApp(&dump->app[i]); + } + + if (verbose) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "Loaded `" _YELLOW_("%s") "`", filename); + } + + PrintAndLogEx(NORMAL, ""); + desfire_dump_free(dump); + free(dump); return PM3_SUCCESS; } @@ -10000,6 +10761,7 @@ static command_t CommandTable[] = { {"getfileisoids", CmdHF14ADesGetFileISOIDs, IfPm3Iso14443a, "Get File ISO IDs list"}, {"lsfiles", CmdHF14ADesLsFiles, IfPm3Iso14443a, "Show all files list"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, + {"view", CmdHF14ADesView, AlwaysAvailable, "Display content from tag dump file"}, {"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"}, {"createvaluefile", CmdHF14ADesCreateValueFile, IfPm3Iso14443a, "Create Value File"}, {"createrecordfile", CmdHF14ADesCreateRecordFile, IfPm3Iso14443a, "Create Linear/Cyclic Record File"}, diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 2c0f58a3c..750dbeb48 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -637,6 +637,503 @@ static void json15_save_tag(json_t *root, const iso15_tag_t *tag, size_t pagesco } } +//----------------------------------------------------------------------------- +// DESFire card image (jsfMfDesfire_v1) helpers. +// Token spellings match what the `hf mfdes` CLI already accepts, so a value +// read out of a dump file can be handed straight back to a command. +//----------------------------------------------------------------------------- +static const char *desfire_algo_name(uint8_t algo) { + static const char *tbl[] = {"des", "2tdea", "3tdea", "aes"}; + return (algo < ARRAYLEN(tbl)) ? tbl[algo] : "unknown"; +} + +static const char *desfire_comm_mode_name(uint8_t mode) { + static const char *tbl[] = {"plain", "mac", "plain_rfu", "encrypt"}; + return (mode < ARRAYLEN(tbl)) ? tbl[mode] : "unknown"; +} + +static const char *desfire_file_type_name(uint8_t type) { + static const char *tbl[] = { + "standard", "backup", "value", "linear_record", "cyclic_record", "transaction_mac" + }; + return (type < ARRAYLEN(tbl)) ? tbl[type] : "unknown"; +} + +// JsonSaveBufAsHexCompact() runs through sprint_hex_inrow(), which silently +// truncates past ~4 kbyte. File contents get that big, so build the hex +// string in a right-sized heap buffer instead +static int desfire_json_save_hex(json_t *root, const char *path, const uint8_t *data, size_t datalen) { + + if (data == NULL || datalen == 0) { + return PM3_EINVARG; + } + + char *hex = calloc((datalen * 2) + 1, sizeof(uint8_t)); + if (hex == NULL) { + return PM3_EMALLOC; + } + + for (size_t i = 0; i < datalen; i++) { + snprintf(hex + (i * 2), 3, "%02X", data[i]); + } + + int res = JsonSaveStr(root, path, hex); + free(hex); + return res; +} + +// JsonSaveHex() goes through JsonSaveBufAsHex(), which space-separates the +// bytes. Everything else in this format is compact, so keep 2-byte fields that +// way too +static int desfire_json_save_u16(json_t *root, const char *path, uint16_t value) { + uint8_t b[2] = { value >> 8, value & 0xFF }; + return JsonSaveBufAsHexCompact(root, path, b, sizeof(b)); +} + +static uint8_t desfire_algo_keylen(uint8_t algo) { + switch (algo) { + case T_DES: + return DES_KEY_LEN; + case T_3DES: + return T2DES_KEY_LEN; + case T_3K3DES: + return T3DES_KEY_LEN; + case T_AES: + return AES_KEY_LEN; + default: + return 0; + } +} + +// A key entry exists as soon as we know anything about the key. "Version" +// without "Key" is the normal shape for a key we saw but could not recover -- +// a missing "Key" never means the key is all zeros +static void desfire_json_save_keys(json_t *root, const char *prefix, uint8_t algo, const desfire_dump_keys_t *keys) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t keylen = desfire_algo_keylen(algo); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (keys->versionknown[keyno]) { + snprintf(path, sizeof(path), "%s.Keys.%u.Version", prefix, keyno); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&keys->version[keyno], 1); + } + + if (keys->present[keyno] && keylen) { + snprintf(path, sizeof(path), "%s.Keys.%u.Key", prefix, keyno); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)keys->key[keyno], keylen); + } + } +} + +// The PICC level is application 000000 and takes the same path through here +static void desfire_json_save_app(json_t *root, char *path, size_t pathlen, const desfire_dump_app_t *app) { + + char apath[PATH_MAX_LENGTH] = {0}; + snprintf(apath, sizeof(apath), "$.Applications.%06X", app->aid); + + if (app->isofid != 0) { + snprintf(path, pathlen, "%s.ISOFileID", apath); + desfire_json_save_u16(root, path, app->isofid); + } + + if (app->dfnamelen > 0) { + snprintf(path, pathlen, "%s.DFName", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)app->dfname, app->dfnamelen); + } + + if (app->settings_ok) { + snprintf(path, pathlen, "%s.KeySettings", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&app->keysettings, 1); + snprintf(path, pathlen, "%s.NumKeysRaw", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&app->numkeysraw, 1); + snprintf(path, pathlen, "%s.NumKeys", apath); + JsonSaveInt(root, path, app->numkeys); + snprintf(path, pathlen, "%s.KeyType", apath); + JsonSaveStr(root, path, desfire_algo_name(app->keytype)); + } + + snprintf(path, pathlen, "%s.Authenticated", apath); + JsonSaveBoolean(root, path, app->auth_ok); + + desfire_json_save_keys(root, apath, app->keytype, &app->keys); + + uint8_t filecount = app->filecount; + if (filecount > DESFIRE_MAX_FILE_COUNT) { + filecount = DESFIRE_MAX_FILE_COUNT; + } + + for (uint8_t n = 0; n < filecount; n++) { + + const desfire_dump_file_t *f = &app->files[n]; + char fpath[PATH_MAX_LENGTH] = {0}; + snprintf(fpath, sizeof(fpath), "%s.Files.%02X", apath, f->num); + + if (f->settings_ok) { + snprintf(path, pathlen, "%s.Type", fpath); + JsonSaveStr(root, path, desfire_file_type_name(f->type)); + snprintf(path, pathlen, "%s.TypeRaw", fpath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&f->type, 1); + snprintf(path, pathlen, "%s.CommMode", fpath); + JsonSaveStr(root, path, desfire_comm_mode_name(f->commmode)); + snprintf(path, pathlen, "%s.AccessRights", fpath); + desfire_json_save_u16(root, path, f->accessrights); + + for (uint8_t a = 0; a < f->addrights_len && a < ARRAYLEN(f->addrights); a++) { + snprintf(path, pathlen, "%s.AdditionalAccessRights.%u", fpath, a); + desfire_json_save_u16(root, path, f->addrights[a]); + } + } + + if (f->isofid != 0) { + snprintf(path, pathlen, "%s.ISOFileID", fpath); + desfire_json_save_u16(root, path, f->isofid); + } + + switch (f->type) { + case 0x00: + case 0x01: { + snprintf(path, pathlen, "%s.FileSize", fpath); + JsonSaveInt(root, path, f->size); + break; + } + case 0x02: { + snprintf(path, pathlen, "%s.LowerLimit", fpath); + JsonSaveInt(root, path, f->lowerlimit); + snprintf(path, pathlen, "%s.UpperLimit", fpath); + JsonSaveInt(root, path, f->upperlimit); + snprintf(path, pathlen, "%s.LimitedCredit", fpath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&f->limitedcredit, 1); + if (f->read_ok) { + snprintf(path, pathlen, "%s.Value", fpath); + JsonSaveInt(root, path, f->value); + } + break; + } + case 0x03: + case 0x04: { + snprintf(path, pathlen, "%s.RecordSize", fpath); + JsonSaveInt(root, path, f->recordsize); + snprintf(path, pathlen, "%s.MaxRecords", fpath); + JsonSaveInt(root, path, f->maxrecords); + snprintf(path, pathlen, "%s.CurRecords", fpath); + JsonSaveInt(root, path, f->currecords); + break; + } + default: { + break; + } + } + + // "Read" says whether we got the contents. A reader must not + // treat a missing "Data" as an empty file + snprintf(path, pathlen, "%s.Read", fpath); + JsonSaveBoolean(root, path, f->read_ok); + + if (f->read_ok == false || f->data == NULL || f->datalen == 0) { + continue; + } + + if (f->type == 0x03 || f->type == 0x04) { + // record files are stored one hex string per record + uint32_t reclen = f->recordsize; + if (reclen == 0 || (f->datalen % reclen) != 0) { + snprintf(path, pathlen, "%s.Data", fpath); + desfire_json_save_hex(root, path, f->data, f->datalen); + } else { + for (uint32_t r = 0; r < f->datalen / reclen; r++) { + snprintf(path, pathlen, "%s.Records.%u", fpath, r); + desfire_json_save_hex(root, path, f->data + (r * reclen), reclen); + } + } + } else if (f->type != 0x02) { + snprintf(path, pathlen, "%s.Data", fpath); + desfire_json_save_hex(root, path, f->data, f->datalen); + } + } +} + +static uint8_t desfire_algo_from_name(const char *name) { + if (name == NULL) { + return T_DES; + } + for (uint8_t i = 0; i < DESFIRE_MAX_ALGO_COUNT; i++) { + if (strcmp(name, desfire_algo_name(i)) == 0) { + return i; + } + } + return T_DES; +} + +static uint8_t desfire_comm_mode_from_name(const char *name) { + if (name == NULL) { + return 0; + } + for (uint8_t i = 0; i < 4; i++) { + if (strcmp(name, desfire_comm_mode_name(i)) == 0) { + return i; + } + } + return 0; +} + +static uint32_t json_load_int(json_t *root, const char *path, uint32_t def) { + json_t *elm = json_path_get((const json_t *)root, path); + if (json_is_integer(elm) == false) { + return def; + } + return (uint32_t)json_integer_value(elm); +} + +static const char *json_load_str(json_t *root, const char *path) { + json_t *elm = json_path_get((const json_t *)root, path); + if (json_is_string(elm) == false) { + return NULL; + } + return json_string_value(elm); +} + +// read a hex string of unknown length into a freshly allocated buffer. +// *dst stays NULL when the element is missing or empty +static int desfire_json_load_hex_alloc(json_t *root, const char *path, uint8_t **dst, uint32_t *dstlen) { + + *dst = NULL; + *dstlen = 0; + + const char *hex = json_load_str(root, path); + if (hex == NULL) { + return PM3_SUCCESS; + } + + size_t n = strlen(hex) / 2; + if (n == 0) { + return PM3_SUCCESS; + } + + uint8_t *buf = calloc(n, sizeof(uint8_t)); + if (buf == NULL) { + PrintAndLogEx(ERR, "loadFileJSONex: failed to allocate %zu bytes for `%s`", n, path); + return PM3_EMALLOC; + } + + size_t len = 0; + if (JsonLoadBufAsHex(root, path, buf, n, &len) != 0) { + free(buf); + return PM3_SUCCESS; + } + + *dst = buf; + *dstlen = len; + return PM3_SUCCESS; +} + +// record files are stored one hex string per record. Concatenate them back +// into the flat buffer the rest of the client works with +static int desfire_json_load_records(json_t *root, desfire_dump_file_t *f) { + + char path[PATH_MAX_LENGTH] = {0}; + + // a record file we could not split stays a flat "Data" blob + json_t *recs = json_path_get((const json_t *)root, "$.Records"); + if (json_is_object(recs) == false && json_is_array(recs) == false) { + return desfire_json_load_hex_alloc(root, "$.Data", &f->data, &f->datalen); + } + + // a record file cannot hold more records than the PICC has bytes, so the + // container size is the bound. Records must be contiguous from 0 + size_t bound = json_is_array(recs) ? json_array_size(recs) : json_object_size(recs); + + uint32_t count = 0; + uint32_t reclen = 0; + for (uint32_t r = 0; r < bound; r++) { + snprintf(path, sizeof(path), "$.Records.%u", r); + const char *hex = json_load_str(root, path); + if (hex == NULL) { + break; + } + if (r == 0) { + reclen = strlen(hex) / 2; + } + count++; + } + + if (count == 0 || reclen == 0) { + return PM3_SUCCESS; + } + + uint8_t *buf = calloc((size_t)count * reclen, sizeof(uint8_t)); + if (buf == NULL) { + PrintAndLogEx(ERR, "loadFileJSONex: failed to allocate %u bytes of record data", count * reclen); + return PM3_EMALLOC; + } + + for (uint32_t r = 0; r < count; r++) { + snprintf(path, sizeof(path), "$.Records.%u", r); + size_t len = 0; + JsonLoadBufAsHex(root, path, buf + ((size_t)r * reclen), reclen, &len); + } + + f->data = buf; + f->datalen = count * reclen; + if (f->recordsize == 0) { + f->recordsize = reclen; + } + return PM3_SUCCESS; +} + +static void desfire_json_load_keys(json_t *root, uint8_t algo, desfire_dump_keys_t *keys) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t keylen = desfire_algo_keylen(algo); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + size_t len = 0; + snprintf(path, sizeof(path), "$.Keys.%u.Version", keyno); + if (JsonLoadBufAsHex(root, path, &keys->version[keyno], 1, &len) == 0 && len == 1) { + keys->versionknown[keyno] = 1; + } + + if (keylen == 0) { + continue; + } + + len = 0; + snprintf(path, sizeof(path), "$.Keys.%u.Key", keyno); + if (JsonLoadBufAsHex(root, path, keys->key[keyno], keylen, &len) == 0 && len == keylen) { + keys->present[keyno] = 1; + } + } +} + +// read one application, PICC included, out of the Applications object +static int desfire_json_load_app(json_t *japp, const char *aidstr, desfire_dump_app_t *app) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t tmp[2] = {0}; + size_t len = 0; + + app->aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + + JsonLoadBufAsHex(japp, "$.ISOFileID", tmp, sizeof(tmp), &len); + if (len == 2) { + app->isofid = (tmp[0] << 8) | tmp[1]; + } + + len = 0; + JsonLoadBufAsHex(japp, "$.DFName", app->dfname, sizeof(app->dfname), &len); + app->dfnamelen = len; + + len = 0; + JsonLoadBufAsHex(japp, "$.KeySettings", &app->keysettings, 1, &len); + app->settings_ok = (len == 1); + JsonLoadBufAsHex(japp, "$.NumKeysRaw", &app->numkeysraw, 1, &len); + app->numkeys = json_load_int(japp, "$.NumKeys", 0); + app->keytype = desfire_algo_from_name(json_load_str(japp, "$.KeyType")); + app->auth_ok = json_is_true(json_path_get((const json_t *)japp, "$.Authenticated")); + + desfire_json_load_keys(japp, app->keytype, &app->keys); + + json_t *files = json_object_get(japp, "Files"); + if (json_is_object(files) == false) { + return PM3_SUCCESS; + } + + const char *fidstr = NULL; + json_t *jfile = NULL; + + json_object_foreach(files, fidstr, jfile) { + + if (app->filecount >= DESFIRE_MAX_FILE_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d files in application %06X, ignoring the rest", DESFIRE_MAX_FILE_COUNT, app->aid); + break; + } + + desfire_dump_file_t *f = &app->files[app->filecount]; + f->num = strtoul(fidstr, NULL, 16) & 0xFF; + + len = 0; + JsonLoadBufAsHex(jfile, "$.TypeRaw", &f->type, 1, &len); + f->settings_ok = (len == 1); + + f->commmode = desfire_comm_mode_from_name(json_load_str(jfile, "$.CommMode")); + + len = 0; + JsonLoadBufAsHex(jfile, "$.AccessRights", tmp, sizeof(tmp), &len); + if (len == 2) { + f->accessrights = (tmp[0] << 8) | tmp[1]; + } + + len = 0; + JsonLoadBufAsHex(jfile, "$.ISOFileID", tmp, sizeof(tmp), &len); + if (len == 2) { + f->isofid = (tmp[0] << 8) | tmp[1]; + } + + for (uint8_t a = 0; a < ARRAYLEN(f->addrights); a++) { + snprintf(path, sizeof(path), "$.AdditionalAccessRights.%u", a); + len = 0; + JsonLoadBufAsHex(jfile, path, tmp, sizeof(tmp), &len); + if (len != 2) { + break; + } + f->addrights[a] = (tmp[0] << 8) | tmp[1]; + f->addrights_len = a + 1; + } + + f->size = json_load_int(jfile, "$.FileSize", 0); + f->lowerlimit = json_load_int(jfile, "$.LowerLimit", 0); + f->upperlimit = json_load_int(jfile, "$.UpperLimit", 0); + f->value = json_load_int(jfile, "$.Value", 0); + f->recordsize = json_load_int(jfile, "$.RecordSize", 0); + f->maxrecords = json_load_int(jfile, "$.MaxRecords", 0); + f->currecords = json_load_int(jfile, "$.CurRecords", 0); + JsonLoadBufAsHex(jfile, "$.LimitedCredit", &f->limitedcredit, 1, &len); + + f->read_ok = json_is_true(json_path_get((const json_t *)jfile, "$.Read")); + + app->filecount++; + + if (f->read_ok == false) { + continue; + } + + // value files carry their payload in "Value", nothing else to load + if (f->type == 0x02) { + continue; + } + + if (f->type == 0x03 || f->type == 0x04) { + if (desfire_json_load_records(jfile, f) != PM3_SUCCESS) { + return PM3_EMALLOC; + } + continue; + } + + if (desfire_json_load_hex_alloc(jfile, "$.Data", &f->data, &f->datalen) != PM3_SUCCESS) { + return PM3_EMALLOC; + } + } + + return PM3_SUCCESS; +} + +void desfire_dump_free(desfire_dump_t *dump) { + + if (dump == NULL) { + return; + } + + for (uint8_t i = 0; i < DESFIRE_MAX_APP_COUNT; i++) { + for (uint8_t n = 0; n < DESFIRE_MAX_FILE_COUNT; n++) { + free(dump->app[i].files[n].data); + dump->app[i].files[n].data = NULL; + dump->app[i].files[n].datalen = 0; + } + } +} + int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, bool verbose, void (*callback)(json_t *)) { if (ftype != jsfCustom) { if (data == NULL || datalen == 0) { @@ -1062,6 +1559,52 @@ int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, } break; } + case jsfMfDesfire_v1: { + + if (datalen != sizeof(desfire_dump_t)) { + return PM3_EINVARG; + } + + const desfire_dump_t *dump = (const desfire_dump_t *)(const void *)data; + + JsonSaveStr(root, "FileType", "mfdes v1"); + JsonSaveInt(root, "$.Version", 1); + + // $.Card is card identity only. Key settings and keys belong to an + // application, and the PICC level is application 000000 + if (dump->card_info.uidlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.UID", (uint8_t *)dump->card_info.uid, dump->card_info.uidlen); + JsonSaveBufAsHexCompact(root, "$.Card.ATQA", (uint8_t *)dump->card_info.atqa, 2); + JsonSaveBufAsHexCompact(root, "$.Card.SAK", (uint8_t *)&dump->card_info.sak, 1); + if (dump->card_info.ats_len > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.ATS", (uint8_t *)dump->card_info.ats, dump->card_info.ats_len); + } + } + + if (dump->versionlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.Version", (uint8_t *)dump->version, dump->versionlen); + } + + if (dump->signaturelen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.Signature", (uint8_t *)dump->signature, dump->signaturelen); + } + + if (dump->freemem_ok) { + JsonSaveInt(root, "$.Card.FreeMem", dump->freemem); + } + + desfire_json_save_app(root, path, sizeof(path), &dump->picc); + + uint8_t appcount = dump->appcount; + if (appcount > DESFIRE_MAX_APP_COUNT) { + appcount = DESFIRE_MAX_APP_COUNT; + } + + for (uint8_t i = 0; i < appcount; i++) { + desfire_json_save_app(root, path, sizeof(path), &dump->app[i]); + } + break; + } case jsfCustom: { (*callback)(root); break; @@ -2780,6 +3323,80 @@ int loadFileJSONex(const char *preferredName, void *data, size_t maxdatalen, siz goto out; } + if (!strcmp(ctype, "mfdes v1")) { + + if (maxdatalen < sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "loadFileJSONex: buffer too small for a DESFire card image. %zu < %zu", maxdatalen, sizeof(desfire_dump_t)); + retval = PM3_EMALLOC; + goto out; + } + + desfire_dump_t *dump = udata.mfdesdump; + memset(dump, 0, sizeof(desfire_dump_t)); + + len = 0; + JsonLoadBufAsHex(root, "$.Card.UID", dump->card_info.uid, sizeof(dump->card_info.uid), &len); + dump->card_info.uidlen = len; + + JsonLoadBufAsHex(root, "$.Card.ATQA", dump->card_info.atqa, sizeof(dump->card_info.atqa), &len); + JsonLoadBufAsHex(root, "$.Card.SAK", &dump->card_info.sak, 1, &len); + + len = 0; + JsonLoadBufAsHex(root, "$.Card.ATS", dump->card_info.ats, sizeof(dump->card_info.ats), &len); + dump->card_info.ats_len = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.Version", dump->version, sizeof(dump->version), &len); + dump->versionlen = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.Signature", dump->signature, sizeof(dump->signature), &len); + dump->signaturelen = len; + + json_t *jfree = json_path_get(root, "$.Card.FreeMem"); + if (json_is_integer(jfree)) { + dump->freemem = json_integer_value(jfree); + dump->freemem_ok = true; + } + + dump->picc.aid = 0x000000; + + json_t *apps = json_object_get(root, "Applications"); + if (json_is_object(apps) == false) { + *datalen = sizeof(desfire_dump_t); + goto out; + } + + const char *aidstr = NULL; + json_t *japp = NULL; + + json_object_foreach(apps, aidstr, japp) { + + // AID 000000 is the PICC level, it is not one of the applications + uint32_t aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + desfire_dump_app_t *app = NULL; + + if (aid == 0x000000) { + app = &dump->picc; + } else { + if (dump->appcount >= DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d applications in file, ignoring the rest", DESFIRE_MAX_APP_COUNT); + break; + } + app = &dump->app[dump->appcount]; + dump->appcount++; + } + + if (desfire_json_load_app(japp, aidstr, app) != PM3_SUCCESS) { + retval = PM3_EMALLOC; + goto out; + } + } + + *datalen = sizeof(desfire_dump_t); + goto out; + } + if (!strcmp(ctype, "mfdes v2")) { if (maxdatalen < sizeof(desfire_keys_dump_t)) { diff --git a/client/src/fileutils.h b/client/src/fileutils.h index b53077d2e..92b3884cc 100644 --- a/client/src/fileutils.h +++ b/client/src/fileutils.h @@ -42,6 +42,102 @@ typedef struct { desfire_app_keys_t app[DESFIRE_MAX_APP_COUNT]; } desfire_keys_dump_t; +//----------------------------------------------------------------------------- +// DESFire card image, as written by `hf mfdes dump` and read back by +// `hf mfdes view`. See doc/mfdes_dump_format.md for the on-disk JSON schema. +// +// Contents of a file live in a heap buffer hanging off desfire_dump_file_t, +// so the image can hold real file sizes without a multi-megabyte struct. +// Whoever fills or loads one of these owns those buffers -- release them with +// desfire_dump_free() before dropping the image. +//----------------------------------------------------------------------------- + +// keys of one application. The key type is a property of the application, not +// of the individual key, so it lives in desfire_dump_app_t. +// +// A key version is readable without knowing the key, so the two are tracked +// separately: `versionknown` without `present` is the normal case for a key we +// found but could not recover +typedef struct { + uint8_t present[DESFIRE_MAX_KEY_COUNT]; // 1 = we have the key value + uint8_t versionknown[DESFIRE_MAX_KEY_COUNT]; // 1 = we read the key version + uint8_t version[DESFIRE_MAX_KEY_COUNT]; + uint8_t key[DESFIRE_MAX_KEY_COUNT][DESFIRE_MAX_KEY_SIZE]; +} desfire_dump_keys_t; + +typedef struct { + uint8_t num; // file number, 0x00 ... 0x1F + uint16_t isofid; // ISO file id, 0 = none + uint8_t type; // raw file type byte, 0x00 ... 0x05 + uint8_t commmode; // raw file communication mode + uint16_t accessrights; // raw access rights word + uint8_t addrights_len; + uint16_t addrights[16]; // additional access rights + + uint32_t size; // standard / backup data file size + uint32_t lowerlimit; // value file + uint32_t upperlimit; + uint32_t value; + uint8_t limitedcredit; + uint32_t recordsize; // record file + uint32_t maxrecords; + uint32_t currecords; + + bool settings_ok; // file settings were read + + // read_ok false means "we could not read it", which is not the same as + // "the file is empty". Never fill `data` with zeros to paper over it, a + // simulator would then confidently answer with contents the card never had. + bool read_ok; + uint32_t datalen; + uint8_t *data; // heap, NULL when read_ok is false +} desfire_dump_file_t; + +// One application. The PICC level is an application too -- AID 000000 -- and +// uses this same struct, so key settings and keys are always stated against an +// AID instead of floating loose at card level +typedef struct { + uint32_t aid; + uint16_t isofid; + uint8_t dfname[16]; + uint8_t dfnamelen; + + uint8_t keysettings; + uint8_t numkeysraw; + uint8_t numkeys; + uint8_t keytype; // DesfireCryptoAlgorithm, one per application + bool settings_ok; // key settings were read + bool auth_ok; // we authenticated to this application + + desfire_dump_keys_t keys; + + uint8_t filecount; + desfire_dump_file_t files[DESFIRE_MAX_FILE_COUNT]; +} desfire_dump_app_t; + +typedef struct { + // card identity only. Anything key related belongs to an application + iso14a_card_select_t card_info; + + uint8_t version[28]; // raw GetVersion answer + uint8_t versionlen; + uint8_t signature[56]; // NXP originality signature + uint8_t signaturelen; + + uint32_t freemem; + bool freemem_ok; + + desfire_dump_app_t picc; // AID 000000, written as Applications.000000 + + // real applications only, the PICC is not counted here + uint8_t appcount; + desfire_dump_app_t app[DESFIRE_MAX_APP_COUNT]; +} desfire_dump_t; + +// release the per-file heap buffers inside an image. Safe on a NULL pointer +// and safe to call twice. Does not free the image itself. +void desfire_dump_free(desfire_dump_t *dump); + typedef union { void *v; uint8_t *bytes; @@ -51,6 +147,7 @@ typedef union { iso14a_mf_dump_ev1_t *mfc_ev1; iso15_tag_t *iso15; desfire_keys_dump_t *mfdes; + desfire_dump_t *mfdesdump; } udata_t; typedef enum { @@ -79,6 +176,7 @@ typedef enum { jsfCustom, jsfMfDesfireKeys, jsfMfDesfireKeys_v2, + jsfMfDesfire_v1, jsfEM4x05, jsfEM4x69, jsfEM4x50, diff --git a/client/src/util.c b/client/src/util.c index ece98c325..30ce4e0f3 100644 --- a/client/src/util.c +++ b/client/src/util.c @@ -36,7 +36,7 @@ #include "comms.h" // SendCommandNG / WaitForResponseTimeout (set_rgb) #include "pm3_cmd.h" // CMD_PM5_RGB_SET -#define UTIL_BUFFER_SIZE_SPRINT 8196 +#define UTIL_BUFFER_SIZE_SPRINT 16384 // global client debug variable uint8_t g_debugMode = 0; // global client enable/disable printing/logging/grabbing variable diff --git a/doc/commands.json b/doc/commands.json index de3f411ec..5b8bb2cdc 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -5996,9 +5996,10 @@ "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", "--ns no save to file", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "--sk Save extracted keys to binary file" ], - "usage": "hf mf dump [-hv] [-f ] [-k ] [--mini] [--1k] [--2k] [--4k] [--ns]" + "usage": "hf mf dump [-hv] [-f ] [-k ] [--mini] [--1k] [--2k] [--4k] [--ns] [--sk]" }, "hf mf ecfill": { "command": "hf mf ecfill", @@ -7145,16 +7146,18 @@ "command": "hf mf view", "description": "Print a MIFARE Classic dump file (bin/eml/json)", "notes": [ - "hf mf view -f hf-mf-01020304-dump.bin" + "hf mf view -f hf-mf-01020304-dump.bin", + "hf mf view --selftest" ], "offline": true, "options": [ "-h, --help This help", "-f, --file Specify a filename for dump file", "-v, --verbose verbose output", - "--sk Save extracted keys to binary file" + "--sk Save extracted keys to binary file", + "--selftest Run the dump parsers self tests and exit" ], - "usage": "hf mf view [-hv] -f [--sk]" + "usage": "hf mf view [-hv] [-f ] [--sk] [--selftest]" }, "hf mf wipe": { "command": "hf mf wipe", @@ -7853,9 +7856,12 @@ }, "hf mfdes dump": { "command": "hf mfdes dump", - "description": "For each application show fil list and then file content. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", + "description": "Dump a DESFire card to a json file. Walks every application and every file unless an application is named with --aid / --isoid / --dfname. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", "notes": [ - "hf mfdes dump --aid 123456 -> show file dump for: app=123456 with channel defaults from `default` command/nhf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit" + "hf mfdes dump -> dump the whole PICC with channel defaults from `default` command", + "hf mfdes dump --aid 123456 -> dump only application 123456", + "hf mfdes dump --keys hf-mfdes-0102030405-keys.json -> use recovered keys per application", + "hf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit" ], "offline": false, "options": [ @@ -7874,9 +7880,12 @@ "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian)", "--dfname Application ISO DF Name (5-16 hex bytes, big endian)", "-l, --length Maximum length for read data files (3 hex bytes, big endian)", - "--no-auth Execute without authentication" + "--no-auth Execute without authentication", + "-f, --file Save dump to file, if no UID will be used as filename", + "--keys Load application keys from a `hf mfdes chk` key file", + "--ns No save to file" ], - "usage": "hf mfdes dump [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-l ] [--no-auth]" + "usage": "hf mfdes dump [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-l ] [--no-auth] [-f ] [--keys ] [--ns]" }, "hf mfdes formatpicc": { "command": "hf mfdes formatpicc", @@ -8189,7 +8198,7 @@ }, "hf mfdes help": { "command": "hf mfdes help", - "description": "help This help list List DESFire (ISO 14443A) history makemfclicense Generate a Mifare Classic license for DESFire EV3C test Regression crypto tests --------------------------------------------------------------------------------------- hf mfdes list available offline: yes Alias of `trace list -t des -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "help This help list List DESFire (ISO 14443A) history view Display content from tag dump file makemfclicense Generate a Mifare Classic license for DESFire EV3C test Regression crypto tests --------------------------------------------------------------------------------------- hf mfdes list available offline: yes Alias of `trace list -t des -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "hf mfdes list --frame -> show frame delay times", "hf mfdes list -1 -> use trace buffer" @@ -8630,6 +8639,20 @@ ], "usage": "hf mfdes verifycert [-hav] [] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [--fid ] [--no-auth] [--ca ]... [--keyaid ] [--keyisoid ] [--keydfname ] [--keyidx ] [--validatemethod ] [--readmethod ]" }, + "hf mfdes view": { + "command": "hf mfdes view", + "description": "Print a DESFire card dump file (json)", + "notes": [ + "hf mfdes view -f hf-mfdes-01020304050607-dump.json" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-f, --file Filename of dump", + "-v, --verbose Verbose output" + ], + "usage": "hf mfdes view [-hv] -f " + }, "hf mfdes write": { "command": "hf mfdes write", "description": "Write data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", @@ -16221,7 +16244,7 @@ "command": "smart raw", "description": "Sends raw bytes to card", "notes": [ - "smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR", + "smart raw --t0 -s -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR", "smart raw --t0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory", "smart raw --t0 -t -d 00a4040007a0000000041010 -> Mastercard", "smart raw --t0 -t -d 00a4040007a0000000031010 -> Visa", @@ -16538,8 +16561,8 @@ } }, "metadata": { - "commands_extracted": 920, + "commands_extracted": 921, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-12T19:49:38+00:00" + "extracted_on": "2026-09-14T06:50:14+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 2153754e6..4f2c8c2d8 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -817,6 +817,7 @@ Check column "offline" for their availability. |`hf mfdes getfileisoids `|N |`Get File ISO IDs list` |`hf mfdes lsfiles `|N |`Show all files list` |`hf mfdes dump `|N |`Dump all files` +|`hf mfdes view `|Y |`Display content from tag dump file` |`hf mfdes createfile `|N |`Create Standard/Backup File` |`hf mfdes createvaluefile`|N |`Create Value File` |`hf mfdes createrecordfile`|N |`Create Linear/Cyclic Record File` diff --git a/doc/mfdes_dump_format.md b/doc/mfdes_dump_format.md index bd6520954..970d1605c 100644 --- a/doc/mfdes_dump_format.md +++ b/doc/mfdes_dump_format.md @@ -342,6 +342,9 @@ hf mfdes chk -k 00000000000000000000000000000000 -j hf-mfdes-043240CAE45380-keys # and dump it hf mfdes dump -t 2tdea -k 00000000000000000000000000000000 + +# to put the card back the way it was +hf mfdes formatpicc -t 2tdea -k 00000000000000000000000000000000 ``` Without that `chk` run, application `112233` cannot be opened with the 2TDEA @@ -525,8 +528,11 @@ The dump picks this file up without `--keys` because its name follows the same Things to read out of it: -* **`FreeMem` is 896**, not the 2080 a blank card reports. The applications and - files took the rest. +* **`FreeMem` is 896** with the two applications in place. Measured on this same + card: 2080 free before the example was built, 896 with it, and 2560 after + `hf mfdes formatpicc`. A format therefore reclaims space that creating and + deleting applications leaves behind -- 0 applications on its own does not mean + a fully free card. * **`NumKeysRaw` `83`** decodes to `KeyType: aes` (top bits 10), ISO file ids enabled (bit 5) and `NumKeys: 3`. * **Keys 1 and 2 of `112233` have a `Version` but no `Key`.** They exist, we