Merge pull request #1381 from merlokk/desf_create_del

Desf create/delete file
This commit is contained in:
Oleg Moiseenko 2021-07-26 14:47:20 +03:00 committed by GitHub
commit 841ef80b43
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 843 additions and 488 deletions

View file

@ -1941,7 +1941,7 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type,
return res;
}
static int handler_desfire_deletefile(uint8_t file_no) {
/*static int handler_desfire_deletefile(uint8_t file_no) {
if (file_no > 0x1F)
return PM3_EINVARG;
@ -1955,7 +1955,7 @@ static int handler_desfire_deletefile(uint8_t file_no) {
return res;
}
return res;
}
}*/
static int handler_desfire_clear_record_file(uint8_t file_no) {
if (file_no > 0x1F)
@ -1980,39 +1980,6 @@ static int handler_desfire_clear_record_file(uint8_t file_no) {
return res;
}
static int handler_desfire_create_value_file(mfdes_value_file_t *value) {
if (value->fileno > 0x1F) return PM3_EINVARG;
sAPDU apdu = {0x90, MFDES_CREATE_VALUE_FILE, 0x00, 0x00, sizeof(mfdes_value_file_t), (uint8_t *)value}; // 0xCc
uint16_t sw = 0;
uint32_t recvlen = 0;
int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_(" Can't create value -> %s"), DesfireGetErrorString(res, &sw));
DropFieldDesfire();
return res;
}
return res;
}
static int handler_desfire_create_std_file(mfdes_file_t *file) {
if (file->fileno > 0x1F)
return PM3_EINVARG;
sAPDU apdu = {0x90, MFDES_CREATE_STD_DATA_FILE, 0x00, 0x00, sizeof(mfdes_file_t), (uint8_t *)file}; // 0xCD
uint16_t sw = 0;
uint32_t recvlen = 0;
int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_(" Can't create file -> %s"), DesfireGetErrorString(res, &sw));
DropFieldDesfire();
return res;
}
return res;
}
static int handler_desfire_create_linearrecordfile(mfdes_linear_t *file) {
if (file->fileno > 0x1F)
return PM3_EINVARG;
@ -2051,7 +2018,7 @@ static int handler_desfire_create_cyclicrecordfile(mfdes_linear_t *file) {
return res;
}
static int handler_desfire_create_backup_file(mfdes_file_t *file) {
/*static int handler_desfire_create_backup_file(mfdes_file_t *file) {
if (file->fileno > 0x1F) return PM3_EINVARG;
sAPDU apdu = {0x90, MFDES_CREATE_BACKUP_DATA_FILE, 0x00, 0x00, sizeof(mfdes_file_t), (uint8_t *)file}; // 0xCB
@ -2065,7 +2032,7 @@ static int handler_desfire_create_backup_file(mfdes_file_t *file) {
return res;
}
return res;
}
}*/
static int getKeySettings(uint8_t *aid) {
if (aid == NULL) return PM3_EINVARG;
@ -2379,173 +2346,6 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) {
return res;
}
static int CmdHF14ADesDeleteFile(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes deletefile",
"Delete File",
"hf mfdes deletefile -n 01 -> Make sure to select aid or authenticate aid before running this command."
);
void *argtable[] = {
arg_param_begin,
arg_int0("n", "fileno", "<dec>", "File Number (0 - 31)"),
arg_strx0("a", "aid", "<hex>", "App ID to select as hex bytes (3 bytes, big endian)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
int fno = arg_get_int_def(ctx, 1, 0);
int aidlength = 3;
uint8_t aid[3] = {0};
CLIGetHexWithReturn(ctx, 2, aid, &aidlength);
swap24(aid);
CLIParserFree(ctx);
if (fno > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno);
return PM3_EINVARG;
}
if (aidlength != 3 && aidlength != 0) {
PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian)."));
return PM3_ESOFT;
} else if (aidlength == 0) {
if (memcmp(&tag->selected_application, aid, 3) == 0) {
PrintAndLogEx(ERR, _RED_(" You need to select an aid first."));
return PM3_ESOFT;
}
memcpy(aid, (uint8_t *)&tag->selected_application, 3);
}
uint8_t cs = 0;
if (selectfile(aid, fno, &cs) != PM3_SUCCESS) {
PrintAndLogEx(ERR, _RED_(" Error on selecting file."));
return PM3_ESOFT;
}
int res = handler_desfire_deletefile(fno);
if (res == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Successfully deleted file..");
} else {
PrintAndLogEx(ERR, "Error on deleting file : %d", res);
}
DropFieldDesfire();
return res;
}
static int CmdHF14ADesCreateFile(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes createfile",
"Create Standard/Backup File",
"hf mfdes createfile -f 0001 -n 01 -c 0 -r EEEE -s 000100 -a 123456"
);
void *argtable[] = {
arg_param_begin,
arg_int0("n", "fileno", "<dec>", "File Number (0 - 31)"),
arg_strx0("f", "fileid", "<hex>", "ISO FID (2 hex bytes, big endian)"),
arg_int0("c", "com", "<dec>", "Communication setting (0 = Plain, 1 = Plain + MAC, 3 = Enciphered)"),
arg_strx0("r", "rights", "<hex>", "Access rights (2 hex bytes -> RW/Chg/R/W, 0x0 - 0xD Key, 0xE Free, 0xF Denied)"),
arg_strx0("s", "filesize", "<hex>", "File size (3 hex bytes, big endian)"),
arg_lit0("b", "backup", "Create backupfile instead of standard file"),
arg_strx0("a", "aid", "<hex>", "App ID to select as hex bytes (3 bytes, big endian)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
int fno = arg_get_int_def(ctx, 1, 0);
int fidlength = 0;
uint8_t fid[2] = {0};
int res_flen = CLIParamHexToBuf(arg_get_str(ctx, 2), fid, 2, &fidlength);
uint8_t comset = arg_get_int(ctx, 3);
int arlength = 0;
uint8_t ar[2] = {0};
CLIGetHexWithReturn(ctx, 4, ar, &arlength);
int fsizelen = 0;
uint8_t filesize[3] = {0};
CLIGetHexWithReturn(ctx, 5, filesize, &fsizelen);
bool isbackup = arg_get_lit(ctx, 6);
int aidlength = 3;
uint8_t aid[3] = {0};
CLIGetHexWithReturn(ctx, 7, aid, &aidlength);
swap24(aid);
CLIParserFree(ctx);
swap16(fid);
swap24(filesize);
if (fno > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno);
return PM3_EINVARG;
}
if (comset != 0 && comset != 1 && comset != 3) {
PrintAndLogEx(ERR, "Communication setting must be either 0=Plain, 1=Plain+MAC or 3=Encrypt.");
return PM3_EINVARG;
}
if (arlength != 2) {
PrintAndLogEx(ERR, "Access rights must have 2 hex bytes length.");
return PM3_EINVARG;
}
if (fsizelen != 3) {
PrintAndLogEx(ERR, "Filesize must have 3 hex bytes length.");
return PM3_EINVARG;
}
if (res_flen || fidlength != 2) {
PrintAndLogEx(ERR, "ISO File id must have 2 hex bytes length.");
return PM3_EINVARG;
}
mfdes_file_t ft;
memcpy(ft.fid, fid, 2);
memcpy(ft.filesize, filesize, 3);
ft.fileno = fno;
ft.comset = comset;
memcpy(ft.access_rights, ar, 2);
if (aidlength != 3 && aidlength != 0) {
PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian)."));
DropFieldDesfire();
return PM3_ESOFT;
} else if (aidlength == 0) {
if (memcmp(&tag->selected_application, aid, 3) == 0) {
PrintAndLogEx(ERR, _RED_(" You need to select an aid first."));
DropFieldDesfire();
return PM3_ESOFT;
}
memcpy(aid, (uint8_t *)&tag->selected_application, 3);
}
// int res;
// a select here seems to invalidate the current authentication with AMK and create file fails if not open access.
// This will be managed when we track Authenticated or Note, so a place holder comment as a reminder.
int res = handler_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Couldn't select aid. Error %d", res);
DropFieldDesfire();
return res;
}
if (isbackup)
res = handler_desfire_create_backup_file(&ft);
else
res = handler_desfire_create_std_file(&ft);
if (res == PM3_SUCCESS)
PrintAndLogEx(SUCCESS, "Successfully created standard / backup file.");
else
PrintAndLogEx(ERR, "Couldn't create standard / backup file. Error %d", res);
DropFieldDesfire();
return res;
}
static int CmdHF14ADesGetValueData(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes getvalue",
@ -3042,152 +2842,6 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) {
return res;
}
static int CmdHF14ADesCreateValueFile(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes createvaluefile",
"Create Value File\n"
"Make sure to select aid or authenticate aid before running this command.",
"hf mfdes createvaluefile -n 03 -c 0 -r EEEE -l 00000000 -u 00002000 --val 00000001 -m 02 -a 123456\n"
);
void *argtable[] = {
arg_param_begin,
arg_int0("n", "fileno", "<dec>", "File Number (0 - 31)"),
arg_int0("c", "com", "<dec>", "Communication setting (0 = Plain, 1 = Plain + MAC, 3 = Enciphered)"),
arg_strx0("r", "rights", "<hex>", "Access rights (2 hex bytes -> RW/Chg/R/W, 0x0 - 0xD Key, 0xE Free, 0xF Denied)"),
arg_strx0("l", "lower", "<hex>", "Lower limit (4 hex bytes, big endian)"),
arg_strx0("u", "upper", "<hex>", "Upper limit (4 hex bytes, big endian)"),
arg_strx0(NULL, "val", "<hex>", "Value (4 hex bytes, big endian)"),
arg_int0("m", NULL, "<dec>", "Limited Credit enabled (Bit 0 = Limited Credit, 1 = FreeValue)"),
arg_strx0("a", "aid", "<hex>", "App ID to select as hex bytes (3 bytes,big endian,optional)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
int fno = arg_get_int_def(ctx, 1, 0);
uint8_t comset = arg_get_int(ctx, 2);
int arlength = 0;
uint8_t ar[2] = {0};
CLIGetHexWithReturn(ctx, 3, ar, &arlength);
int lllen = 0;
uint8_t lowerlimit[4] = {0};
CLIGetHexWithReturn(ctx, 4, lowerlimit, &lllen);
int ullen = 0;
uint8_t upperlimit[4] = {0};
CLIGetHexWithReturn(ctx, 5, upperlimit, &ullen);
int vllen = 0;
uint8_t value[4] = {0};
CLIGetHexWithReturn(ctx, 6, value, &vllen);
uint8_t limited = arg_get_int_def(ctx, 7, 0);
int aidlength = 3;
uint8_t aid[3] = {0};
CLIGetHexWithReturn(ctx, 8, aid, &aidlength);
swap24(aid);
CLIParserFree(ctx);
swap32(lowerlimit);
swap32(upperlimit);
swap32(value);
if (fno > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno);
return PM3_EINVARG;
}
if (comset != 0 && comset != 1 && comset != 3) {
PrintAndLogEx(ERR, "Communication setting must be either 0=Plain, 1=Plain+MAC or 3=Encrypt");
return PM3_EINVARG;
}
if (arlength != 2) {
PrintAndLogEx(ERR, "Access rights must have 2 hex bytes length");
return PM3_EINVARG;
}
if (lllen != 4) {
PrintAndLogEx(ERR, "Lower limit must have 4 hex bytes length");
return PM3_EINVARG;
}
if (ullen != 4) {
PrintAndLogEx(ERR, "Upper limit must have 4 hex bytes length");
return PM3_EINVARG;
}
if (vllen != 4) {
PrintAndLogEx(ERR, "Value must have 4 hex bytes length");
return PM3_EINVARG;
}
mfdes_value_file_t ft = {
.fileno = fno,
.comset = comset,
.limitedcreditenabled = limited,
};
memcpy(ft.access_rights, ar, 2);
memcpy(ft.lowerlimit, lowerlimit, 4);
memcpy(ft.upperlimit, upperlimit, 4);
memcpy(ft.value, value, 4);
if (aidlength != 3 && aidlength != 0) {
PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian)."));
return PM3_ESOFT;
} else if (aidlength == 0) {
if (memcmp(&tag->selected_application, aid, 3) == 0) {
PrintAndLogEx(ERR, _RED_(" You need to select an aid first."));
return PM3_ESOFT;
}
memcpy(aid, (uint8_t *)&tag->selected_application, 3);
}
if (handler_desfire_select_application(aid) != PM3_SUCCESS) {
PrintAndLogEx(ERR, _RED_(" Error on selecting aid."));
return PM3_ESOFT;
}
int res = handler_desfire_create_value_file(&ft);
if (res == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Successfully created value file.");
} else {
PrintAndLogEx(ERR, "Couldn't create value file. Error %d", res);
}
DropFieldDesfire();
return res;
}
/*
static int CmdHF14ADesFormatPICC(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes formatpicc",
"Formats MIFARE DESFire PICC to factory state\n"
"Make sure to authenticate picc before running this command.",
"hf mfdes formatpicc"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
sAPDU apdu = {0x90, MFDES_FORMAT_PICC, 0x00, 0x00, 0, NULL}; // 0xDF
uint16_t sw = 0;
uint32_t recvlen = 0;
int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true);
if (res != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_(" Can't format picc -> %s"), DesfireGetErrorString(res, &sw));
} else {
PrintAndLogEx(INFO, "Card successfully reset");
}
DropFieldDesfire();
return res;
}*/
static int CmdHF14ADesInfo(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes info",
@ -5178,6 +4832,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
bool fileidpresent = (res == 1);
if (res == 2) {
PrintAndLogEx(ERR, "ISO file ID must have 2 bytes length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
@ -5189,6 +4844,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
res = arg_get_u32_hexstr_def_nlen(ctx, 15, 0x0f, &ks1, 1, true);
if (res == 2) {
PrintAndLogEx(ERR, "Key settings 1 must have 1 byte length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
@ -5197,12 +4853,15 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
bool ks2present = (res == 1);
if (res == 2) {
PrintAndLogEx(ERR, "Key settings 2 must have 1 byte length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
int dstalgo = T_DES;
if (CLIGetOptionList(arg_get_str(ctx, 17), DesfireAlgoOpts, &dstalgo))
if (CLIGetOptionList(arg_get_str(ctx, 17), DesfireAlgoOpts, &dstalgo)) {
CLIParserFree(ctx);
return PM3_ESOFT;
}
int keycount = arg_get_int_def(ctx, 18, 0x0e);
@ -5274,7 +4933,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
PrintAndLogEx(INFO, "ISO file ID %s", (data[4] & 0x20) ? "enabled" : "disabled");
if ((data[4] & 0x20)) {
PrintAndLogEx(INFO, "FID 0x%02x%02x", data[6], data[5]);
PrintAndLogEx(INFO, "DF Name[%02d] %s\n", strnlen((char *)&data[7], 16), (char *)&data[7]);
PrintAndLogEx(INFO, "DF Name[%02zu] %s\n", strnlen((char *)&data[7], 16), (char *)&data[7]);
}
PrintKeySettings(data[3], data[4], true, true);
PrintAndLogEx(INFO, "---------------------------");
@ -6024,7 +5683,7 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) {
return PM3_ESOFT;
}
if (buflen >= 3) {
if (buflen > 0) {
PrintAndLogEx(INFO, "---- " _CYAN_("File ID list") " ----");
for (int i = 0; i < buflen; i++)
PrintAndLogEx(INFO, "File ID: %02x", buf[i]);
@ -6102,7 +5761,7 @@ static int CmdHF14ADesGetFileISOIDs(const char *Cmd) {
return PM3_ESOFT;
}
if (buflen >= 3) {
if (buflen > 1) {
PrintAndLogEx(INFO, "---- " _CYAN_("File ISO ID list") " ----");
for (int i = 0; i < buflen; i += 2)
PrintAndLogEx(INFO, "File ID: %02x%02x", buf[i], buf[i + 1]);
@ -6202,7 +5861,7 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) {
CLIParserInit(&ctx, "hf mfdes chfilesettings",
"Get File Settings from file from application. Master key needs to be provided or flag --no-auth set (depend on cards settings).",
"hf mfdes chfilesettings --aid 123456 --fid 01 --amode plain --rrights free --wrights free --rwrights free --chrights key0 -> change file settings app=123456, file=01 with defaults from `default` command\n"
"hf mfdes chfilesettings -n 0 -t des -k 0000000000000000 -f none --aid 123456 --fid 01 -rawdata 00EEEE -> execute with default factory setup\n"
"hf mfdes chfilesettings -n 0 -t des -k 0000000000000000 -f none --aid 123456 --fid 01 --rawdata 00EEEE -> execute with default factory setup\n"
"hf mfdes chfilesettings --aid 123456 --fid 01 --rawdata 810000021f112f22 -> change file settings with additional rights for keys 1 and 2");
void *argtable[] = {
@ -6290,9 +5949,8 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) {
int ch_mode = 0x0e;
if (CLIGetOptionList(arg_get_str(ctx, 18), DesfireFileAccessModeOpts, &ch_mode))
return PM3_ESOFT;
settings[1] = ((rw_mode & 0x0f) << 4) | (ch_mode & 0x0f);
settings[2] = ((r_mode & 0x0f) << 4) | (w_mode & 0x0f);
DesfireEncodeFileAcessMode(&settings[1], r_mode, w_mode, rw_mode, ch_mode) ;
}
SetAPDULogging(APDULogging);
@ -6321,7 +5979,8 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) {
DesfireSetCommMode(&dctx, DCMPlain);
res = DesfireGetFileSettings(&dctx, fileid, buf, &buflen);
if (res == PM3_SUCCESS && buflen > 5) {
uint8_t chright = buf[2] & 0x0f;
uint8_t chright = 0;
DesfireDecodeFileAcessMode(&buf[2], NULL, NULL, NULL, &chright) ;
if (verbose)
PrintAndLogEx(INFO, "Current access right for change file settings: %s", GetDesfireAccessRightStr(chright));
@ -6360,6 +6019,491 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) {
return PM3_SUCCESS;
}
static int DesfireCreateFileParameters(
CLIParserContext *ctx,
uint8_t pfileid, uint8_t pisofileid,
uint8_t amodeid,
uint8_t frightsid,
uint8_t r_modeid, uint8_t w_modeid, uint8_t rw_modeid, uint8_t ch_modeid,
uint8_t *data,
size_t *datalen
) {
*datalen = 0;
int res = 0;
uint32_t fileid = 1;
if (pfileid) {
res = arg_get_u32_hexstr_def_nlen(ctx, pfileid, 1, &fileid, 1, true);
if (res == 2) {
PrintAndLogEx(ERR, "File ID must have 1 byte length");
return PM3_EINVARG;
}
}
uint32_t isofileid = 0;
if (pisofileid) {
res = arg_get_u32_hexstr_def_nlen(ctx, pisofileid, 0, &isofileid, 2, true);
if (res == 2) {
PrintAndLogEx(ERR, "ISO file ID must have 2 bytes length");
return PM3_EINVARG;
}
}
data[0] = fileid;
*datalen = 1;
if (isofileid > 0) {
data[1] = (isofileid >> 8) & 0xff;
data[2] = isofileid & 0xff;
*datalen += 2;
}
uint8_t *settings = &data[*datalen];
// file access mode
int cmode = DCMNone;
if (amodeid) {
if (CLIGetOptionList(arg_get_str(ctx, amodeid), DesfireCommunicationModeOpts, &cmode)) {
return PM3_ESOFT;
}
if (cmode == DCMPlain)
settings[0] = 0x00;
if (cmode == DCMMACed)
settings[0] = 0x01;
if (cmode == DCMEncrypted)
settings[0] = 0x03;
(*datalen)++;
}
// file rights
uint32_t frights = 0xeeee;
bool userawfrights = false;
if (frightsid) {
res = arg_get_u32_hexstr_def_nlen(ctx, frightsid, 0xeeee, &frights, 2, true);
userawfrights = (res == 1);
if (res == 2) {
PrintAndLogEx(ERR, "File rights must have 2 bytes length");
return PM3_EINVARG;
}
}
settings[1] = frights & 0xff;
settings[2] = (frights >> 8) & 0xff;
if (userawfrights == false) {
int r_mode = 0x0e;
if (r_modeid) {
if (CLIGetOptionList(arg_get_str(ctx, r_modeid), DesfireFileAccessModeOpts, &r_mode))
return PM3_ESOFT;
}
int w_mode = 0x0e;
if (w_modeid) {
if (CLIGetOptionList(arg_get_str(ctx, w_modeid), DesfireFileAccessModeOpts, &w_mode))
return PM3_ESOFT;
}
int rw_mode = 0x0e;
if (rw_modeid) {
if (CLIGetOptionList(arg_get_str(ctx, rw_modeid), DesfireFileAccessModeOpts, &rw_mode))
return PM3_ESOFT;
}
int ch_mode = 0x0e;
if (ch_modeid) {
if (CLIGetOptionList(arg_get_str(ctx, ch_modeid), DesfireFileAccessModeOpts, &ch_mode))
return PM3_ESOFT;
}
DesfireEncodeFileAcessMode(&settings[1], r_mode, w_mode, rw_mode, ch_mode) ;
}
*datalen += 2;
return PM3_SUCCESS;
}
static int CmdHF14ADesCreateFile(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes createfile",
"Create Standard/Backup file in the application. Application master key needs to be provided or flag --no-auth set (depend on application settings).",
"--rawtype/--rawdata have priority over the other settings. and with these parameters you can create any file. file id comes from parameters, all the rest data must be in the --rawdata parameter\n"
"--rawrights have priority over the separate rights settings.\n"
"Key/mode/etc of the authentication depends on application settings\n"
"hf mfdes createfile --aid 123456 --fid 01 --rawtype 01 --rawdata 000100EEEE000100 -> create file via sending rawdata to the card. Can be used to create any type of file. Authentication with defaults from `default` command\n"
"hf mfdes createfile --aid 123456 --fid 01 --amode plain --rrights free --wrights free --rwrights free --chrights key0 -> create file app=123456, file=01 and mentioned rights with defaults from `default` command\n"
"hf mfdes createfile -n 0 -t des -k 0000000000000000 -f none --aid 123456 --fid 01 --rawtype 00 --rawdata 00EEEE000100 -> execute with default factory setup");
void *argtable[] = {
arg_param_begin,
arg_lit0("a", "apdu", "show APDU requests and responses"),
arg_lit0("v", "verbose", "show technical data"),
arg_int0("n", "keyno", "<keyno>", "Key number"),
arg_str0("t", "algo", "<DES/2TDEA/3TDEA/AES>", "Crypt algo: DES, 2TDEA, 3TDEA, AES"),
arg_str0("k", "key", "<Key>", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"),
arg_str0("f", "kdf", "<none/AN10922/gallagher>", "Key Derivation Function (KDF): None, AN10922, Gallagher"),
arg_str0("i", "kdfi", "<kdfi>", "KDF input (HEX 1-31 bytes)"),
arg_str0("m", "cmode", "<plain/mac/encrypt>", "Communicaton mode: plain/mac/encrypt"),
arg_str0("c", "ccset", "<native/niso/iso>", "Communicaton command set: native/niso/iso"),
arg_str0("s", "schann", "<d40/ev1/ev2>", "Secure channel: d40/ev1/ev2"),
arg_str0(NULL, "aid", "<app id hex>", "Application ID (3 hex bytes, big endian)"),
arg_str0(NULL, "fid", "<file id hex>", "File ID (1 hex byte)"),
arg_str0(NULL, "isofid", "<iso file id hex>", "ISO File ID (2 hex bytes)"),
arg_str0(NULL, "rawtype", "<file type HEX 1b>", "Raw file type (HEX 1 byte)"),
arg_str0(NULL, "rawdata", "<file settings HEX>", "Raw file settings (HEX > 5 bytes)"),
arg_str0(NULL, "amode", "<plain/mac/encrypt>", "File access mode: plain/mac/encrypt"),
arg_str0(NULL, "rawrights", "<access rights HEX>", "Access rights for file (HEX 2 byte) R/W/RW/Chg, 0x0 - 0xD Key, 0xE Free, 0xF Denied"),
arg_str0(NULL, "rrights", "<key0/../key13/free/deny>", "Read file access mode: the specified key, free, deny"),
arg_str0(NULL, "wrights", "<key0/../key13/free/deny>", "Write file access mode: the specified key, free, deny"),
arg_str0(NULL, "rwrights","<key0/../key13/free/deny>", "Read/Write file access mode: the specified key, free, deny"),
arg_str0(NULL, "chrights","<key0/../key13/free/deny>", "Change file settings access mode: the specified key, free, deny"),
arg_lit0(NULL, "no-auth", "execute without authentication"),
arg_str0(NULL, "size", "<hex>", "File size (3 hex bytes, big endian)"),
arg_lit0(NULL, "backup", "Create backupfile instead of standard file"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
bool APDULogging = arg_get_lit(ctx, 1);
bool verbose = arg_get_lit(ctx, 2);
bool noauth = arg_get_lit(ctx, 22);
bool backup = arg_get_lit(ctx, 24);
uint8_t filetype = (backup) ? 0x01 : 0x00; // backup / standard data file
DesfireContext dctx;
int securechann = defaultSecureChannel;
uint32_t appid = 0x000000;
int res = CmdDesGetSessionParameters(ctx, &dctx, 3, 4, 5, 6, 7, 8, 9, 10, 11, &securechann, DCMPlain, &appid);
if (res) {
CLIParserFree(ctx);
return res;
}
if (appid == 0x000000) {
PrintAndLogEx(ERR, "Can't create files at card level.");
CLIParserFree(ctx);
return PM3_EINVARG;
}
uint8_t data[250] = {0};
size_t datalen = 0;
res = DesfireCreateFileParameters(ctx, 12, 13, 16, 17, 18, 19, 20, 21, data, &datalen);
if (res) {
CLIParserFree(ctx);
return res;
}
uint32_t rawftype = 0x00;
res = arg_get_u32_hexstr_def_nlen(ctx, 14, 0x00, &rawftype, 1, true);
bool useraw = (res == 1);
if (res == 2) {
PrintAndLogEx(ERR, "Raw file type must have 1 byte length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
uint8_t sdata[250] = {0};
int sdatalen = sizeof(sdata);
CLIGetHexWithReturn(ctx, 15, sdata, &sdatalen);
if (sdatalen > 20) {
PrintAndLogEx(ERR, "Rawdata length must be less than 20 bytes instead of %d.", sdatalen);
CLIParserFree(ctx);
return PM3_EINVARG;
}
if (useraw && sdatalen > 0) {
filetype = rawftype;
memcpy(&data[1], sdata, sdatalen);
datalen = 1 + sdatalen;
} else {
useraw = false;
}
if (useraw == false) {
uint32_t filesize = 0;
res = arg_get_u32_hexstr_def_nlen(ctx, 23, 0, &filesize, 3, true);
if (res == 2) {
PrintAndLogEx(ERR, "File size must have 3 bytes length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
if (filesize == 0) {
PrintAndLogEx(ERR, "File size must be greater than 0");
CLIParserFree(ctx);
return PM3_EINVARG;
}
Uint3byteToMemLe(&data[datalen], filesize);
datalen += 3;
}
SetAPDULogging(APDULogging);
CLIParserFree(ctx);
if (noauth) {
res = DesfireSelectAIDHex(&dctx, appid, false, 0);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Desfire select " _RED_("error") ".");
DropField();
return res;
}
} else {
res = DesfireSelectAndAuthenticate(&dctx, securechann, appid, verbose);
if (res != PM3_SUCCESS) {
DropField();
return res;
}
}
if (verbose)
PrintAndLogEx(INFO, "App: %06x. File num: 0x%02x type: 0x%02x data[%d]: %s", appid, data[0], filetype, datalen, sprint_hex(data, datalen));
DesfirePrintCreateFileSettings(filetype, data, datalen);
res = DesfireCreateFile(&dctx, filetype, data, datalen, useraw == false); // check length only if we nont use raw mode
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Desfire CreateFile command " _RED_("error") ". Result: %d", res);
DropField();
return PM3_ESOFT;
}
PrintAndLogEx(SUCCESS, "File %02x in the app %06x created " _GREEN_("successfully"), data[0], appid);
DropField();
return PM3_SUCCESS;
}
static int CmdHF14ADesCreateValueFile(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes createvaluefile",
"Create Value file in the application. Application master key needs to be provided or flag --no-auth set (depend on application settings).",
"--rawrights have priority over the separate rights settings.\n"
"Key/mode/etc of the authentication depends on application settings\n"
"hf mfdes createvaluefile --aid 123456 --fid 01 --lower 00000010 --upper 00010000 --value 00000100 -> create file with parameters. Rights from default. Authentication with defaults from `default` command\n"
"hf mfdes createvaluefile --aid 123456 --fid 01 --amode plain --rrights free --wrights free --rwrights free --chrights key0 -> create file app=123456, file=01 and mentioned rights with defaults from `default` command\n"
"hf mfdes createvaluefile -n 0 -t des -k 0000000000000000 -f none --aid 123456 --fid 01 -> execute with default factory setup");
void *argtable[] = {
arg_param_begin,
arg_lit0("a", "apdu", "show APDU requests and responses"),
arg_lit0("v", "verbose", "show technical data"),
arg_int0("n", "keyno", "<keyno>", "Key number"),
arg_str0("t", "algo", "<DES/2TDEA/3TDEA/AES>", "Crypt algo: DES, 2TDEA, 3TDEA, AES"),
arg_str0("k", "key", "<Key>", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"),
arg_str0("f", "kdf", "<none/AN10922/gallagher>", "Key Derivation Function (KDF): None, AN10922, Gallagher"),
arg_str0("i", "kdfi", "<kdfi>", "KDF input (HEX 1-31 bytes)"),
arg_str0("m", "cmode", "<plain/mac/encrypt>", "Communicaton mode: plain/mac/encrypt"),
arg_str0("c", "ccset", "<native/niso/iso>", "Communicaton command set: native/niso/iso"),
arg_str0("s", "schann", "<d40/ev1/ev2>", "Secure channel: d40/ev1/ev2"),
arg_str0(NULL, "aid", "<app id hex>", "Application ID (3 hex bytes, big endian)"),
arg_str0(NULL, "fid", "<file id hex>", "File ID (1 hex byte)"),
arg_str0(NULL, "amode", "<plain/mac/encrypt>", "File access mode: plain/mac/encrypt"),
arg_str0(NULL, "rawrights", "<access rights HEX>", "Access rights for file (HEX 2 byte) R/W/RW/Chg, 0x0 - 0xD Key, 0xE Free, 0xF Denied"),
arg_str0(NULL, "rrights", "<key0/../key13/free/deny>", "Read file access mode: the specified key, free, deny"),
arg_str0(NULL, "wrights", "<key0/../key13/free/deny>", "Write file access mode: the specified key, free, deny"),
arg_str0(NULL, "rwrights","<key0/../key13/free/deny>", "Read/Write file access mode: the specified key, free, deny"),
arg_str0(NULL, "chrights","<key0/../key13/free/deny>", "Change file settings access mode: the specified key, free, deny"),
arg_lit0(NULL, "no-auth", "execute without authentication"),
arg_str0(NULL, "lower", "<hex>", "Lower limit (4 hex bytes, big endian)"),
arg_str0(NULL, "upper", "<hex>", "Upper limit (4 hex bytes, big endian)"),
arg_str0(NULL, "value", "<hex>", "Value (4 hex bytes, big endian)"),
arg_int0(NULL, "lcredit", "<dec>", "Limited Credit enabled (Bit 0 = Limited Credit, 1 = FreeValue)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
bool APDULogging = arg_get_lit(ctx, 1);
bool verbose = arg_get_lit(ctx, 2);
bool noauth = arg_get_lit(ctx, 19);
uint8_t filetype = 0x02; // value file
DesfireContext dctx;
int securechann = defaultSecureChannel;
uint32_t appid = 0x000000;
int res = CmdDesGetSessionParameters(ctx, &dctx, 3, 4, 5, 6, 7, 8, 9, 10, 11, &securechann, DCMPlain, &appid);
if (res) {
CLIParserFree(ctx);
return res;
}
if (appid == 0x000000) {
PrintAndLogEx(ERR, "Can't create files at card level.");
CLIParserFree(ctx);
return PM3_EINVARG;
}
if (appid == 0x000000) {
PrintAndLogEx(ERR, "Can't create files at card level.");
CLIParserFree(ctx);
return PM3_EINVARG;
}
uint8_t data[250] = {0};
size_t datalen = 0;
res = DesfireCreateFileParameters(ctx, 12, 0, 13, 14, 15, 16, 17, 18, data, &datalen);
if (res) {
CLIParserFree(ctx);
return res;
}
uint32_t lowerlimit = 0;
res = arg_get_u32_hexstr_def_nlen(ctx, 20, 0, &lowerlimit, 4, true);
if (res == 2) {
PrintAndLogEx(ERR, "Lower limit value must have 4 bytes length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
uint32_t upperlimit = 0;
res = arg_get_u32_hexstr_def_nlen(ctx, 21, 0, &upperlimit, 4, true);
if (res == 2) {
PrintAndLogEx(ERR, "Upper limit value must have 4 bytes length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
uint32_t value = 0;
res = arg_get_u32_hexstr_def_nlen(ctx, 22, 0, &value, 4, true);
if (res == 2) {
PrintAndLogEx(ERR, "Lower limit value must have 4 bytes length");
CLIParserFree(ctx);
return PM3_EINVARG;
}
uint32_t lcredit = arg_get_int_def(ctx, 23, 0);
SetAPDULogging(APDULogging);
CLIParserFree(ctx);
Uint4byteToMemLe(&data[datalen], lowerlimit);
datalen += 4;
Uint4byteToMemLe(&data[datalen], upperlimit);
datalen += 4;
Uint4byteToMemLe(&data[datalen], value);
datalen += 4;
data[datalen] = lcredit;
datalen++;
if (noauth) {
res = DesfireSelectAIDHex(&dctx, appid, false, 0);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Desfire select " _RED_("error") ".");
DropField();
return res;
}
} else {
res = DesfireSelectAndAuthenticate(&dctx, securechann, appid, verbose);
if (res != PM3_SUCCESS) {
DropField();
return res;
}
}
if (verbose)
PrintAndLogEx(INFO, "App: %06x. File num: 0x%02x type: 0x%02x data[%d]: %s", appid, data[0], filetype, datalen, sprint_hex(data, datalen));
DesfirePrintCreateFileSettings(filetype, data, datalen);
res = DesfireCreateFile(&dctx, filetype, data, datalen, true);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Desfire CreateFile command " _RED_("error") ". Result: %d", res);
DropField();
return PM3_ESOFT;
}
PrintAndLogEx(SUCCESS, "Value file %02x in the app %06x created " _GREEN_("successfully"), data[0], appid);
DropField();
return PM3_SUCCESS;
}
static int CmdHF14ADesDeleteFile(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes deletefile",
"Delete file from application. Master key needs to be provided or flag --no-auth set (depend on cards settings).",
"hf mfdes deletefile --aid 123456 --fid 01 -> delete file for: app=123456, file=01 with defaults from `default` command");
void *argtable[] = {
arg_param_begin,
arg_lit0("a", "apdu", "show APDU requests and responses"),
arg_lit0("v", "verbose", "show technical data"),
arg_int0("n", "keyno", "<keyno>", "Key number"),
arg_str0("t", "algo", "<DES/2TDEA/3TDEA/AES>", "Crypt algo: DES, 2TDEA, 3TDEA, AES"),
arg_str0("k", "key", "<Key>", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"),
arg_str0("f", "kdf", "<none/AN10922/gallagher>", "Key Derivation Function (KDF): None, AN10922, Gallagher"),
arg_str0("i", "kdfi", "<kdfi>", "KDF input (HEX 1-31 bytes)"),
arg_str0("m", "cmode", "<plain/mac/encrypt>", "Communicaton mode: plain/mac/encrypt"),
arg_str0("c", "ccset", "<native/niso/iso>", "Communicaton command set: native/niso/iso"),
arg_str0("s", "schann", "<d40/ev1/ev2>", "Secure channel: d40/ev1/ev2"),
arg_str0(NULL, "aid", "<app id hex>", "Application ID (3 hex bytes, big endian)"),
arg_str0(NULL, "fid", "<file id hex>", "File ID (1 hex byte)"),
arg_lit0(NULL, "no-auth", "execute without authentication"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
bool APDULogging = arg_get_lit(ctx, 1);
bool verbose = arg_get_lit(ctx, 2);
bool noauth = arg_get_lit(ctx, 13);
DesfireContext dctx;
int securechann = defaultSecureChannel;
uint32_t appid = 0x000000;
int res = CmdDesGetSessionParameters(ctx, &dctx, 3, 4, 5, 6, 7, 8, 9, 10, 11, &securechann, DCMPlain, &appid);
if (res) {
CLIParserFree(ctx);
return res;
}
uint32_t fnum = 1;
res = arg_get_u32_hexstr_def_nlen(ctx, 12, 1, &fnum, 1, true);
if (res == 2) {
PrintAndLogEx(ERR, "File ID must have 1 byte length");
return PM3_EINVARG;
}
SetAPDULogging(APDULogging);
CLIParserFree(ctx);
if (fnum > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fnum);
return PM3_EINVARG;
}
if (noauth) {
res = DesfireSelectAIDHex(&dctx, appid, false, 0);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Desfire select " _RED_("error") ".");
DropField();
return res;
}
} else {
res = DesfireSelectAndAuthenticate(&dctx, securechann, appid, verbose);
if (res != PM3_SUCCESS) {
DropField();
return res;
}
}
res = DesfireDeleteFile(&dctx, fnum);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Desfire DeleteFile command " _RED_("error") ". Result: %d", res);
DropField();
return PM3_ESOFT;
}
PrintAndLogEx(SUCCESS, "File %02x in the app %06x deleted " _GREEN_("successfully"), fnum, appid);
DropField();
return PM3_SUCCESS;
}
static int CmdHF14ADesTest(const char *Cmd) {
DesfireTest(true);
return PM3_SUCCESS;
@ -6399,10 +6543,10 @@ static command_t CommandTable[] = {
{"chfilesettings", CmdHF14ADesChFileSettings, IfPm3Iso14443a, "[new]Change file settings"},
{"changevalue", CmdHF14ADesChangeValue, IfPm3Iso14443a, "Write value of a value file (credit/debit/clear)"},
{"clearfile", CmdHF14ADesClearRecordFile, IfPm3Iso14443a, "Clear record File"},
{"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"},
{"createvaluefile", CmdHF14ADesCreateValueFile, IfPm3Iso14443a, "Create Value File"},
{"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "[new]Create Standard/Backup File"},
{"createvaluefile", CmdHF14ADesCreateValueFile, IfPm3Iso14443a, "[new]Create Value File"},
{"createrecordfile", CmdHF14ADesCreateRecordFile, IfPm3Iso14443a, "Create Linear/Cyclic Record File"},
{"deletefile", CmdHF14ADesDeleteFile, IfPm3Iso14443a, "Delete File"},
{"deletefile", CmdHF14ADesDeleteFile, IfPm3Iso14443a, "[new]Delete File"},
{"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"},
{"getvalue", CmdHF14ADesGetValueData, IfPm3Iso14443a, "Get value of file"},
{"read", CmdHF14ADesReadData, IfPm3Iso14443a, "Read data from standard/backup/record file"},

View file

@ -19,13 +19,13 @@
#include <stdlib.h>
#include <string.h>
#include <util.h>
#include "commonutil.h"
#include "aes.h"
#include "ui.h"
#include "crc.h"
#include "crc16.h" // crc16 ccitt
#include "crc32.h"
#include "protocols.h"
#include "commonutil.h"
#include "cmdhf14a.h"
#include "iso7816/apduinfo.h" // APDU manipulation / errorcodes
#include "iso7816/iso7816core.h" // APDU logging
@ -1049,12 +1049,30 @@ int DesfireGetFileISOIDList(DesfireContext *dctx, uint8_t *resp, size_t *resplen
int DesfireGetFileSettings(DesfireContext *dctx, uint8_t fileid, uint8_t *resp, size_t *resplen) {
return DesfireCommand(dctx, MFDES_GET_FILE_SETTINGS, &fileid, 1, resp, resplen, -1);
}
int DesfireCreateFile(DesfireContext *dctx, uint8_t *fdata, size_t fdatalen) {
return DesfireCommandTxData(dctx, MFDES_CREATE_STD_DATA_FILE, fdata, fdatalen);
int DesfireCreateFile(DesfireContext *dctx, uint8_t ftype, uint8_t *fdata, size_t fdatalen, bool checklen) {
const DesfireCreateFileCommandsS *rcmd = GetDesfireFileCmdRec(ftype);
if (rcmd == NULL)
return -100;
if (checklen && fdatalen != (rcmd->len + 1) && fdatalen != (rcmd->len + 1 + (rcmd->mayHaveISOfid ? 2 : 0)))
return -110;
return DesfireCommandTxData(dctx, rcmd->cmd, fdata, fdatalen);
}
int DesfireDeleteFile(DesfireContext *dctx, uint8_t fid) {
return DesfireCommandTxData(dctx, MFDES_DELETE_FILE, &fid, 1);
int DesfireDeleteFile(DesfireContext *dctx, uint8_t fnum) {
return DesfireCommandTxData(dctx, MFDES_DELETE_FILE, &fnum, 1);
}
int DesfireCommitTrqansaction(DesfireContext *dctx, bool enable_options, uint8_t options) {
if (enable_options)
return DesfireCommandTxData(dctx, MFDES_COMMIT_TRANSACTION, &options, 1);
else
return DesfireCommandNoData(dctx, MFDES_COMMIT_TRANSACTION);
}
int DesfireAbortTrqansaction(DesfireContext *dctx) {
return DesfireCommandNoData(dctx, MFDES_ABORT_TRANSACTION);
}
uint8_t DesfireKeyAlgoToType(DesfireCryptoAlgorythm keyType) {
@ -1148,18 +1166,27 @@ void PrintKeySettings(uint8_t keysettings, uint8_t numkeys, bool applevel, bool
static const char *DesfireUnknownStr = "unknown";
static const char *DesfireDisabledStr = "disabled";
static const char *DesfireFreeStr = "free";
static const char *DesfireFileTypes[] = {
"Standard data",
"Backup data",
"Value",
"Linear Record",
"Cyclic Record",
"Transaction MAC",
static const DesfireCreateFileCommandsS DesfireFileCommands[] = {
{0x00, "Standard data", MFDES_CREATE_STD_DATA_FILE, 6, 6, true},
{0x01, "Backup data", MFDES_CREATE_BACKUP_DATA_FILE, 6, 6, true},
{0x02, "Value", MFDES_CREATE_VALUE_FILE, 16, 16, false},
{0x03, "Linear Record", MFDES_CREATE_LINEAR_RECORD_FILE, 12, 9, true},
{0x04, "Cyclic Record", MFDES_CREATE_CYCLIC_RECORD_FILE, 12, 9, true},
{0x05, "Transaction MAC", MFDES_CREATE_TRANS_MAC_FILE, 5, 22, false},
};
const DesfireCreateFileCommandsS *GetDesfireFileCmdRec(uint8_t type) {
for (int i = 0; i < ARRAYLEN(DesfireFileCommands); i++)
if (DesfireFileCommands[i].id == type)
return &DesfireFileCommands[i];
return NULL;
}
static const char *GetDesfireFileType(uint8_t type) {
if (type < ARRAYLEN(DesfireFileTypes))
return DesfireFileTypes[type];
const DesfireCreateFileCommandsS *res = GetDesfireFileCmdRec(type);
if (res != NULL)
return res->text;
else
return DesfireUnknownStr;
}
@ -1196,9 +1223,6 @@ const char *GetDesfireAccessRightStr(uint8_t right) {
static char int_access_str[200];
memset(int_access_str, 0, sizeof(int_access_str));
if (right > 0x0f)
return DesfireUnknownStr;
if (right <= 0x0d) {
sprintf(int_access_str, "key 0x%02x", right);
return int_access_str;
@ -1212,16 +1236,106 @@ const char *GetDesfireAccessRightStr(uint8_t right) {
return DesfireUnknownStr;
}
void DesfireEncodeFileAcessMode(uint8_t *mode, uint8_t r, uint8_t w, uint8_t rw, uint8_t ch) {
mode[0] = (ch & 0x0f) | ((rw << 4) & 0xf0);
mode[1] = (w & 0x0f) | ((r << 4) & 0xf0);
}
void DesfireDecodeFileAcessMode(uint8_t *mode, uint8_t *r, uint8_t *w, uint8_t *rw, uint8_t *ch) {
// read
if (r)
*r = (mode[1] >> 4) & 0x0f; // hi 2b
// write
if (w)
*w = mode[1] & 0x0f;
// read/write
if (rw)
*rw = (mode[0] >> 4) & 0x0f; // low 2b
// change
if (ch)
*ch = mode[0] & 0x0f;
}
void DesfirePrintAccessRight(uint8_t *data) {
PrintAndLogEx(SUCCESS, "read : %s", GetDesfireAccessRightStr((data[1] >> 4) & 0x0f)); // hi 2b
PrintAndLogEx(SUCCESS, "write : %s", GetDesfireAccessRightStr(data[1] & 0x0f));
PrintAndLogEx(SUCCESS, "readwrite: %s", GetDesfireAccessRightStr((data[0] >> 4) & 0x0f)); // low 2b
PrintAndLogEx(SUCCESS, "change : %s", GetDesfireAccessRightStr(data[0] & 0x0f));
uint8_t r = 0;
uint8_t w = 0;
uint8_t rw = 0;
uint8_t ch = 0;
DesfireDecodeFileAcessMode(data, &r, &w, &rw, &ch);
PrintAndLogEx(SUCCESS, "read : %s", GetDesfireAccessRightStr(r));
PrintAndLogEx(SUCCESS, "write : %s", GetDesfireAccessRightStr(w));
PrintAndLogEx(SUCCESS, "readwrite: %s", GetDesfireAccessRightStr(rw));
PrintAndLogEx(SUCCESS, "change : %s", GetDesfireAccessRightStr(ch));
}
static void DesfirePrintFileSettDynPart(uint8_t filetype, uint8_t *data, size_t datalen, uint8_t *dynlen, bool create) {
switch (filetype) {
case 0x00:
case 0x01: {
int filesize = MemLeToUint3byte(&data[0]);
PrintAndLogEx(INFO, "File size : %d (0x%X) bytes", filesize, filesize);
*dynlen = 3;
break;
}
case 0x02: {
int lowerlimit = MemLeToUint4byte(&data[0]);
int upperlimit = MemLeToUint4byte(&data[4]);
int value = MemLeToUint4byte(&data[8]);
uint8_t limited_credit_enabled = data[12];
PrintAndLogEx(INFO, "Lower limit : %d (0x%08X)", lowerlimit, lowerlimit);
PrintAndLogEx(INFO, "Upper limit : %d (0x%08X)", upperlimit, upperlimit);
if (create) {
PrintAndLogEx(INFO, "Value : %d (0x%08X)", value, value);
PrintAndLogEx(INFO, "Limited credit : [%d - %s]", limited_credit_enabled, ((limited_credit_enabled & 1) != 0) ? "enabled" : "disabled");
} else {
PrintAndLogEx(INFO, "Limited credit : [%d - %s] %d (0x%08X)", limited_credit_enabled, ((limited_credit_enabled & 1) != 0) ? "enabled" : "disabled", value, value);
}
PrintAndLogEx(INFO, "GetValue access : %s", ((limited_credit_enabled & 0x02) != 0) ? "Free" : "Not Free");
*dynlen = 13;
break;
}
case 0x03:
case 0x04: {
uint32_t recordsize = MemLeToUint3byte(&data[0]);
uint32_t maxrecords = MemLeToUint3byte(&data[3]);
uint32_t currentrecord = 0;
if (!create)
currentrecord = MemLeToUint3byte(&data[6]);
PrintAndLogEx(INFO, "Record size : %d (0x%X) bytes", recordsize, recordsize);
PrintAndLogEx(INFO, "Max num records : %d (0x%X)", maxrecords, maxrecords);
if (!create)
PrintAndLogEx(INFO, "Curr num records : %d (0x%X)", currentrecord, currentrecord);
*dynlen = (create) ? 6 : 9;
break;
}
case 0x05: {
PrintAndLogEx(INFO, "Key type [0x%02x] : %s", data[0], GetDesfireKeyType(data[0]));
*dynlen = 1;
if (create) {
PrintAndLogEx(INFO, "Key : %s", sprint_hex(&data[1], 16));
*dynlen += 16;
}
PrintAndLogEx(INFO, "Key version : %d (0x%X)", data[*dynlen], data[*dynlen]);
(*dynlen)++;
break;
}
default: {
break;
}
}
}
void DesfirePrintFileSettings(uint8_t *data, size_t len) {
if (len < 6) {
PrintAndLogEx(ERR, "Wrong file settings length: %d", len);
PrintAndLogEx(ERR, "Wrong file settings length: %zu", len);
return;
}
@ -1234,60 +1348,17 @@ void DesfirePrintFileSettings(uint8_t *data, size_t len) {
addaccess = ((data[1] & 0x80) != 0);
PrintAndLogEx(SUCCESS, "Additional access: %s", (addaccess) ? "Yes" : "No");
}
PrintAndLogEx(SUCCESS, "Access rights : %02x%02x", data[2], data[3]);
PrintAndLogEx(SUCCESS, "Access rights : %04x", MemLeToUint2byte(&data[2]));
DesfirePrintAccessRight(&data[2]); //2 bytes
uint8_t reclen = 0;
switch (filetype) {
case 0x00:
case 0x01: {
int filesize = (data[6] << 16) + (data[5] << 8) + data[4];
PrintAndLogEx(INFO, "File size : %d (0x%X) bytes", filesize, filesize);
reclen = 7;
break;
}
case 0x02: {
int lowerlimit = (data[7] << 24) + (data[6] << 16) + (data[5] << 8) + data[4];
int upperlimit = (data[11] << 24) + (data[10] << 16) + (data[9] << 8) + data[8];
int limitcredvalue = (data[15] << 24) + (data[14] << 16) + (data[13] << 8) + data[12];
uint8_t limited_credit_enabled = data[16];
PrintAndLogEx(INFO, "Lower limit : %d (0x%X)", lowerlimit, lowerlimit);
PrintAndLogEx(INFO, "Upper limit : %d (0x%X)", upperlimit, upperlimit);
PrintAndLogEx(INFO, "Limited credit : [%d - %s] %d (0x%X)", limited_credit_enabled, (limited_credit_enabled == 1) ? "enabled" : "disabled", limitcredvalue, limitcredvalue);
reclen = 17;
break;
}
case 0x03:
case 0x04: {
uint32_t recordsize = (data[6] << 16) + (data[5] << 8) + data[4];
uint32_t maxrecords = (data[9] << 16) + (data[8] << 8) + data[7];
uint32_t currentrecord = (data[12] << 16) + (data[11] << 8) + data[10];
PrintAndLogEx(INFO, "Record size : %d (0x%X) bytes", recordsize, recordsize);
PrintAndLogEx(INFO, "Max num records : %d (0x%X)", maxrecords, maxrecords);
PrintAndLogEx(INFO, "Curr num records : %d (0x%X)", currentrecord, currentrecord);
reclen = 13;
break;
}
case 0x05: {
PrintAndLogEx(INFO, "Key type [0x%02x] : %s", data[4], GetDesfireKeyType(data[4]));
PrintAndLogEx(INFO, "Key version : %d (0x%X)", data[5], data[5]);
break;
}
default: {
break;
}
}
DesfirePrintFileSettDynPart(filetype, &data[4], len - 4, &reclen, false);
reclen += 4; // static part
if (addaccess && reclen > 0 && len > reclen && len == reclen + data[reclen] * 2) {
if (addaccess && filetype != 0x05 && reclen > 0 && len > reclen && len == reclen + data[reclen] * 2) {
PrintAndLogEx(SUCCESS, "Add access records: %d", data[reclen]);
for (int i = 0; i < data[reclen] * 2; i += 2) {
PrintAndLogEx(SUCCESS, "Add access rights : [%d] %02x%02x", i / 2, data[reclen + 1 + i], data[reclen + 2 + i]);
PrintAndLogEx(SUCCESS, "Add access rights : [%d] %04x", i / 2, MemLeToUint2byte(&data[reclen + 1 + i]));
DesfirePrintAccessRight(&data[reclen + 1 + i]);
}
}
@ -1300,18 +1371,53 @@ void DesfirePrintSetFileSettings(uint8_t *data, size_t len) {
bool addaccess = ((data[0] & 0x80) != 0);
PrintAndLogEx(SUCCESS, "Additional access: %s", (addaccess) ? "Yes" : "No");
PrintAndLogEx(SUCCESS, "Access rights : %02x%02x", data[1], data[2]);
PrintAndLogEx(SUCCESS, "Access rights : %04x", MemLeToUint2byte(&data[1]));
DesfirePrintAccessRight(&data[1]); //2 bytes
if (addaccess && len > 3 && len == 4 + data[3] * 2) {
PrintAndLogEx(SUCCESS, "Add access records: %d", data[3]);
for (int i = 0; i < data[3] * 2; i += 2) {
PrintAndLogEx(SUCCESS, "Add access rights : [%d] %02x%02x", i / 2, data[4 + i], data[5 + i]);
PrintAndLogEx(SUCCESS, "Add access rights : [%d] %04x", i / 2, MemLeToUint2byte(&data[4 + i]));
DesfirePrintAccessRight(&data[4 + i]);
}
}
}
void DesfirePrintCreateFileSettings(uint8_t filetype, uint8_t *data, size_t len) {
const DesfireCreateFileCommandsS *ftyperec = GetDesfireFileCmdRec(filetype);
if (ftyperec == NULL) {
PrintAndLogEx(WARNING, "Unknown file type 0x%02x", filetype);
return;
}
bool isoidpresent = ftyperec->mayHaveISOfid && (len == ftyperec->createlen + 2 + 1);
PrintAndLogEx(INFO, "---- " _CYAN_("Create file settings") " ----");
PrintAndLogEx(SUCCESS, "File type : %s", ftyperec->text);
PrintAndLogEx(SUCCESS, "File number : 0x%02x (%d)", data[0], data[0]);
size_t xlen = 1;
if (isoidpresent) {
PrintAndLogEx(SUCCESS, "File ISO number : 0x%04x", MemBeToUint2byte(&data[xlen]));
xlen += 2;
} else {
PrintAndLogEx(SUCCESS, "File ISO number : n/a");
}
PrintAndLogEx(SUCCESS, "File comm mode : %s", GetDesfireCommunicationMode(data[xlen] & 0x03));
bool addaccess = ((data[xlen] & 0x80) != 0);
PrintAndLogEx(SUCCESS, "Additional access: %s", (addaccess) ? "Yes" : "No");
xlen++;
PrintAndLogEx(SUCCESS, "Access rights : %04x", MemLeToUint2byte(&data[xlen]));
DesfirePrintAccessRight(&data[xlen]);
xlen += 2;
uint8_t reclen = 0;
DesfirePrintFileSettDynPart(filetype, &data[xlen], len - xlen, &reclen, true);
xlen += reclen;
}
int DesfireChangeKey(DesfireContext *dctx, bool change_master_key, uint8_t newkeynum, DesfireCryptoAlgorythm newkeytype, uint32_t newkeyver, uint8_t *newkey, DesfireCryptoAlgorythm oldkeytype, uint8_t *oldkey, bool verbose) {
uint8_t okeybuf[DESFIRE_MAX_KEY_SIZE] = {0};

View file

@ -19,6 +19,15 @@
#include "mifare/desfire_crypto.h"
#include "mifare/mifare4.h"
typedef struct {
const uint8_t id;
const char *text;
const uint8_t cmd;
const uint8_t len;
const uint8_t createlen;
const bool mayHaveISOfid;
} DesfireCreateFileCommandsS;
extern const CLIParserOption DesfireAlgoOpts[];
extern const CLIParserOption DesfireKDFAlgoOpts[];
extern const CLIParserOption DesfireCommunicationModeOpts[];
@ -64,13 +73,22 @@ int DesfireSetConfiguration(DesfireContext *dctx, uint8_t paramid, uint8_t *para
int DesfireGetFileIDList(DesfireContext *dctx, uint8_t *resp, size_t *resplen);
int DesfireGetFileISOIDList(DesfireContext *dctx, uint8_t *resp, size_t *resplen);
int DesfireGetFileSettings(DesfireContext *dctx, uint8_t fileid, uint8_t *resp, size_t *resplen);
int DesfireChangeFileSettings(DesfireContext *dctx, uint8_t *data, size_t datalen);
const DesfireCreateFileCommandsS *GetDesfireFileCmdRec(uint8_t type);
const char *GetDesfireAccessRightStr(uint8_t right);
void DesfireEncodeFileAcessMode(uint8_t *mode, uint8_t r, uint8_t w, uint8_t rw, uint8_t ch);
void DesfireDecodeFileAcessMode(uint8_t *mode, uint8_t *r, uint8_t *w, uint8_t *rw, uint8_t *ch);
void DesfirePrintAccessRight(uint8_t *data);
void DesfirePrintFileSettings(uint8_t *data, size_t len);
void DesfirePrintSetFileSettings(uint8_t *data, size_t len);
int DesfireCreateFile(DesfireContext *dctx, uint8_t *fdata, size_t fdatalen);
void DesfirePrintCreateFileSettings(uint8_t filetype, uint8_t *data, size_t len);
int DesfireCreateFile(DesfireContext *dctx, uint8_t ftype, uint8_t *fdata, size_t fdatalen, bool checklen);
int DesfireDeleteFile(DesfireContext *dctx, uint8_t fid);
int DesfireCommitTrqansaction(DesfireContext *dctx, bool enable_options, uint8_t options);
int DesfireAbortTrqansaction(DesfireContext *dctx);
#endif // __DESFIRECORE_H

View file

@ -24,70 +24,83 @@
#include "mifare/desfire_crypto.h"
AllowedChannelModesS AllowedChannelModes[] = {
{MFDES_CREATE_APPLICATION, DACd40, DCCNative, DCMPlain},
{MFDES_DELETE_APPLICATION, DACd40, DCCNative, DCMPlain},
{MFDES_GET_APPLICATION_IDS, DACd40, DCCNative, DCMPlain},
{MFDES_GET_DF_NAMES, DACd40, DCCNative, DCMPlain},
{MFDES_GET_KEY_SETTINGS, DACd40, DCCNative, DCMPlain},
{MFDES_GET_KEY_VERSION, DACd40, DCCNative, DCMPlain},
{MFDES_GET_FREE_MEMORY, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_APPLICATION, DACd40, DCCNative, DCMPlain},
{MFDES_DELETE_APPLICATION, DACd40, DCCNative, DCMPlain},
{MFDES_GET_APPLICATION_IDS, DACd40, DCCNative, DCMPlain},
{MFDES_GET_DF_NAMES, DACd40, DCCNative, DCMPlain},
{MFDES_GET_KEY_SETTINGS, DACd40, DCCNative, DCMPlain},
{MFDES_GET_KEY_VERSION, DACd40, DCCNative, DCMPlain},
{MFDES_GET_FREE_MEMORY, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_STD_DATA_FILE, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_BACKUP_DATA_FILE, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_VALUE_FILE, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_LINEAR_RECORD_FILE, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_CYCLIC_RECORD_FILE, DACd40, DCCNative, DCMPlain},
{MFDES_CREATE_TRANS_MAC_FILE, DACd40, DCCNative, DCMPlain},
{MFDES_READ_DATA, DACd40, DCCNative, DCMMACed},
{MFDES_WRITE_DATA, DACd40, DCCNative, DCMMACed},
{MFDES_GET_VALUE, DACd40, DCCNative, DCMMACed},
{MFDES_CREDIT, DACd40, DCCNative, DCMMACed},
{MFDES_DEBIT, DACd40, DCCNative, DCMMACed},
{MFDES_LIMITED_CREDIT, DACd40, DCCNative, DCMMACed},
{MFDES_READ_RECORDS, DACd40, DCCNative, DCMMACed},
{MFDES_WRITE_RECORD, DACd40, DCCNative, DCMMACed},
{MFDES_UPDATE_RECORD1, DACd40, DCCNative, DCMMACed},
{MFDES_UPDATE_RECORD2, DACd40, DCCNativeISO, DCMMACed},
{MFDES_INIT_KEY_SETTINGS, DACd40, DCCNative, DCMMACed},
{MFDES_FINALIZE_KEY_SETTINGS, DACd40, DCCNative, DCMMACed},
{MFDES_ROLL_KEY_SETTINGS, DACd40, DCCNative, DCMMACed},
{MFDES_COMMIT_READER_ID, DACd40, DCCNative, DCMMACed},
{MFDES_FORMAT_PICC, DACd40, DCCNative, DCMMACed},
{MFDES_GET_FILE_IDS, DACd40, DCCNative, DCMMACed},
{MFDES_GET_ISOFILE_IDS, DACd40, DCCNative, DCMMACed},
{MFDES_READ_DATA, DACd40, DCCNative, DCMMACed},
{MFDES_WRITE_DATA, DACd40, DCCNative, DCMMACed},
{MFDES_GET_VALUE, DACd40, DCCNative, DCMMACed},
{MFDES_CREDIT, DACd40, DCCNative, DCMMACed},
{MFDES_DEBIT, DACd40, DCCNative, DCMMACed},
{MFDES_LIMITED_CREDIT, DACd40, DCCNative, DCMMACed},
{MFDES_READ_RECORDS, DACd40, DCCNative, DCMMACed},
{MFDES_WRITE_RECORD, DACd40, DCCNative, DCMMACed},
{MFDES_UPDATE_RECORD1, DACd40, DCCNative, DCMMACed},
{MFDES_UPDATE_RECORD2, DACd40, DCCNativeISO, DCMMACed},
{MFDES_INIT_KEY_SETTINGS, DACd40, DCCNative, DCMMACed},
{MFDES_FINALIZE_KEY_SETTINGS, DACd40, DCCNative, DCMMACed},
{MFDES_ROLL_KEY_SETTINGS, DACd40, DCCNative, DCMMACed},
{MFDES_COMMIT_READER_ID, DACd40, DCCNative, DCMMACed},
{MFDES_FORMAT_PICC, DACd40, DCCNative, DCMMACed},
{MFDES_GET_FILE_IDS, DACd40, DCCNative, DCMMACed},
{MFDES_GET_ISOFILE_IDS, DACd40, DCCNative, DCMMACed},
{MFDES_GET_UID, DACd40, DCCNative, DCMEncrypted},
{MFDES_CHANGE_KEY_SETTINGS, DACd40, DCCNative, DCMEncrypted},
{MFDES_CHANGE_FILE_SETTINGS, DACd40, DCCNative, DCMEncrypted},
{MFDES_READ_DATA, DACd40, DCCNative, DCMEncrypted},
{MFDES_WRITE_DATA, DACd40, DCCNative, DCMEncrypted},
{MFDES_GET_UID, DACd40, DCCNative, DCMEncrypted},
{MFDES_CHANGE_KEY_SETTINGS, DACd40, DCCNative, DCMEncrypted},
{MFDES_CHANGE_FILE_SETTINGS, DACd40, DCCNative, DCMEncrypted},
{MFDES_READ_DATA, DACd40, DCCNative, DCMEncrypted},
{MFDES_WRITE_DATA, DACd40, DCCNative, DCMEncrypted},
{MFDES_CHANGE_KEY, DACd40, DCCNative, DCMEncryptedPlain},
{MFDES_CHANGE_KEY_EV2, DACd40, DCCNative, DCMEncryptedPlain},
{MFDES_CHANGE_KEY, DACd40, DCCNative, DCMEncryptedPlain},
{MFDES_CHANGE_KEY_EV2, DACd40, DCCNative, DCMEncryptedPlain},
{MFDES_GET_KEY_VERSION, DACEV1, DCCNative, DCMPlain},
{MFDES_GET_FREE_MEMORY, DACEV1, DCCNative, DCMPlain},
{MFDES_GET_KEY_VERSION, DACEV1, DCCNative, DCMPlain},
{MFDES_GET_FREE_MEMORY, DACEV1, DCCNative, DCMPlain},
{MFDES_CREATE_APPLICATION, DACEV1, DCCNative, DCMMACed},
{MFDES_DELETE_APPLICATION, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_APPLICATION_IDS, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_DF_NAMES, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_KEY_SETTINGS, DACEV1, DCCNative, DCMMACed},
{MFDES_FORMAT_PICC, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_FILE_IDS, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_ISOFILE_IDS, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_FILE_SETTINGS, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_APPLICATION, DACEV1, DCCNative, DCMMACed},
{MFDES_DELETE_APPLICATION, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_APPLICATION_IDS, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_DF_NAMES, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_KEY_SETTINGS, DACEV1, DCCNative, DCMMACed},
{MFDES_FORMAT_PICC, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_FILE_IDS, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_ISOFILE_IDS, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_FILE_SETTINGS, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_STD_DATA_FILE, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_BACKUP_DATA_FILE, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_VALUE_FILE, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_LINEAR_RECORD_FILE, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_CYCLIC_RECORD_FILE, DACEV1, DCCNative, DCMMACed},
{MFDES_CREATE_TRANS_MAC_FILE, DACEV1, DCCNative, DCMMACed},
{MFDES_GET_UID, DACEV1, DCCNative, DCMEncrypted},
{MFDES_CHANGE_KEY_SETTINGS, DACEV1, DCCNative, DCMEncrypted},
{MFDES_CHANGE_FILE_SETTINGS, DACEV1, DCCNative, DCMEncrypted},
{MFDES_GET_UID, DACEV1, DCCNative, DCMEncrypted},
{MFDES_CHANGE_KEY_SETTINGS, DACEV1, DCCNative, DCMEncrypted},
{MFDES_CHANGE_FILE_SETTINGS, DACEV1, DCCNative, DCMEncrypted},
{MFDES_CHANGE_KEY, DACEV1, DCCNative, DCMEncryptedPlain},
{MFDES_CHANGE_KEY_EV2, DACEV1, DCCNative, DCMEncryptedPlain},
{MFDES_CHANGE_KEY, DACEV1, DCCNative, DCMEncryptedPlain},
{MFDES_CHANGE_KEY_EV2, DACEV1, DCCNative, DCMEncryptedPlain},
};
#define CMD_HEADER_LEN_ALL 0xffff
CmdHeaderLengthsS CmdHeaderLengths[] = {
{MFDES_CREATE_APPLICATION, CMD_HEADER_LEN_ALL},
{MFDES_DELETE_APPLICATION, CMD_HEADER_LEN_ALL},
{MFDES_CHANGE_KEY, 1},
{MFDES_CHANGE_KEY_EV2, 2},
{MFDES_CHANGE_CONFIGURATION, 1},
{MFDES_CHANGE_FILE_SETTINGS, 1},
{MFDES_CREATE_APPLICATION, CMD_HEADER_LEN_ALL},
{MFDES_DELETE_APPLICATION, CMD_HEADER_LEN_ALL},
{MFDES_CHANGE_KEY, 1},
{MFDES_CHANGE_KEY_EV2, 2},
{MFDES_CHANGE_CONFIGURATION, 1},
{MFDES_CHANGE_FILE_SETTINGS, 1},
{MFDES_CREATE_TRANS_MAC_FILE, 17},
};
static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd) {

View file

@ -129,6 +129,66 @@ uint64_t bytes_to_num(uint8_t *src, size_t len) {
return num;
}
uint16_t MemLeToUint2byte(uint8_t *data) {
return (data[1] << 8) + data[0];
}
uint32_t MemLeToUint3byte(uint8_t *data) {
return (data[2] << 16) + (data[1] << 8) + data[0];
}
uint32_t MemLeToUint4byte(uint8_t *data) {
return (data[3] << 24) + (data[2] << 16) + (data[1] << 8) + data[0];
}
uint16_t MemBeToUint2byte(uint8_t *data) {
return (data[0] << 8) + data[1];
}
uint32_t MemBeToUint3byte(uint8_t *data) {
return (data[0] << 16) + (data[1] << 8) + data[2];
}
uint32_t MemBeToUint4byte(uint8_t *data) {
return (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
}
void Uint2byteToMemLe(uint8_t *data, uint16_t value) {
data[1] = (value >> 8) & 0xff;
data[0] = value & 0xff;
}
void Uint3byteToMemLe(uint8_t *data, uint32_t value) {
data[2] = (value >> 16) & 0xff;
data[1] = (value >> 8) & 0xff;
data[0] = value & 0xff;
}
void Uint4byteToMemLe(uint8_t *data, uint32_t value) {
data[3] = (value >> 24) & 0xff;
data[2] = (value >> 16) & 0xff;
data[1] = (value >> 8) & 0xff;
data[0] = value & 0xff;
}
void Uint2byteToMemBe(uint8_t *data, uint16_t value) {
data[0] = (value >> 8) & 0xff;
data[1] = value & 0xff;
}
void Uint3byteToMemBe(uint8_t *data, uint32_t value) {
data[0] = (value >> 16) & 0xff;
data[1] = (value >> 8) & 0xff;
data[2] = value & 0xff;
}
void Uint4byteToMemBe(uint8_t *data, uint32_t value) {
data[0] = (value >> 24) & 0xff;
data[1] = (value >> 16) & 0xff;
data[2] = (value >> 8) & 0xff;
data[3] = value & 0xff;
}
// RotateLeft - Ultralight, Desfire
void rol(uint8_t *data, const size_t len) {
uint8_t first = data[0];

View file

@ -52,6 +52,20 @@ uint32_t reflect32(uint32_t b); // dedicated 32bit reversal
void num_to_bytes(uint64_t n, size_t len, uint8_t *dest);
uint64_t bytes_to_num(uint8_t *src, size_t len);
// LE and BE to/from memory
uint16_t MemLeToUint2byte(uint8_t *data);
uint32_t MemLeToUint3byte(uint8_t *data);
uint32_t MemLeToUint4byte(uint8_t *data);
uint16_t MemBeToUint2byte(uint8_t *data);
uint32_t MemBeToUint3byte(uint8_t *data);
uint32_t MemBeToUint4byte(uint8_t *data);
void Uint2byteToMemLe(uint8_t *data, uint16_t value);
void Uint3byteToMemLe(uint8_t *data, uint32_t value);
void Uint4byteToMemLe(uint8_t *data, uint32_t value);
void Uint2byteToMemBe(uint8_t *data, uint16_t value);
void Uint3byteToMemBe(uint8_t *data, uint32_t value);
void Uint4byteToMemBe(uint8_t *data, uint32_t value);
// rotate left byte array
void rol(uint8_t *data, const size_t len);
void lsl(uint8_t *data, size_t len);