Files
proxmark3/client/src/cmdtrace.c
T
iceman1001andClaude Opus 5.5 d11643c8f2 trace list: show a negative frame delay time instead of wrapping it
The -r and --frame delay was an unsigned difference, so a frame starting
before the end of the previous one, or after the timer restarted, eg
between the sessions of traces/hf_14b_xerox_info.trace or the frames of
traces/lf_HitagS256_dump.trace, showed as about 4294967296 instead of
-83024 or -117.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 14:59:13 +07:00

2068 lines
81 KiB
C

//-----------------------------------------------------------------------------
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// Trace commands
//-----------------------------------------------------------------------------
#include "cmdtrace.h"
#include <ctype.h>
#include "cmdparser.h" // command_t
#include "protocols.h"
#include "parity.h" // oddparity
#include "cmdhflist.h" // annotations
#include "commonutil.h" // ARRAYLEN
#include "mifare/mifaredefault.h" // mifare default key array
#include "comms.h" // for sending cmds to device. GetFromBigBuf
#include "fileutils.h" // for saveFile
#include "cmdlfhitag.h" // annotate hitag
#include "cmdlfhitaghts.h" // annotate hitags
#include "cmdlfhitagu.h" // annotate hitagu
#include "pm3_cmd.h" // tracelog_hdr_t
#include "cliparser.h" // args..
#include "crc16.h" // check_crc
static int CmdHelp(const char *Cmd);
// trace pointer
static uint8_t *gs_trace;
static uint32_t gs_traceLen = 0;
typedef enum {
TRACE_CRC_FAIL = 0,
TRACE_CRC_OK = 1,
TRACE_CRC_NONE = 2,
TRACE_CRC_A_OK = 3,
TRACE_CRC_B_OK = 4,
} trace_crc_status_t;
static bool is_last_record(uint32_t tracepos, uint32_t traceLen) {
return ((tracepos + TRACELOG_HDR_LEN) >= traceLen);
}
static bool next_record_is_response(uint32_t tracepos, uint8_t *trace) {
const tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos);
return (hdr->isResponse);
}
// the record at tracepos, NULL when it does not fit in the trace
static const tracelog_hdr_t *get_record(uint32_t tracepos, uint32_t traceLen, const uint8_t *trace) {
if (is_last_record(tracepos, traceLen)) {
return NULL;
}
const tracelog_hdr_t *hdr = (const tracelog_hdr_t *)(trace + tracepos);
if (tracepos + TRACELOG_HDR_LEN + hdr->data_len + TRACELOG_PARITY_LEN(hdr) > traceLen) {
return NULL;
}
return hdr;
}
// bits of a Hitag frame whose last byte holds last_bits of them, 0 for a whole byte
static uint16_t hitag_frame_bits(uint16_t data_len, uint8_t last_bits) {
if (data_len == 0) {
return 0;
}
if ((last_bits == 0) || (last_bits > 8)) {
return data_len * 8;
}
return ((data_len - 1) * 8) + last_bits;
}
// Topaz reader commands are at most 16 bytes long (RSEG/READ8/WRITE-*8:
// cmd + adds + 8 data bytes + 4 UID bytes + 2 CRC bytes)
#define MAX_TOPAZ_READER_CMD_LEN 16
// a 14a frame that lasts less than this has 7 bits or fewer
#define ISO14A_SHORT_FRAME_DURATION (1056 + 32)
// in a Topaz trace, the reader's last frame was an ISO14443-A one: the answer
// to it is one too
static bool gs_topaz_14a_exchange = false;
// the frames of a Topaz command, the 7 bit command code included; 0 for an
// unknown code
static uint8_t topaz_reader_cmd_len(uint8_t code) {
switch (code) {
case TOPAZ_RID:
case TOPAZ_RALL:
case TOPAZ_READ:
case TOPAZ_WRITE_E:
case TOPAZ_WRITE_NE:
return 9;
case TOPAZ_RSEG:
case TOPAZ_READ8:
case TOPAZ_WRITE_E8:
case TOPAZ_WRITE_NE8:
return MAX_TOPAZ_READER_CMD_LEN;
default:
return 0;
}
}
static bool merge_topaz_reader_frames(uint32_t timestamp, uint32_t *duration, uint32_t *tracepos, uint32_t traceLen,
uint8_t *trace, const uint8_t *frame, uint8_t *topaz_reader_command, uint16_t *data_len) {
uint32_t last_timestamp = timestamp + *duration;
if ((*data_len != 1) || (frame[0] == TOPAZ_WUPA) || (frame[0] == TOPAZ_REQA)) return false;
// a command starts with its 7 bit code: an 8 bit frame is an operand left
// from a command cut short
if (*duration >= ISO14A_SHORT_FRAME_DURATION) return false;
memcpy(topaz_reader_command, frame, *data_len);
// stop at the frames the command code takes, or before when a reader sent
// fewer: the next command starts with its 7 bit code, an operand has 8 bits
uint8_t cmd_len = topaz_reader_cmd_len(frame[0]);
if (cmd_len == 0) {
cmd_len = MAX_TOPAZ_READER_CMD_LEN;
}
while ((*data_len < cmd_len) && !is_last_record(*tracepos, traceLen) && !next_record_is_response(*tracepos, trace)) {
const tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + *tracepos);
if ((hdr->data_len != 1) || (hdr->duration < ISO14A_SHORT_FRAME_DURATION)) {
break;
}
if (*tracepos + TRACELOG_HDR_LEN + hdr->data_len + TRACELOG_PARITY_LEN(hdr) > traceLen) {
break;
}
memcpy(topaz_reader_command + *data_len, hdr->frame, hdr->data_len);
*data_len += hdr->data_len;
last_timestamp = hdr->timestamp + hdr->duration;
*tracepos += TRACELOG_HDR_LEN + hdr->data_len + TRACELOG_PARITY_LEN(hdr);
}
*duration = last_timestamp - timestamp;
return true;
}
static uint8_t calc_pos(const uint8_t *d) {
// PCB [CID] [NAD] [INF] CRC CRC
uint8_t pos = 1;
if ((d[0] & 0x08) == 0x08) // cid byte following
pos++;
if ((d[0] & 0x04) == 0x04) // nad byte following
pos++;
return pos;
}
// offset of the challenge in a DESFire auth reply, native puts the AF status before it
static uint8_t mfdes_chall_pos(const uint8_t *d, uint8_t long_jmp) {
return calc_pos(d) + ((long_jmp == 1) ? 1 : 0);
}
// Discard the client side trace buffer
void ClearTraceBuffer(void) {
free(gs_trace);
gs_trace = NULL;
gs_traceLen = 0;
}
// Copy an existing buffer into client trace buffer
// I think this is cleaner than further globalizing gs_trace, and may lend itself to more modularity later?
bool ImportTraceBuffer(const uint8_t *trace_src, uint32_t trace_len) {
if (trace_len == 0 || trace_src == NULL) return (false);
ClearTraceBuffer();
gs_trace = calloc(trace_len, sizeof(uint8_t));
if (gs_trace == NULL) {
return (false);
}
memcpy(gs_trace, trace_src, trace_len);
gs_traceLen = trace_len;
return (true);
}
static uint8_t extract_uid[10] = {0};
static uint8_t extract_uidlen = 0;
static uint8_t extract_epurse[8] = {0};
#define SKIP_TO_NEXT(a) (TRACELOG_HDR_LEN + (a)->data_len + TRACELOG_PARITY_LEN((a)))
static uint32_t extractChall_ev2(uint32_t tracepos, uint32_t traceLen, uint8_t *trace, uint8_t cmdpos, uint8_t long_jmp) {
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if ((next_hdr == NULL) || (next_hdr->data_len != 21)) {
return 0;
}
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
PrintAndLogEx(INFO, "1499999999 %s " NOLF, sprint_hex_inrow(next_hdr->frame + 1, 16));
next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr == NULL) {
PrintAndLogEx(NORMAL, "");
return tracepos;
}
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
if ((next_hdr->data_len >= cmdpos + long_jmp + 32) && (next_hdr->frame[cmdpos] == MFDES_ADDITIONAL_FRAME)) {
PrintAndLogEx(NORMAL, "%s", sprint_hex_inrow(next_hdr->frame + cmdpos + long_jmp, 32));
} else {
PrintAndLogEx(NORMAL, "");
}
return tracepos;
}
static uint32_t extractChallenges(uint32_t tracepos, uint32_t traceLen, uint8_t *trace) {
// sanity check
if (is_last_record(tracepos, traceLen)) {
return traceLen;
}
tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos);
uint16_t data_len = hdr->data_len;
uint8_t *frame = hdr->frame;
// sanity check tracking position is less than available trace size
if (tracepos + TRACELOG_HDR_LEN + data_len + TRACELOG_PARITY_LEN(hdr) > traceLen) {
PrintAndLogEx(DEBUG, "trace pos offset %"PRIu64 " larger than reported tracelen %u",
tracepos + TRACELOG_HDR_LEN + data_len + TRACELOG_PARITY_LEN(hdr),
traceLen
);
return traceLen;
}
// set trace position
tracepos += SKIP_TO_NEXT(hdr);
// sanity check data frame length
if (data_len == 0) {
return tracepos;
}
// extract MFC
/*
switch (frame[0]) {
case MIFARE_AUTH_KEYA: {
if (data_len > 3) {
}
break;
}
case MIFARE_AUTH_KEYB: {
if (data_len > 3) {
}
break;
}
}
*/
// extract UL-C KEY when written.
switch (frame[0]) {
case MIFARE_ULC_AUTH_1: {
if (data_len != 4) {
break;
}
// time to skip to next
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr == NULL) {
break;
}
tracepos += SKIP_TO_NEXT(next_hdr);
if (next_hdr->data_len != 11) {
break;
}
if (next_hdr->frame[0] != MIFARE_ULC_AUTH_2) {
break;
}
PrintAndLogEx(INFO, "Found a MFU-C authententication attempt");
PrintAndLogEx(INFO, "3DES %s " NOLF, sprint_hex_inrow(next_hdr->frame + 1, 8));
next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr != NULL) {
tracepos += SKIP_TO_NEXT(next_hdr);
}
if ((next_hdr != NULL) && (next_hdr->data_len == 19) && (next_hdr->frame[0] == MIFARE_ULC_AUTH_2)) {
PrintAndLogEx(NORMAL, "%s", sprint_hex_inrow(next_hdr->frame + 1, 16));
} else {
PrintAndLogEx(NORMAL, "( " _RED_("partial") " )");
}
return tracepos;
}
}
// extract iCLASS
// --csn 9655a400f8ff12e0 --epurse f0ffffffffffffff --macs 0000000089cb984b
if (hdr->isResponse == false) {
uint8_t c = frame[0] & 0x0F;
switch (c) {
case ICLASS_CMD_SELECT: {
// SELECT CSN[8], answered by CSN[8] CRC[2]
if (data_len != 9) {
break;
}
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr == NULL) {
break;
}
if ((next_hdr->data_len != 10) || (check_crc(CRC_ICLASS, next_hdr->frame, 10) == false)) {
break;
}
tracepos += SKIP_TO_NEXT(next_hdr);
memcpy(extract_uid, next_hdr->frame, 8);
extract_uidlen = 8;
break;
}
case ICLASS_CMD_READCHECK: {
// get epurse
if (data_len == 2 && frame[1] == 2) {
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr == NULL) {
break;
}
tracepos += SKIP_TO_NEXT(next_hdr);
if (next_hdr->data_len < 8) {
break;
}
memcpy(extract_epurse, next_hdr->frame, 8);
}
break;
}
case ICLASS_CMD_CHECK: {
// get macs, CHECK has no CRC unlike a 14a CL2 SELECT 95 70 UID BCC CRC
if ((data_len == 9) && (check_crc(CRC_14443_A, frame, data_len) == false)) {
if (extract_uidlen == 8) {
PrintAndLogEx(INFO, "hf iclass lookup --csn %s " NOLF, sprint_hex_inrow(extract_uid, extract_uidlen));
PrintAndLogEx(NORMAL, "--epurse %s " NOLF, sprint_hex_inrow(extract_epurse, 8));
PrintAndLogEx(NORMAL, "--macs %s " NOLF, sprint_hex_inrow(frame + 1, 8));
PrintAndLogEx(NORMAL, "-f iclass_default_keys.dic");
return tracepos;
}
}
break;
}
}
}
// extract UID
switch (frame[0]) {
case ISO14443A_CMD_ANTICOLL_OR_SELECT: {
// 93 20 = Anticollision (usage: 9320 - answer: 4bytes UID+1byte UID-bytes-xor)
// 93 50 = Bit oriented anti-collision (usage: 9350+ up to 5bytes, 9350 answer - up to 5bytes UID+BCC)
// 93 70 = Select (usage: 9370+5bytes 9370 answer - answer: 1byte SAK)
if ((data_len >= 6) && (frame[1] == 0x70)) {
if (frame[2] == 0x88) {
memcpy(extract_uid, frame + 3, 3);
extract_uidlen = 3;
} else {
memcpy(extract_uid, frame + 2, 4);
extract_uidlen = 4;
PrintAndLogEx(INFO, "UID... " _YELLOW_("%s"), sprint_hex_inrow(extract_uid, extract_uidlen));
}
}
break;
}
case ISO14443A_CMD_ANTICOLL_OR_SELECT_2: {
// 95 20 = Anticollision of cascade level2
// 95 50 = Bit oriented anti-collision level2
// 95 70 = Select of cascade level2
if ((data_len >= 6) && (frame[1] == 0x70)) {
// cascade level 2 starts at UID byte 3, level 3 at byte 6
if (frame[2] == 0x88) {
memcpy(extract_uid + 3, frame + 3, 3);
extract_uidlen = 6;
} else {
memcpy(extract_uid + 3, frame + 2, 4);
extract_uidlen = 7;
PrintAndLogEx(INFO, "UID... " _YELLOW_("%s"), sprint_hex_inrow(extract_uid, extract_uidlen));
}
}
break;
}
case ISO14443A_CMD_ANTICOLL_OR_SELECT_3: {
// 97 20 = Anticollision of cascade level3
// 97 50 = Bit oriented anti-collision level3
// 97 70 = Select of cascade level3
if ((data_len >= 6) && (frame[1] == 0x70)) {
memcpy(extract_uid + 6, frame + 2, 4);
extract_uidlen = 10;
PrintAndLogEx(INFO, "UID... " _YELLOW_("%s"), sprint_hex_inrow(extract_uid, extract_uidlen));
}
break;
}
}
// extract DESFIRE, from an ISO14443-4 I-block
if ((frame[0] & 0xE2) != 0x02) {
return tracepos;
}
if (hdr->isResponse) {
return tracepos;
}
// PCB [CID] [NAD] [CLA] INS ... CRC CRC
uint8_t pos = calc_pos(frame);
bool wrapped = (pos < data_len) && (frame[pos] == MFDES_NATIVE_ISO7816_WRAP_CLA);
if (wrapped) {
pos++;
}
// wrapped: INS P1 P2 Lc keyNo, native: CMD keyNo
uint8_t long_jmp = (wrapped) ? 4 : 1;
// the command and its key number, before the CRC
if (pos + long_jmp + 2 >= data_len) {
return tracepos;
}
switch (frame[pos]) {
case MFDES_AUTHENTICATE: {
// Assume wrapped or unwrapped
PrintAndLogEx(INFO, "Found a MFDES Auth NATIVE (keyNo %d)", frame[pos + long_jmp]);
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if ((next_hdr == NULL) || (next_hdr->isResponse == false)) {
break;
}
uint8_t cpos = mfdes_chall_pos(next_hdr->frame, long_jmp);
if (next_hdr->data_len < cpos + 8 + 2) {
break;
}
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
PrintAndLogEx(INFO, "DES 1499999999 %s " NOLF, sprint_hex_inrow(next_hdr->frame + cpos, 8));
next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr != NULL) {
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
}
if ((next_hdr != NULL) && (next_hdr->data_len >= pos + long_jmp + 16) && (next_hdr->frame[pos] == MFDES_ADDITIONAL_FRAME)) {
PrintAndLogEx(NORMAL, "%s", sprint_hex_inrow(next_hdr->frame + pos + long_jmp, 16));
} else {
PrintAndLogEx(NORMAL, "");
}
return tracepos; // AUTHENTICATE_NATIVE
}
case MFDES_AUTHENTICATE_ISO: {
// Assume wrapped or unwrapped
PrintAndLogEx(INFO, "Found a MFDES Auth ISO (keyNo %d)", frame[pos + long_jmp]);
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if ((next_hdr == NULL) || (next_hdr->isResponse == false)) {
break;
}
uint8_t cpos = mfdes_chall_pos(next_hdr->frame, long_jmp);
if (next_hdr->data_len < cpos + 8 + 2) {
break;
}
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
// wrapped replies end with SW 91 AF before the CRC
uint8_t sw_len = (long_jmp == 1) ? 0 : 2;
uint8_t tdea = 8;
if (next_hdr->data_len >= cpos + 16 + sw_len + 2) {
tdea = 16;
PrintAndLogEx(INFO, "3TDEA 1499999999 %s " NOLF, sprint_hex_inrow(next_hdr->frame + cpos, tdea));
} else {
PrintAndLogEx(INFO, "2TDEA 1499999999 %s " NOLF, sprint_hex_inrow(next_hdr->frame + cpos, tdea));
}
next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr != NULL) {
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
}
if ((next_hdr != NULL) && (next_hdr->data_len >= pos + long_jmp + (tdea << 1)) && (next_hdr->frame[pos] == MFDES_ADDITIONAL_FRAME)) {
PrintAndLogEx(NORMAL, "%s", sprint_hex_inrow(next_hdr->frame + pos + long_jmp, (tdea << 1)));
} else {
PrintAndLogEx(NORMAL, "");
}
return tracepos; // AUTHENTICATE_STANDARD
}
case MFDES_AUTHENTICATE_AES: {
// Assume wrapped or unwrapped
PrintAndLogEx(INFO, "Found a MFDES Auth AES (keyNo %d)", frame[pos + long_jmp]);
const tracelog_hdr_t *next_hdr = get_record(tracepos, traceLen, trace);
if ((next_hdr == NULL) || (next_hdr->isResponse == false)) {
break;
}
uint8_t cpos = mfdes_chall_pos(next_hdr->frame, long_jmp);
if (next_hdr->data_len < cpos + 16 + 2) {
break;
}
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
PrintAndLogEx(INFO, "AES 1499999999 %s " NOLF, sprint_hex_inrow(next_hdr->frame + cpos, 16));
next_hdr = get_record(tracepos, traceLen, trace);
if (next_hdr != NULL) {
tracepos += TRACELOG_HDR_LEN + next_hdr->data_len + TRACELOG_PARITY_LEN(next_hdr);
}
if ((next_hdr != NULL) && (next_hdr->data_len >= pos + long_jmp + 32) && (next_hdr->frame[pos] == MFDES_ADDITIONAL_FRAME)) {
PrintAndLogEx(NORMAL, "%s", sprint_hex_inrow(next_hdr->frame + pos + long_jmp, 32));
} else {
PrintAndLogEx(NORMAL, "");
}
return tracepos;
}
case MFDES_AUTHENTICATE_EV2F: {
PrintAndLogEx(INFO, "Found a MFDES Auth EV2 First");
uint32_t tmp = extractChall_ev2(tracepos, traceLen, trace, pos, long_jmp);
if (tmp == 0)
break;
else
return tmp;
}
case MFDES_AUTHENTICATE_EV2NF: {
PrintAndLogEx(INFO, "Found a MFDES Auth EV2 Non First");
uint32_t tmp = extractChall_ev2(tracepos, traceLen, trace, pos, long_jmp);
if (tmp == 0)
break;
else
return tmp;
}
}
return tracepos;
}
static uint32_t printHexLine(uint32_t tracepos, uint32_t traceLen, uint8_t *trace, uint8_t protocol) {
// sanity check
if (is_last_record(tracepos, traceLen)) return traceLen;
tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos);
if (tracepos + TRACELOG_HDR_LEN + hdr->data_len + TRACELOG_PARITY_LEN(hdr) > traceLen) {
return traceLen;
}
//set trace position
tracepos += TRACELOG_HDR_LEN + hdr->data_len + TRACELOG_PARITY_LEN(hdr);
if (hdr->data_len == 0) {
PrintAndLogEx(NORMAL, "<empty trace - possible error>");
return tracepos;
}
uint32_t ret;
switch (protocol) {
case ISO_14443A: {
/* https://www.kaiser.cx/pcap-iso14443.html defines a pseudo header:
* version (currently 0x00), event (Rdr: 0xfe, Tag: 0xff), length (2 bytes)
* to convert to pcap(ng) via text2pcap or to import into Wireshark
* we use format timestamp, newline, offset (0x000000), pseudo header, data
* `text2pcap -t "%S." -l 264 -n <input-text-file> <output-pcapng-file>`
*/
int line_len = (hdr->data_len * 3) + 1;
char line[line_len];
char *ptr = line;
for (int i = 0; i < hdr->data_len ; i++) {
ptr += snprintf(ptr, line_len, "%02x ", hdr->frame[i]);
line_len -= 3;
if (line_len <= 0) {
break;
}
}
char data_len_str[5];
char temp_str1[3] = {0};
char temp_str2[3] = {0};
snprintf(data_len_str, sizeof(data_len_str), "%04x", hdr->data_len);
memmove(temp_str1, data_len_str, 2);
memmove(temp_str2, data_len_str + 2, 2);
PrintAndLogEx(NORMAL, "0.%010u", hdr->timestamp);
PrintAndLogEx(NORMAL, "000000 00 %s %s %s %s",
(hdr->isResponse ? "ff" : "fe"),
temp_str1,
temp_str2,
line);
ret = tracepos;
break;
}
default:
PrintAndLogEx(NORMAL, "Currently only 14a supported");
ret = traceLen;
break;
}
return ret;
}
// wrap the two hex chars at pos in cyan, returns the escape bytes added
static int trace_colour_hex(char *line, size_t line_size, size_t pos) {
size_t len = strlen(line);
size_t pre = strlen(ANSI_CYAN);
size_t post = strlen(AEND);
if (pos + 2 > len || len + pre + post + 1 > line_size) {
return 0;
}
char hex[2] = {line[pos], line[pos + 1]};
memmove(line + pos + 2 + pre + post, line + pos + 2, len - pos - 2 + 1);
memcpy(line + pos, ANSI_CYAN, pre);
memcpy(line + pos + pre, hex, 2);
memcpy(line + pos + pre + 2, AEND, post);
return (int)(pre + post);
}
static uint32_t printTraceLine(uint32_t tracepos, uint32_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles, bool markCRCBytes, uint32_t *prev_eot, bool use_us,
const uint64_t *mfDicKeys, uint32_t mfDicKeysCount) {
// sanity check
if (is_last_record(tracepos, traceLen)) {
PrintAndLogEx(DEBUG, "last record triggered. t-pos: %u t-len %u", tracepos, traceLen);
return traceLen;
}
uint32_t end_of_transmission_timestamp = 0;
uint8_t topaz_reader_command[MAX_TOPAZ_READER_CMD_LEN];
// Shared by every annotate* function below.
// annotateHitagU() and annotateHitagS() accumulate into it without clamping.
// annotateHitagU(): 76 chars for flags PEXT|INV|RFU|NOS|CRCT on a WRITE SINGLE BLOCK
char explanation[80] = {0};
tracelog_hdr_t *first_hdr = (tracelog_hdr_t *)(trace);
tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos);
uint32_t duration = hdr->duration;
uint16_t data_len = hdr->data_len;
if (tracepos + TRACELOG_HDR_LEN + data_len + TRACELOG_PARITY_LEN(hdr) > traceLen) {
PrintAndLogEx(DEBUG, "trace pos offset %"PRIu64 " larger than reported tracelen %u",
tracepos + TRACELOG_HDR_LEN + data_len + TRACELOG_PARITY_LEN(hdr),
traceLen
);
return traceLen;
}
// adjust for different time scales
if (protocol == ICLASS || protocol == ISO_15693) {
duration *= 32;
}
uint8_t *frame = hdr->frame;
uint8_t *parityBytes = hdr->frame + data_len;
// Hitag keeps the bit count of the last byte in the first parity byte, 0 for a whole byte
uint8_t hitag_last_bits = (parityBytes[0] <= 8) ? parityBytes[0] : 0;
tracepos += TRACELOG_HDR_LEN + data_len + TRACELOG_PARITY_LEN(hdr);
bool topaz_merged = false;
if (protocol == TOPAZ && !hdr->isResponse) {
// topaz reader commands come in 1, 9 or 16 separate frames with 7 or 8 Bits each.
// merge them:
if (merge_topaz_reader_frames(hdr->timestamp, &duration, &tracepos, traceLen, trace, frame, topaz_reader_command, &data_len)) {
frame = topaz_reader_command;
topaz_merged = true;
}
}
// a Topaz command comes one byte per frame: a longer reader frame is an
// ISO14443-A one, the HLTA or the anticollision of a multi protocol reader
bool topaz_14a_frame = (protocol == TOPAZ) && (hdr->isResponse == false) && (topaz_merged == false) && (data_len > 1);
if ((protocol == TOPAZ) && (hdr->isResponse == false)) {
gs_topaz_14a_exchange = topaz_14a_frame;
}
bool topaz_14a_answer = (protocol == TOPAZ) && hdr->isResponse && gs_topaz_14a_exchange;
// a lone 8 bit reader frame: an operand of a command cut short, no command code
bool topaz_operand = (protocol == TOPAZ) && (hdr->isResponse == false) && (topaz_merged == false) &&
(data_len == 1) && (hdr->duration >= ISO14A_SHORT_FRAME_DURATION);
// a Topaz command with fewer frames than its code takes, cut by the end of
// the trace or by the reader, carries no CRC to check
bool topaz_cut = topaz_merged && (data_len < topaz_reader_cmd_len(frame[0]));
// an iCLASS trace also holds the ISO15693 frames of a reader that polls
// both: their CRC covers the whole frame, an iCLASS one the bytes after the command
bool iclass_15693_frame = (protocol == ICLASS) && (hdr->isResponse == false) && (data_len >= 3) && (iso15693_CRC_check(frame, data_len) == 1);
//Check the CRC status
trace_crc_status_t crcStatus = TRACE_CRC_NONE;
if (data_len > 2) {
switch (protocol) {
case ICLASS:
crcStatus = (iclass_15693_frame) ? TRACE_CRC_OK : iclass_CRC_check(hdr->isResponse, frame, data_len);
break;
case ISO_14443B:
crcStatus = iso14443B_CRC_check(frame, data_len);
break;
case TOPAZ:
if (topaz_cut) {
crcStatus = TRACE_CRC_NONE;
} else {
crcStatus = (topaz_14a_frame || topaz_14a_answer) ? iso14443A_CRC_check(hdr->isResponse, frame, data_len) : iso14443B_CRC_check(frame, data_len);
}
break;
case FELICA:
// after the B2 4D sync, the CRC covers LEN to the end
crcStatus = felica_CRC_check(frame + 2, data_len - 2);
break;
case PROTO_MIFARE:
case PROTO_MFPLUS:
crcStatus = mifare_CRC_check(hdr->isResponse, frame, data_len);
break;
case ISO_14443A:
case MFDES:
case LTO:
crcStatus = iso14443A_CRC_check(hdr->isResponse, frame, data_len);
break;
case SEOS:
crcStatus = seos_CRC_check(hdr->isResponse, frame, data_len);
break;
case ISO_7816_4:
// A contact ISO 7816-3 frame carries no trailing CRC. T=0 has
// no frame checksum at all, and T=1 keeps its EDC inside the
// block - so running the ISO 14443 A/B CRC checks over one only
// ever produced a red "!!" on every line.
//
// The T=1 LRC is not verified here either: TRACE_CRC_OK/FAIL
// make the renderer below highlight the last *two* bytes as the
// checksum, which would be wrong for a one byte LRC.
crcStatus = TRACE_CRC_NONE;
break;
case PROTO_CALYPSO: {
uint8_t crcA = iso14443A_CRC_check(hdr->isResponse, frame, data_len);
uint8_t crcB = iso14443B_CRC_check(frame, data_len);
if (crcA == TRACE_CRC_OK) {
crcStatus = TRACE_CRC_A_OK;
} else if (crcB == TRACE_CRC_OK) {
crcStatus = TRACE_CRC_B_OK;
} else {
crcStatus = crcA;
}
break;
}
case THINFILM:
frame[data_len - 1] ^= frame[data_len - 2];
frame[data_len - 2] ^= frame[data_len - 1];
frame[data_len - 1] ^= frame[data_len - 2];
crcStatus = iso14443A_CRC_check(true, frame, data_len);
frame[data_len - 1] ^= frame[data_len - 2];
frame[data_len - 2] ^= frame[data_len - 1];
frame[data_len - 1] ^= frame[data_len - 2];
break;
case ISO_15693:
crcStatus = iso15693_CRC_check(frame, data_len);
break;
case PROTO_HITAG1:
case PROTO_HITAGS:
crcStatus = hitag1_CRC_check(frame, hitag_frame_bits(data_len, hitag_last_bits));
break;
case PROTO_HITAGU:
crcStatus = hitagu_CRC_check(frame, hitag_frame_bits(data_len, hitag_last_bits));
break;
case PROTO_HITAG2:
case PROTO_CRYPTORF:
default:
break;
}
} else if (hdr->isResponse == false) {
// an ISO14443-A anticollision answer is told by the request before it,
// ANTICOLL 93 20 among them: the 14a checks see the short frames too
switch (protocol) {
case PROTO_MIFARE:
case PROTO_MFPLUS:
mifare_CRC_check(false, frame, data_len);
break;
case ISO_14443A:
case MFDES:
case LTO:
case SEOS:
iso14443A_CRC_check(false, frame, data_len);
break;
case TOPAZ:
if (topaz_14a_frame) {
iso14443A_CRC_check(false, frame, data_len);
}
break;
default:
break;
}
}
//0 CRC-command, CRC not ok
//1 CRC-command, CRC ok
//2 Not crc-command
// Draw the data column
#define TRACE_MAX_LINES 36
// number of hex bytes to be printed per row (16 data + 2 crc)
#define TRACE_MAX_HEX_BYTES 18
char line[TRACE_MAX_LINES][160] = {{0}};
if (data_len == 0) {
if (protocol == ICLASS && duration == 2048) {
snprintf(line[0], sizeof(line[0]), "<SOF>");
} else if (protocol == ISO_15693 && duration == 512) {
snprintf(line[0], sizeof(line[0]), "<EOF>");
} else {
snprintf(line[0], sizeof(line[0]), "<empty trace - possible error>");
}
}
// uint8_t partialbytebuff = 0;
uint8_t offset = 0;
for (int j = 0; j < data_len && (j / TRACE_MAX_HEX_BYTES) < TRACE_MAX_HEX_BYTES; j++) {
uint8_t parityBits = parityBytes[j >> 3];
if (protocol != LEGIC
&& protocol != ISO_14443B
&& protocol != ISO_15693
&& protocol != ICLASS
&& protocol != ISO_7816_4
&& protocol != PROTO_CALYPSO
&& protocol != PROTO_HITAG1
&& protocol != PROTO_HITAG2
&& protocol != PROTO_HITAGS
&& protocol != PROTO_HITAGU
&& protocol != THINFILM
&& protocol != FELICA
&& protocol != LTO
&& protocol != PROTO_CRYPTORF
&& (hdr->isResponse || protocol == ISO_14443A || protocol == PROTO_MIFARE || protocol == PROTO_MFPLUS || protocol == SEOS)
&& (oddparity8(frame[j]) != ((parityBits >> (7 - (j & 0x0007))) & 0x01))) {
snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02X! ", frame[j]);
} else if (protocol == ICLASS && hdr->isResponse == false && iclass_15693_frame == false) {
uint8_t parity = 0;
for (int i = 0; i < 6; i++) {
parity ^= ((frame[0] >> i) & 1);
}
if (parity == ((frame[0] >> 7) & 1)) {
snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02X ", frame[j]);
} else {
snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02X! ", frame[j]);
}
} else if (((protocol == PROTO_HITAG1) || (protocol == PROTO_HITAG2) || (protocol == PROTO_HITAGS) || (protocol == PROTO_HITAGU))) {
if (j == 0) {
// handle partial bytes. The parity array[0] is used to store number of left over bits from NBYTES
// The bit count now goes in the CRC column, which is unused for
// hitag, so the data field holds nothing but data.
uint8_t nbits = hitag_last_bits;
// only apply this to lesser than one byte
// One leading space, so the hex lines up under the "Data" header.
if (data_len == 1 && nbits != 0) {
snprintf(line[0], 120, " %02X ", frame[0] >> (8 - nbits));
} else {
snprintf(line[0], 120, " %02X ", frame[0]);
}
offset = 1;
} else if ((j % 18) == 0) {
// the next rows start with the same leading space
snprintf(line[j / 18], 120, " %02X ", frame[j]);
} else {
snprintf(line[j / 18] + ((j % 18) * 4) + offset, 120, "%02X ", frame[j]);
}
} else {
snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02X ", frame[j]);
}
}
// the rows above hold TRACE_MAX_HEX_BYTES * TRACE_MAX_HEX_BYTES bytes, a longer frame has its CRC past them
if (markCRCBytes && (data_len > 2) && (data_len <= (TRACE_MAX_HEX_BYTES * TRACE_MAX_HEX_BYTES))) {
// CRC-command
if (((protocol == PROTO_HITAG1) || (protocol == PROTO_HITAGS))) {
// Note that UID REQUEST response has no CRC, but we don't know
// if the response we see is a UID
char *pos1 = line[(data_len - 1) / 18] + (((data_len - 1) % 18) * 4) + offset - 1;
(*pos1) = '[';
char *pos2 = line[(data_len - 1) / 18] + (((data_len - 1) % 18) * 4) + offset + 2;
(*pos2) = ']';
(*(pos2 + 1)) = '\0';
} else {
if (crcStatus == TRACE_CRC_FAIL || crcStatus == TRACE_CRC_OK) {
char *pos1 = line[(data_len - 2) / TRACE_MAX_HEX_BYTES];
int delta = (data_len - 2) % TRACE_MAX_HEX_BYTES ? 1 : 0;
pos1 += (((data_len - 2) % TRACE_MAX_HEX_BYTES) * 4) - delta;
(*(pos1 + 6 + delta)) = '\0';
char *cb_str = str_dup(pos1 + delta);
if (g_session.supports_colors) {
if (crcStatus == TRACE_CRC_FAIL) {
snprintf(pos1, 24, AEND " " _RED_("%s"), cb_str);
} else {
snprintf(pos1, 24, AEND " " _GREEN_("%s"), cb_str);
}
} else {
snprintf(pos1, 9, "[%s]", cb_str);
}
// odd case of second crc byte is alone in a new line
if (strlen(cb_str) < 5) {
free(cb_str);
pos1 = line[((data_len - 2) / TRACE_MAX_HEX_BYTES) + 1];
cb_str = str_dup(pos1);
if (g_session.supports_colors) {
if (crcStatus == TRACE_CRC_FAIL) {
snprintf(pos1, 24, _RED_("%s"), cb_str);
} else {
snprintf(pos1, 24, _GREEN_("%s"), cb_str);
}
} else {
snprintf(pos1, 9, "[%s]", cb_str);
}
}
free(cb_str);
}
}
}
// Draw the CRC column
const char *crcstrings[] = {
[TRACE_CRC_FAIL] = _RED_(" !! "),
[TRACE_CRC_OK] = _GREEN_(" ok "),
[TRACE_CRC_NONE] = " ",
[TRACE_CRC_A_OK] = _GREEN_("A ok"),
[TRACE_CRC_B_OK] = _GREEN_("B ok"),
};
const char *crc = crcstrings[crcStatus];
// Hitag carries no CRC, so the column shows the frame's bit count instead.
//
// It used to be printed as a "%2u: " prefix inside the data field, which cost
// four columns of every Hitag row and pushed the hex out of line with every
// other protocol. The CRC column is exactly four wide and otherwise blank
// here, so the count fits with nothing displaced.
char hitag_nbits[8] = {0};
if ((protocol == PROTO_HITAG1) || (protocol == PROTO_HITAG2) ||
(protocol == PROTO_HITAGS) || (protocol == PROTO_HITAGU)) {
snprintf(hitag_nbits, sizeof(hitag_nbits), "%3u ", hitag_frame_bits(data_len, hitag_last_bits));
crc = hitag_nbits;
}
// mark short bytes (less than 8 Bit + Parity)
if (protocol == ISO_14443A ||
protocol == PROTO_MIFARE ||
protocol == PROTO_MFPLUS ||
protocol == THINFILM) {
// approximated with 128 * (9 * data_len);
uint16_t bitime = ISO14A_SHORT_FRAME_DURATION;
if (duration < bitime) {
uint8_t m = 7;
while (m > 0) {
bitime -= 128;
if (duration > bitime) {
break;
}
m--;
}
// only a one byte frame can be that short, a longer one has a wrong duration
if (data_len == 1) {
line[0][2] = '(';
line[0][3] = m + 0x30;
line[0][4] = ')';
}
}
}
uint32_t previous_end_of_transmission_timestamp = 0;
if (prev_eot) {
if (*prev_eot) {
previous_end_of_transmission_timestamp = *prev_eot;
} else {
previous_end_of_transmission_timestamp = hdr->timestamp;
}
}
end_of_transmission_timestamp = hdr->timestamp + duration;
if (prev_eot) {
*prev_eot = end_of_transmission_timestamp;
}
// Always annotate these protocols both reader/tag messages
switch (protocol) {
case ISO_14443A:
case ISO_7816_4:
case PROTO_FMCOS20:
annotateIso14443a(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case ISO_14443B:
annotateIso14443b(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case PROTO_CALYPSO:
annotateCalypso(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case PROTO_MIFARE:
case PROTO_MFPLUS:
annotateMifare(explanation, sizeof(explanation), frame, data_len, parityBytes, TRACELOG_PARITY_LEN(hdr), hdr->isResponse);
break;
case PROTO_HITAG1:
annotateHitag1(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case PROTO_HITAG2:
annotateHitag2(explanation, sizeof(explanation), frame, data_len, hitag_last_bits, hdr->isResponse, mfDicKeys, mfDicKeysCount, false);
break;
case PROTO_HITAGS:
annotateHitagS(explanation, sizeof(explanation), frame, hitag_frame_bits(data_len, hitag_last_bits), hdr->isResponse);
break;
case FELICA:
annotateFelica(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case PROTO_HITAGU:
annotateHitagU(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case ICLASS:
if (iclass_15693_frame) {
annotateIso15693(explanation, sizeof(explanation), frame, data_len);
} else {
annotateIclass(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
}
break;
case SEOS:
annotateSeos(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
default:
break;
}
if (hdr->isResponse == false) {
switch (protocol) {
case LEGIC:
annotateLegic(explanation, sizeof(explanation), frame, data_len);
break;
case MFDES:
annotateMfDesfire(explanation, sizeof(explanation), frame, data_len);
break;
case PROTO_MFPLUS:
annotateMfPlus(explanation, sizeof(explanation), frame, data_len);
break;
case TOPAZ:
if (topaz_14a_frame) {
annotateIso14443a(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
} else if (topaz_operand) {
snprintf(explanation, sizeof(explanation), "operand");
} else {
annotateTopaz(explanation, sizeof(explanation), frame, data_len);
if (topaz_cut) {
size_t n = strlen(explanation);
snprintf(explanation + n, sizeof(explanation) - n, " (incomplete)");
}
}
break;
case ISO_7816_4:
// trace type "7816" is the contact reader, i.e. `smart list`
annotateIso7816(explanation, sizeof(explanation), frame, data_len, hdr->isResponse, true);
break;
case ISO_15693:
annotateIso15693(explanation, sizeof(explanation), frame, data_len);
break;
case LTO:
annotateLTO(explanation, sizeof(explanation), frame, data_len);
break;
case PROTO_CRYPTORF:
annotateCryptoRF(explanation, sizeof(explanation), frame, data_len);
break;
case PROTO_FMCOS20:
annotateFMCOS20(explanation, sizeof(explanation), frame, data_len);
break;
default:
break;
}
}
// colour SW1 SW2 of an ISO 14443-4 response APDU, right to left so offsets hold
int sw_escapes[TRACE_MAX_LINES] = {0};
if (g_session.supports_colors && hdr->isResponse && data_len >= 4 &&
data_len <= (TRACE_MAX_HEX_BYTES * TRACE_MAX_HEX_BYTES) &&
(protocol == ISO_14443A || protocol == ISO_7816_4 || protocol == PROTO_FMCOS20) &&
annotateIso14443aLastHasSW()) {
for (int k = data_len - 3; k >= data_len - 4; k--) {
int l = k / TRACE_MAX_HEX_BYTES;
sw_escapes[l] += trace_colour_hex(line[l], sizeof(line[l]), (k % TRACE_MAX_HEX_BYTES) * 4);
}
}
int str_padder = 72;
int num_lines = MIN((data_len - 1) / TRACE_MAX_HEX_BYTES + 1, TRACE_MAX_HEX_BYTES);
// Relative timing is shown as its own row, not as a pair of columns.
//
// It used to rename Start/End to Gap/Duration, which meant the two display
// modes could not be read the same way - the same column held an absolute
// timestamp in one and an interval in the other. A frame delay row keeps the
// timestamps meaning one thing everywhere and puts the interval where the
// wait-cycle annotation already puts it, between the frames it separates.
if (prev_eot && (previous_end_of_transmission_timestamp != hdr->timestamp)) {
// signed, a frame can start before the previous one ended or the timer restarted
int64_t fdt = (int64_t)hdr->timestamp - previous_end_of_transmission_timestamp;
// Carry the column rules through, so the row does not break the table.
//
// The width has to be corrected for the colour escapes, which take up
// bytes that %-*s counts but the terminal does not draw - the same
// adjustment the CRC column already makes below.
char fdt_txt[160] = {0};
int visible;
if (use_us) {
visible = snprintf(NULL, 0, " Frame Delay Time %.1f", (float)fdt / 13.56);
snprintf(fdt_txt, sizeof(fdt_txt), " Frame Delay Time " _CYAN_("%.1f"), (float)fdt / 13.56);
} else {
visible = snprintf(NULL, 0, " Frame Delay Time %" PRId64, fdt);
snprintf(fdt_txt, sizeof(fdt_txt), " Frame Delay Time " _CYAN_("%" PRId64), fdt);
}
int fdt_pad = str_padder + (int)strlen(fdt_txt) - visible;
PrintAndLogEx(NORMAL, " %10s | %10s | %s |%-*s | %s| %s",
"", "", " ", fdt_pad, fdt_txt, " ", "");
}
for (int j = 0; j < num_lines ; j++) {
bool last_line = (j == num_lines - 1);
str_padder = 72;
if (j == 0) {
uint32_t time1 = hdr->timestamp - first_hdr->timestamp;
uint32_t time2 = end_of_transmission_timestamp - first_hdr->timestamp;
// ansi codes addes extra chars that needs to be taken in consideration.
if (last_line && (memcmp(crc, "\x20\x20\x20\x20", 4) != 0) && g_session.supports_colors && markCRCBytes) {
str_padder = 85;
}
str_padder += sw_escapes[j];
if (hdr->isResponse) {
// tag row
if (use_us) {
PrintAndLogEx(NORMAL, " %10.1f | %10.1f | Tag |%-*s | %s| %s",
(float)time1 / 13.56,
(float)time2 / 13.56,
str_padder,
line[j],
(last_line) ? crc : " ",
(last_line) ? explanation : ""
);
} else {
PrintAndLogEx(NORMAL, " %10u | %10u | Tag |%-*s | %s| %s",
time1,
time2,
str_padder,
line[j],
(last_line) ? crc : " ",
(last_line) ? explanation : ""
);
}
} else {
// reader row
if (use_us) {
PrintAndLogEx(NORMAL,
_YELLOW_(" %10.1f") " | " _YELLOW_("%10.1f") " | " _YELLOW_("Rdr") " |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"),
(float)time1 / 13.56,
(float)time2 / 13.56,
str_padder,
line[j],
(last_line) ? crc : " ",
(last_line) ? explanation : ""
);
} else {
PrintAndLogEx(NORMAL,
_YELLOW_(" %10u") " | " _YELLOW_("%10u") " | " _YELLOW_("Rdr") " |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"),
time1,
time2,
str_padder,
line[j],
(last_line) ? crc : " ",
(last_line) ? explanation : ""
);
}
}
} else {
if (last_line && (memcmp(crc, "\x20\x20\x20\x20", 4) != 0) && g_session.supports_colors && markCRCBytes) {
str_padder = 85;
// odd case of multiline, and last single byte on empty row has been colorised...
if (strlen(line[j]) < 14) {
str_padder = 81;
}
}
str_padder += sw_escapes[j];
if (hdr->isResponse) {
PrintAndLogEx(NORMAL, " | | |%-*s | %s| %s",
str_padder,
line[j],
last_line ? crc : " ",
last_line ? explanation : ""
);
} else {
PrintAndLogEx(NORMAL, " | | |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"),
str_padder,
line[j],
last_line ? crc : " ",
last_line ? explanation : ""
);
}
}
}
if (protocol == PROTO_MIFARE || protocol == PROTO_MFPLUS) {
uint8_t mfData[32] = {0};
size_t mfDataLen = 0;
if (DecodeMifareData(frame, data_len, parityBytes, hdr->isResponse, mfData, &mfDataLen, mfDicKeys, mfDicKeysCount)) {
memset(explanation, 0x00, sizeof(explanation));
if (protocol == PROTO_MFPLUS) {
annotateMfPlus(explanation, sizeof(explanation), mfData, mfDataLen);
} else {
annotateIso14443a(explanation, sizeof(explanation), mfData, mfDataLen, hdr->isResponse);
}
uint8_t crcc = iso14443A_CRC_check(hdr->isResponse, mfData, mfDataLen);
// iceman: colorise crc bytes here will need a refactor of code from above.
for (int j = 0; j < mfDataLen; j += TRACE_MAX_HEX_BYTES) {
int plen = MIN((mfDataLen - j), TRACE_MAX_HEX_BYTES);
if (hdr->isResponse) {
PrintAndLogEx(NORMAL, " | | * |%-*s | %-4s| %s",
str_padder,
sprint_hex_inrow_spaces(mfData + j, plen, 2),
(crcc == 0 ? _RED_(" !! ") : (crcc == 1 ? _GREEN_(" ok ") : " ")),
explanation);
} else {
PrintAndLogEx(NORMAL, " | | * |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"),
str_padder,
sprint_hex_inrow_spaces(mfData + j, plen, 2),
(crcc == 0 ? _RED_(" !! ") : (crcc == 1 ? _GREEN_(" ok ") : " ")),
explanation);
}
}
}
}
if (protocol == PROTO_HITAG2) {
uint8_t ht2plain[9] = {0};
uint8_t n = 0;
if (hitag2_get_plain(ht2plain, &n)) {
memset(explanation, 0x00, sizeof(explanation));
// handle partial bytes. The parity array[0] is used to store number of left over bits from NBYTES
// This part prints the number of bits in the trace entry for hitag.
uint8_t nbits = hitag_last_bits;
annotateHitag2(explanation, sizeof(explanation), ht2plain, n, nbits, hdr->isResponse, NULL, 0, true);
// iceman: colorise crc bytes here will need a refactor of code from above.
for (int j = 0; j < n && (j / TRACE_MAX_HEX_BYTES) < TRACE_MAX_HEX_BYTES; j++) {
if (j == 0) {
// Bit count goes in the Bit column, same as the frame above.
// One leading space so the hex lines up under "Data".
if ((n == 1) && (nbits != 0)) {
snprintf(line[0], 120, " %02X ", ht2plain[0] >> (8 - nbits));
} else {
snprintf(line[0], 120, " %02X ", ht2plain[0]);
}
offset = 1;
} else {
snprintf(line[j / 18] + ((j % 18) * 4) + offset, 120, "%02X ", ht2plain[j]);
}
}
num_lines = MIN((n - 1) / TRACE_MAX_HEX_BYTES + 1, TRACE_MAX_HEX_BYTES);
char plain_nbits[8] = {0};
snprintf(plain_nbits, sizeof(plain_nbits), "%3u ", hitag_frame_bits(n, nbits));
for (int j = 0; j < num_lines ; j++) {
bool last = (j == num_lines - 1);
if (hdr->isResponse) {
PrintAndLogEx(NORMAL, " | | * |%-*s | %s| %s",
str_padder,
line[j],
(last) ? plain_nbits : " ",
explanation);
} else {
PrintAndLogEx(NORMAL, " | | * |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"),
str_padder,
line[j],
(last) ? plain_nbits : " ",
explanation);
}
}
}
}
if (is_last_record(tracepos, traceLen)) {
return traceLen;
}
if (showWaitCycles && hdr->isResponse == false && next_record_is_response(tracepos, trace)) {
const tracelog_hdr_t *next_hdr = (tracelog_hdr_t *)(trace + tracepos);
uint32_t time1 = end_of_transmission_timestamp - first_hdr->timestamp;
uint32_t time2 = next_hdr->timestamp - first_hdr->timestamp;
if (prev_eot) {
time1 = 0;
time2 = next_hdr->timestamp - end_of_transmission_timestamp;
}
// Same column rules as a data row, so the table is not broken. The pad
// is corrected for the colour escapes, which %-*s counts but the terminal
// does not draw.
// signed, a frame can start before the previous one ended or the timer restarted
int64_t fdt = (int64_t)next_hdr->timestamp - end_of_transmission_timestamp;
char fdt_txt[160] = {0};
int visible;
if (use_us) {
visible = snprintf(NULL, 0, " Frame Delay Time %.1f", (float)fdt / 13.56);
snprintf(fdt_txt, sizeof(fdt_txt), " Frame Delay Time " _CYAN_("%.1f"), (float)fdt / 13.56);
} else {
visible = snprintf(NULL, 0, " Frame Delay Time %" PRId64, fdt);
snprintf(fdt_txt, sizeof(fdt_txt), " Frame Delay Time " _CYAN_("%" PRId64), fdt);
}
int fdt_pad = 72 + (int)strlen(fdt_txt) - visible;
if (use_us) {
PrintAndLogEx(NORMAL, " %10.1f | %10.1f | %s |%-*s | %s| %s",
(float)time1 / 13.56, (float)time2 / 13.56, " ",
fdt_pad, fdt_txt, " ", "");
} else {
PrintAndLogEx(NORMAL, " %10u | %10u | %s |%-*s | %s| %s",
time1, time2, " ", fdt_pad, fdt_txt, " ", "");
}
}
return tracepos;
}
// Download the device side trace into a buffer owned by the caller, who must
// free it. The client side trace buffer ( gs_trace ) is left untouched
static int download_trace_ex(uint8_t **ptrace, uint32_t *ptrace_len) {
if (IfPm3Present() == false) {
PrintAndLogEx(FAILED, "You requested a trace upload in offline mode, consider using parameter `" _YELLOW_("-1") "` for working from Tracebuffer");
return PM3_EINVARG;
}
uint8_t *trace = calloc(g_conn.max_cmd_data_size, sizeof(uint8_t));
if (trace == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
return PM3_EMALLOC;
}
PrintAndLogEx(DEBUG, "downloading tracelog data from device");
// Query for the size of the trace, downloading PM3_CMD_DATA_SIZE
PacketResponseNG resp;
if (!GetFromDevice(BIG_BUF, trace, g_conn.max_cmd_data_size, 0, NULL, 0, &resp, 4000, true)) {
PrintAndLogEx(WARNING, "timeout while waiting for reply");
free(trace);
return PM3_ETIMEOUT;
}
// the download terminator carries the trace length in download_done_t.extra
if (resp.length < sizeof(download_done_t)) {
PrintAndLogEx(WARNING, "short download reply from device");
free(trace);
return PM3_ESOFT;
}
uint32_t traceLen = ((const download_done_t *)resp.data.asBytes)->extra;
// if tracelog buffer was larger and we need to download more.
if (traceLen > g_conn.max_cmd_data_size) {
free(trace);
trace = calloc(traceLen, sizeof(uint8_t));
if (trace == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
return PM3_EMALLOC;
}
if (!GetFromDevice(BIG_BUF, trace, traceLen, 0, NULL, 0, NULL, 2500, false)) {
PrintAndLogEx(WARNING, "command execution time out");
free(trace);
return PM3_ETIMEOUT;
}
}
*ptrace = trace;
*ptrace_len = traceLen;
return PM3_SUCCESS;
}
// Download the device side trace and make it the client side trace buffer.
// On failure the existing buffer is kept, ie a timeout no longer throws away
// a trace the user loaded with `trace load`
static int download_trace(void) {
uint8_t *trace = NULL;
uint32_t trace_len = 0;
int res = download_trace_ex(&trace, &trace_len);
if (res != PM3_SUCCESS) {
return res;
}
free(gs_trace);
gs_trace = trace;
gs_traceLen = trace_len;
return PM3_SUCCESS;
}
// sanity check. Don't use proxmark if it is offline and you didn't specify useTraceBuffer
/*
static int SanityOfflineCheck( bool useTraceBuffer ){
if ( !useTraceBuffer && offline) {
PrintAndLogEx(NORMAL, "Your proxmark3 device is offline. Specify [1] to use TraceBuffer data instead");
return 0;
}
return 1;
}
*/
static int CmdTraceExtract(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "trace extract",
"Extracts protocol authentication challenges from trace buffer\n",
"trace extract\n"
"trace extract -1\n"
);
void *argtable[] = {
arg_param_begin,
arg_lit0("1", "buffer", "use data from trace buffer"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool use_buffer = arg_get_lit(ctx, 1);
CLIParserFree(ctx);
clearCommandBuffer();
// offline falls back to the trace buffer, like `trace save`
if ((use_buffer == false) && IfPm3Present()) {
int res = download_trace();
if (res != PM3_SUCCESS) {
return res;
}
} else if (gs_traceLen == 0) {
PrintAndLogEx(FAILED, "You requested a trace list in offline mode but there is no trace.");
if (use_buffer) {
PrintAndLogEx(FAILED, "Consider using `" _YELLOW_("trace load") "` or removing parameter `" _YELLOW_("-1") "`");
} else {
PrintAndLogEx(FAILED, "Consider using `" _YELLOW_("trace load") "`");
}
return PM3_EINVARG;
}
PrintAndLogEx(SUCCESS, "Recorded activity ( " _YELLOW_("%u") " bytes )", gs_traceLen);
if (gs_traceLen == 0) {
return PM3_SUCCESS;
}
// don't carry a UID or epurse over from the previous trace
memset(extract_uid, 0, sizeof(extract_uid));
extract_uidlen = 0;
memset(extract_epurse, 0, sizeof(extract_epurse));
uint32_t tracepos = 0;
while (tracepos < gs_traceLen) {
tracepos = extractChallenges(tracepos, gs_traceLen, gs_trace);
if (kbd_enter_pressed()) {
break;
}
}
return PM3_SUCCESS;
}
static int CmdTraceClear(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "trace clear",
"Clear the client side trace buffer.\n"
"That is the buffer `trace load` fills and the `-1` param reads from.\n"
"It is not the device side trace, see `data clear` for that one",
"trace clear"
);
void *argtable[] = {
arg_param_begin,
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
if (gs_traceLen == 0) {
PrintAndLogEx(INFO, "Trace buffer is already empty");
return PM3_SUCCESS;
}
PrintAndLogEx(SUCCESS, "Trace buffer cleared ( " _YELLOW_("%u") " bytes )", gs_traceLen);
ClearTraceBuffer();
return PM3_SUCCESS;
}
static int CmdTraceLoad(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "trace load",
"Load protocol data from binary file to trace buffer\n"
"File extension is <.trace>",
"trace load -f mytracefile -> w/o file extension"
);
void *argtable[] = {
arg_param_begin,
arg_str1("f", "file", "<fn>", "Specify trace file to load"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
int fnlen = 0;
char filename[FILE_PATH_SIZE] = {0};
CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
CLIParserFree(ctx);
// keep the current trace until the new one has loaded
uint8_t *trace = NULL;
size_t len = 0;
if (loadFile_safe(filename, ".trace", (void **)&trace, &len) != PM3_SUCCESS) {
PrintAndLogEx(FAILED, "Could not open file " _YELLOW_("%s"), filename);
return PM3_EIO;
}
ClearTraceBuffer();
gs_trace = trace;
gs_traceLen = (uint32_t)len;
PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = " _YELLOW_("%u") " bytes)", gs_traceLen);
PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace list -1 -t ...") "` to view trace. Remember the " _YELLOW_("`-1`") " param");
return PM3_SUCCESS;
}
static int CmdTraceSave(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "trace save",
"Save protocol data to binary file\n"
"By default the trace is downloaded from device.\n"
"Use `-1` to save the client side trace buffer instead, ie a trace\n"
"loaded with `trace load` or downloaded by an earlier `trace list`\n"
"File extension is <.trace>",
"trace save -f mytracefile -> download from device, w/o file extension\n"
"trace save -1 -f mytracefile -> use trace buffer"
);
void *argtable[] = {
arg_param_begin,
arg_lit0("1", "buffer", "use data from trace buffer"),
arg_str1("f", "file", "<fn>", "Specify trace file to save"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
bool use_buffer = arg_get_lit(ctx, 1);
int fnlen = 0;
char filename[FILE_PATH_SIZE] = {0};
CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
CLIParserFree(ctx);
// default to a fresh download, so a stale client side trace buffer never
// gets saved as if it was the trace you just captured.
// when offline we fall back to the buffer, ie `trace load` -> `trace save`
uint8_t *trace = gs_trace;
uint32_t trace_len = gs_traceLen;
bool is_owner = false;
if ((use_buffer == false) && IfPm3Present()) {
// saving is not supposed to alter the client side trace buffer, so
// download to a buffer of our own and leave gs_trace alone
int res = download_trace_ex(&trace, &trace_len);
if (res != PM3_SUCCESS) {
return res;
}
is_owner = true;
}
int res = PM3_SUCCESS;
if (trace_len == 0) {
PrintAndLogEx(WARNING, "trace is empty, nothing to save");
if (use_buffer) {
PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace load") "` or removing parameter `" _YELLOW_("-1") "`");
} else if (IfPm3Present() == false) {
PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace load") "` to load a trace from file");
}
} else {
res = saveFile(filename, ".trace", trace, trace_len);
}
if (is_owner) {
free(trace);
}
return res;
}
int CmdTraceListAlias(const char *Cmd, const char *alias, const char *protocol) {
CLIParserContext *ctx;
char desc[500] = {0};
snprintf(desc, sizeof(desc) - 1,
"Alias of `trace list -t %s` with selected protocol data to annotate trace buffer\n"
"You can load a trace from file (see `trace load -h`) or it be downloaded from device by default\n"
"It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol",
protocol);
char example[200] = {0};
snprintf(example, sizeof(example) - 1,
"%s list --frame -> show frame delay times\n"
"%s list -1 -> use trace buffer ",
alias, alias);
char fullalias[100] = {0};
snprintf(fullalias, sizeof(fullalias) - 1, "%s list", alias);
CLIParserInit(&ctx, fullalias, desc, example);
void *argtable[] = {
arg_param_begin,
arg_lit0("1", "buffer", "use data from trace buffer"),
arg_lit0(NULL, "frame", "show frame delay times"),
arg_lit0("c", NULL, "mark CRC bytes"),
arg_lit0("r", NULL, "show frame delay times relative to the previous transfer"),
arg_lit0("u", NULL, "display times in microseconds instead of clock cycles"),
arg_lit0("x", NULL, "show hexdump to convert to pcap(ng)\n"
" or to import into Wireshark using encapsulation type \"ISO 14443\""),
arg_str0("f", "file", "<fn>", "filename of dictionary"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
CLIParserFree(ctx);
// "-t " protocol " " Cmd NUL, sized to fit a long dictionary path
size_t args_len = strlen(protocol) + strlen(Cmd) + 5;
char *args = calloc(args_len, sizeof(char));
if (args == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
return PM3_EMALLOC;
}
snprintf(args, args_len, "-t %s %s", protocol, Cmd);
int res = CmdTraceList(args);
free(args);
return res;
}
int CmdTraceList(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "trace list",
"Annotate trace buffer with selected protocol data\n"
"You can load a trace from file (see `trace load -h`) or it be downloaded from device by default\n",
"trace list -t raw -> just show raw data without annotations\n"
"\n"
"trace list -t 14a -> interpret as " _YELLOW_("ISO14443-A") "\n"
"trace list -t 14b -> interpret as " _YELLOW_("ISO14443-B") "\n"
"trace list -t 15 -> interpret as " _YELLOW_("ISO15693") "\n"
"trace list -t 7816 -> interpret as " _YELLOW_("ISO7816-4") "\n"
"trace list -t calypso -> interpret as " _YELLOW_("Calypso") "\n"
"trace list -t cryptorf -> interpret as " _YELLOW_("CryptoRF") "\n"
"trace list -t des -> interpret as " _YELLOW_("MIFARE DESFire") "\n"
"trace list -t felica -> interpret as " _YELLOW_("ISO18092 / FeliCa") "\n"
"trace list -t ht1 -> interpret as " _YELLOW_("Hitag 1") "\n"
"trace list -t ht2 -> interpret as " _YELLOW_("Hitag 2") "\n"
"trace list -t hts -> interpret as " _YELLOW_("Hitag S") "\n"
"trace list -t htu -> interpret as " _YELLOW_("Hitag µ") "\n"
"trace list -t iclass -> interpret as " _YELLOW_("iCLASS") "\n"
"trace list -t legic -> interpret as " _YELLOW_("LEGIC") "\n"
"trace list -t lto -> interpret as " _YELLOW_("LTO-CM") "\n"
"trace list -t mf -> interpret as " _YELLOW_("MIFARE Classic") " and decrypt crypto1 stream\n"
"trace list -t seos -> interpret as " _YELLOW_("SEOS") "\n"
"trace list -t thinfilm -> interpret as " _YELLOW_("Thinfilm") "\n"
"trace list -t topaz -> interpret as " _YELLOW_("Topaz") "\n"
"trace list -t mfp -> interpret as " _YELLOW_("MIFARE Plus") "\n"
"trace list -t fmcos20 -> interpret as " _YELLOW_("FMCOS 2.0") "\n"
"\n"
"trace list -t mf -f mfc_default_keys.dic -> use default dictionary file\n"
"trace list -t 14a --frame -> show frame delay times\n"
"trace list -t 14a -1 -> use trace buffer "
);
void *argtable[] = {
arg_param_begin,
arg_lit0("1", "buffer", "use data from trace buffer"),
arg_lit0(NULL, "frame", "show frame delay times"),
arg_lit0("c", NULL, "mark CRC bytes"),
arg_lit0("r", NULL, "show frame delay times relative to the previous transfer"),
arg_lit0("u", NULL, "display times in microseconds instead of clock cycles"),
arg_lit0("x", NULL, "show hexdump to convert to pcap(ng)\n"
" or to import into Wireshark using encapsulation type \"ISO 14443\""),
arg_str0("t", "type", "<str>", "protocol to annotate the trace"),
arg_str0("f", "file", "<fn>", "filename of dictionary"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool use_buffer = arg_get_lit(ctx, 1);
bool show_wait_cycles = arg_get_lit(ctx, 2);
bool mark_crc = arg_get_lit(ctx, 3);
bool use_relative = arg_get_lit(ctx, 4);
// Both insert a Frame Delay Time row, so together they print it twice.
if (show_wait_cycles && use_relative) {
PrintAndLogEx(ERR, "Select only one of `--frame` and `-r`, they both show frame delay times");
CLIParserFree(ctx);
return PM3_EINVARG;
}
bool use_us = arg_get_lit(ctx, 5);
bool show_hex = arg_get_lit(ctx, 6);
int tlen = 0;
char type[10] = {0};
CLIParamStrToBuf(arg_get_str(ctx, 7), (uint8_t *)type, sizeof(type), &tlen);
str_lower(type);
int diclen = 0;
char dictionary[FILE_PATH_SIZE + 2] = {0};
if (CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)dictionary, FILE_PATH_SIZE, &diclen)) {
PrintAndLogEx(FAILED, "Dictionary file name too long or invalid.");
diclen = 0;
}
CLIParserFree(ctx);
clearCommandBuffer();
// no crc, no annotations
uint8_t protocol = -1;
// validate type of output
if (strcmp(type, "14a") == 0) protocol = ISO_14443A;
else if (strcmp(type, "14b") == 0) protocol = ISO_14443B;
else if (strcmp(type, "15") == 0) protocol = ISO_15693;
else if (strcmp(type, "7816") == 0) protocol = ISO_7816_4;
else if (strcmp(type, "calypso") == 0) protocol = PROTO_CALYPSO;
else if (strcmp(type, "cryptorf") == 0) protocol = PROTO_CRYPTORF;
else if (strcmp(type, "des") == 0) protocol = MFDES;
else if (strcmp(type, "felica") == 0) protocol = FELICA;
else if (strcmp(type, "ht1") == 0) protocol = PROTO_HITAG1;
else if (strcmp(type, "ht2") == 0) protocol = PROTO_HITAG2;
else if (strcmp(type, "hts") == 0) protocol = PROTO_HITAGS;
else if (strcmp(type, "htu") == 0) protocol = PROTO_HITAGU;
else if (strcmp(type, "iclass") == 0) protocol = ICLASS;
else if (strcmp(type, "legic") == 0) protocol = LEGIC;
else if (strcmp(type, "lto") == 0) protocol = LTO;
else if (strcmp(type, "mf") == 0) protocol = PROTO_MIFARE;
else if (strcmp(type, "raw") == 0) protocol = -1;
else if (strcmp(type, "seos") == 0) protocol = SEOS;
else if (strcmp(type, "thinfilm") == 0) protocol = THINFILM;
else if (strcmp(type, "topaz") == 0) protocol = TOPAZ;
else if (strcmp(type, "mfp") == 0) protocol = PROTO_MFPLUS;
else if (strcmp(type, "fmcos20") == 0) protocol = PROTO_FMCOS20;
else if (strcmp(type, "") == 0) protocol = -1;
else {
PrintAndLogEx(FAILED, "Unknown protocol \"%s\"", type);
return PM3_EINVARG;
}
// offline falls back to the trace buffer, like `trace save`
if ((use_buffer == false) && IfPm3Present()) {
int res = download_trace();
if (res != PM3_SUCCESS) {
return res;
}
} else if (gs_traceLen == 0 || gs_trace == NULL) {
if (IfPm3Present() == false) {
PrintAndLogEx(FAILED, "You requested a trace list in offline mode but there is no trace.");
} else {
PrintAndLogEx(FAILED, "You requested a trace list but there is no trace.");
}
if (use_buffer) {
PrintAndLogEx(FAILED, "Consider using `" _YELLOW_("trace load") "` or removing parameter `" _YELLOW_("-1") "`");
} else {
PrintAndLogEx(FAILED, "Consider using `" _YELLOW_("trace load") "`");
}
return PM3_EINVARG;
}
PrintAndLogEx(SUCCESS, "Recorded activity ( " _YELLOW_("%u") " bytes )", gs_traceLen);
if (gs_traceLen == 0) {
return PM3_SUCCESS;
}
uint32_t tracepos = 0;
/*
if (protocol == FELICA) {
printFelica(gs_traceLen, gs_trace);
} */
if (show_hex) {
while (tracepos < gs_traceLen) {
tracepos = printHexLine(tracepos, gs_traceLen, gs_trace, protocol);
}
} else {
if (use_relative) {
PrintAndLogEx(INFO, _YELLOW_("start") " = start of start frame. " _YELLOW_("end") " = end of frame. " _YELLOW_("src") " = source of transfer. A " _YELLOW_("Frame Delay Time") " row shows the gap between transfers.");
} else {
PrintAndLogEx(INFO, _YELLOW_("start") " = start of start frame. " _YELLOW_("end") " = end of frame. " _YELLOW_("src") " = source of transfer.");
}
if (protocol == ISO_14443A || protocol == PROTO_MIFARE || protocol == MFDES || protocol == PROTO_MFPLUS || protocol == TOPAZ || protocol == LTO) {
if (use_us)
PrintAndLogEx(INFO, _YELLOW_("ISO14443A") " - all times are in microseconds");
else
PrintAndLogEx(INFO, _YELLOW_("ISO14443A") " - all times are in carrier periods (1/13.56MHz)");
}
if (protocol == THINFILM) {
if (use_us)
PrintAndLogEx(INFO, _YELLOW_("Thinfilm") " - all times are in microseconds");
else
PrintAndLogEx(INFO, _YELLOW_("Thinfilm") " - all times are in carrier periods (1/13.56MHz)");
}
if (protocol == ICLASS || protocol == ISO_15693) {
if (use_us)
PrintAndLogEx(INFO, _YELLOW_("ISO15693 / iCLASS") " - all times are in microseconds");
else
PrintAndLogEx(INFO, _YELLOW_("ISO15693 / iCLASS") " - all times are in carrier periods (1/13.56MHz)");
}
if (protocol == LEGIC)
PrintAndLogEx(INFO, _YELLOW_("LEGIC") " - Reader Mode: Timings are in ticks (1us == 1.5ticks)\n"
" Tag Mode: Timings are in sub carrier periods (1/212 kHz == 4.7us)");
if (protocol == ISO_14443B || protocol == PROTO_CRYPTORF) {
if (use_us)
PrintAndLogEx(INFO, _YELLOW_("ISO14443B") " - all times are in microseconds");
else
PrintAndLogEx(INFO, _YELLOW_("ISO14443B") " - all times are in carrier periods (1/13.56MHz)");
}
if (protocol == ISO_7816_4)
PrintAndLogEx(INFO, _YELLOW_("ISO7816-4 / Smartcard") " - Timings in ticks (1/1.5MHz == 0.67us)");
if (protocol == PROTO_CALYPSO)
PrintAndLogEx(INFO, _YELLOW_("Calypso") " - Timings n/a");
if (protocol == PROTO_HITAG1 || protocol == PROTO_HITAG2 || protocol == PROTO_HITAGS || protocol == PROTO_HITAGU) {
PrintAndLogEx(INFO, _YELLOW_("Hitag 1 / Hitag 2 / Hitag S / Hitag µ") " - Timings in ETU (8us)");
}
if (protocol == PROTO_FMCOS20) {
PrintAndLogEx(INFO, _YELLOW_("FMCOS 2.0 / CPU Card") " - Timings n/a");
}
if (protocol == FELICA) {
if (use_us)
PrintAndLogEx(INFO, _YELLOW_("ISO18092 / FeliCa") " - all times are in microseconds");
else
PrintAndLogEx(INFO, _YELLOW_("ISO18092 / FeliCa") " - all times are in carrier periods (1/13.56MHz)");
}
const uint64_t *dicKeys = NULL;
uint32_t dicKeysCount = 0;
bool load_dictionary = false;
if (protocol == PROTO_MIFARE || protocol == PROTO_MFPLUS) {
if (diclen > 0) {
uint8_t *keyBlock = NULL;
int res = loadFileDICTIONARY_safe(dictionary, (void **) &keyBlock, 6, &dicKeysCount);
if (res != PM3_SUCCESS || dicKeysCount == 0 || keyBlock == NULL) {
PrintAndLogEx(FAILED, "An error occurred while loading the dictionary! (we will use the default keys now)");
} else {
dicKeys = calloc(dicKeysCount, sizeof(uint64_t));
if (dicKeys == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
} else {
for (int i = 0; i < dicKeysCount; i++) {
uint64_t key = bytes_to_num(keyBlock + i * 6, 6);
memcpy((uint8_t *) &dicKeys[i], &key, sizeof(uint64_t));
}
load_dictionary = true;
}
}
if (keyBlock != NULL) {
free(keyBlock);
}
}
if (dicKeys == NULL) {
dicKeys = g_mifare_default_keys;
dicKeysCount = ARRAYLEN(g_mifare_default_keys);
}
}
if (protocol == PROTO_HITAG2) {
if (strlen(dictionary) == 0) {
snprintf(dictionary, sizeof(dictionary), HITAG_DICTIONARY);
}
// load keys
uint8_t *keyBlock = NULL;
int res = loadFileDICTIONARY_safe(dictionary, (void **) &keyBlock, HITAG_CRYPTOKEY_SIZE, &dicKeysCount);
if (res != PM3_SUCCESS || dicKeysCount == 0 || keyBlock == NULL) {
PrintAndLogEx(FAILED, "An error occurred while loading the dictionary!");
} else {
dicKeys = calloc(dicKeysCount, sizeof(uint64_t));
if (dicKeys == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
} else {
for (int i = 0; i < dicKeysCount; i++) {
uint64_t key = bytes_to_num(keyBlock + i * HITAG_CRYPTOKEY_SIZE, HITAG_CRYPTOKEY_SIZE);
memcpy((uint8_t *) &dicKeys[i], &key, sizeof(uint64_t));
}
load_dictionary = true;
}
}
if (keyBlock != NULL) {
free(keyBlock);
}
}
PrintAndLogEx(NORMAL, "");
// Hitag has no CRC; that column carries the frame's bit count instead,
// so label it for what it actually holds. Both headings are three
// characters wide, which keeps the rule line below unchanged.
const char *col5 = "CRC";
if ((protocol == PROTO_HITAG1) || (protocol == PROTO_HITAG2) ||
(protocol == PROTO_HITAGS) || (protocol == PROTO_HITAGU)) {
col5 = "Bit";
}
PrintAndLogEx(NORMAL, " Start | End | Src | Data (! denotes parity error) | %s | Annotation", col5);
PrintAndLogEx(NORMAL, "------------+------------+-----+-------------------------------------------------------------------------+-----+--------------------");
// clean authentication data used with the mifare classic decrypt fct,
// and the anticollision state of the ISO14443-A checks
if (protocol == ISO_14443A || protocol == PROTO_MIFARE || protocol == PROTO_MFPLUS ||
protocol == MFDES || protocol == LTO || protocol == SEOS || protocol == TOPAZ ||
protocol == ISO_7816_4 || protocol == PROTO_FMCOS20) {
ClearAuthData();
}
gs_topaz_14a_exchange = false;
// reset hitag state machine
if (protocol == PROTO_HITAG1 || protocol == PROTO_HITAG2 || protocol == PROTO_HITAGS || protocol == PROTO_HITAGU) {
annotateHitag2_init();
}
uint32_t previous_EOT = 0;
uint32_t *prev_EOT = NULL;
if (use_relative) {
prev_EOT = &previous_EOT;
}
while (tracepos < gs_traceLen) {
tracepos = printTraceLine(tracepos, gs_traceLen, gs_trace, protocol, show_wait_cycles, mark_crc, prev_EOT, use_us, dicKeys, dicKeysCount);
if (kbd_enter_pressed()) {
PrintAndLogEx(INFO, "User interrupted detected. Aborting");
break;
}
}
if (load_dictionary) {
free((void *) dicKeys);
}
}
if (show_hex) {
PrintAndLogEx(HINT, "Hint: Syntax is: `" _YELLOW_("text2pcap -t \"%%S.\" -l 264 -n <input-text-file> <output-pcapng-file>") "`");
}
return PM3_SUCCESS;
}
static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"clear", CmdTraceClear, AlwaysAvailable, "Clear the client side trace buffer"},
{"extract", CmdTraceExtract, AlwaysAvailable, "Extract authentication challenges found in trace"},
{"list", CmdTraceList, AlwaysAvailable, "List protocol data in trace buffer"},
{"load", CmdTraceLoad, AlwaysAvailable, "Load trace from file"},
{"save", CmdTraceSave, AlwaysAvailable, "Save trace buffer to file"},
{NULL, NULL, NULL, NULL}
};
static int CmdHelp(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CmdsHelp(CommandTable);
return PM3_SUCCESS;
}
int CmdTrace(const char *Cmd) {
clearCommandBuffer();
return CmdsParse(CommandTable, Cmd);
}