Merge branch 'master' into sim_half_duplex

update 210117
This commit is contained in:
tharexde committed 2021-01-17 00:31:38 +01:00
commit ef56bee76a
122 files changed
+18746 -4074

No files matched your search

+460 -345
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -410,11 +410,11 @@ static command_t CommandTable[] = {
{"waveshare", CmdHFWaveshare, AlwaysAvailable, "{ Waveshare NFC ePaper... }"},
{"-----------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("General") " ---------------------"},
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"list", CmdTraceList, AlwaysAvailable, "List protocol data in trace buffer"},
{"list", CmdTraceList, AlwaysAvailable, "List protocol data in trace buffer"},
{"plot", CmdHFPlot, IfPm3Hfplot, "Plot signal"},
{"tune", CmdHFTune, IfPm3Present, "Continuously measure HF antenna tuning"},
{"search", CmdHFSearch, AlwaysAvailable, "Search for known HF tags"},
{"sniff", CmdHFSniff, IfPm3Hfsniff, "<samples to skip (10000)> <triggers to skip (1)> Generic HF Sniff"},
{"sniff", CmdHFSniff, IfPm3Hfsniff, "Generic HF Sniff"},
{NULL, NULL, NULL, NULL}
};
+356 -362
View File
@@ -170,93 +170,6 @@ const char *getTagInfo(uint8_t uid) {
static uint16_t frameLength = 0;
uint16_t atsFSC[] = {16, 24, 32, 40, 48, 64, 96, 128, 256};
static int usage_hf_14a_config(void) {
PrintAndLogEx(NORMAL, "Usage: hf 14a config [a 0|1|2] [b 0|1|2] [2 0|1|2] [3 0|1|2]");
PrintAndLogEx(NORMAL, "\nOptions:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " a 0|1|2 ATQA<>anticollision: 0=follow standard 1=execute anticol 2=skip anticol");
PrintAndLogEx(NORMAL, " b 0|1|2 BCC: 0=follow standard 1=use fixed BCC 2=use card BCC");
PrintAndLogEx(NORMAL, " 2 0|1|2 SAK<>CL2: 0=follow standard 1=execute CL2 2=skip CL2");
PrintAndLogEx(NORMAL, " 3 0|1|2 SAK<>CL3: 0=follow standard 1=execute CL3 2=skip CL3");
PrintAndLogEx(NORMAL, " r 0|1|2 SAK<>ATS: 0=follow standard 1=execute RATS 2=skip RATS");
PrintAndLogEx(NORMAL, "\nExamples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config ")" Print current configuration");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 1 ")" Force execution of anticollision");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 0 ")" Restore ATQA interpretation");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config b 1 ")" Force fix of bad BCC in anticollision");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config b 0 ")" Restore BCC check");
PrintAndLogEx(NORMAL, "\nExamples to revive Gen2/DirectWrite magic cards failing at anticollision:");
PrintAndLogEx(NORMAL, _CYAN_(" MFC 1k 4b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 1 b 2 2 2 r 2"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 11223344440804006263646566676869"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 0 b 0 2 0 r 0"));
PrintAndLogEx(NORMAL, _CYAN_(" MFC 4k 4b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 1 b 2 2 2 r 2"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 11223344441802006263646566676869"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 0 b 0 2 0 r 0"));
PrintAndLogEx(NORMAL, _CYAN_(" MFC 1k 7b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 1 b 2 2 1 3 2 r 2"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 04112233445566084400626364656667"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 0 b 0 2 0 3 0 r 0"));
PrintAndLogEx(NORMAL, _CYAN_(" MFC 4k 7b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 1 b 2 2 1 3 2 r 2"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 04112233445566184200626364656667"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 0 b 0 2 0 3 0 r 0"));
PrintAndLogEx(NORMAL, _CYAN_(" MFUL ")"/" _CYAN_(" MFUL EV1 ")"/" _CYAN_(" MFULC")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 1 b 2 2 1 3 2 r 2"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mfu setuid 04112233445566"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config a 0 b 0 2 0 3 0 r 0"));
return PM3_SUCCESS;
}
static int usage_hf_14a_sim(void) {
PrintAndLogEx(NORMAL, "\n Emulating ISO/IEC 14443 type A tag with 4,7 or 10 byte UID\n");
PrintAndLogEx(NORMAL, "Usage: hf 14a sim [h] t <type> u <uid> [n <numreads>] [x] [e] [v]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h : This help");
PrintAndLogEx(NORMAL, " t : 1 = MIFARE Classic 1k");
PrintAndLogEx(NORMAL, " 2 = MIFARE Ultralight");
PrintAndLogEx(NORMAL, " 3 = MIFARE Desfire");
PrintAndLogEx(NORMAL, " 4 = ISO/IEC 14443-4");
PrintAndLogEx(NORMAL, " 5 = MIFARE Tnp3xxx");
PrintAndLogEx(NORMAL, " 6 = MIFARE Mini");
PrintAndLogEx(NORMAL, " 7 = AMIIBO (NTAG 215), pack 0x8080");
PrintAndLogEx(NORMAL, " 8 = MIFARE Classic 4k");
PrintAndLogEx(NORMAL, " 9 = FM11RF005SH Shanghai Metro");
PrintAndLogEx(NORMAL, " 10 = JCOP 31/41 Rothult");
PrintAndLogEx(NORMAL, " u : 4, 7 or 10 byte UID");
PrintAndLogEx(NORMAL, " n : (Optional) Exit simulation after <numreads> blocks have been read by reader. 0 = infinite");
PrintAndLogEx(NORMAL, " x : (Optional) Performs the 'reader attack', nr/ar attack against a reader");
PrintAndLogEx(NORMAL, " e : (Optional) Fill simulator keys from found keys");
PrintAndLogEx(NORMAL, " v : (Optional) Verbose");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344 x"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344556677"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 112233445566778899AA"));
return PM3_SUCCESS;
}
static int usage_hf_14a_sniff(void) {
PrintAndLogEx(NORMAL, "Collect data from the field and save into command buffer.");
PrintAndLogEx(NORMAL, "Buffer accessible from command 'hf 14a list'");
PrintAndLogEx(NORMAL, "Usage: hf 14a sniff [c][r]");
PrintAndLogEx(NORMAL, "c - triggered by first data from card");
PrintAndLogEx(NORMAL, "r - triggered by first 7-bit request from reader (REQ,WUP,...)");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sniff c r"));
return PM3_SUCCESS;
}
static int usage_hf_14a_reader(void) {
PrintAndLogEx(NORMAL, "Usage: hf 14a reader [k|s|x] [3]");
PrintAndLogEx(NORMAL, " k keep the field active after command executed");
PrintAndLogEx(NORMAL, " s silent (no messages)");
PrintAndLogEx(NORMAL, " x just drop the signal field");
PrintAndLogEx(NORMAL, " 3 ISO14443-3 select only (skip RATS)");
PrintAndLogEx(NORMAL, " @ continuous mode. Updates hf plot as well");
return PM3_SUCCESS;
}
static int CmdHF14AList(const char *Cmd) {
char args[128] = {0};
if (strlen(Cmd) == 0) {
@@ -285,142 +198,168 @@ int hf14a_getconfig(hf14a_config *config) {
return PM3_SUCCESS;
}
int hf14a_setconfig(hf14a_config *config) {
int hf14a_setconfig(hf14a_config *config, bool verbose) {
if (!session.pm3_present) return PM3_ENOTTY;
clearCommandBuffer();
if (config != NULL)
if (config != NULL) {
SendCommandNG(CMD_HF_ISO14443A_SET_CONFIG, (uint8_t *)config, sizeof(hf14a_config));
else
if (verbose) {
SendCommandNG(CMD_HF_ISO14443A_PRINT_CONFIG, NULL, 0);
}
} else {
SendCommandNG(CMD_HF_ISO14443A_PRINT_CONFIG, NULL, 0);
}
return PM3_SUCCESS;
}
static int hf_14a_config_example(void) {
PrintAndLogEx(NORMAL, "\nExamples to revive Gen2/DirectWrite magic cards failing at anticollision:");
PrintAndLogEx(NORMAL, _CYAN_(" MFC 1k 4b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --atqa force --bcc ignore --cl2 skip --rats skip"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 11223344440804006263646566676869"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --std"));
PrintAndLogEx(NORMAL, _CYAN_(" MFC 4k 4b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --atqa force --bcc ignore --cl2 skip --rats skip"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 11223344441802006263646566676869"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --std"));
PrintAndLogEx(NORMAL, _CYAN_(" MFC 1k 7b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --atqa force --bcc ignore --cl2 force --cl3 skip --rats skip"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 04112233445566084400626364656667"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --std"));
PrintAndLogEx(NORMAL, _CYAN_(" MFC 4k 7b UID")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --atqa forcce --bcc ignore --cl2 force --cl3 skip --rats skip"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf wrbl 0 A FFFFFFFFFFFF 04112233445566184200626364656667"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --std"));
PrintAndLogEx(NORMAL, _CYAN_(" MFUL ")"/" _CYAN_(" MFUL EV1 ")"/" _CYAN_(" MFULC")":");
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --atqa force --bcc ignore --cl2 force --cl3 skip -rats skip"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf mfu setuid 04112233445566"));
PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a config --std"));
return PM3_SUCCESS;
}
static int CmdHf14AConfig(const char *Cmd) {
if (!session.pm3_present) return PM3_ENOTTY;
// if called with no params, just print the device config
if (strlen(Cmd) == 0) {
return hf14a_setconfig(NULL);
}
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14a config",
"Configure 14a settings (use with caution)",
"hf 14a config -> Print current configuration\n"
"hf 14a config --std -> Reset default configuration (follow standard)\n"
"hf 14a config --atqa std -> Follow standard\n"
"hf 14a config --atqa force -> Force execution of anticollision\n"
"hf 14a config --atqa skip -> Skip anticollision\n"
"hf 14a config --bcc std -> Follow standard\n"
"hf 14a config --bcc fix -> Fix bad BCC in anticollision\n"
"hf 14a config --bcc ignore -> Ignore bad BCC and use it as such\n"
"hf 14a config --cl2 std -> Follow standard\n"
"hf 14a config --cl2 force -> Execute CL2\n"
"hf 14a config --cl2 skip -> Skip CL2\n"
"hf 14a config --cl3 std -> Follow standard\n"
"hf 14a config --cl3 force -> Execute CL3\n"
"hf 14a config --cl3 skip -> Skip CL3\n"
"hf 14a config --rats std -> Follow standard\n"
"hf 14a config --rats force -> Execute RATS\n"
"hf 14a config --rats skip -> Skip RATS");
hf14a_config config = {
.forceanticol = -1,
.forcebcc = -1,
.forcecl2 = -1,
.forcecl3 = -1,
.forcerats = -1
void *argtable[] = {
arg_param_begin,
arg_str0(NULL, "atqa", "<std|force|skip>", "Configure ATQA<>anticollision behavior"),
arg_str0(NULL, "bcc", "<std|fix|ignore>", "Configure BCC behavior"),
arg_str0(NULL, "cl2", "<std|force|skip>", "Configure SAK<>CL2 behavior"),
arg_str0(NULL, "cl3", "<std|force|skip>", "Configure SAK<>CL3 behavior"),
arg_str0(NULL, "rats", "<std|force|skip>", "Configure RATS behavior"),
arg_lit0(NULL, "std", "Reset default configuration: follow all standard"),
arg_lit0("v", "verbose", "verbose output, also prints examples for reviving Gen2 cards"),
arg_param_end
};
bool errors = false;
uint8_t cmdp = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (param_getchar(Cmd, cmdp)) {
case 'h':
return usage_hf_14a_config();
case 'a':
switch (param_getchar(Cmd, cmdp + 1)) {
case '0':
config.forceanticol = 0;
break;
case '1':
config.forceanticol = 1;
break;
case '2':
config.forceanticol = 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown value '%c'", param_getchar(Cmd, cmdp + 1));
errors = 1;
break;
}
cmdp += 2;
break;
case 'b':
switch (param_getchar(Cmd, cmdp + 1)) {
case '0':
config.forcebcc = 0;
break;
case '1':
config.forcebcc = 1;
break;
case '2':
config.forcebcc = 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown value '%c'", param_getchar(Cmd, cmdp + 1));
errors = 1;
break;
}
cmdp += 2;
break;
case '2':
switch (param_getchar(Cmd, cmdp + 1)) {
case '0':
config.forcecl2 = 0;
break;
case '1':
config.forcecl2 = 1;
break;
case '2':
config.forcecl2 = 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown value '%c'", param_getchar(Cmd, cmdp + 1));
errors = 1;
break;
}
cmdp += 2;
break;
case '3':
switch (param_getchar(Cmd, cmdp + 1)) {
case '0':
config.forcecl3 = 0;
break;
case '1':
config.forcecl3 = 1;
break;
case '2':
config.forcecl3 = 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown value '%c'", param_getchar(Cmd, cmdp + 1));
errors = 1;
break;
}
cmdp += 2;
break;
case 'r':
switch (param_getchar(Cmd, cmdp + 1)) {
case '0':
config.forcerats = 0;
break;
case '1':
config.forcerats = 1;
break;
case '2':
config.forcerats = 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown value '%c'", param_getchar(Cmd, cmdp + 1));
errors = 1;
break;
}
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = 1;
break;
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool defaults = arg_get_lit(ctx, 6);
int vlen = 0;
char value[10];
int atqa = defaults ? 0 : -1;
CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)value, sizeof(value), &vlen);
if (vlen > 0) {
if (strcmp(value, "std") == 0) atqa = 0;
else if (strcmp(value, "force") == 0) atqa = 1;
else if (strcmp(value, "skip") == 0) atqa = 2;
else {
PrintAndLogEx(ERR, "atqa argument must be 'std', 'force', or 'skip'");
CLIParserFree(ctx);
return PM3_EINVARG;
}
}
int bcc = defaults ? 0 : -1;
CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)value, sizeof(value), &vlen);
if (vlen > 0) {
if (strcmp(value, "std") == 0) bcc = 0;
else if (strcmp(value, "fix") == 0) bcc = 1;
else if (strcmp(value, "ignore") == 0) bcc = 2;
else {
PrintAndLogEx(ERR, "bcc argument must be 'std', 'fix', or 'ignore'");
CLIParserFree(ctx);
return PM3_EINVARG;
}
}
int cl2 = defaults ? 0 : -1;
CLIParamStrToBuf(arg_get_str(ctx, 3), (uint8_t *)value, sizeof(value), &vlen);
if (vlen > 0) {
if (strcmp(value, "std") == 0) cl2 = 0;
else if (strcmp(value, "force") == 0) cl2 = 1;
else if (strcmp(value, "skip") == 0) cl2 = 2;
else {
PrintAndLogEx(ERR, "cl2 argument must be 'std', 'force', or 'skip'");
CLIParserFree(ctx);
return PM3_EINVARG;
}
}
int cl3 = defaults ? 0 : -1;
CLIParamStrToBuf(arg_get_str(ctx, 4), (uint8_t *)value, sizeof(value), &vlen);
if (vlen > 0) {
if (strcmp(value, "std") == 0) cl3 = 0;
else if (strcmp(value, "force") == 0) cl3 = 1;
else if (strcmp(value, "skip") == 0) cl3 = 2;
else {
PrintAndLogEx(ERR, "cl3 argument must be 'std', 'force', or 'skip'");
CLIParserFree(ctx);
return PM3_EINVARG;
}
}
int rats = defaults ? 0 : -1;
CLIParamStrToBuf(arg_get_str(ctx, 5), (uint8_t *)value, sizeof(value), &vlen);
if (vlen > 0) {
if (strcmp(value, "std") == 0) rats = 0;
else if (strcmp(value, "force") == 0) rats = 1;
else if (strcmp(value, "skip") == 0) rats = 2;
else {
PrintAndLogEx(ERR, "rats argument must be 'std', 'force', or 'skip'");
CLIParserFree(ctx);
return PM3_EINVARG;
}
}
// validations
if (errors) return usage_hf_14a_config();
bool verbose = arg_get_lit(ctx, 7);
return hf14a_setconfig(&config);
CLIParserFree(ctx);
// validations
if (strlen(Cmd) == 0) {
return hf14a_setconfig(NULL, verbose);
}
if (verbose) {
hf_14a_config_example();
}
hf14a_config config = {
.forceanticol = atqa,
.forcebcc = bcc,
.forcecl2 = cl2,
.forcecl3 = cl3,
.forcerats = rats
};
return hf14a_setconfig(&config, verbose);
}
int Hf14443_4aGetCardData(iso14a_card_select_t *card) {
@@ -462,37 +401,44 @@ int Hf14443_4aGetCardData(iso14a_card_select_t *card) {
}
static int CmdHF14AReader(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14a reader",
"Reader for ISO 14443A based tags",
"hf 14a reader -@ <- Continuous mode");
void *argtable[] = {
arg_param_begin,
arg_lit0("k", "keep", "keep the field active after command executed"),
arg_lit0("s", "silent", "silent (no messages)"),
arg_lit0(NULL, "drop", "just drop the signal field"),
arg_lit0(NULL, "skip", "ISO14443-3 select only (skip RATS)"),
arg_lit0("@", NULL, "optional - continuous reader mode"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool disconnectAfter = true;
if (arg_get_lit(ctx, 1)) {
disconnectAfter = false;
}
bool silent = arg_get_lit(ctx, 2);
uint32_t cm = ISO14A_CONNECT;
bool disconnectAfter = true, silent = false, continuous = false;
int cmdp = 0;
int res = PM3_SUCCESS;
while (param_getchar(Cmd, cmdp) != 0x00) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_hf_14a_reader();
case '3':
cm |= ISO14A_NO_RATS;
break;
case 'k':
disconnectAfter = false;
break;
case 's':
silent = true;
break;
case 'x':
cm &= ~ISO14A_CONNECT;
break;
case '@':
continuous = true;
break;
default:
PrintAndLogEx(WARNING, "Unknown command.");
return PM3_EINVARG;
}
cmdp++;
if (arg_get_lit(ctx, 3)) {
cm &= ~ISO14A_CONNECT;
}
if (arg_get_lit(ctx, 4)) {
cm |= ISO14A_NO_RATS;
}
bool continuous = arg_get_lit(ctx, 5);
CLIParserFree(ctx);
int res = PM3_SUCCESS;
if (!disconnectAfter)
cm |= ISO14A_NO_DISCONNECT;
if (continuous) {
@@ -608,10 +554,23 @@ static int CmdHF14AInfo(const char *Cmd) {
// Collect ISO14443 Type A UIDs
static int CmdHF14ACUIDs(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14a cuids",
"Collect n>0 ISO14443-a UIDs in one go",
"hf 14a cuids -n 5 <-- Collect 5 UIDs");
void *argtable[] = {
arg_param_begin,
arg_int0("n", "num", "<dec>", "Number of UIDs to collect"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
// requested number of UIDs
int n = atoi(Cmd);
// collect at least 1 (e.g. if no parameter was given)
n = n > 0 ? n : 1;
int n = arg_get_int_def(ctx, 1, 1);
CLIParserFree(ctx);
uint64_t t1 = msclock();
PrintAndLogEx(SUCCESS, "collecting %d UIDs", n);
@@ -646,83 +605,81 @@ static int CmdHF14ACUIDs(const char *Cmd) {
PrintAndLogEx(SUCCESS, "end: %" PRIu64 " seconds", (msclock() - t1) / 1000);
return 1;
}
// ## simulate iso14443a tag
int CmdHF14ASim(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14a sim",
"Simulate ISO/IEC 14443 type A tag with 4,7 or 10 byte UID",
"hf 14a sim -t 1 --uid 11223344 -> MIFARE Classic 1k\n"
"hf 14a sim -t 2 -> MIFARE Ultralight\n"
"hf 14a sim -t 3 -> MIFARE Desfire\n"
"hf 14a sim -t 4 -> ISO/IEC 14443-4\n"
"hf 14a sim -t 5 -> MIFARE Tnp3xxx\n"
"hf 14a sim -t 6 -> MIFARE Mini\n"
"hf 14a sim -t 7 -> AMIIBO (NTAG 215), pack 0x8080\n"
"hf 14a sim -t 8 -> MIFARE Classic 4k\n"
"hf 14a sim -t 9 -> FM11RF005SH Shanghai Metro\n"
"hf 14a sim -t 10 -> ST25TA IKEA Rothult\n");
int uidlen = 0;
uint8_t flags = 0, tagtype = 1, cmdp = 0;
uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
void *argtable[] = {
arg_param_begin,
arg_int1("t", "type", "<1-10> ", "Simulation type to use"),
arg_str0("u", "uid", "<hex>", "4, 7 or 10 byte UID"),
arg_int0("n", "num", "<dec>", "Exit simulation after <numreads> blocks have been read by reader. 0 = infinite"),
arg_lit0(NULL, "nr", "Performs the 'reader attack', nr/ar attack against a reader"),
arg_lit0(NULL, "sk", "Fill simulator keys from found keys"),
arg_lit0("v", "verbose", "verbose output"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
int tagtype = arg_get_int(ctx, 1);
int uid_len = 0;
uint8_t uid[10] = {0};
CLIGetHexWithReturn(ctx, 2, uid, &uid_len);
uint8_t flags = 0;
bool useUIDfromEML = true;
bool setEmulatorMem = false;
bool verbose = false;
bool errors = false;
sector_t *k_sector = NULL;
uint8_t k_sectorsCount = 40;
uint8_t exitAfterNReads = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_hf_14a_sim();
case 't':
// Retrieve the tag type
tagtype = param_get8ex(Cmd, cmdp + 1, 0, 10);
if (tagtype == 0)
errors = true;
cmdp += 2;
if (uid_len > 0) {
switch (uid_len) {
case 10:
flags |= FLAG_10B_UID_IN_DATA;
break;
case 'u':
// Retrieve the full 4,7,10 byte long uid
param_gethex_ex(Cmd, cmdp + 1, uid, &uidlen);
uidlen >>= 1;
switch (uidlen) {
case 10:
flags |= FLAG_10B_UID_IN_DATA;
break;
case 7:
flags |= FLAG_7B_UID_IN_DATA;
break;
case 4:
flags |= FLAG_4B_UID_IN_DATA;
break;
default:
errors = true;
break;
}
if (!errors) {
PrintAndLogEx(SUCCESS, "Emulating " _YELLOW_("ISO/IEC 14443 type A tag")" with " _GREEN_("%d byte UID (%s)"), uidlen, sprint_hex(uid, uidlen));
useUIDfromEML = false;
}
cmdp += 2;
case 7:
flags |= FLAG_7B_UID_IN_DATA;
break;
case 'n':
exitAfterNReads = param_get8(Cmd, cmdp + 1);
cmdp += 2;
break;
case 'v':
verbose = true;
cmdp++;
break;
case 'x':
flags |= FLAG_NR_AR_ATTACK;
cmdp++;
break;
case 'e':
setEmulatorMem = true;
cmdp++;
case 4:
flags |= FLAG_4B_UID_IN_DATA;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter " _RED_("'%c'"), param_getchar(Cmd, cmdp));
errors = true;
break;
PrintAndLogEx(ERR, "Please specify a 4, 7, or 10 byte UID");
CLIParserFree(ctx);
return PM3_EINVARG;
}
PrintAndLogEx(SUCCESS, "Emulating " _YELLOW_("ISO/IEC 14443 type A tag")" with " _GREEN_("%d byte UID (%s)"), uid_len, sprint_hex(uid, uid_len));
useUIDfromEML = false;
}
//Validations
if (errors || cmdp == 0) return usage_hf_14a_sim();
uint8_t exitAfterNReads = arg_get_int(ctx, 3);
if (useUIDfromEML)
if (arg_get_lit(ctx, 4)) {
flags |= FLAG_NR_AR_ATTACK;
}
bool setEmulatorMem = arg_get_lit(ctx, 5);
bool verbose = arg_get_lit(ctx, 6);
CLIParserFree(ctx);
sector_t *k_sector = NULL;
uint8_t k_sectorsCount = 40;
if (useUIDfromEML) {
flags |= FLAG_UID_IN_EMUL;
}
struct {
uint8_t tagtype;
@@ -734,7 +691,7 @@ int CmdHF14ASim(const char *Cmd) {
payload.tagtype = tagtype;
payload.flags = flags;
payload.exitAfter = exitAfterNReads;
memcpy(payload.uid, uid, uidlen);
memcpy(payload.uid, uid, uid_len);
clearCommandBuffer();
SendCommandNG(CMD_HF_ISO14443A_SIMULATE, (uint8_t *)&payload, sizeof(payload));
@@ -768,13 +725,32 @@ int CmdHF14ASim(const char *Cmd) {
}
int CmdHF14ASniff(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14a sniff",
"Collect data from the field and save into command buffer.\n"
"Buffer accessible from command 'hf 14a list'",
" hf 14a sniff -c -r");
void *argtable[] = {
arg_param_begin,
arg_lit0("c", "card", "triggered by first data from card"),
arg_lit0("r", "reader", "triggered by first 7-bit request from reader (REQ,WUP,...)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint8_t param = 0;
for (uint8_t i = 0; i < 2; i++) {
uint8_t ctmp = tolower(param_getchar(Cmd, i));
if (ctmp == 'h') return usage_hf_14a_sniff();
if (ctmp == 'c') param |= 0x01;
if (ctmp == 'r') param |= 0x02;
if (arg_get_lit(ctx, 1)) {
param |= 0x01;
}
if (arg_get_lit(ctx, 2)) {
param |= 0x02;
}
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_HF_ISO14443A_SNIFF, (uint8_t *)&param, sizeof(uint8_t));
return PM3_SUCCESS;
@@ -1539,6 +1515,7 @@ static int detect_nxp_card(uint8_t sak, uint16_t atqa, uint64_t select_status) {
printTag("MIFARE DESFire CL2");
printTag("MIFARE DESFire EV1 256B/2K/4K/8K CL2");
printTag("MIFARE DESFire EV2 2K/4K/8K/16K/32K");
printTag("MIFARE DESFire EV3 2K/4K/8K");
printTag("MIFARE DESFire Light 640B");
} else {
printTag("MIFARE Plus EV1 2K/4K CL2 in SL3");
@@ -2135,38 +2112,51 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) {
}
static uint16_t get_sw(uint8_t *d, uint8_t n) {
if (n < 2)
if (n < 2) {
return 0;
}
n -= 2;
return d[n] * 0x0100 + d[n + 1];
}
static uint64_t inc_sw_error_occurence(uint16_t sw, uint64_t all_sw[256][256]) {
uint8_t sw1 = (uint8_t)(sw >> 8);
uint8_t sw2 = (uint8_t)(0xff & sw);
if (sw1 == 0x90 && sw2 == 0x00) {
return 0; // Don't count successes.
}
if (sw1 == 0x6d && sw2 == 0x00) {
return 0xffffffffffffffffULL; // Always max "Instruction not supported".
}
return ++all_sw[sw1][sw2];
}
static int CmdHf14AFindapdu(const char *Cmd) {
// TODO: What response values should be considerd "valid" or "instersting" (worth dispalying)?
// TODO: Option to select AID/File (and skip INS 0xA4).
// TODO: Validate the decoding of the APDU (not specific to this command, check
// https://cardwerk.com/smartcards/smartcard_standard_ISO7816-4_5_basic_organizations.aspx#chap5_3_2).
// TODO: Check all cases (APDUs) with no data bytes (no/short/extended length).
// TODO: Option to blacklist instructions (or whole APDUs).
// TODO: Check all instructions with extended APDUs if the card support it.
// TODO: Option to reset tag before every command.
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14a apdufind",
"Enumerate APDU's of ISO7816 protocol to find valid CLS/INS/P1P2 commands.\n"
"Enumerate APDU's of ISO7816 protocol to find valid CLS/INS/P1/P2 commands.\n"
"It loops all 256 possible values for each byte.\n"
"The loop oder is INS -> P1/P2 (alternating) -> CLA\n"
"The loop oder is INS -> P1/P2 (alternating) -> CLA.\n"
"Tag must be on antenna before running.",
"hf 14a apdufind\n"
"hf 14a apdufind --cla 80\n"
"hf 14a apdufind --cla 80 --error-limit 20 --skip-ins a4 --skip-ins b0 --with-le\n"
);
void *argtable[] = {
arg_param_begin,
arg_str0("c", "cla", "<hex>", "Start value of CLASS (1 hex byte)"),
arg_str0("i", "ins", "<hex>", "Start value of INSTRUCTION (1 hex byte)"),
arg_str0(NULL, "p1", "<hex>", "Start value of P1 (1 hex byte)"),
arg_str0(NULL, "p2", "<hex>", "Start value of P2 (1 hex byte)"),
arg_u64_0("r", "reset", "<number>", "Minimum secondes before resetting the tag (to prevent timeout issues). Default is 5 minutes"),
arg_lit0("v", "verbose", "Verbose output"),
arg_str0("c", "cla", "<hex>", "Start value of CLASS (1 hex byte)"),
arg_str0("i", "ins", "<hex>", "Start value of INSTRUCTION (1 hex byte)"),
arg_str0(NULL, "p1", "<hex>", "Start value of P1 (1 hex byte)"),
arg_str0(NULL, "p2", "<hex>", "Start value of P2 (1 hex byte)"),
arg_u64_0("r", "reset", "<number>", "Minimum secondes before resetting the tag (to prevent timeout issues). Default is 5 minutes"),
arg_u64_0("e", "error-limit", "<number>", "Maximum times an status word other than 0x9000 or 0x6D00 is shown. Default is 512."),
arg_strx0("s", "skip-ins", "<hex>", "Do not test an instructions (can be specifed multiple times)"),
arg_lit0("l", "with-le", "Serach for APDUs with Le=0 (case 2S) as well"),
arg_lit0("v", "verbose", "Verbose output"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
@@ -2183,8 +2173,13 @@ static int CmdHf14AFindapdu(const char *Cmd) {
int p2_len = 0;
uint8_t p2_arg[1] = {0};
CLIGetHexWithReturn(ctx, 4, p2_arg, &p2_len);
uint64_t reset_time = arg_get_u64_def(ctx, 5, 5 * 60); // Reset every 5 minutes.
bool verbose = arg_get_lit(ctx, 6);
uint64_t reset_time = arg_get_u64_def(ctx, 5, 5 * 60);
uint64_t error_limit = arg_get_u64_def(ctx, 6, 512);
int ignore_ins_len = 0;
uint8_t ignore_ins_arg[250] = {0};
CLIGetHexWithReturn(ctx, 7, ignore_ins_arg, &ignore_ins_len);
bool with_le = arg_get_lit(ctx, 8);
bool verbose = arg_get_lit(ctx, 9);
CLIParserFree(ctx);
@@ -2211,6 +2206,9 @@ static int CmdHf14AFindapdu(const char *Cmd) {
PrintAndLogEx(INFO, "Press " _GREEN_("<Enter>") " to exit");
bool inc_p1 = true;
bool skip_ins = false;
uint64_t all_sw[256][256] = { { 0 } };
uint64_t sw_occurences = 0;
uint64_t t_start = msclock();
uint64_t t_last_reset = msclock();
@@ -2218,59 +2216,55 @@ static int CmdHf14AFindapdu(const char *Cmd) {
do {
do {
do {
retry_ins:
// Exit (was the Enter key pressed)?
if (kbd_enter_pressed()) {
PrintAndLogEx(INFO, "User interrupted detected. Aborting");
goto out;
}
// Skip/Ignore this instrctuion?
for (int i = 0; i < ignore_ins_len; i++) {
if (ins == ignore_ins_arg[i]) {
skip_ins = true;
break;
}
}
if (skip_ins) {
skip_ins = false;
continue;
}
if (verbose) {
PrintAndLogEx(INFO, "Status: [ CLA " _GREEN_("%02X") " INS " _GREEN_("%02X") " P1 " _GREEN_("%02X") " P2 " _GREEN_("%02X") " ]", cla, ins, p1, p2);
}
// Send APDU.
uint8_t command[4] = {cla, ins, p1, p2};
int command_n = sizeof(command);
res = ExchangeAPDU14a(command, command_n, activate_field, keep_field_on, response, sizeof(response), &response_n);
if (res) {
continue;
}
// Was there and length error? If so, try with Le length (case 2 instad of case 1,
// https://stackoverflow.com/a/30679558). Le = 0x00 will get interpreted as extended length APDU
// with Le being 0x0100.
uint16_t sw = get_sw(response, response_n);
bool command_with_le = false;
if (sw == 0x6700) {
PrintAndLogEx(INFO, "Got response for APDU \"%02X%02X%02X%02X\": %04X (%s)", cla, ins, p1, p2,
sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
PrintAndLogEx(INFO, "Resending current command with Le = 0x0100 (extended length APDU)");
uint8_t command2[7] = {cla, ins, p1, p2, 0x00};
int command2_n = sizeof(command2);
res = ExchangeAPDU14a(command2, command2_n, activate_field, keep_field_on, response, sizeof(response), &response_n);
// Send APDU without Le (case 1) and with Le = 0 (case 2S), if "with-le" was set.
uint8_t command[5] = {cla, ins, p1, p2, 0x00};
int command_n = 4;
for (int i = 0; i < 1 + with_le; i++) {
// Send APDU.
res = ExchangeAPDU14a(command, command_n + i, activate_field, keep_field_on, response, sizeof(response), &response_n);
if (res) {
continue;
DropField();
activate_field = true;
goto retry_ins;
}
command_with_le = true;
}
uint16_t sw = get_sw(response, response_n);
sw_occurences = inc_sw_error_occurence(sw, all_sw);
// Check response.
sw = get_sw(response, response_n);
if (sw != 0x6a86 &&
sw != 0x6986 &&
sw != 0x6d00
) {
if (command_with_le) {
PrintAndLogEx(INFO, "Got response for APDU \"%02X%02X%02X%02X00\": %04X (%s)", cla, ins, p1, p2,
// Show response.
if (sw_occurences < error_limit) {
logLevel_t log_level = INFO;
if (sw == 0x9000) {
log_level = SUCCESS;
}
PrintAndLogEx(log_level, "Got response for APDU \"%s\": %04X (%s)", sprint_hex_inrow(command, command_n + i),
sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
} else {
PrintAndLogEx(INFO, "Got response for APDU \"%02X%02X%02X%02X\": %04X (%s)", cla, ins, p1, p2,
sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
}
// Show response data.
if (response_n > 2) {
PrintAndLogEx(SUCCESS, "Response data is: %s | %s", sprint_hex_inrow(response, response_n - 2),
sprint_ascii(response, response_n - 2));
if (response_n > 2) {
PrintAndLogEx(SUCCESS, "Response data is: %s | %s", sprint_hex_inrow(response, response_n - 2),
sprint_ascii(response, response_n - 2));
}
}
}
activate_field = false; // Do not reativate the filed until the next reset.
@@ -2304,11 +2298,11 @@ out:
static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"list", CmdHF14AList, AlwaysAvailable, "List ISO 14443-a history"},
{"list", CmdHF14AList, AlwaysAvailable, "List ISO 14443-a history"},
{"info", CmdHF14AInfo, IfPm3Iso14443a, "Tag information"},
{"reader", CmdHF14AReader, IfPm3Iso14443a, "Act like an ISO14443-a reader"},
{"cuids", CmdHF14ACUIDs, IfPm3Iso14443a, "<n> Collect n>0 ISO14443-a UIDs in one go"},
{"sim", CmdHF14ASim, IfPm3Iso14443a, "<UID> -- Simulate ISO 14443-a tag"},
{"cuids", CmdHF14ACUIDs, IfPm3Iso14443a, "Collect n>0 ISO14443-a UIDs in one go"},
{"sim", CmdHF14ASim, IfPm3Iso14443a, "Simulate ISO 14443-a tag"},
{"sniff", CmdHF14ASniff, IfPm3Iso14443a, "sniff ISO 14443-a traffic"},
{"apdu", CmdHF14AAPDU, IfPm3Iso14443a, "Send ISO 14443-4 APDU to tag"},
{"chaining", CmdHF14AChaining, IfPm3Iso14443a, "Control ISO 14443-4 input chaining"},
+1 -1
View File
@@ -27,7 +27,7 @@ int CmdHF14ASniff(const char *Cmd); // used by hf topaz sniff
int CmdHF14ASim(const char *Cmd); // used by hf mfu sim
int hf14a_getconfig(hf14a_config *config);
int hf14a_setconfig(hf14a_config *config);
int hf14a_setconfig(hf14a_config *config, bool verbose);
int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search);
const char *getTagInfo(uint8_t uid);
int Hf14443_4aGetCardData(iso14a_card_select_t *card);
+1 -1
View File
@@ -287,7 +287,7 @@ static int CmdHF14BCmdRaw(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf 14b raw",
"Sends raw bytes to card ",
"Sends raw bytes to card",
"hf 14b raw -cks --data 0200a40400 -> standard select\n"
"hf 14b raw -ck --sr --data 0200a40400 -> SRx select\n"
"hf 14b raw -ck --cts --data 0200a40400 -> C-ticket select\n"
+409 -97
View File
@@ -19,7 +19,7 @@
#include "cmdhf14a.h" // ExchangeAPDU14a
#include "protocols.h" // definitions of ISO14A/7816 protocol
#include "emv/apduinfo.h" // GetAPDUCodeDescription
#include "sha1.h" // KSeed calculation etc
#include "crypto/libpcrypto.h" // Hash calculation (sha1, sha256, sha512)
#include "mifare/desfire_crypto.h" // des_encrypt/des_decrypt
#include "des.h" // mbedtls_des_key_set_parity
#include "cmdhf14b.h" // exchange_14b_apdu
@@ -50,15 +50,14 @@
const uint8_t KENC_type[4] = {0x00, 0x00, 0x00, 0x01};
const uint8_t KMAC_type[4] = {0x00, 0x00, 0x00, 0x02};
static int emrtd_dump_ef_dg2(uint8_t *file_contents, size_t file_length);
static int emrtd_dump_ef_dg5(uint8_t *file_contents, size_t file_length);
static int emrtd_dump_ef_dg7(uint8_t *file_contents, size_t file_length);
static int emrtd_dump_ef_sod(uint8_t *file_contents, size_t file_length);
static int emrtd_dump_ef_dg2(uint8_t *file_contents, size_t file_length, const char *path);
static int emrtd_dump_ef_dg5(uint8_t *file_contents, size_t file_length, const char *path);
static int emrtd_dump_ef_dg7(uint8_t *file_contents, size_t file_length, const char *path);
static int emrtd_dump_ef_sod(uint8_t *file_contents, size_t file_length, const char *path);
static int emrtd_print_ef_com_info(uint8_t *data, size_t datalen);
static int emrtd_print_ef_dg1_info(uint8_t *data, size_t datalen);
static int emrtd_print_ef_dg11_info(uint8_t *data, size_t datalen);
static int emrtd_print_ef_dg12_info(uint8_t *data, size_t datalen);
static int emrtd_print_ef_sod_info(uint8_t *data, size_t datalen);
typedef enum { // list must match dg_table
EF_COM = 0,
@@ -84,28 +83,38 @@ typedef enum { // list must match dg_table
} emrtd_dg_enum;
static emrtd_dg_t dg_table[] = {
// tag fileid filename desc pace req fast parser dumper
{0x60, "011E", "EF_COM", "Header and Data Group Presence Information", false, true, true, emrtd_print_ef_com_info, NULL},
{0x61, "0101", "EF_DG1", "Details recorded in MRZ", false, true, true, emrtd_print_ef_dg1_info, NULL},
{0x75, "0102", "EF_DG2", "Encoded Face", false, true, false, NULL, emrtd_dump_ef_dg2},
{0x63, "0103", "EF_DG3", "Encoded Finger(s)", true, false, false, NULL, NULL},
{0x76, "0104", "EF_DG4", "Encoded Eye(s)", true, false, false, NULL, NULL},
{0x65, "0105", "EF_DG5", "Displayed Portrait", false, false, false, NULL, emrtd_dump_ef_dg5},
{0x66, "0106", "EF_DG6", "Reserved for Future Use", false, false, false, NULL, NULL},
{0x67, "0107", "EF_DG7", "Displayed Signature or Usual Mark", false, false, false, NULL, emrtd_dump_ef_dg7},
{0x68, "0108", "EF_DG8", "Data Feature(s)", false, false, true, NULL, NULL},
{0x69, "0109", "EF_DG9", "Structure Feature(s)", false, false, true, NULL, NULL},
{0x6a, "010A", "EF_DG10", "Substance Feature(s)", false, false, true, NULL, NULL},
{0x6b, "010B", "EF_DG11", "Additional Personal Detail(s)", false, false, true, emrtd_print_ef_dg11_info, NULL},
{0x6c, "010C", "EF_DG12", "Additional Document Detail(s)", false, false, true, emrtd_print_ef_dg12_info, NULL},
{0x6d, "010D", "EF_DG13", "Optional Detail(s)", false, false, true, NULL, NULL},
{0x6e, "010E", "EF_DG14", "Security Options", false, false, true, NULL, NULL},
{0x6f, "010F", "EF_DG15", "Active Authentication Public Key Info", false, false, true, NULL, NULL},
{0x70, "0110", "EF_DG16", "Person(s) to Notify", false, false, true, NULL, NULL},
{0x77, "011D", "EF_SOD", "Document Security Object", false, false, true, emrtd_print_ef_sod_info, emrtd_dump_ef_sod},
{0xff, "011C", "EF_CardAccess", "PACE SecurityInfos", true, true, true, NULL, NULL},
{0xff, "011D", "EF_CardSecurity", "PACE SecurityInfos for Chip Authentication Mapping", true, false, true, NULL, NULL},
{0x00, NULL, NULL, NULL, false, false, false, NULL, NULL}
// tag dg# fileid filename desc pace eac req fast parser dumper
{0x60, 0, "011E", "EF_COM", "Header and Data Group Presence Information", false, false, true, true, emrtd_print_ef_com_info, NULL},
{0x61, 1, "0101", "EF_DG1", "Details recorded in MRZ", false, false, true, true, emrtd_print_ef_dg1_info, NULL},
{0x75, 2, "0102", "EF_DG2", "Encoded Face", false, false, true, false, NULL, emrtd_dump_ef_dg2},
{0x63, 3, "0103", "EF_DG3", "Encoded Finger(s)", false, true, false, false, NULL, NULL},
{0x76, 4, "0104", "EF_DG4", "Encoded Eye(s)", false, true, false, false, NULL, NULL},
{0x65, 5, "0105", "EF_DG5", "Displayed Portrait", false, false, false, false, NULL, emrtd_dump_ef_dg5},
{0x66, 6, "0106", "EF_DG6", "Reserved for Future Use", false, false, false, false, NULL, NULL},
{0x67, 7, "0107", "EF_DG7", "Displayed Signature or Usual Mark", false, false, false, false, NULL, emrtd_dump_ef_dg7},
{0x68, 8, "0108", "EF_DG8", "Data Feature(s)", false, false, false, true, NULL, NULL},
{0x69, 9, "0109", "EF_DG9", "Structure Feature(s)", false, false, false, true, NULL, NULL},
{0x6a, 10, "010A", "EF_DG10", "Substance Feature(s)", false, false, false, true, NULL, NULL},
{0x6b, 11, "010B", "EF_DG11", "Additional Personal Detail(s)", false, false, false, true, emrtd_print_ef_dg11_info, NULL},
{0x6c, 12, "010C", "EF_DG12", "Additional Document Detail(s)", false, false, false, true, emrtd_print_ef_dg12_info, NULL},
{0x6d, 13, "010D", "EF_DG13", "Optional Detail(s)", false, false, false, true, NULL, NULL},
{0x6e, 14, "010E", "EF_DG14", "Security Options", false, false, false, true, NULL, NULL},
{0x6f, 15, "010F", "EF_DG15", "Active Authentication Public Key Info", false, false, false, true, NULL, NULL},
{0x70, 16, "0110", "EF_DG16", "Person(s) to Notify", false, false, false, true, NULL, NULL},
{0x77, 0, "011D", "EF_SOD", "Document Security Object", false, false, false, false, NULL, emrtd_dump_ef_sod},
{0xff, 0, "011C", "EF_CardAccess", "PACE SecurityInfos", true, false, true, true, NULL, NULL},
{0xff, 0, "011D", "EF_CardSecurity", "PACE SecurityInfos for Chip Authentication Mapping", true, false, false, true, NULL, NULL},
{0x00, 0, NULL, NULL, NULL, false, false, false, false, NULL, NULL}
};
// https://security.stackexchange.com/questions/131241/where-do-magic-constants-for-signature-algorithms-come-from
// https://tools.ietf.org/html/rfc3447#page-43
static emrtd_hashalg_t hashalg_table[] = {
// name hash func len len descriptor
{"SHA-1", sha1hash, 20, 7, {0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A}},
{"SHA-256", sha256hash, 32, 11, {0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01}},
{"SHA-512", sha512hash, 64, 11, {0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03}},
{NULL, NULL, 0, 0, {}}
};
static emrtd_dg_t *emrtd_tag_to_dg(uint8_t tag) {
@@ -203,11 +212,16 @@ static char emrtd_calculate_check_digit(char *data) {
}
static int emrtd_get_asn1_data_length(uint8_t *datain, int datainlen, int offset) {
PrintAndLogEx(DEBUG, "asn1datalength, datain: %s", sprint_hex_inrow(datain, datainlen));
PrintAndLogEx(DEBUG, "asn1 datalength, datain: %s", sprint_hex_inrow(datain, datainlen));
int lenfield = (int) * (datain + offset);
PrintAndLogEx(DEBUG, "asn1datalength, lenfield: %i", lenfield);
PrintAndLogEx(DEBUG, "asn1 datalength, lenfield: %02X", lenfield);
if (lenfield <= 0x7f) {
return lenfield;
} else if (lenfield == 0x80) {
// TODO: 0x80 means indeterminate, and this impl is a workaround.
// Giving rest of the file is a workaround, nothing more, nothing less.
// https://wf.lavatech.top/ave-but-random/emrtd-data-quirks#EF_SOD
return datainlen;
} else if (lenfield == 0x81) {
return ((int) * (datain + offset + 1));
} else if (lenfield == 0x82) {
@@ -221,8 +235,8 @@ static int emrtd_get_asn1_data_length(uint8_t *datain, int datainlen, int offset
static int emrtd_get_asn1_field_length(uint8_t *datain, int datainlen, int offset) {
PrintAndLogEx(DEBUG, "asn1 fieldlength, datain: %s", sprint_hex_inrow(datain, datainlen));
int lenfield = (int) * (datain + offset);
PrintAndLogEx(DEBUG, "asn1 fieldlength, thing: %i", lenfield);
if (lenfield <= 0x7F) {
PrintAndLogEx(DEBUG, "asn1 fieldlength, lenfield: %02X", lenfield);
if (lenfield <= 0x80) {
return 1;
} else if (lenfield == 0x81) {
return 2;
@@ -339,7 +353,7 @@ static void emrtd_deskey(uint8_t *seed, const uint8_t *type, int length, uint8_t
// SHA1 the key
unsigned char key[64];
mbedtls_sha1(data, length + 4, key);
sha1hash(data, length + 4, key);
PrintAndLogEx(DEBUG, "key............... %s", sprint_hex_inrow(key, length + 4));
// Set parity bits
@@ -622,9 +636,21 @@ static int emrtd_read_file(uint8_t *dataout, int *dataoutlen, uint8_t *kenc, uin
return true;
}
static bool emrtd_lds_get_data_by_tag(uint8_t *datain, int datainlen, uint8_t *dataout, int *dataoutlen, int tag1, int tag2, bool twobytetag) {
int offset = 1;
offset += emrtd_get_asn1_field_length(datain, datainlen, offset);
static int emrtd_lds_determine_tag_length(uint8_t tag) {
if ((tag == 0x5F) || (tag == 0x7F)) {
return 2;
}
return 1;
}
static bool emrtd_lds_get_data_by_tag(uint8_t *datain, size_t datainlen, uint8_t *dataout, size_t *dataoutlen, int tag1, int tag2, bool twobytetag, bool entertoptag, size_t skiptagcount) {
int offset = 0;
int skipcounter = 0;
if (entertoptag) {
offset += emrtd_lds_determine_tag_length(*datain);
offset += emrtd_get_asn1_field_length(datain, datainlen, offset);
}
int e_idlen = 0;
int e_datalen = 0;
@@ -632,11 +658,7 @@ static bool emrtd_lds_get_data_by_tag(uint8_t *datain, int datainlen, uint8_t *d
while (offset < datainlen) {
PrintAndLogEx(DEBUG, "emrtd_lds_get_data_by_tag, offset: %i, data: %X", offset, *(datain + offset));
// Determine element ID length to set as offset on asn1datalength
if ((*(datain + offset) == 0x5F) || (*(datain + offset) == 0x7F)) {
e_idlen = 2;
} else {
e_idlen = 1;
}
e_idlen = emrtd_lds_determine_tag_length(*(datain + offset));
// Get the length of the element
e_datalen = emrtd_get_asn1_data_length(datain + offset, datainlen - offset, e_idlen);
@@ -644,9 +666,13 @@ static bool emrtd_lds_get_data_by_tag(uint8_t *datain, int datainlen, uint8_t *d
// Get the length of the element's length
e_fieldlen = emrtd_get_asn1_field_length(datain + offset, datainlen - offset, e_idlen);
PrintAndLogEx(DEBUG, "emrtd_lds_get_data_by_tag, e_idlen: %02X, e_datalen: %02X, e_fieldlen: %02X", e_idlen, e_datalen, e_fieldlen);
// If the element is what we're looking for, get the data and return true
if (*(datain + offset) == tag1 && (!twobytetag || *(datain + offset + 1) == tag2)) {
if (datainlen > e_datalen) {
if (skipcounter < skiptagcount) {
skipcounter += 1;
} else if (datainlen > e_datalen) {
*dataoutlen = e_datalen;
memcpy(dataout, datain + offset + e_idlen + e_fieldlen, e_datalen);
return true;
@@ -681,17 +707,19 @@ static bool emrtd_select_and_read(uint8_t *dataout, int *dataoutlen, const char
return true;
}
static int emrtd_dump_ef_dg2(uint8_t *file_contents, size_t file_length) {
const uint8_t jpeg_header[4] = { 0xFF, 0xD8, 0xFF, 0xE0 };
const uint8_t jpeg2k_header[6] = { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50 };
static int emrtd_dump_ef_dg2(uint8_t *file_contents, size_t file_length, const char *path) {
int offset, datalen = 0;
// This is a hacky impl that just looks for the image header. I'll improve it eventually.
// based on mrpkey.py
// FF D8 FF E0 -> JPEG
// 00 00 00 0C 6A 50 -> JPEG 2000
// Note: Doing file_length - 6 to account for the longest data we're checking.
// Checks first byte before the rest to reduce overhead
for (offset = 0; offset < file_length - 6; offset++) {
if ((file_contents[offset] == 0xFF && file_contents[offset + 1] == 0xD8 && file_contents[offset + 2] == 0xFF && file_contents[offset + 3] == 0xE0) ||
(file_contents[offset] == 0x00 && file_contents[offset + 1] == 0x00 && file_contents[offset + 2] == 0x00 && file_contents[offset + 3] == 0x0C && file_contents[offset + 4] == 0x6A && file_contents[offset + 5] == 0x50)) {
if ((file_contents[offset] == 0xFF && memcmp(jpeg_header, file_contents + offset, 4) != 0) ||
(file_contents[offset] == 0x00 && memcmp(jpeg2k_header, file_contents + offset, 6) != 0)) {
datalen = file_length - offset;
break;
}
@@ -702,21 +730,39 @@ static int emrtd_dump_ef_dg2(uint8_t *file_contents, size_t file_length) {
return PM3_ESOFT;
}
saveFile(dg_table[EF_DG2].filename, file_contents[offset] == 0xFF ? ".jpg" : ".jp2", file_contents + offset, datalen);
char *filepath = calloc(strlen(path) + 100, sizeof(char));
if (filepath == NULL)
return PM3_EMALLOC;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg_table[EF_DG2].filename);
saveFile(filepath, file_contents[offset] == 0xFF ? ".jpg" : ".jp2", file_contents + offset, datalen);
free(filepath);
return PM3_SUCCESS;
}
static int emrtd_dump_ef_dg5(uint8_t *file_contents, size_t file_length) {
static int emrtd_dump_ef_dg5(uint8_t *file_contents, size_t file_length, const char *path) {
uint8_t data[EMRTD_MAX_FILE_SIZE];
int datalen = 0;
size_t datalen = 0;
// If we can't find image in EF_DG5, return false.
if (emrtd_lds_get_data_by_tag(file_contents, file_length, data, &datalen, 0x5F, 0x40, true) == false) {
if (emrtd_lds_get_data_by_tag(file_contents, file_length, data, &datalen, 0x5F, 0x40, true, true, 0) == false) {
return PM3_ESOFT;
}
if (datalen < EMRTD_MAX_FILE_SIZE) {
saveFile(dg_table[EF_DG5].filename, data[0] == 0xFF ? ".jpg" : ".jp2", data, datalen);
char *filepath = calloc(strlen(path) + 100, sizeof(char));
if (filepath == NULL)
return PM3_EMALLOC;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg_table[EF_DG5].filename);
saveFile(filepath, data[0] == 0xFF ? ".jpg" : ".jp2", data, datalen);
free(filepath);
} else {
PrintAndLogEx(ERR, "error (emrtd_dump_ef_dg5) datalen out-of-bounds");
return PM3_ESOFT;
@@ -724,17 +770,26 @@ static int emrtd_dump_ef_dg5(uint8_t *file_contents, size_t file_length) {
return PM3_SUCCESS;
}
static int emrtd_dump_ef_dg7(uint8_t *file_contents, size_t file_length) {
static int emrtd_dump_ef_dg7(uint8_t *file_contents, size_t file_length, const char *path) {
uint8_t data[EMRTD_MAX_FILE_SIZE];
int datalen = 0;
size_t datalen = 0;
// If we can't find image in EF_DG7, return false.
if (emrtd_lds_get_data_by_tag(file_contents, file_length, data, &datalen, 0x5F, 0x42, true) == false) {
if (emrtd_lds_get_data_by_tag(file_contents, file_length, data, &datalen, 0x5F, 0x42, true, true, 0) == false) {
return PM3_ESOFT;
}
if (datalen < EMRTD_MAX_FILE_SIZE) {
saveFile(dg_table[EF_DG7].filename, data[0] == 0xFF ? ".jpg" : ".jp2", data, datalen);
char *filepath = calloc(strlen(path) + 100, sizeof(char));
if (filepath == NULL)
return PM3_EMALLOC;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg_table[EF_DG7].filename);
saveFile(filepath, data[0] == 0xFF ? ".jpg" : ".jp2", data, datalen);
free(filepath);
} else {
PrintAndLogEx(ERR, "error (emrtd_dump_ef_dg7) datalen out-of-bounds");
return PM3_ESOFT;
@@ -742,7 +797,7 @@ static int emrtd_dump_ef_dg7(uint8_t *file_contents, size_t file_length) {
return PM3_SUCCESS;
}
static int emrtd_dump_ef_sod(uint8_t *file_contents, size_t file_length) {
static int emrtd_dump_ef_sod(uint8_t *file_contents, size_t file_length, const char *path) {
int fieldlen = emrtd_get_asn1_field_length(file_contents, file_length, 1);
int datalen = emrtd_get_asn1_data_length(file_contents, file_length, 1);
@@ -751,11 +806,19 @@ static int emrtd_dump_ef_sod(uint8_t *file_contents, size_t file_length) {
return PM3_SUCCESS;
}
saveFile(dg_table[EF_SOD].filename, ".p7b", file_contents + fieldlen + 1, datalen);
char *filepath = calloc(strlen(path) + 100, sizeof(char));
if (filepath == NULL)
return PM3_EMALLOC;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg_table[EF_SOD].filename);
saveFile(filepath, ".p7b", file_contents + fieldlen + 1, datalen);
free(filepath);
return PM3_ESOFT;
}
static bool emrtd_dump_file(uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, const char *file, const char *name, bool use_secure, bool use_14b) {
static bool emrtd_dump_file(uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, const char *file, const char *name, bool use_secure, bool use_14b, const char *path) {
uint8_t response[EMRTD_MAX_FILE_SIZE];
int resplen = 0;
@@ -763,13 +826,22 @@ static bool emrtd_dump_file(uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, cons
return false;
}
char *filepath = calloc(strlen(path) + 100, sizeof(char));
if (filepath == NULL)
return PM3_EMALLOC;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, name);
PrintAndLogEx(INFO, "Read %s, len: %i.", name, resplen);
PrintAndLogEx(DEBUG, "Contents (may be incomplete over 2k chars): %s", sprint_hex_inrow(response, resplen));
saveFile(name, ".BIN", response, resplen);
saveFile(filepath, ".BIN", response, resplen);
emrtd_dg_t *dg = emrtd_fileid_to_dg(file);
if ((dg != NULL) && (dg->dumper != NULL)) {
dg->dumper(response, resplen);
dg->dumper(response, resplen, path);
}
free(filepath);
return true;
}
@@ -808,7 +880,7 @@ static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t
PrintAndLogEx(DEBUG, "kmrz.............. " _GREEN_("%s"), kmrz);
uint8_t kseed[20] = { 0x00 };
mbedtls_sha1((unsigned char *)kmrz, strlen(kmrz), kseed);
sha1hash((unsigned char *)kmrz, strlen(kmrz), kseed);
PrintAndLogEx(DEBUG, "kseed (sha1)...... %s ", sprint_hex_inrow(kseed, 16));
emrtd_deskey(kseed, KENC_type, 16, kenc);
@@ -955,7 +1027,7 @@ static bool emrtd_do_auth(char *documentnumber, char *dob, char *expiry, bool BA
return true;
}
int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available) {
int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available, const char *path) {
uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 };
int resplen = 0;
uint8_t ssc[8] = { 0x00 };
@@ -971,7 +1043,7 @@ int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab
}
// Dump EF_CardAccess (if available)
if (!emrtd_dump_file(ks_enc, ks_mac, ssc, dg_table[EF_CardAccess].fileid, dg_table[EF_CardAccess].filename, BAC, use_14b)) {
if (!emrtd_dump_file(ks_enc, ks_mac, ssc, dg_table[EF_CardAccess].fileid, dg_table[EF_CardAccess].filename, BAC, use_14b, path)) {
PrintAndLogEx(INFO, "Couldn't dump EF_CardAccess, card does not support PACE.");
PrintAndLogEx(HINT, "This is expected behavior for cards without PACE, and isn't something to be worried about.");
}
@@ -988,14 +1060,25 @@ int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab
DropField();
return PM3_ESOFT;
}
char *filepath = calloc(strlen(path) + 100, sizeof(char));
if (filepath == NULL)
return PM3_EMALLOC;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg_table[EF_COM].filename);
PrintAndLogEx(INFO, "Read EF_COM, len: %i.", resplen);
PrintAndLogEx(DEBUG, "Contents (may be incomplete over 2k chars): %s", sprint_hex_inrow(response, resplen));
saveFile(dg_table[EF_COM].filename, ".BIN", response, resplen);
saveFile(filepath, ".BIN", response, resplen);
free(filepath);
uint8_t filelist[50];
int filelistlen = 0;
size_t filelistlen = 0;
if (!emrtd_lds_get_data_by_tag(response, resplen, filelist, &filelistlen, 0x5c, 0x00, false)) {
if (!emrtd_lds_get_data_by_tag(response, resplen, filelist, &filelistlen, 0x5c, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read file list from EF_COM.");
DropField();
return PM3_ESOFT;
@@ -1012,8 +1095,8 @@ int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab
continue;
}
PrintAndLogEx(DEBUG, "Current file: %s", dg->filename);
if (!dg->pace) {
emrtd_dump_file(ks_enc, ks_mac, ssc, dg->fileid, dg->filename, BAC, use_14b);
if (!dg->pace && !dg->eac) {
emrtd_dump_file(ks_enc, ks_mac, ssc, dg->fileid, dg->filename, BAC, use_14b, path);
}
}
DropField();
@@ -1220,8 +1303,8 @@ static void emrtd_print_unknown_timestamp_5f85(uint8_t *data) {
static int emrtd_print_ef_com_info(uint8_t *data, size_t datalen) {
uint8_t filelist[50];
int filelistlen = 0;
int res = emrtd_lds_get_data_by_tag(data, datalen, filelist, &filelistlen, 0x5c, 0x00, false);
size_t filelistlen = 0;
int res = emrtd_lds_get_data_by_tag(data, datalen, filelist, &filelistlen, 0x5c, 0x00, false, true, 0);
if (!res) {
PrintAndLogEx(ERR, "Failed to read file list from EF_COM.");
return PM3_ESOFT;
@@ -1250,9 +1333,9 @@ static int emrtd_print_ef_dg1_info(uint8_t *data, size_t datalen) {
// MRZ on TD1 is 90 characters, 30 on each row.
// MRZ on TD3 is 88 characters, 44 on each row.
char mrz[90] = { 0x00 };
int mrzlen = 0;
size_t mrzlen = 0;
if (!emrtd_lds_get_data_by_tag(data, datalen, (uint8_t *) mrz, &mrzlen, 0x5f, 0x1f, true)) {
if (!emrtd_lds_get_data_by_tag(data, datalen, (uint8_t *) mrz, &mrzlen, 0x5f, 0x1f, true, true, 0)) {
PrintAndLogEx(ERR, "Failed to read MRZ from EF_DG1.");
return PM3_ESOFT;
}
@@ -1327,20 +1410,20 @@ static int emrtd_print_ef_dg1_info(uint8_t *data, size_t datalen) {
static int emrtd_print_ef_dg11_info(uint8_t *data, size_t datalen) {
uint8_t taglist[100] = { 0x00 };
int taglistlen = 0;
size_t taglistlen = 0;
uint8_t tagdata[1000] = { 0x00 };
int tagdatalen = 0;
size_t tagdatalen = 0;
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "-------------------- " _CYAN_("EF_DG11") " -------------------");
if (!emrtd_lds_get_data_by_tag(data, datalen, taglist, &taglistlen, 0x5c, 0x00, false)) {
if (!emrtd_lds_get_data_by_tag(data, datalen, taglist, &taglistlen, 0x5c, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read file list from EF_DG11.");
return PM3_ESOFT;
}
for (int i = 0; i < taglistlen; i++) {
emrtd_lds_get_data_by_tag(data, datalen, tagdata, &tagdatalen, taglist[i], taglist[i + 1], taglist[i] == 0x5f);
emrtd_lds_get_data_by_tag(data, datalen, tagdata, &tagdatalen, taglist[i], taglist[i + 1], taglist[i] == 0x5f, true, 0);
// Don't bother with empty tags
if (tagdatalen == 0) {
continue;
@@ -1406,20 +1489,20 @@ static int emrtd_print_ef_dg11_info(uint8_t *data, size_t datalen) {
static int emrtd_print_ef_dg12_info(uint8_t *data, size_t datalen) {
uint8_t taglist[100] = { 0x00 };
int taglistlen = 0;
size_t taglistlen = 0;
uint8_t tagdata[1000] = { 0x00 };
int tagdatalen = 0;
size_t tagdatalen = 0;
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "-------------------- " _CYAN_("EF_DG12") " -------------------");
if (!emrtd_lds_get_data_by_tag(data, datalen, taglist, &taglistlen, 0x5c, 0x00, false)) {
if (!emrtd_lds_get_data_by_tag(data, datalen, taglist, &taglistlen, 0x5c, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read file list from EF_DG12.");
return PM3_ESOFT;
}
for (int i = 0; i < taglistlen; i++) {
emrtd_lds_get_data_by_tag(data, datalen, tagdata, &tagdatalen, taglist[i], taglist[i + 1], taglist[i] == 0x5f);
emrtd_lds_get_data_by_tag(data, datalen, tagdata, &tagdatalen, taglist[i], taglist[i + 1], taglist[i] == 0x5f, true, 0);
// Don't bother with empty tags
if (tagdatalen == 0) {
continue;
@@ -1470,10 +1553,176 @@ static int emrtd_print_ef_dg12_info(uint8_t *data, size_t datalen) {
return PM3_SUCCESS;
}
static int emrtd_print_ef_sod_info(uint8_t *data, size_t datalen) {
// PrintAndLogEx(NORMAL, "");
// PrintAndLogEx(INFO, "-------------------- " _CYAN_("EF_SOD") " --------------------");
// PrintAndLogEx(WARNING, "TODO");
static int emrtd_ef_sod_extract_signatures(uint8_t *data, size_t datalen, uint8_t *dataout, size_t *dataoutlen) {
uint8_t top[EMRTD_MAX_FILE_SIZE] = { 0x00 };
uint8_t signeddata[EMRTD_MAX_FILE_SIZE] = { 0x00 };
uint8_t emrtdsigcontainer[EMRTD_MAX_FILE_SIZE] = { 0x00 };
uint8_t emrtdsig[EMRTD_MAX_FILE_SIZE] = { 0x00 };
uint8_t emrtdsigtext[EMRTD_MAX_FILE_SIZE] = { 0x00 };
size_t toplen, signeddatalen, emrtdsigcontainerlen, emrtdsiglen, emrtdsigtextlen = 0;
if (!emrtd_lds_get_data_by_tag(data, datalen, top, &toplen, 0x30, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read top from EF_SOD.");
return false;
}
PrintAndLogEx(DEBUG, "top: %s.", sprint_hex_inrow(top, toplen));
if (!emrtd_lds_get_data_by_tag(top, toplen, signeddata, &signeddatalen, 0xA0, 0x00, false, false, 0)) {
PrintAndLogEx(ERR, "Failed to read signedData from EF_SOD.");
return false;
}
PrintAndLogEx(DEBUG, "signeddata: %s.", sprint_hex_inrow(signeddata, signeddatalen));
// Do true on reading into the tag as it's a "sequence"
if (!emrtd_lds_get_data_by_tag(signeddata, signeddatalen, emrtdsigcontainer, &emrtdsigcontainerlen, 0x30, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read eMRTDSignature container from EF_SOD.");
return false;
}
PrintAndLogEx(DEBUG, "emrtdsigcontainer: %s.", sprint_hex_inrow(emrtdsigcontainer, emrtdsigcontainerlen));
if (!emrtd_lds_get_data_by_tag(emrtdsigcontainer, emrtdsigcontainerlen, emrtdsig, &emrtdsiglen, 0xA0, 0x00, false, false, 0)) {
PrintAndLogEx(ERR, "Failed to read eMRTDSignature from EF_SOD.");
return false;
}
PrintAndLogEx(DEBUG, "emrtdsig: %s.", sprint_hex_inrow(emrtdsig, emrtdsiglen));
// TODO: Not doing memcpy here, it didn't work, fix it somehow
if (!emrtd_lds_get_data_by_tag(emrtdsig, emrtdsiglen, emrtdsigtext, &emrtdsigtextlen, 0x04, 0x00, false, false, 0)) {
PrintAndLogEx(ERR, "Failed to read eMRTDSignature (text) from EF_SOD.");
return false;
}
memcpy(dataout, emrtdsigtext, emrtdsigtextlen);
*dataoutlen = emrtdsigtextlen;
return PM3_SUCCESS;
}
static int emrtd_parse_ef_sod_hash_algo(uint8_t *data, size_t datalen, int *hashalgo) {
uint8_t hashalgoset[64] = { 0x00 };
size_t hashalgosetlen = 0;
// We'll return hash algo -1 if we can't find anything
*hashalgo = -1;
if (!emrtd_lds_get_data_by_tag(data, datalen, hashalgoset, &hashalgosetlen, 0x30, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read hash algo set from EF_SOD.");
return false;
}
PrintAndLogEx(DEBUG, "hash algo set: %s", sprint_hex_inrow(hashalgoset, hashalgosetlen));
// If last two bytes are 05 00, ignore them.
// https://wf.lavatech.top/ave-but-random/emrtd-data-quirks#EF_SOD
if (hashalgoset[hashalgosetlen - 2] == 0x05 && hashalgoset[hashalgosetlen - 1] == 0x00) {
hashalgosetlen -= 2;
}
for (int hashi = 0; hashalg_table[hashi].name != NULL; hashi++) {
PrintAndLogEx(DEBUG, "trying: %s", hashalg_table[hashi].name);
// We're only interested in checking if the length matches to avoid memory shenanigans
if (hashalg_table[hashi].descriptorlen != hashalgosetlen) {
PrintAndLogEx(DEBUG, "len mismatch: %i", hashalgosetlen);
continue;
}
if (memcmp(hashalg_table[hashi].descriptor, hashalgoset, hashalgosetlen) == 0) {
*hashalgo = hashi;
return PM3_SUCCESS;
}
}
PrintAndLogEx(ERR, "Failed to parse hash list (Unknown algo: %s). Hash verification won't be available.", sprint_hex_inrow(hashalgoset, hashalgosetlen));
return PM3_ESOFT;
}
static int emrtd_parse_ef_sod_hashes(uint8_t *data, size_t datalen, uint8_t *hashes, int *hashalgo) {
uint8_t emrtdsig[EMRTD_MAX_FILE_SIZE] = { 0x00 };
uint8_t hashlist[EMRTD_MAX_FILE_SIZE] = { 0x00 };
uint8_t hash[64] = { 0x00 };
size_t hashlen = 0;
uint8_t hashidstr[4] = { 0x00 };
size_t hashidstrlen = 0;
size_t emrtdsiglen = 0;
size_t hashlistlen = 0;
size_t e_datalen = 0;
size_t e_fieldlen = 0;
size_t offset = 0;
if (emrtd_ef_sod_extract_signatures(data, datalen, emrtdsig, &emrtdsiglen) != PM3_SUCCESS) {
return false;
}
PrintAndLogEx(DEBUG, "hash data: %s", sprint_hex_inrow(emrtdsig, emrtdsiglen));
emrtd_parse_ef_sod_hash_algo(emrtdsig, emrtdsiglen, hashalgo);
if (!emrtd_lds_get_data_by_tag(emrtdsig, emrtdsiglen, hashlist, &hashlistlen, 0x30, 0x00, false, true, 1)) {
PrintAndLogEx(ERR, "Failed to read hash list from EF_SOD.");
return false;
}
PrintAndLogEx(DEBUG, "hash list: %s", sprint_hex_inrow(hashlist, hashlistlen));
while (offset < hashlistlen) {
// Get the length of the element
e_datalen = emrtd_get_asn1_data_length(hashlist + offset, hashlistlen - offset, 1);
// Get the length of the element's length
e_fieldlen = emrtd_get_asn1_field_length(hashlist + offset, hashlistlen - offset, 1);
switch (hashlist[offset]) {
case 0x30:
emrtd_lds_get_data_by_tag(hashlist + offset + e_fieldlen + 1, e_datalen, hashidstr, &hashidstrlen, 0x02, 0x00, false, false, 0);
emrtd_lds_get_data_by_tag(hashlist + offset + e_fieldlen + 1, e_datalen, hash, &hashlen, 0x04, 0x00, false, false, 0);
if (hashlen <= 64) {
memcpy(hashes + (hashidstr[0] * 64), hash, hashlen);
} else {
PrintAndLogEx(ERR, "error (emrtd_parse_ef_sod_hashes) hashlen out-of-bounds");
}
break;
}
// + 1 for length of ID
offset += 1 + e_datalen + e_fieldlen;
}
return PM3_SUCCESS;
}
static int emrtd_print_ef_sod_info(uint8_t *dg_hashes_calc, uint8_t *dg_hashes_sod, int hash_algo) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "-------------------- " _CYAN_("EF_SOD") " --------------------");
if (hash_algo == -1) {
PrintAndLogEx(SUCCESS, "Hash algorithm: " _YELLOW_("Unknown"));
} else {
PrintAndLogEx(SUCCESS, "Hash algorithm: " _YELLOW_("%s"), hashalg_table[hash_algo].name);
uint8_t all_zeroes[64] = { 0x00 };
bool calc_all_zero, sod_all_zero, hash_matches;
for (int i = 1; i <= 16; i++) {
calc_all_zero = (memcmp(dg_hashes_calc + (i * 64), all_zeroes, hashalg_table[hash_algo].hashlen) == 0);
sod_all_zero = (memcmp(dg_hashes_sod + (i * 64), all_zeroes, hashalg_table[hash_algo].hashlen) == 0);
hash_matches = (memcmp(dg_hashes_sod + (i * 64), dg_hashes_calc + (i * 64), hashalg_table[hash_algo].hashlen) == 0);
// Ignore files we don't haven't read and lack hashes to
if (calc_all_zero == true && sod_all_zero == true) {
continue;
} else if (calc_all_zero == true) {
PrintAndLogEx(SUCCESS, "EF_DG%i: " _YELLOW_("File couldn't be read, but is in EF_SOD."), i);
} else if (sod_all_zero == true) {
PrintAndLogEx(SUCCESS, "EF_DG%i: " _YELLOW_("File is not in EF_SOD."), i);
} else if (hash_matches == false) {
PrintAndLogEx(SUCCESS, "EF_DG%i: " _RED_("Invalid"), i);
} else {
PrintAndLogEx(SUCCESS, "EF_DG%i: " _GREEN_("Valid"), i);
}
}
}
return PM3_SUCCESS;
}
@@ -1519,15 +1768,30 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab
}
uint8_t filelist[50];
int filelistlen = 0;
size_t filelistlen = 0;
if (!emrtd_lds_get_data_by_tag(response, resplen, filelist, &filelistlen, 0x5c, 0x00, false)) {
if (!emrtd_lds_get_data_by_tag(response, resplen, filelist, &filelistlen, 0x5c, 0x00, false, true, 0)) {
PrintAndLogEx(ERR, "Failed to read file list from EF_COM.");
DropField();
return PM3_ESOFT;
}
// Add EF_SOD to the list
filelist[filelistlen++] = 0x77;
// Grab the hash list
uint8_t dg_hashes_sod[17][64] = { { 0 } };
uint8_t dg_hashes_calc[17][64] = { { 0 } };
int hash_algo = 0;
if (!emrtd_select_and_read(response, &resplen, dg_table[EF_SOD].fileid, ks_enc, ks_mac, ssc, BAC, use_14b)) {
PrintAndLogEx(ERR, "Failed to read EF_SOD.");
DropField();
return PM3_ESOFT;
}
res = emrtd_parse_ef_sod_hashes(response, resplen, *dg_hashes_sod, &hash_algo);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Failed to read hash list from EF_SOD. Hash checks will fail.");
}
// Dump all files in the file list
for (int i = 0; i < filelistlen; i++) {
emrtd_dg_t *dg = emrtd_tag_to_dg(filelist[i]);
@@ -1535,14 +1799,25 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab
PrintAndLogEx(INFO, "File tag not found, skipping: %02X", filelist[i]);
continue;
}
if (dg->fastdump && !dg->pace) {
if (dg->fastdump && !dg->pace && !dg->eac) {
if (emrtd_select_and_read(response, &resplen, dg->fileid, ks_enc, ks_mac, ssc, BAC, use_14b)) {
if (dg->parser != NULL)
dg->parser(response, resplen);
PrintAndLogEx(DEBUG, "EF_DG%i hash algo: %i", dg->dgnum, hash_algo);
// Check file hash
if (hash_algo != -1) {
PrintAndLogEx(DEBUG, "EF_DG%i hash on EF_SOD: %s", dg->dgnum, sprint_hex_inrow(dg_hashes_sod[dg->dgnum], hashalg_table[hash_algo].hashlen));
hashalg_table[hash_algo].hasher(response, resplen, dg_hashes_calc[dg->dgnum]);
PrintAndLogEx(DEBUG, "EF_DG%i hash calc: %s", dg->dgnum, sprint_hex_inrow(dg_hashes_calc[dg->dgnum], hashalg_table[hash_algo].hashlen));
}
}
}
}
DropField();
emrtd_print_ef_sod_info(*dg_hashes_calc, *dg_hashes_sod, hash_algo);
return PM3_SUCCESS;
}
@@ -1570,8 +1845,8 @@ int infoHF_EMRTD_offline(const char *path) {
}
uint8_t filelist[50];
int filelistlen = 0;
res = emrtd_lds_get_data_by_tag(data, datalen, filelist, &filelistlen, 0x5c, 0x00, false);
size_t filelistlen = 0;
res = emrtd_lds_get_data_by_tag(data, datalen, filelist, &filelistlen, 0x5c, 0x00, false, true, 0);
if (!res) {
PrintAndLogEx(ERR, "Failed to read file list from EF_COM.");
free(data);
@@ -1579,8 +1854,28 @@ int infoHF_EMRTD_offline(const char *path) {
return PM3_ESOFT;
}
free(data);
// Add EF_SOD to the list
filelist[filelistlen++] = 0x77;
// Grab the hash list
uint8_t dg_hashes_sod[17][64] = { { 0 } };
uint8_t dg_hashes_calc[17][64] = { { 0 } };
int hash_algo = 0;
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg_table[EF_SOD].filename);
if (loadFile_safeEx(filepath, ".BIN", (void **)&data, (size_t *)&datalen, false) != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Failed to read EF_SOD.");
free(filepath);
return PM3_ESOFT;
}
res = emrtd_parse_ef_sod_hashes(data, datalen, *dg_hashes_sod, &hash_algo);
if (res != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Failed to read hash list from EF_SOD. Hash checks will fail.");
}
free(data);
// Read files in the file list
for (int i = 0; i < filelistlen; i++) {
emrtd_dg_t *dg = emrtd_tag_to_dg(filelist[i]);
@@ -1588,7 +1883,7 @@ int infoHF_EMRTD_offline(const char *path) {
PrintAndLogEx(INFO, "File tag not found, skipping: %02X", filelist[i]);
continue;
}
if (!dg->pace) {
if (!dg->pace && !dg->eac) {
strcpy(filepath, path);
strncat(filepath, PATHSEP, 2);
strcat(filepath, dg->filename);
@@ -1596,11 +1891,22 @@ int infoHF_EMRTD_offline(const char *path) {
// we won't halt on parsing errors
if (dg->parser != NULL)
dg->parser(data, datalen);
PrintAndLogEx(DEBUG, "EF_DG%i hash algo: %i", dg->dgnum, hash_algo);
// Check file hash
if (hash_algo != -1) {
PrintAndLogEx(DEBUG, "EF_DG%i hash on EF_SOD: %s", dg->dgnum, sprint_hex_inrow(dg_hashes_sod[dg->dgnum], hashalg_table[hash_algo].hashlen));
hashalg_table[hash_algo].hasher(data, datalen, dg_hashes_calc[dg->dgnum]);
PrintAndLogEx(DEBUG, "EF_DG%i hash calc: %s", dg->dgnum, sprint_hex_inrow(dg_hashes_calc[dg->dgnum], hashalg_table[hash_algo].hashlen));
}
free(data);
}
}
}
free(filepath);
emrtd_print_ef_sod_info(*dg_hashes_calc, *dg_hashes_sod, hash_algo);
return PM3_SUCCESS;
}
@@ -1640,6 +1946,7 @@ static int cmd_hf_emrtd_dump(const char *Cmd) {
arg_str0("d", "dateofbirth", "<YYMMDD>", "date of birth in YYMMDD format"),
arg_str0("e", "expiry", "<YYMMDD>", "expiry in YYMMDD format"),
arg_str0("m", "mrz", "<[0-9A-Z<]>", "2nd line of MRZ, 44 chars"),
arg_str0(NULL, "path", "<dirpath>", "save dump to the given dirpath"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
@@ -1706,11 +2013,16 @@ static int cmd_hf_emrtd_dump(const char *Cmd) {
}
}
uint8_t path[FILENAME_MAX] = { 0x00 };
if (CLIParamStrToBuf(arg_get_str(ctx, 5), path, sizeof(path), &slen) != 0 || slen == 0) {
path[0] = '.';
}
CLIParserFree(ctx);
if (error) {
return PM3_ESOFT;
}
return dumpHF_EMRTD((char *)docnum, (char *)dob, (char *)expiry, BAC);
return dumpHF_EMRTD((char *)docnum, (char *)dob, (char *)expiry, BAC, (const char *)path);
}
static int cmd_hf_emrtd_info(const char *Cmd) {
@@ -1725,7 +2037,7 @@ static int cmd_hf_emrtd_info(const char *Cmd) {
arg_str0("n", "documentnumber", "<alphanum>", "document number, up to 9 chars"),
arg_str0("d", "dateofbirth", "<YYMMDD>", "date of birth in YYMMDD format"),
arg_str0("e", "expiry", "<YYMMDD>", "expiry in YYMMDD format"),
arg_str0("m", "mrz", "<[0-9A-Z<]>", "2nd line of MRZ, 44 chars"),
arg_str0("m", "mrz", "<[0-9A-Z<]>", "2nd line of MRZ, 44 chars (passports only)"),
arg_str0(NULL, "path", "<dirpath>", "display info from offline dump stored in dirpath"),
arg_param_end
};
+12 -2
View File
@@ -15,19 +15,29 @@
typedef struct emrtd_dg_s {
uint8_t tag;
uint8_t dgnum;
const char *fileid;
const char *filename;
const char *desc;
bool pace;
bool eac; // EAC only (we can't dump these)
bool required; // some are required only if PACE
bool fastdump; // fast to dump
int (*parser)(uint8_t *data, size_t datalen);
int (*dumper)(uint8_t *data, size_t datalen);
int (*dumper)(uint8_t *data, size_t datalen, const char *path);
} emrtd_dg_t;
typedef struct emrtd_hashalg_s {
const char *name;
int (*hasher)(uint8_t *datain, int datainlen, uint8_t *dataout);
size_t hashlen;
size_t descriptorlen;
const uint8_t descriptor[15];
} emrtd_hashalg_t;
int CmdHFeMRTD(const char *Cmd);
int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available);
int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available, const char *path);
int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available);
int infoHF_EMRTD_offline(const char *path);
#endif
+25 -25
View File
@@ -3488,36 +3488,36 @@ static int CmdHFiClassAutopwn(const char *Cmd) {
static command_t CommandTable[] = {
{"-----------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("operations") " ---------------------"},
{"help", CmdHelp, AlwaysAvailable, " This help"},
// {"clone", CmdHFiClassClone, IfPm3Iclass, "[*] Create a HID credential to Picopass / iCLASS tag"},
{"dump", CmdHFiClassDump, IfPm3Iclass, "[*] Dump Picopass / iCLASS tag to file"},
{"info", CmdHFiClassInfo, AlwaysAvailable, " Tag information"},
{"list", CmdHFiClassList, AlwaysAvailable, " List iclass history"},
{"rdbl", CmdHFiClass_ReadBlock, IfPm3Iclass, "[*] Read Picopass / iCLASS block"},
{"reader", CmdHFiClassReader, IfPm3Iclass, " Act like an Picopass / iCLASS reader"},
{"restore", CmdHFiClassRestore, IfPm3Iclass, "[*] Restore a dump file onto a Picopass / iCLASS tag"},
{"sniff", CmdHFiClassSniff, IfPm3Iclass, " Eavesdrop Picopass / iCLASS communication"},
{"wrbl", CmdHFiClass_WriteBlock, IfPm3Iclass, "[*] Write Picopass / iCLASS block"},
{"help", CmdHelp, AlwaysAvailable, "This help"},
// {"clone", CmdHFiClassClone, IfPm3Iclass, "Create a HID credential to Picopass / iCLASS tag"},
{"dump", CmdHFiClassDump, IfPm3Iclass, "Dump Picopass / iCLASS tag to file"},
{"info", CmdHFiClassInfo, AlwaysAvailable, "Tag information"},
{"list", CmdHFiClassList, AlwaysAvailable, "List iclass history"},
{"rdbl", CmdHFiClass_ReadBlock, IfPm3Iclass, "Read Picopass / iCLASS block"},
{"reader", CmdHFiClassReader, IfPm3Iclass, "Act like an Picopass / iCLASS reader"},
{"restore", CmdHFiClassRestore, IfPm3Iclass, "Restore a dump file onto a Picopass / iCLASS tag"},
{"sniff", CmdHFiClassSniff, IfPm3Iclass, "Eavesdrop Picopass / iCLASS communication"},
{"wrbl", CmdHFiClass_WriteBlock, IfPm3Iclass, "Write Picopass / iCLASS block"},
{"-----------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("recovery") " ---------------------"},
// {"autopwn", CmdHFiClassAutopwn, IfPm3Iclass, "[*] Automatic key recovery tool for iCLASS"},
{"chk", CmdHFiClassCheckKeys, IfPm3Iclass, "[*] Check keys"},
{"loclass", CmdHFiClass_loclass, AlwaysAvailable, "[*] Use loclass to perform bruteforce reader attack"},
{"lookup", CmdHFiClassLookUp, AlwaysAvailable, "[*] Uses authentication trace to check for key in dictionary file"},
// {"autopwn", CmdHFiClassAutopwn, IfPm3Iclass, "Automatic key recovery tool for iCLASS"},
{"chk", CmdHFiClassCheckKeys, IfPm3Iclass, "Check keys"},
{"loclass", CmdHFiClass_loclass, AlwaysAvailable, "Use loclass to perform bruteforce reader attack"},
{"lookup", CmdHFiClassLookUp, AlwaysAvailable, "Uses authentication trace to check for key in dictionary file"},
{"-----------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("simulation") " ---------------------"},
{"sim", CmdHFiClassSim, IfPm3Iclass, "[*] Simulate iCLASS tag"},
{"eload", CmdHFiClassELoad, IfPm3Iclass, "[*] Load Picopass / iCLASS dump file into emulator memory"},
{"esave", CmdHFiClassESave, IfPm3Iclass, "[*] Save emulator memory to file"},
{"eview", CmdHFiClassEView, IfPm3Iclass, "[.] View emulator memory"},
{"sim", CmdHFiClassSim, IfPm3Iclass, "Simulate iCLASS tag"},
{"eload", CmdHFiClassELoad, IfPm3Iclass, "Load Picopass / iCLASS dump file into emulator memory"},
{"esave", CmdHFiClassESave, IfPm3Iclass, "Save emulator memory to file"},
{"eview", CmdHFiClassEView, IfPm3Iclass, "View emulator memory"},
{"-----------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("utils") " ---------------------"},
{"calcnewkey", CmdHFiClassCalcNewKey, AlwaysAvailable, "[*] Calc diversified keys (blocks 3 & 4) to write new keys"},
{"encode", CmdHFiClassEncode, AlwaysAvailable, "[*] Encode binary wiegand to block 7"},
{"encrypt", CmdHFiClassEncryptBlk, AlwaysAvailable, "[*] Encrypt given block data"},
{"decrypt", CmdHFiClassDecrypt, AlwaysAvailable, "[*] Decrypt given block data or tag dump file" },
{"managekeys", CmdHFiClassManageKeys, AlwaysAvailable, "[*] Manage keys to use with iclass commands"},
{"permutekey", CmdHFiClassPermuteKey, IfPm3Iclass, " Permute function from 'heart of darkness' paper"},
{"view", CmdHFiClassView, AlwaysAvailable, "[*] Display content from tag dump file"},
{"calcnewkey", CmdHFiClassCalcNewKey, AlwaysAvailable, "Calc diversified keys (blocks 3 & 4) to write new keys"},
{"encode", CmdHFiClassEncode, AlwaysAvailable, "Encode binary wiegand to block 7"},
{"encrypt", CmdHFiClassEncryptBlk, AlwaysAvailable, "Encrypt given block data"},
{"decrypt", CmdHFiClassDecrypt, AlwaysAvailable, "Decrypt given block data or tag dump file" },
{"managekeys", CmdHFiClassManageKeys, AlwaysAvailable, "Manage keys to use with iclass commands"},
{"permutekey", CmdHFiClassPermuteKey, IfPm3Iclass, "Permute function from 'heart of darkness' paper"},
{"view", CmdHFiClassView, AlwaysAvailable, "Display content from tag dump file"},
{NULL, NULL, NULL, NULL}
};
+27 -11
View File
@@ -4869,25 +4869,41 @@ static int CmdHF14AMfMAD(const char *Cmd) {
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool verbose = arg_get_lit(ctx, 1);
uint8_t aid[2] = {0};
int aidlen;
int aidlen = 0;
CLIGetHexWithReturn(ctx, 2, aid, &aidlen);
uint8_t key[6] = {0};
int keylen;
CLIGetHexWithReturn(ctx, 3, key, &keylen);
uint8_t userkey[6] = {0};
int keylen = 0;
CLIGetHexWithReturn(ctx, 3, userkey, &keylen);
bool keyB = arg_get_lit(ctx, 4);
bool swapmad = arg_get_lit(ctx, 5);
bool decodeholder = arg_get_lit(ctx, 6);
CLIParserFree(ctx);
if (aidlen != 2 && !decodeholder && keylen > 0) {
PrintAndLogEx(WARNING, "Using default MAD keys instead");
}
uint8_t sector0[16 * 4] = {0};
uint8_t sector10[16 * 4] = {0};
if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) {
PrintAndLogEx(ERR, "error, read sector 0. card don't have MAD or don't have MAD on default keys");
bool got_first = true;
if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0) != PM3_SUCCESS) {
PrintAndLogEx(WARNING, "error, read sector 0. card don't have MAD or don't have MAD on default keys");
got_first = false;
} else {
PrintAndLogEx(INFO, "Authentication ( " _GREEN_("OK") " )");
}
// User supplied key
if (got_first == false && keylen == 6) {
PrintAndLogEx(INFO, "Trying user specified key...");
if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, userkey, sector0) != PM3_SUCCESS) {
PrintAndLogEx(ERR, "error, read sector 0. card don't have MAD or don't the custom key is wrong");
} else {
PrintAndLogEx(INFO, "Authentication ( " _GREEN_("OK") " )");
got_first = true;
}
}
// Both default and user supplied key failed
if (got_first == false) {
return PM3_ESOFT;
}
@@ -4921,7 +4937,7 @@ static int CmdHF14AMfMAD(const char *Cmd) {
// user specified key
if (keylen == 6) {
memcpy(akey, key, 6);
memcpy(akey, userkey, 6);
}
uint16_t aaid = 0x0004;
+34 -3
View File
@@ -2256,7 +2256,17 @@ static int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t *aid,
}
static int CmdHF14ADesGetUID(const char *Cmd) {
(void)Cmd;
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes getuid",
"Get UID from a MIFARE DESfire tag",
"hf mfdes getuid");
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
uint8_t uid[16] = {0};
int res = handler_desfire_getuid(uid);
@@ -3438,7 +3448,18 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) {
}
static int CmdHF14ADesInfo(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes info",
"Get info from MIFARE DESfire tags",
"hf mfdes info");
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
DropFieldDesfire();
mfdes_info_res_t info;
@@ -3862,8 +3883,18 @@ static int CmdHF14ADesDump(const char *Cmd) {
}
static int CmdHF14ADesEnumApplications(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfdes enum",
"Enumerate all AID's on MIFARE DESfire tag",
"hf mfdes enum");
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
(void)Cmd; // Cmd is not used so far
DropFieldDesfire();
uint8_t aid[3] = {0};
+866 -851
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -59,6 +59,9 @@ typedef enum TAGTYPE_UL {
UL_NANO_40 = 0x2000000,
NTAG_213_TT = 0x4000000,
NTAG_213_C = 0x8000000,
MAGIC_1A = 0x10000000 | MAGIC,
MAGIC_1B = 0x20000000 | MAGIC,
MAGIC_NTAG = 0x40000000 | MAGIC,
UL_MAGIC = UL | MAGIC,
UL_C_MAGIC = UL_C | MAGIC,
UL_ERROR = 0xFFFFFF,
+1 -1
View File
@@ -351,7 +351,7 @@ static int cmd_hf_st_sim(const char *Cmd) {
}
char param[40];
snprintf(param, sizeof(param), "t 10 u %s", sprint_hex_inrow(uid, uidlen));
snprintf(param, sizeof(param), "-t 10 -u %s", sprint_hex_inrow(uid, uidlen));
return CmdHF14ASim(param);
}
+304 -134
View File
@@ -26,65 +26,6 @@
static int CmdHelp(const char *Cmd);
static int usage_dbg(void) {
PrintAndLogEx(NORMAL, "Usage: hw dbg [h] <debug level>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h this help");
PrintAndLogEx(NORMAL, " <debug level> (Optional) see list for valid levels");
PrintAndLogEx(NORMAL, " 0 - no debug messages");
PrintAndLogEx(NORMAL, " 1 - error messages");
PrintAndLogEx(NORMAL, " 2 - plus information messages");
PrintAndLogEx(NORMAL, " 3 - plus debug messages");
PrintAndLogEx(NORMAL, " 4 - print even debug messages in timing critical functions");
PrintAndLogEx(NORMAL, " Note: this option therefore may cause malfunction itself");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hw dbg 3"));
return 0;
}
static int usage_hw_detectreader(void) {
PrintAndLogEx(NORMAL, "Start to detect presences of reader field");
PrintAndLogEx(NORMAL, "press pm3 button to change modes and finally exit");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: hw detectreader [h] <L|H>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " <type> L = 125/134 kHz, H = 13.56 MHz");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hw detectreader L"));
return PM3_SUCCESS;
}
static int usage_hw_setmux(void) {
PrintAndLogEx(NORMAL, "Set the ADC mux to a specific value");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: hw setmux [h] <lopkd | loraw | hipkd | hiraw>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " <type> Low peak, Low raw, Hi peak, Hi raw");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hw setmux lopkd"));
return PM3_SUCCESS;
}
static int usage_hw_connect(void) {
PrintAndLogEx(NORMAL, "Connects to a Proxmark3 device via specified serial port");
PrintAndLogEx(NORMAL, "Baudrate here is only for physical UART or UART-BT, " _YELLOW_("not")" for USB-CDC or blue shark add-on");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: hw connect [h] [p <port>] [b <baudrate>]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " p <port> Serial port to connect to, else retry the last used one");
PrintAndLogEx(NORMAL, " b <baudrate> Baudrate");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hw connect p "SERIAL_PORT_EXAMPLE_H));
PrintAndLogEx(NORMAL, _YELLOW_(" hw connect p "SERIAL_PORT_EXAMPLE_H" b 115200"));
return PM3_SUCCESS;
}
static void lookupChipID(uint32_t iChipID, uint32_t mem_used) {
char asBuff[120];
memset(asBuff, 0, sizeof(asBuff));
@@ -371,32 +312,81 @@ static void lookupChipID(uint32_t iChipID, uint32_t mem_used) {
static int CmdDbg(const char *Cmd) {
char ctmp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) < 1 || ctmp == 'h') return usage_dbg();
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw dbg",
"Set device side debug level output.\n"
"Note: option -4, this option may cause malfunction itself",
"hw dbg -1\n"
);
uint8_t dbgMode = param_get8ex(Cmd, 0, 0, 10);
if (dbgMode > 4) return usage_dbg();
void *argtable[] = {
arg_param_begin,
arg_lit0("0", NULL, "no debug messages"),
arg_lit0("1", NULL, "error messages"),
arg_lit0("2", NULL, "plus information messages"),
arg_lit0("3", NULL, "plus debug messages"),
arg_lit0("4", NULL, "print even debug messages in timing critical functions"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool lv0 = arg_get_lit(ctx, 1);
bool lv1 = arg_get_lit(ctx, 2);
bool lv2 = arg_get_lit(ctx, 3);
bool lv3 = arg_get_lit(ctx, 3);
bool lv4 = arg_get_lit(ctx, 4);
CLIParserFree(ctx);
SendCommandNG(CMD_SET_DBGMODE, &dbgMode, 1);
if ((lv0 + lv1 + lv2 + lv3 + lv4) > 1) {
PrintAndLogEx(INFO, "Can only set one debug level");
return PM3_EINVARG;
}
uint8_t dbg = 0;
if (lv0)
dbg = 0;
else if (lv1)
dbg = 1;
else if (lv2)
dbg = 2;
else if (lv3)
dbg = 3;
else if (lv4)
dbg = 4;
SendCommandNG(CMD_SET_DBGMODE, &dbg, sizeof(dbg));
return PM3_SUCCESS;
}
static int CmdDetectReader(const char *Cmd) {
uint8_t arg = 0;
char c = toupper(Cmd[0]);
switch (c) {
case 'L':
arg = 1;
break;
case 'H':
arg = 2;
break;
default: {
usage_hw_detectreader();
return PM3_EINVARG;
}
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw detectreader",
"Start to detect presences of reader field",
"hw detectreader -L\n"
);
void *argtable[] = {
arg_param_begin,
arg_lit0("L", "LF", "detect low frequence 125/134 kHz"),
arg_lit0("H", "HF", "detect high frequence 13.56 MHZ"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool lf = arg_get_lit(ctx, 1);
bool hf = arg_get_lit(ctx, 2);
CLIParserFree(ctx);
if ((lf + hf) > 1) {
PrintAndLogEx(INFO, "Can only set one frequence");
return PM3_EINVARG;
}
uint8_t arg = 0;
if (lf)
arg = 1;
else if (hf)
arg = 2;
PrintAndLogEx(INFO, "press pm3 button to change modes and finally exit");
clearCommandBuffer();
SendCommandNG(CMD_LISTEN_READER_FIELD, (uint8_t *)&arg, sizeof(arg));
return PM3_SUCCESS;
@@ -404,38 +394,107 @@ static int CmdDetectReader(const char *Cmd) {
// ## FPGA Control
static int CmdFPGAOff(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw fpgaoff",
"Turn of fpga and antenna field",
"hw fpgaoff\n"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_FPGA_MAJOR_MODE_OFF, NULL, 0);
return PM3_SUCCESS;
}
static int CmdLCD(const char *Cmd) {
int i, j;
sscanf(Cmd, "%x %d", &i, &j);
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw lcd",
"Send command/data to LCD",
"hw lcd -r AA -c 03 -> sends 0xAA three times"
);
void *argtable[] = {
arg_param_begin,
arg_int1("r", "raw", "<hex>", "data "),
arg_int1("c", "cnt", "<dec>", "number of times to send"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
int r_len = 0;
uint8_t raw[1] = {0};
CLIGetHexWithReturn(ctx, 1, raw, &r_len);
int j = arg_get_int(ctx, 2);
if (j < 1) {
PrintAndLogEx(WARNING, "Count must be larger than zero");
return PM3_EINVARG;
}
while (j--) {
clearCommandBuffer();
SendCommandMIX(CMD_LCD, i & 0x1ff, 0, 0, NULL, 0);
SendCommandMIX(CMD_LCD, raw[0], 0, 0, NULL, 0);
}
return PM3_SUCCESS;
}
static int CmdLCDReset(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw lcdreset",
"Hardware reset LCD",
"hw lcdreset\n"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_LCD_RESET, NULL, 0);
return PM3_SUCCESS;
}
static int CmdReadmem(const char *Cmd) {
uint32_t address = strtol(Cmd, NULL, 0);
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw readmem",
"Read memory at decimal address from ARM chip flash.",
"hw readmem -a 10000"
);
void *argtable[] = {
arg_param_begin,
arg_u64_1("a", "adr", "<dec>", "address to read"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint32_t address = arg_get_u32(ctx, 1);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_READ_MEM, (uint8_t *)&address, sizeof(address));
return PM3_SUCCESS;
}
static int CmdReset(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw reset",
"Reset the Proxmark3 device.",
"hw reset"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_HARDWARE_RESET, NULL, 0);
PrintAndLogEx(INFO, "Proxmark3 has been reset.");
@@ -447,10 +506,24 @@ static int CmdReset(const char *Cmd) {
* 600kHz.
*/
static int CmdSetDivisor(const char *Cmd) {
uint8_t arg = param_get8ex(Cmd, 0, 95, 10);
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw setlfdivisor",
"Drive LF antenna at 12 MHz / (divisor + 1).",
"hw setlfdivisor -d 88"
);
void *argtable[] = {
arg_param_begin,
arg_u64_1("d", "div", "<dec>", "19 - 255 divisor value (def 95)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint8_t arg = arg_get_u32_def(ctx, 1, 95);
CLIParserFree(ctx);
if (arg < 19) {
PrintAndLogEx(ERR, "divisor must be between" _YELLOW_("19") " and " _YELLOW_("255"));
PrintAndLogEx(ERR, "Divisor must be between" _YELLOW_("19") " and " _YELLOW_("255"));
return PM3_EINVARG;
}
// 12 000 000 (12MHz)
@@ -462,51 +535,114 @@ static int CmdSetDivisor(const char *Cmd) {
static int CmdSetMux(const char *Cmd) {
if (strlen(Cmd) < 5) {
usage_hw_setmux();
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw setmux",
"Set the ADC mux to a specific value",
"hw setmux --hiraw -> set HIGH RAW"
);
void *argtable[] = {
arg_param_begin,
arg_lit0(NULL, "lopkd", "low peak"),
arg_lit0(NULL, "loraw", "low raw"),
arg_lit0(NULL, "hipkd", "high peak"),
arg_lit0(NULL, "hiraw", "high raw"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool lopkd = arg_get_lit(ctx, 1);
bool loraw = arg_get_lit(ctx, 2);
bool hipkd = arg_get_lit(ctx, 3);
bool hiraw = arg_get_lit(ctx, 4);
CLIParserFree(ctx);
if ((lopkd + loraw + hipkd + hiraw) > 1) {
PrintAndLogEx(INFO, "Can only set one mux");
return PM3_EINVARG;
}
str_lower((char *)Cmd);
uint8_t arg = 0;
if (strcmp(Cmd, "lopkd") == 0)
if (lopkd)
arg = 0;
else if (strcmp(Cmd, "loraw") == 0)
else if (loraw)
arg = 1;
else if (strcmp(Cmd, "hipkd") == 0)
else if (hipkd)
arg = 2;
else if (strcmp(Cmd, "hiraw") == 0)
else if (hiraw)
arg = 3;
else {
usage_hw_setmux();
return PM3_EINVARG;
}
clearCommandBuffer();
SendCommandNG(CMD_SET_ADC_MUX, (uint8_t *)&arg, sizeof(arg));
return PM3_SUCCESS;
}
static int CmdStandalone(const char *Cmd) {
// (void)Cmd; // Cmd is not used so far
uint8_t arg = param_get8ex(Cmd, 0, 0, 10);
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw standalone",
"Start standalone mode",
"hw standalone -> start \n"
"hw standalone -a 1 -> start and send arg 1"
);
void *argtable[] = {
arg_param_begin,
arg_u64_0("a", "arg", "<dec>", "argument byte"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint8_t arg = arg_get_u32(ctx, 1);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_STANDALONE, (uint8_t *)&arg, sizeof(arg));
return PM3_SUCCESS;
}
static int CmdTune(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw tune",
"Measure antenna tuning",
"hw tune"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
return CmdTuneSamples(Cmd);
}
static int CmdVersion(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw version",
"Show version information about the connected Proxmark3",
"hw version"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
pm3_version(true, false);
return PM3_SUCCESS;
}
static int CmdStatus(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw status",
"Show runtime status information about the connected Proxmark3",
"hw status"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
clearCommandBuffer();
PacketResponseNG resp;
SendCommandNG(CMD_STATUS, NULL, 0);
@@ -590,7 +726,19 @@ static int CmdTearoff(const char *Cmd) {
}
static int CmdTia(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw tia",
"Trigger a Timing Interval Acquisition to re-adjust the RealTimeCounter divider",
"hw tia"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
PrintAndLogEx(INFO, "Triggering new Timing Interval Acquisition (TIA)...");
clearCommandBuffer();
SendCommandNG(CMD_TIA, NULL, 0);
@@ -604,19 +752,38 @@ static int CmdTia(const char *Cmd) {
}
static int CmdPing(const char *Cmd) {
uint32_t len = strtol(Cmd, NULL, 0);
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw ping",
"Test if the Proxmark3 is responsive",
"hw ping\n"
"hw ping --len 32"
);
void *argtable[] = {
arg_param_begin,
arg_u64_0("l", "len", "<dec>", "length of payload to send"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint32_t len = arg_get_u32(ctx, 1);
CLIParserFree(ctx);
if (len > PM3_CMD_DATA_SIZE)
len = PM3_CMD_DATA_SIZE;
if (len) {
PrintAndLogEx(INFO, "Ping sent with payload len = %d", len);
PrintAndLogEx(INFO, "Ping sent with payload len " _YELLOW_("%d"), len);
} else {
PrintAndLogEx(INFO, "Ping sent");
}
clearCommandBuffer();
PacketResponseNG resp;
uint8_t data[PM3_CMD_DATA_SIZE] = {0};
for (uint16_t i = 0; i < len; i++)
data[i] = i & 0xFF;
SendCommandNG(CMD_PING, data, len);
if (WaitForResponseTimeout(CMD_PING, &resp, 1000)) {
if (len) {
@@ -632,35 +799,38 @@ static int CmdPing(const char *Cmd) {
static int CmdConnect(const char *Cmd) {
uint32_t baudrate = USART_BAUD_RATE;
uint8_t cmdp = 0;
char port[FILE_PATH_SIZE] = {0};
CLIParserContext *ctx;
CLIParserInit(&ctx, "hw connect",
"Connects to a Proxmark3 device via specified serial port.\n"
"Baudrate here is only for physical UART or UART-BT, NOT for USB-CDC or blue shark add-on",
"hw connect -p "SERIAL_PORT_EXAMPLE_H"\n"
"hw connect -p "SERIAL_PORT_EXAMPLE_H" -b 115200"
);
while (param_getchar(Cmd, cmdp) != 0x00) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_hw_connect();
case 'p': {
param_getstr(Cmd, cmdp + 1, port, sizeof(port));
cmdp += 2;
break;
}
case 'b':
baudrate = param_get32ex(Cmd, cmdp + 1, USART_BAUD_RATE, 10);
if (baudrate == 0)
return usage_hw_connect();
cmdp += 2;
break;
default:
usage_hw_connect();
return PM3_EINVARG;
}
void *argtable[] = {
arg_param_begin,
arg_str0("p", "port", NULL, "Serial port to connect to, else retry the last used one"),
arg_u64_0("b", "baud", "<dec>", "Baudrate"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
int p_len = FILE_PATH_SIZE;
char port[FILE_PATH_SIZE] = {0};
CLIGetStrWithReturn(ctx, 1, (uint8_t *)port, &p_len);
uint32_t baudrate = arg_get_u32_def(ctx, 2, USART_BAUD_RATE);
CLIParserFree(ctx);
if (baudrate == 0) {
PrintAndLogEx(WARNING, "Baudrate can't be zero");
return PM3_EINVARG;
}
// default back to previous used serial port
if (strlen(port) == 0) {
if (strlen(conn.serial_port_name) == 0) {
return usage_hw_connect();
PrintAndLogEx(WARNING, "Must specify a serial port");
return PM3_EINVARG;
}
memcpy(port, conn.serial_port_name, sizeof(port));
}
@@ -683,16 +853,16 @@ static int CmdConnect(const char *Cmd) {
static command_t CommandTable[] = {
{"-------------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("Hardware") " -----------------------"},
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"connect", CmdConnect, AlwaysAvailable, "connect Proxmark3 to serial port"},
{"connect", CmdConnect, AlwaysAvailable, "Connect Proxmark3 to serial port"},
{"dbg", CmdDbg, IfPm3Present, "Set Proxmark3 debug level"},
{"detectreader", CmdDetectReader, IfPm3Present, "['l'|'h'] -- Detect external reader field (option 'l' or 'h' to limit to LF or HF)"},
{"detectreader", CmdDetectReader, IfPm3Present, "Detect external reader field"},
{"fpgaoff", CmdFPGAOff, IfPm3Present, "Set FPGA off"},
{"lcd", CmdLCD, IfPm3Lcd, "<HEX command> <count> -- Send command/data to LCD"},
{"lcd", CmdLCD, IfPm3Lcd, "Send command/data to LCD"},
{"lcdreset", CmdLCDReset, IfPm3Lcd, "Hardware reset LCD"},
{"ping", CmdPing, IfPm3Present, "Test if the Proxmark3 is responsive"},
{"readmem", CmdReadmem, IfPm3Present, "[address] -- Read memory at decimal address from flash"},
{"readmem", CmdReadmem, IfPm3Present, "Read memory at decimal address from flash"},
{"reset", CmdReset, IfPm3Present, "Reset the Proxmark3"},
{"setlfdivisor", CmdSetDivisor, IfPm3Present, "<19 - 255> -- Drive LF antenna at 12MHz/(divisor+1)"},
{"setlfdivisor", CmdSetDivisor, IfPm3Present, "Drive LF antenna at 12MHz / (divisor + 1)"},
{"setmux", CmdSetMux, IfPm3Present, "Set the ADC mux to a specific value"},
{"standalone", CmdStandalone, IfPm3Present, "Jump to the standalone mode"},
{"status", CmdStatus, IfPm3Present, "Show runtime status information about the connected Proxmark3"},
@@ -793,7 +963,7 @@ void pm3_version(bool verbose, bool oneliner) {
PrintAndLogEx(NORMAL, "\n [ " _YELLOW_("PROXMARK3") " ]");
if (IfPm3Rdv4Fw() == false) {
PrintAndLogEx(NORMAL, " firmware.................. %s", _YELLOW_("PM3OTHER"));
PrintAndLogEx(NORMAL, " firmware.................. %s", _YELLOW_("PM3GENERIC"));
if (IfPm3FpcUsartHost()) {
PrintAndLogEx(NORMAL, " FPC USART for BT add-on... %s", _GREEN_("present"));
}
+2 -2
View File
@@ -585,8 +585,8 @@ static int CmdEM410xClone(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "lf em 410x clone",
"Writes EM410x ID to a T55x7 or Q5/T5555 tag",
"lf em 410x clone --id 0F0368568B -> write id to T55x7 tag\n"
"lf em 410x clone --id 0F0368568B --q5 -> write id to Q5/T5555 tag"
"lf em 410x clone --uid 0F0368568B -> write id to T55x7 tag\n"
"lf em 410x clone --uid 0F0368568B --q5 -> write id to Q5/T5555 tag"
);
void *argtable[] = {
+12
View File
@@ -344,6 +344,7 @@ static int CmdHIDClone(const char *Cmd) {
arg_strx0("r", "raw", "<hex>", "raw bytes"),
arg_lit0(NULL, "q5", "optional - specify writing to Q5/T5555 tag"),
arg_lit0(NULL, "em", "optional - specify writing to EM4305/4469 tag"),
arg_str0(NULL, "bin", "<bin>", "Binary string i.e 0001001001"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
@@ -365,6 +366,12 @@ static int CmdHIDClone(const char *Cmd) {
bool q5 = arg_get_lit(ctx, 7);
bool em = arg_get_lit(ctx, 8);
int bin_len = 63;
uint8_t bin[70] = {0};
CLIGetStrWithReturn(ctx, 9, bin, &bin_len);
CLIParserFree(ctx);
if (q5 && em) {
@@ -372,6 +379,11 @@ static int CmdHIDClone(const char *Cmd) {
return PM3_EINVARG;
}
if (bin_len > 127) {
PrintAndLogEx(ERR, "Binary wiegand string must be less than 128 bits");
return PM3_EINVARG;
}
wiegand_message_t packed;
memset(&packed, 0, sizeof(wiegand_message_t));
+30 -30
View File
@@ -7,18 +7,16 @@
//-----------------------------------------------------------------------------
// Low frequency Hitag support
//-----------------------------------------------------------------------------
#include "cmdlfhitag.h"
#include <ctype.h>
#include "cmdparser.h" // command_t
#include "cmdparser.h" // command_t
#include "comms.h"
#include "cmdtrace.h"
#include "commonutil.h"
#include "hitag.h"
#include "fileutils.h" // savefile
#include "protocols.h" // defines
#include "fileutils.h" // savefile
#include "protocols.h" // defines
#include "cliparser.h"
static int CmdHelp(const char *Cmd);
@@ -52,17 +50,7 @@ static size_t nbytes(size_t nbits) {
return (nbits / 8) + ((nbits % 8) > 0);
}
*/
static int usage_hitag_sniff(void) {
PrintAndLogEx(NORMAL, "Sniff traffic between Hitag reader and tag. Use " _YELLOW_("`lf hitag list`")" to view collected data.");
PrintAndLogEx(NORMAL, "Usage: lf hitag sniff [h] ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
// PrintAndLogEx(NORMAL, " p <pwd> Password");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf hitag sniff");
return PM3_SUCCESS;
}
static int usage_hitag_sim(void) {
PrintAndLogEx(NORMAL, "Simulate " _YELLOW_("Hitag2 / HitagS")" transponder");
PrintAndLogEx(NORMAL, "Usage: lf hitag sim [h] [2|s] e|j|b <filename w/o extension>");
@@ -77,15 +65,6 @@ static int usage_hitag_sim(void) {
PrintAndLogEx(NORMAL, " lf hitag sim 2 b lf-hitag-dump");
return PM3_SUCCESS;
}
static int usage_hitag_info(void) {
PrintAndLogEx(NORMAL, "Usage: lf hitag info [h] p <pwd>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " p <pwd> password");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf hitag info");
return PM3_SUCCESS;
}
/*
static int usage_hitag_dump(void) {
PrintAndLogEx(NORMAL, "Usage: lf hitag dump [h] p <pwd> f <name>");
@@ -287,12 +266,23 @@ static int CmdLFHitagList(const char *Cmd) {
}
static int CmdLFHitagSniff(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "lf hitag sniff",
"Sniff traffic between Hitag reader and tag.\n"
"Use " _YELLOW_("`lf hitag list`")" to view collected data.",
"lf hitag sniff"
);
char ctmp = tolower(param_getchar(Cmd, 0));
if (ctmp == 'h') return usage_hitag_sniff();
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_LF_HITAG_SNIFF, NULL, 0);
PrintAndLogEx(HINT, "HINT: Try " _YELLOW_("`lf hitag list`")" to view collected data");
return PM3_SUCCESS;
}
@@ -508,8 +498,18 @@ static bool getHitagUid(uint32_t *uid) {
}
static int CmdLFHitagInfo(const char *Cmd) {
char ctmp = tolower(param_getchar(Cmd, 0));
if (ctmp == 'h') return usage_hitag_info();
CLIParserContext *ctx;
CLIParserInit(&ctx, "lf hitag info",
"Sniff traffic between Hitag reader and tag.",
"lf hitag info"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
// read UID
uint32_t uid = 0;
+483 -487
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -198,7 +198,7 @@ bool tryDetectP1(bool getData);
bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5);
int special(const char *Cmd);
bool AcquireData(uint8_t page, uint8_t block, bool pwdmode, uint32_t password, uint8_t downlink_mode);
uint8_t tryOnePassword(uint32_t password, uint8_t downlink_mode);
uint8_t t55xx_try_one_password(uint32_t password, uint8_t downlink_mode, bool try_all_dl_modes);
void printT55x7Trace(t55x7_tracedata_t data, uint8_t repeat);
void printT5555Trace(t5555_tracedata_t data, uint8_t repeat);
+16
View File
@@ -210,6 +210,22 @@ int CmdsParse(const command_t Commands[], const char *Cmd) {
return PM3_SUCCESS;
}
if (strcmp(Cmd, "star") == 0) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, " \\o o/");
PrintAndLogEx(NORMAL, " v\\ /v");
PrintAndLogEx(NORMAL, " <\\ />");
PrintAndLogEx(NORMAL, " |\\o/|");
PrintAndLogEx(NORMAL, " _\\__o | o__/");
PrintAndLogEx(NORMAL, " |/ \\|");
PrintAndLogEx(NORMAL, " o/ \\o");
PrintAndLogEx(NORMAL, " /v v\\");
PrintAndLogEx(NORMAL, " /> <\\");
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
char cmd_name[128];
memset(cmd_name, 0, sizeof(cmd_name));
+150 -254
View File
@@ -22,75 +22,10 @@
#include "util.h"
#include "fileutils.h"
#include "crc16.h" // crc
#include "cliparser.h" // cliparsing
static int CmdHelp(const char *Cmd);
static int usage_sm_raw(void) {
PrintAndLogEx(NORMAL, "Usage: smart raw [h|r|c] d <0A 0B 0C ... hex>");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " r : do not read response");
PrintAndLogEx(NORMAL, " a : active smartcard without select (reset sc module)");
PrintAndLogEx(NORMAL, " s : active smartcard with select (get ATR)");
PrintAndLogEx(NORMAL, " t : executes TLV decoder if it possible");
PrintAndLogEx(NORMAL, " 0 : use protocol T=0");
PrintAndLogEx(NORMAL, " d <bytes> : bytes to send");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " smart raw s 0 d 00a404000e315041592e5359532e4444463031 - `1PAY.SYS.DDF01` PPSE directory with get ATR");
PrintAndLogEx(NORMAL, " smart raw 0 d 00a404000e325041592e5359532e4444463031 - `2PAY.SYS.DDF01` PPSE directory");
PrintAndLogEx(NORMAL, " smart raw 0 t d 00a4040007a0000000041010 - Mastercard");
PrintAndLogEx(NORMAL, " smart raw 0 t d 00a4040007a0000000031010 - Visa");
return PM3_SUCCESS;
}
static int usage_sm_reader(void) {
PrintAndLogEx(NORMAL, "Usage: smart reader [h|s]");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " s : silent (no messages)");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " smart reader");
return PM3_SUCCESS;
}
static int usage_sm_info(void) {
PrintAndLogEx(NORMAL, "Usage: smart info [h|s]");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " s : silent (no messages)");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " smart info");
return PM3_SUCCESS;
}
static int usage_sm_upgrade(void) {
PrintAndLogEx(NORMAL, "Upgrade RDV4.0 Sim module firmware");
PrintAndLogEx(NORMAL, "Usage: smart upgrade f <file name>");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " f <filename> : firmware file name");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " smart upgrade f ../tools/simmodule/sim011.bin");
return PM3_SUCCESS;
}
static int usage_sm_setclock(void) {
PrintAndLogEx(NORMAL, "Usage: smart setclock [h] c <clockspeed>");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " c <> : clockspeed (0 = 16MHz, 1=8MHz, 2=4MHz) ");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " smart setclock c 2");
return PM3_SUCCESS;
}
static int usage_sm_brute(void) {
PrintAndLogEx(NORMAL, "Tries to bruteforce SFI, using a known list of AID's ");
PrintAndLogEx(NORMAL, "Usage: smart brute [h]");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " t : executes TLV decoder if it possible");
// PrintAndLogEx(NORMAL, " 0 : use protocol T=0");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " smart brute t");
return PM3_SUCCESS;
}
static int smart_loadjson(const char *preferredName, json_t **root) {
json_error_t error;
@@ -402,68 +337,43 @@ static int smart_response(uint8_t *data) {
}
static int CmdSmartRaw(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart raw",
"Sends raw bytes to card",
"smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR\n"
"smart raw -0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory\n"
"smart raw -0 -t -d 00a4040007a0000000041010 -> Mastercard\n"
"smart raw -0 -t -d 00a4040007a0000000031010 -> Visa"
);
int hexlen = 0;
bool active = false;
bool active_select = false;
bool useT0 = false;
uint8_t cmdp = 0;
bool errors = false, reply = true, decodeTLV = false, breakloop = false;
void *argtable[] = {
arg_param_begin,
arg_lit0("r", NULL, "do not read response"),
arg_lit0("a", NULL, "active smartcard without select (reset sc module)"),
arg_lit0("s", NULL, "active smartcard with select (get ATR)"),
arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
arg_lit0("0", NULL, "use protocol T=0"),
arg_str1("d", "data", "<hex>", "bytes to send"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool reply = arg_get_lit(ctx, 1);
bool active = arg_get_lit(ctx, 2);
bool active_select = arg_get_lit(ctx, 3);
bool decode_tlv = arg_get_lit(ctx, 4);
bool use_t0 = arg_get_lit(ctx, 5);
int dlen = 0;
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
int res = CLIParamHexToBuf(arg_get_str(ctx, 6), data, sizeof(data), &dlen);
CLIParserFree(ctx);
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_sm_raw();
case 'r':
reply = false;
cmdp++;
break;
case 'a':
active = true;
cmdp++;
break;
case 's':
active_select = true;
cmdp++;
break;
case 't':
decodeTLV = true;
cmdp++;
break;
case '0':
useT0 = true;
cmdp++;
break;
case 'd': {
switch (param_gethex_to_eol(Cmd, cmdp + 1, data, sizeof(data), &hexlen)) {
case 1:
PrintAndLogEx(WARNING, "Invalid HEX value.");
return PM3_EINVARG;
case 2:
PrintAndLogEx(WARNING, "Too many bytes. Max %zu bytes", sizeof(data));
return PM3_EINVARG;
case 3:
PrintAndLogEx(WARNING, "Hex must have even number of digits.");
return PM3_EINVARG;
}
cmdp++;
breakloop = true;
break;
}
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
if (breakloop)
break;
if (res) {
PrintAndLogEx(FAILED, "Error parsing bytes");
return PM3_EINVARG;
}
//Validations
if (errors || cmdp == 0) return usage_sm_raw();
uint8_t flags = SC_LOG;
if (active || active_select) {
@@ -472,15 +382,15 @@ static int CmdSmartRaw(const char *Cmd) {
flags |= SC_SELECT;
}
if (hexlen > 0) {
if (useT0)
if (dlen > 0) {
if (use_t0)
flags |= SC_RAW_T0;
else
flags |= SC_RAW;
}
clearCommandBuffer();
SendCommandOLD(CMD_SMART_RAW, flags, hexlen, 0, data, hexlen);
SendCommandOLD(CMD_SMART_RAW, flags, dlen, 0, data, dlen);
// reading response from smart card
if (reply) {
@@ -499,13 +409,13 @@ static int CmdSmartRaw(const char *Cmd) {
data[4] = buf[1];
clearCommandBuffer();
SendCommandMIX(CMD_SMART_RAW, 0, hexlen, 0, data, hexlen);
SendCommandMIX(CMD_SMART_RAW, 0, dlen, 0, data, dlen);
len = smart_response(buf);
data[4] = 0;
}
if (decodeTLV && len > 4)
if (decode_tlv && len > 4)
TLVPrintFromBuffer(buf, len - 2);
else {
if (len > 16) {
@@ -523,37 +433,28 @@ static int CmdSmartRaw(const char *Cmd) {
}
static int CmdSmartUpgrade(const char *Cmd) {
PrintAndLogEx(WARNING, "WARNING - Sim module firmware upgrade.");
PrintAndLogEx(WARNING, "A dangerous command, do wrong and you could brick the sim module");
PrintAndLogEx(INFO, "-------------------------------------------------------------------");
PrintAndLogEx(WARNING, _RED_("WARNING") " - sim module firmware upgrade");
PrintAndLogEx(WARNING, _RED_("A dangerous command, do wrong and you could brick the sim module"));
PrintAndLogEx(INFO, "-------------------------------------------------------------------");
PrintAndLogEx(NORMAL, "");
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart upgrade",
"Upgrade RDV4.0 sim module firmware",
"smart upgrade -f sim011.bin"
);
void *argtable[] = {
arg_param_begin,
arg_str1("f", "file", "<filename>", "firmware file name"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
int fnlen = 0;
char filename[FILE_PATH_SIZE] = {0};
uint8_t cmdp = 0;
bool errors = false;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'f':
if (param_getstr(Cmd, cmdp + 1, filename, FILE_PATH_SIZE) >= FILE_PATH_SIZE) {
PrintAndLogEx(FAILED, "Filename too long");
errors = true;
break;
}
cmdp += 2;
break;
case 'h':
return usage_sm_upgrade();
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors || cmdp == 0) return usage_sm_upgrade();
CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, sizeof(filename), &fnlen);
CLIParserFree(ctx);
char *bin_extension = filename;
char *dot_position = NULL;
@@ -623,7 +524,8 @@ static int CmdSmartUpgrade(const char *Cmd) {
}
free(hashstring);
PrintAndLogEx(SUCCESS, "Sim module firmware uploading to PM3");
PrintAndLogEx(INFO, _GREEN_("Don\'t turn off your PM3!"));
PrintAndLogEx(SUCCESS, "Sim module firmware uploading to PM3...");
PacketResponseNG resp;
@@ -669,7 +571,7 @@ static int CmdSmartUpgrade(const char *Cmd) {
PrintAndLogEx(INPLACE, "%d bytes sent", bytes_sent);
}
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(SUCCESS, "Sim module firmware updating, don\'t turn off your PM3!");
PrintAndLogEx(SUCCESS, "Sim module firmware updating...");
// trigger the firmware upgrade
clearCommandBuffer();
@@ -700,37 +602,35 @@ static int CmdSmartUpgrade(const char *Cmd) {
}
static int CmdSmartInfo(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false, silent = false;
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart info",
"Extract more detailed information from smart card.",
"smart info -v"
);
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_sm_info();
case 's':
silent = true;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
cmdp++;
}
//Validations
if (errors) return usage_sm_info();
void *argtable[] = {
arg_param_begin,
arg_lit0("v", "verbose", "verbose"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool verbose = arg_get_lit(ctx, 1);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_SMART_ATR, NULL, 0);
PacketResponseNG resp;
if (!WaitForResponseTimeout(CMD_SMART_ATR, &resp, 2500)) {
if (!silent) PrintAndLogEx(WARNING, "smart card select failed");
if (verbose) {
PrintAndLogEx(WARNING, "smart card select failed");
}
return PM3_ETIMEOUT;
}
if (resp.status != PM3_SUCCESS) {
if (!silent) PrintAndLogEx(WARNING, "smart card select failed");
if (verbose) {
PrintAndLogEx(WARNING, "smart card select failed");
}
return PM3_ESOFT;
}
@@ -772,37 +672,36 @@ static int CmdSmartInfo(const char *Cmd) {
}
static int CmdSmartReader(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false, silent = false;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_sm_reader();
case 's':
silent = true;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
cmdp++;
}
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart reader",
"Act as a smart card reader.",
"smart reader"
);
//Validations
if (errors) return usage_sm_reader();
void *argtable[] = {
arg_param_begin,
arg_lit0("v", "verbose", "verbose"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool verbose = arg_get_lit(ctx, 1);
CLIParserFree(ctx);
clearCommandBuffer();
SendCommandNG(CMD_SMART_ATR, NULL, 0);
PacketResponseNG resp;
if (!WaitForResponseTimeout(CMD_SMART_ATR, &resp, 2500)) {
if (!silent) PrintAndLogEx(WARNING, "smart card select failed");
if (verbose) {
PrintAndLogEx(WARNING, "smart card select failed");
}
return PM3_ETIMEOUT;
}
if (resp.status != PM3_SUCCESS) {
if (!silent) PrintAndLogEx(WARNING, "smart card select failed");
if (verbose) {
PrintAndLogEx(WARNING, "smart card select failed");
}
return PM3_ESOFT;
}
smart_card_atr_t card;
@@ -813,34 +712,42 @@ static int CmdSmartReader(const char *Cmd) {
}
static int CmdSmartSetClock(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
uint8_t new_clk = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_sm_setclock();
case 'c':
new_clk = param_get8ex(Cmd, cmdp + 1, 2, 10);
if (new_clk > 2)
errors = true;
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart setclock",
"Set clock speed for smart card interface.",
"smart setclock --4mhz\n"
"smart setclock --16mhz"
);
void *argtable[] = {
arg_param_begin,
arg_lit0(NULL, "16mhz", "16 MHz clock speed"),
arg_lit0(NULL, "8mhz", "8 MHz clock speed"),
arg_lit0(NULL, "4mhz", "4 MHz clock speed"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
bool c16 = arg_get_lit(ctx, 1);
bool c8 = arg_get_lit(ctx, 2);
bool c4 = arg_get_lit(ctx, 3);
CLIParserFree(ctx);
if ((c16 + c8 + c4) > 1) {
PrintAndLogEx(WARNING, "Only one clock speed can be used at a time");
return PM3_EINVARG;
}
//Validations
if (errors || cmdp == 0) return usage_sm_setclock();
struct {
uint32_t new_clk;
} PACKED payload;
payload.new_clk = new_clk;
if (c16)
payload.new_clk = 0;
else if (c8)
payload.new_clk = 1;
else if (c4)
payload.new_clk = 2;
clearCommandBuffer();
SendCommandNG(CMD_SMART_SETCLOCK, (uint8_t *)&payload, sizeof(payload));
@@ -855,15 +762,15 @@ static int CmdSmartSetClock(const char *Cmd) {
return PM3_ESOFT;
}
switch (new_clk) {
switch (payload.new_clk) {
case 0:
PrintAndLogEx(SUCCESS, "Clock changed to 16MHz giving 10800 baudrate");
PrintAndLogEx(SUCCESS, "Clock changed to " _GREEN_("16") " MHz giving " _GREEN_("10800") " baudrate");
break;
case 1:
PrintAndLogEx(SUCCESS, "Clock changed to 8MHz giving 21600 baudrate");
PrintAndLogEx(SUCCESS, "Clock changed to " _GREEN_("8") " MHz giving " _GREEN_("21600") " baudrate");
break;
case 2:
PrintAndLogEx(SUCCESS, "Clock changed to 4MHz giving 86400 baudrate");
PrintAndLogEx(SUCCESS, "Clock changed to " _GREEN_("4") " MHz giving " _GREEN_("86400") " baudrate");
break;
default:
break;
@@ -1000,33 +907,22 @@ static void smart_brute_options(bool decodeTLV) {
}
static int CmdSmartBruteforceSFI(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart brute",
"Tries to bruteforce SFI, using a known list of AID's",
"smart brute -t"
);
uint8_t cmdp = 0;
bool errors = false, decodeTLV = false; //, useT0 = false;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_sm_brute();
case 't':
decodeTLV = true;
cmdp++;
break;
/*
case '0':
useT0 = true;
cmdp++;
break;
*/
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors) return usage_sm_brute();
void *argtable[] = {
arg_param_begin,
arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
// arg_lit0("0", NULL, "use protocol T=0"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool decode_tlv = arg_get_lit(ctx, 1);
// bool use_t0 = arg_get_lit(ctx, 2);
CLIParserFree(ctx);
const char *SELECT = "00a40400%02zu%s";
@@ -1119,11 +1015,11 @@ static int CmdSmartBruteforceSFI(const char *Cmd) {
PrintAndLogEx(SUCCESS, "\nAID %s | %s | %s", aid, vendor, name);
smart_brute_options(decodeTLV);
smart_brute_options(decode_tlv);
smart_brute_prim();
smart_brute_sfi(decodeTLV);
smart_brute_sfi(decode_tlv);
PrintAndLogEx(SUCCESS, "\nSFI brute force done\n");
}
@@ -1144,7 +1040,7 @@ static command_t CommandTable[] = {
{"info", CmdSmartInfo, IfPm3Smartcard, "Tag information"},
{"reader", CmdSmartReader, IfPm3Smartcard, "Act like an IS07816 reader"},
{"raw", CmdSmartRaw, IfPm3Smartcard, "Send raw hex data to tag"},
{"upgrade", CmdSmartUpgrade, AlwaysAvailable, "Upgrade sim module firmware"},
{"upgrade", CmdSmartUpgrade, AlwaysAvailable, "Upgrade sim module firmware"},
{"setclock", CmdSmartSetClock, IfPm3Smartcard, "Set clock speed"},
{"brute", CmdSmartBruteforceSFI, IfPm3Smartcard, "Bruteforce SFI"},
{NULL, NULL, NULL, NULL}
+218 -378
View File
@@ -13,9 +13,9 @@
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "cmdparser.h" // command_t
#include "commonutil.h" // ARRAYLEN
#include "cliparser.h" //
#include "commonutil.h" // ARRAYLEN
#include "comms.h"
#include "util_posix.h"
#include "usart_defs.h"
@@ -23,134 +23,6 @@
static int CmdHelp(const char *Cmd);
static int usage_usart_bt_pin(void) {
PrintAndLogEx(NORMAL, "Change BT add-on PIN");
PrintAndLogEx(NORMAL, "WARNING: this requires");
PrintAndLogEx(NORMAL, " 1) BTpower to be turned ON");
PrintAndLogEx(NORMAL, " 2) BT add-on to NOT be connected");
PrintAndLogEx(NORMAL, " => the add-on blue LED must blink");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart btpin [h] d NNNN");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " d NNNN Desired PIN");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Example:");
PrintAndLogEx(NORMAL, " usart btpin d 1234");
PrintAndLogEx(NORMAL, "expected output: nothing");
return PM3_SUCCESS;
}
static int usage_usart_bt_factory(void) {
PrintAndLogEx(NORMAL, "Reset BT add-on to factory settings");
PrintAndLogEx(NORMAL, _RED_("WARNING: process only if strictly needed!"));
PrintAndLogEx(NORMAL, "This requires");
PrintAndLogEx(NORMAL, " 1) BTpower to be turned ON");
PrintAndLogEx(NORMAL, " 2) BT add-on to NOT be connected");
PrintAndLogEx(NORMAL, " => the add-on blue LED must blink");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart btfactory [h]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
return PM3_SUCCESS;
}
static int usage_usart_tx(void) {
PrintAndLogEx(NORMAL, "Send string over USART");
PrintAndLogEx(NORMAL, _RED_("WARNING: it will have side-effects if used in USART HOST mode!"));
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart tx [h] d \"string\"");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " d string string to send");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " usart tx d \"AT+VERSION\"");
PrintAndLogEx(NORMAL, " usart tx d \"AT+VERSION\\r\\n\"");
PrintAndLogEx(NORMAL, "expected output: nothing");
return PM3_SUCCESS;
}
static int usage_usart_txhex(void) {
PrintAndLogEx(NORMAL, "Send bytes over USART");
PrintAndLogEx(NORMAL, _RED_("WARNING: it will have side-effects if used in USART HOST mode!"));
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart txhex [h] d <bytes>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " d <bytes> bytes to send");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " usart txhex d 504d33620a80000000010100f09f988ef09fa5b36233");
PrintAndLogEx(NORMAL, "expected output: nothing");
return PM3_SUCCESS;
}
static int usage_usart_rx(void) {
PrintAndLogEx(NORMAL, "Receive string over USART [t <timeout>]");
PrintAndLogEx(NORMAL, _RED_("WARNING: it will have side-effects if used in USART HOST mode!"));
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart rx [h]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " t <timeout> timeout in ms, default is 0ms");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "expected output: Received string");
return PM3_SUCCESS;
}
static int usage_usart_rxhex(void) {
PrintAndLogEx(NORMAL, "Receive bytes over USART");
PrintAndLogEx(NORMAL, _RED_("WARNING: it will have side-effects if used in USART HOST mode!"));
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart rxhex [h] [t <timeout>]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " t <timeout> timeout in ms, default is 0ms");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "expected output: Received bytes");
return PM3_SUCCESS;
}
static int usage_usart_txrx(void) {
PrintAndLogEx(NORMAL, "Send string over USART and wait for response");
PrintAndLogEx(NORMAL, _YELLOW_("WARNING: if used in USART HOST mode, you can only send AT commands"));
PrintAndLogEx(NORMAL, _YELLOW_("to add-on when BT connection is not established (LED needs to be blinking)"));
PrintAndLogEx(NORMAL, _RED_("Any other usage in USART HOST mode will have side-effects!"));
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart txrx [h] [t <timeout>] d \"string\"");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " t <timeout> timeout in ms, default is 1000ms");
PrintAndLogEx(NORMAL, " d string string to send");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " Talking to the BT add-on (when no connection):");
PrintAndLogEx(NORMAL, " usart txrx d \"AT+VERSION\"");
PrintAndLogEx(NORMAL, " Talking to a target requiring longer time and end-of-line chars:");
PrintAndLogEx(NORMAL, " usart txrx t 2000 d \"AT+SOMESTUFF\\r\\n\"");
PrintAndLogEx(NORMAL, "expected output: Received string");
return PM3_SUCCESS;
}
static int usage_usart_config(void) {
PrintAndLogEx(NORMAL, "Configure USART");
PrintAndLogEx(NORMAL, _RED_("WARNING: it will have side-effects if used in USART HOST mode!"));
PrintAndLogEx(NORMAL, "The changes are not permanent, restart Proxmark3 to get default settings back.");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: usart config [h] [b <baudrate>] [p <N|O|E>]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " b <baudrate> Baudrate");
PrintAndLogEx(NORMAL, " p <N|O|E> Parity (None/Odd/Even)");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " usart config b 9600");
PrintAndLogEx(NORMAL, " usart config b 9600 p N");
PrintAndLogEx(NORMAL, " usart config p E");
return PM3_SUCCESS;
}
static int usart_tx(uint8_t *data, size_t len) {
clearCommandBuffer();
SendCommandNG(CMD_USART_TX, data, len);
@@ -221,51 +93,45 @@ static int set_usart_config(uint32_t baudrate, uint8_t parity) {
}
static int CmdUsartConfig(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
uint32_t baudrate = 0;
uint8_t parity = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_config();
case 'p':
switch (tolower(param_getchar(Cmd, cmdp + 1))) {
case 'n':
parity = 'N';
break;
case 'o':
parity = 'O';
break;
case 'e':
parity = 'E';
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp + 1));
errors = true;
break;
}
cmdp += 2;
break;
case 'b':
baudrate = param_get32ex(Cmd, cmdp + 1, 0, 10);
if (baudrate == 0) {
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp + 1));
errors = true;
}
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors || ((baudrate == 0) && (parity == 0))) {
usage_usart_config();
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart config",
"Configure USART.\n"
"WARNING: it will have side-effects if used in USART HOST mode!\n"
"The changes are not permanent, restart Proxmark3 to get default settings back.",
"usart config -b 9600\n"
"usart config -b 9600 --none\n"
"usart config -E"
);
void *argtable[] = {
arg_param_begin,
arg_u64_0("b", "baud", "<dec>", "baudrate"),
arg_lit0("N", "none", "mone parity"),
arg_lit0("E", "even", "even parity"),
arg_lit0("O", "odd", "odd parity"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
uint32_t baudrate = arg_get_u32_def(ctx, 1, 0);
bool pn = arg_get_lit(ctx, 2);
bool pe = arg_get_lit(ctx, 3);
bool po = arg_get_lit(ctx, 4);
CLIParserFree(ctx);
if ((pn + pe + po) > 1) {
PrintAndLogEx(WARNING, "Only one parity can be used at a time");
return PM3_EINVARG;
}
uint8_t parity = 0;
if (pn)
parity = 'N';
else if (po)
parity = 'O';
else if (pe)
parity = 'E';
return set_usart_config(baudrate, parity);
}
@@ -292,28 +158,30 @@ static int usart_bt_testcomm(uint32_t baudrate, uint8_t parity) {
}
static int CmdUsartBtFactory(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart btfactory",
"Reset BT add-on to factory settings\n"
"This requires\n"
" 1) BTpower to be turned ON\n"
" 2) BT add-on to NOT be connected\n"
" => the add-on blue LED must blink\n\n"
_RED_("WARNING:") _CYAN_(" process only if strictly needed!"),
"usart btfactory"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
// take care to define compatible settings:
# define BTADDON_BAUD_AT "AT+BAUD8"
# define BTADDON_BAUD_NUM "115200"
uint8_t cmdp = 0;
bool errors = false;
uint32_t baudrate = 0;
uint8_t parity = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_bt_factory();
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors) {
usage_usart_bt_factory();
return PM3_EINVARG;
}
if (USART_BAUD_RATE != atoi(BTADDON_BAUD_NUM)) {
PrintAndLogEx(WARNING, _RED_("WARNING:") " current Proxmark3 firmware has default USART baudrate = %i", USART_BAUD_RATE);
@@ -476,40 +344,37 @@ static int CmdUsartBtFactory(const char *Cmd) {
}
static int CmdUsartBtPin(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
char pin[5] = {0};
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart btpin",
"Change BT add-on PIN.\n"
"WARNING: this requires\n"
" 1) BTpower to be turned ON\n"
" 2) BT add-on to NOT be connected\n"
" => the add-on blue LED must blink",
"usart btpin -p 1234"
);
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_bt_pin();
case 'd':
if (param_getstr(Cmd, cmdp + 1, pin, sizeof(pin)) != sizeof(pin) - 1) {
PrintAndLogEx(FAILED, "PIN has wrong length, must be 4 digits");
errors = true;
break;
}
for (size_t i = 0; i < sizeof(pin) - 1; i++) {
if ((pin[i] < '0') || (pin[i] > '9')) {
PrintAndLogEx(FAILED, "PIN has wrong char \"%c\", must be 4 digits", pin[i]);
errors = true;
break;
}
}
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
void *argtable[] = {
arg_param_begin,
arg_str1("p", "pin", "<dec>", "Desired PIN number (4 digits)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
int plen = 4;
char pin[5] = { 0, 0, 0, 0, 0 };
CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)pin, sizeof(pin), &plen);
CLIParserFree(ctx);
if (plen != 4) {
PrintAndLogEx(FAILED, "PIN must be 4 digits");
return PM3_EINVARG;
}
//Validations
if (errors || cmdp == 0) {
usage_usart_bt_pin();
return PM3_EINVARG;
for (uint8_t i = 0; i < plen; i++) {
if (isdigit(pin[i]) == false) {
PrintAndLogEx(FAILED, "PIN must be 4 digits");
return PM3_EINVARG;
}
}
char string[6 + sizeof(pin)] = {0};
@@ -537,222 +402,197 @@ static int CmdUsartBtPin(const char *Cmd) {
}
static int CmdUsartTX(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
char string[PM3_CMD_DATA_SIZE] = {0};
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart tx",
"Send string over USART.\n"
"WARNING: it will have side-effects if used in USART HOST mode!",
"usart tx -d \"AT+VERSION\"\n"
"usart tx -d \"AT+VERSION\\r\\n\""
);
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_tx();
case 'd':
if (param_getstr(Cmd, cmdp + 1, string, sizeof(string)) >= sizeof(string)) {
PrintAndLogEx(FAILED, "String too long");
errors = true;
break;
}
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors || cmdp == 0) {
usage_usart_tx();
return PM3_EINVARG;
}
char string2[PM3_CMD_DATA_SIZE] = {0};
void *argtable[] = {
arg_param_begin,
arg_str1("d", "data", NULL, "string to send"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
int slen = 0;
char s[PM3_CMD_DATA_SIZE] = {0};
CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)s, sizeof(s), &slen);
CLIParserFree(ctx);
char clean[PM3_CMD_DATA_SIZE] = {0};
size_t i2 = 0;
size_t n = strlen(string);
size_t n = strlen(s);
// strip / replace
for (size_t i = 0; i < n; i++) {
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == '\\')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == '\\')) {
i++;
string2[i2++] = '\\';
clean[i2++] = '\\';
continue;
}
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == '"')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == '"')) {
i++;
string2[i2++] = '"';
clean[i2++] = '"';
continue;
}
if (string[i] == '"') {
if (s[i] == '"') {
continue;
}
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == 'r')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == 'r')) {
i++;
string2[i2++] = '\r';
clean[i2++] = '\r';
continue;
}
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == 'n')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == 'n')) {
i++;
string2[i2++] = '\n';
clean[i2++] = '\n';
continue;
}
string2[i2++] = string[i];
clean[i2++] = s[i];
}
return usart_tx((uint8_t *)string2, strlen(string2));
return usart_tx((uint8_t *)clean, strlen(clean));
}
static int CmdUsartRX(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
uint32_t waittime = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_rx();
case 't':
waittime = param_get32ex(Cmd, cmdp + 1, 0, 10);
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors) {
usage_usart_rx();
return PM3_EINVARG;
}
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart rx",
"Receive string over USART.\n"
"WARNING: it will have side-effects if used in USART HOST mode!\n",
"usart rx -t 2000 -> 2 second timeout"
);
void *argtable[] = {
arg_param_begin,
arg_u64_0("t", "timeout", "<dec>", "timeout in ms, default is 0ms"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint32_t waittime = arg_get_u32_def(ctx, 1, 0);
CLIParserFree(ctx);
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0;
int ret = usart_rx(data, &len, waittime);
if (ret != PM3_SUCCESS)
return ret;
PrintAndLogEx(NORMAL, "RX:%.*s", (int)len, data);
PrintAndLogEx(SUCCESS, "RX:%.*s", (int)len, data);
return PM3_SUCCESS;
}
static int CmdUsartTXRX(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
char string[PM3_CMD_DATA_SIZE] = {0};
uint32_t waittime = 1000;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_txrx();
case 'd':
if (param_getstr(Cmd, cmdp + 1, string, sizeof(string)) >= sizeof(string)) {
PrintAndLogEx(FAILED, "String too long");
errors = true;
break;
}
cmdp += 2;
break;
case 't':
waittime = param_get32ex(Cmd, cmdp + 1, 1000, 10);
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors || cmdp == 0) {
usage_usart_txrx();
return PM3_EINVARG;
}
char string2[PM3_CMD_DATA_SIZE] = {0};
size_t i2 = 0;
size_t n = strlen(string);
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart txrx",
"Send string over USART and wait for response.\n"
"WARNING: if used in USART HOST mode, you can only send AT commands\n"
"to add-on when BT connection is not established (LED needs to be blinking)\n"
_RED_("Any other usage in USART HOST mode will have side-effects!"),
"usart txrx -d \"AT+VERSION\" -> Talking to BT add-on (when no connection)\n"
"usart txrx -t 2000 -d \"AT+SOMESTUFF\\r\\n\" -> Talking to a target requiring longer time and end-of-line chars"
);
void *argtable[] = {
arg_param_begin,
arg_u64_0("t", "timeout", "<dec>", "timeout in ms, default is 1000 ms"),
arg_str1("d", "data", NULL, "string to send"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint32_t waittime = arg_get_u32_def(ctx, 1, 1000);
int slen = 0;
char s[PM3_CMD_DATA_SIZE] = {0};
CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)s, sizeof(s), &slen);
CLIParserFree(ctx);
char clean[PM3_CMD_DATA_SIZE] = {0};
size_t j = 0;
size_t n = strlen(s);
for (size_t i = 0; i < n; i++) {
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == '\\')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == '\\')) {
i++;
string2[i2++] = '\\';
clean[j++] = '\\';
continue;
}
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == '"')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == '"')) {
i++;
string2[i2++] = '"';
clean[j++] = '"';
continue;
}
if (string[i] == '"') {
if (s[i] == '"') {
continue;
}
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == 'r')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == 'r')) {
i++;
string2[i2++] = '\r';
clean[j++] = '\r';
continue;
}
if ((i < n - 1) && (string[i] == '\\') && (string[i + 1] == 'n')) {
if ((i < n - 1) && (s[i] == '\\') && (s[i + 1] == 'n')) {
i++;
string2[i2++] = '\n';
clean[j++] = '\n';
continue;
}
string2[i2++] = string[i];
clean[j++] = s[i];
}
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0;
PrintAndLogEx(NORMAL, "TX (%3zu):%.*s", strlen(string2), (int)strlen(string2), string2);
int ret = usart_txrx((uint8_t *)string2, strlen(string2), data, &len, waittime);
PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s", strlen(clean), (int)strlen(clean), clean);
int ret = usart_txrx((uint8_t *)clean, strlen(clean), data, &len, waittime);
if (ret != PM3_SUCCESS)
return ret;
PrintAndLogEx(NORMAL, "RX (%3zu):%.*s", len, (int)len, data);
PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
return PM3_SUCCESS;
}
static int CmdUsartTXhex(const char *Cmd) {
int hexlen, len = 0;
uint8_t cmdp = 0;
bool errors = false;
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart txhex",
"Send bytes over USART.\n"
"WARNING: it will have side-effects if used in USART HOST mode!",
"usart txhex -d 504d33620a80000000010100f09f988ef09fa5b36233"
);
void *argtable[] = {
arg_param_begin,
arg_str1("d", "data", "<hex>", "bytes to send"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
int dlen = 0;
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_txhex();
case 'd':
if (param_gethex_ex(Cmd, cmdp + 1, data, &hexlen)) {
PrintAndLogEx(ERR, "Error parsing bytes");
return PM3_EINVARG;
}
len = hexlen >> 1;
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors || cmdp == 0) {
usage_usart_txhex();
int res = CLIParamHexToBuf(arg_get_str(ctx, 1), data, sizeof(data), &dlen);
CLIParserFree(ctx);
if (res) {
PrintAndLogEx(FAILED, "Error parsing bytes");
return PM3_EINVARG;
}
return usart_tx(data, len);
return usart_tx(data, dlen);
}
static int CmdUsartRXhex(const char *Cmd) {
uint8_t cmdp = 0;
bool errors = false;
uint32_t waittime = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_usart_rxhex();
case 't':
waittime = param_get32ex(Cmd, cmdp + 1, 0, 10);
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
//Validations
if (errors) {
usage_usart_rxhex();
return PM3_EINVARG;
}
CLIParserContext *ctx;
CLIParserInit(&ctx, "usart rxhex",
"Receive bytes over USART.\n"
"WARNING: it will have side-effects if used in USART HOST mode!\n",
"usart rxhex -t 2000 -> 2 second timeout"
);
void *argtable[] = {
arg_param_begin,
arg_u64_0("t", "timeout", "<dec>", "timeout in ms, default is 0ms"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint32_t waittime = arg_get_u32_def(ctx, 1, 0);
CLIParserFree(ctx);
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0;
@@ -781,7 +621,7 @@ static command_t CommandTable[] = {
static int CmdHelp(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CmdsHelp(CommandTable);
return 0;
return PM3_SUCCESS;
}
int CmdUsart(const char *Cmd) {
+10
View File
@@ -19,6 +19,7 @@
#include <mbedtls/cmac.h>
#include <mbedtls/pk.h>
#include <mbedtls/ecdsa.h>
#include <mbedtls/sha1.h>
#include <mbedtls/sha256.h>
#include <mbedtls/sha512.h>
#include <mbedtls/ctr_drbg.h>
@@ -93,6 +94,15 @@ static int fixed_rand(void *rng_state, unsigned char *output, size_t len) {
return 0;
}
int sha1hash(uint8_t *input, int length, uint8_t *hash) {
if (!hash || !input)
return 1;
mbedtls_sha1(input, length, hash);
return 0;
}
int sha256hash(uint8_t *input, int length, uint8_t *hash) {
if (!hash || !input)
return 1;
+1
View File
@@ -21,6 +21,7 @@ int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int l
int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length);
int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length);
int sha1hash(uint8_t *input, int length, uint8_t *hash);
int sha256hash(uint8_t *input, int length, uint8_t *hash);
int sha512hash(uint8_t *input, int length, uint8_t *hash);
+7 -9
View File
@@ -195,12 +195,12 @@ bool create_path(const char *dirname) {
return true;
}
*/
/*
bool setDefaultPath (savePaths_t pathIndex,const char *Path) {
bool setDefaultPath(savePaths_t pathIndex, const char *Path) {
if (pathIndex < spItemCount) {
if ((Path == NULL) && (session.defaultPaths[pathIndex] != NULL)) {
free (session.defaultPaths[pathIndex]);
free(session.defaultPaths[pathIndex]);
session.defaultPaths[pathIndex] = NULL;
}
@@ -208,13 +208,11 @@ bool setDefaultPath (savePaths_t pathIndex,const char *Path) {
session.defaultPaths[pathIndex] = (char *)realloc(session.defaultPaths[pathIndex], strlen(Path) + 1);
strcpy(session.defaultPaths[pathIndex], Path);
}
} else {
return false;
return true;
}
return true;
return false;
}
*/
static char *filenamemcopy(const char *preferredName, const char *suffix) {
if (preferredName == NULL) return NULL;
if (suffix == NULL) return NULL;
@@ -735,7 +733,7 @@ int createMfcKeyDump(const char *preferredName, uint8_t sectorsCnt, sector_t *e_
fflush(f);
fclose(f);
PrintAndLogEx(SUCCESS, "Found keys have been dumped to " _YELLOW_("%s"), fileName);
PrintAndLogEx(INFO, " OBS! --> 0xFFFFFFFFFFFF <-- has been inserted for unknown keys.");
PrintAndLogEx(INFO, "FYI! --> " _YELLOW_("0xFFFFFFFFFFFF") " <-- has been inserted for unknown keys where " _YELLOW_("res") " is " _YELLOW_("0"));
free(fileName);
return PM3_SUCCESS;
}
+1 -1
View File
@@ -78,7 +78,7 @@ typedef enum {
int fileExists(const char *filename);
//bool create_path(const char *dirname);
//bool setDefaultPath (savePaths_t pathIndex,const char *Path); // set a path in the path list session.defaultPaths
bool setDefaultPath(savePaths_t pathIndex, const char *Path); // set a path in the path list session.defaultPaths
char *newfilenamemcopy(const char *preferredName, const char *suffix);
+456 -547
View File
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -711,7 +711,7 @@ void pm3_init(void) {
session.help_dump_mode = false;
session.incognito = false;
session.supports_colors = false;
session.emoji_mode = ALTTEXT;
session.emoji_mode = EMO_ALTTEXT;
session.stdinOnTTY = false;
session.stdoutOnTTY = false;
@@ -769,14 +769,14 @@ int main(int argc, char *argv[]) {
session.stdinOnTTY = isatty(STDIN_FILENO);
session.stdoutOnTTY = isatty(STDOUT_FILENO);
session.supports_colors = false;
session.emoji_mode = ALTTEXT;
session.emoji_mode = EMO_ALTTEXT;
if (session.stdinOnTTY && session.stdoutOnTTY) {
#if defined(__linux__) || defined(__APPLE__)
session.supports_colors = true;
session.emoji_mode = EMOJI;
session.emoji_mode = EMO_EMOJI;
#elif defined(_WIN32)
session.supports_colors = DetectWindowsAnsiSupport();
session.emoji_mode = ALTTEXT;
session.emoji_mode = EMO_ALTTEXT;
#endif
}
for (int i = 1; i < argc; i++) {
@@ -976,7 +976,7 @@ int main(int argc, char *argv[]) {
// even if prefs, we disable colors if stdin or stdout is not a TTY
if ((! session.stdinOnTTY) || (! session.stdoutOnTTY)) {
session.supports_colors = false;
session.emoji_mode = ALTTEXT;
session.emoji_mode = EMO_ALTTEXT;
}
// Let's take a baudrate ok for real UART, USB-CDC & BT don't use that info anyway
+15 -14
View File
@@ -22,6 +22,7 @@
#include <stdlib.h>
#ifdef HAVE_READLINE
//Load readline after stdio.h
#include <readline/readline.h>
#endif
@@ -201,14 +202,14 @@ void PrintAndLogEx(logLevel_t level, const char *fmt, ...) {
};
switch (level) {
case ERR:
if (session.emoji_mode == EMOJI)
if (session.emoji_mode == EMO_EMOJI)
strncpy(prefix, "[" _RED_("!!") "] :rotating_light: ", sizeof(prefix) - 1);
else
strncpy(prefix, "[" _RED_("!!") "] ", sizeof(prefix) - 1);
stream = stderr;
break;
case FAILED:
if (session.emoji_mode == EMOJI)
if (session.emoji_mode == EMO_EMOJI)
strncpy(prefix, "[" _RED_("-") "] :no_entry: ", sizeof(prefix) - 1);
else
strncpy(prefix, "[" _RED_("-") "] ", sizeof(prefix) - 1);
@@ -223,7 +224,7 @@ void PrintAndLogEx(logLevel_t level, const char *fmt, ...) {
strncpy(prefix, "[" _GREEN_("+") "] ", sizeof(prefix) - 1);
break;
case WARNING:
if (session.emoji_mode == EMOJI)
if (session.emoji_mode == EMO_EMOJI)
strncpy(prefix, "[" _CYAN_("!") "] :warning: ", sizeof(prefix) - 1);
else
strncpy(prefix, "[" _CYAN_("!") "] ", sizeof(prefix) - 1);
@@ -232,7 +233,7 @@ void PrintAndLogEx(logLevel_t level, const char *fmt, ...) {
strncpy(prefix, "[" _YELLOW_("=") "] ", sizeof(prefix) - 1);
break;
case INPLACE:
if (session.emoji_mode == EMOJI) {
if (session.emoji_mode == EMO_EMOJI) {
strncpy(prefix, spinner_emoji[PrintAndLogEx_spinidx], sizeof(prefix) - 1);
PrintAndLogEx_spinidx++;
if (PrintAndLogEx_spinidx >= ARRAYLEN(spinner_emoji))
@@ -387,7 +388,7 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) {
#endif
if ((g_printAndLog & PRINTANDLOG_LOG) && logging && logfile) {
memcpy_filter_emoji(buffer3, buffer2, sizeof(buffer2), ALTTEXT);
memcpy_filter_emoji(buffer3, buffer2, sizeof(buffer2), EMO_ALTTEXT);
if (filter_ansi) { // already done
fprintf(logfile, "%s", buffer3);
} else {
@@ -465,12 +466,12 @@ static bool emojify_token(const char *token, uint8_t token_length, const char **
while (EmojiTable[i].alias && EmojiTable[i].emoji) {
if ((strlen(EmojiTable[i].alias) == token_length) && (0 == memcmp(EmojiTable[i].alias, token, token_length))) {
switch (mode) {
case EMOJI: {
case EMO_EMOJI: {
*emojified_token = EmojiTable[i].emoji;
*emojified_token_length = strlen(EmojiTable[i].emoji);
break;
}
case ALTTEXT: {
case EMO_ALTTEXT: {
int j = 0;
*emojified_token_length = 0;
while (EmojiAltTable[j].alias && EmojiAltTable[i].alttext) {
@@ -483,11 +484,11 @@ static bool emojify_token(const char *token, uint8_t token_length, const char **
}
break;
}
case ERASE: {
case EMO_NONE: {
*emojified_token_length = 0;
break;
}
case ALIAS: { // should never happen
case EMO_ALIAS: { // should never happen
return false;
}
}
@@ -507,7 +508,7 @@ static bool token_charset(uint8_t c) {
}
void memcpy_filter_emoji(void *dest, const void *src, size_t n, emojiMode_t mode) {
if (mode == ALIAS) {
if (mode == EMO_ALIAS) {
memcpy(dest, src, n);
} else {
// tokenize emoji
@@ -657,7 +658,7 @@ void print_progress(size_t count, uint64_t max, barMode_t style) {
"\xe2\x96\x88",
};
uint8_t mode = (session.emoji_mode == EMOJI);
uint8_t mode = (session.emoji_mode == EMO_EMOJI);
const char *block[] = {"#", "\xe2\x96\x88"};
// use a 3-byte space in emoji mode to ease computations
@@ -689,7 +690,7 @@ void print_progress(size_t count, uint64_t max, barMode_t style) {
char *cbar = calloc(collen, sizeof(uint8_t));
// Add colors
if ( session.supports_colors ) {
if (session.supports_colors) {
int p60 = unit * (width * 60 / 100);
int p20 = unit * (width * 20 / 100);
snprintf(cbar, collen, _GREEN_("%.*s"), p60, bar);
@@ -709,12 +710,12 @@ void print_progress(size_t count, uint64_t max, barMode_t style) {
break;
}
case STYLE_MIXED: {
sprintf(buffer, "%s [ %zu mV / %2u V / %2u Vmax ]", cbar, count, (uint32_t)(count / 1000), (uint32_t)(max / 1000));
sprintf(buffer, "%s [ %zu mV / %2u V / %2u Vmax ] ", cbar, count, (uint32_t)(count / 1000), (uint32_t)(max / 1000));
printf("\b%c[2K\r[" _YELLOW_("=")"] %s ", 27, buffer);
break;
}
case STYLE_VALUE: {
printf("[" _YELLOW_("=")"] %zu mV / %2u V / %2u Vmax\r", count, (uint32_t)(count / 1000), (uint32_t)(max / 1000));
printf("[" _YELLOW_("=")"] %zu mV / %2u V / %2u Vmax \r", count, (uint32_t)(count / 1000), (uint32_t)(max / 1000));
break;
}
}
+3 -3
View File
@@ -24,10 +24,10 @@ extern "C" {
typedef enum {STYLE_BAR, STYLE_MIXED, STYLE_VALUE} barMode_t;
typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t;
typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t;
typedef enum emojiMode {EMO_ALIAS, EMO_EMOJI, EMO_ALTTEXT, EMO_NONE} emojiMode_t;
typedef enum clientdebugLevel {cdbOFF, cdbSIMPLE, cdbFULL} clientdebugLevel_t;
// typedef enum devicedebugLevel {ddbOFF, ddbERROR, ddbINFO, ddbDEBUG, ddbEXTENDED} devicedebugLevel_t;
//typedef enum savePaths {spDefault, spDump, spTrace, spItemCount} savePaths_t; // last item spItemCount used to auto map to number of files
typedef enum savePaths {spDefault, spDump, spTrace, spItemCount} savePaths_t; // last item spItemCount used to auto map to number of files
typedef struct {int x; int y; int h; int w;} qtWindow_t;
typedef struct {
@@ -44,7 +44,7 @@ typedef struct {
qtWindow_t overlay;
bool overlay_sliders;
bool incognito;
// char *defaultPaths[spItemCount]; // Array should allow loop searching for files
char *defaultPaths[spItemCount]; // Array should allow loop searching for files
clientdebugLevel_t client_debug_level;
barMode_t bar_mode;
// uint8_t device_debug_level;