Merge pull request #12 from RfidResearchGroup/master

Update
This commit is contained in:
mwalker33 2019-10-08 19:53:01 +11:00 committed by GitHub
commit 1e3d2d80b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
73 changed files with 971 additions and 547 deletions

View file

@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file.
This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log...
## [unreleased][unreleased] ## [unreleased][unreleased]
- Add option `-n` to scripts pm3* (@doegox)
- Add `wiegand list/encode/decode` - wiegand format manipulation. Adapted to fit here. (@grauerfuchs) - Add `wiegand list/encode/decode` - wiegand format manipulation. Adapted to fit here. (@grauerfuchs)
- Add `lf t55xx protect` - sets password and enables password protection on t55x7 tag (@iceman1001) - Add `lf t55xx protect` - sets password and enables password protection on t55x7 tag (@iceman1001)
- Chg `lf t55xx wipe` - now accepts user provided configuration block (@iceman1001) - Chg `lf t55xx wipe` - now accepts user provided configuration block (@iceman1001)

View file

@ -143,11 +143,25 @@ uint16_t AvgAdc(int ch) {
void MeasureAntennaTuning(void) { void MeasureAntennaTuning(void) {
uint8_t LF_Results[256]; uint32_t peak = 0;
uint32_t i, peak = 0, peakv = 0, peakf = 0;
uint32_t v_lf125 = 0, v_lf134 = 0, v_hf = 0; // in mV // in mVolt
struct p {
uint32_t v_lf134;
uint32_t v_lf125;
uint32_t v_lfconf;
uint32_t v_hf;
uint32_t peak_v;
uint32_t peak_f;
int divisor;
uint8_t results[256];
} PACKED payload;
memset(payload.results, 0, sizeof(payload.results));
sample_config *sc = getSamplingConfig();
payload.divisor = sc->divisor;
memset(LF_Results, 0, sizeof(LF_Results));
LED_B_ON(); LED_B_ON();
/* /*
@ -163,21 +177,26 @@ void MeasureAntennaTuning(void) {
FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
SpinDelay(50); SpinDelay(50);
for (i = 255; i >= 19; i--) { for (uint8_t i = 255; i >= 19; i--) {
WDT_HIT(); WDT_HIT();
FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i);
SpinDelay(20); SpinDelay(20);
uint32_t adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10); uint32_t adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10);
if (i == 95) if (i == LF_DIVISOR_125)
v_lf125 = adcval; // voltage at 125kHz payload.v_lf125 = adcval; // voltage at 125kHz
if (i == 89)
v_lf134 = adcval; // voltage at 134kHz
LF_Results[i] = adcval >> 9; // scale int to fit in byte for graphing purposes if (i == LF_DIVISOR_134)
if (LF_Results[i] > peak) { payload.v_lf134 = adcval; // voltage at 134kHz
peakv = adcval;
peakf = i; if (i == sc->divisor)
peak = LF_Results[i]; payload.v_lfconf = adcval; // voltage at `lf config q`
payload.results[i] = adcval >> 9; // scale int to fit in byte for graphing purposes
if (payload.results[i] > peak) {
payload.peak_v = adcval;
payload.peak_f = i;
peak = payload.results[i];
} }
} }
@ -186,23 +205,16 @@ void MeasureAntennaTuning(void) {
FpgaDownloadAndGo(FPGA_BITSTREAM_HF); FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
SpinDelay(50); SpinDelay(50);
v_hf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10;
payload.v_hf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10;
// RDV40 will hit the roof, try other ADC channel used in that hardware revision. // RDV40 will hit the roof, try other ADC channel used in that hardware revision.
if (v_hf > MAX_ADC_HF_VOLTAGE - 300) { if (payload.v_hf > MAX_ADC_HF_VOLTAGE - 300) {
v_hf = (MAX_ADC_HF_VOLTAGE_RDV40 * AvgAdc(ADC_CHAN_HF_RDV40)) >> 10; payload.v_hf = (MAX_ADC_HF_VOLTAGE_RDV40 * AvgAdc(ADC_CHAN_HF_RDV40)) >> 10;
} }
uint64_t arg0 = v_lf134;
arg0 <<= 32;
arg0 |= v_lf125;
uint64_t arg2 = peakv;
arg2 <<= 32;
arg2 |= peakf;
reply_mix(CMD_MEASURE_ANTENNA_TUNING, arg0, v_hf, arg2, LF_Results, 256);
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
reply_ng(CMD_MEASURE_ANTENNA_TUNING, PM3_SUCCESS, (uint8_t*)&payload, sizeof(payload));
LEDsoff(); LEDsoff();
} }
@ -234,7 +246,7 @@ void ReadMem(int addr) {
/* osimage version information is linked in */ /* osimage version information is linked in */
extern struct version_information version_information; extern struct version_information version_information;
/* bootrom version information is pointed to from _bootphase1_version_pointer */ /* bootrom version information is pointed to from _bootphase1_version_pointer */
extern char *_bootphase1_version_pointer, _flash_start, _flash_end, _bootrom_start, _bootrom_end, __data_src_start__; extern char *_bootphase1_version_pointer, _flash_start, _flash_end, __data_src_start__;
void SendVersion(void) { void SendVersion(void) {
char temp[PM3_CMD_DATA_SIZE - 12]; /* Limited data payload in USB packets */ char temp[PM3_CMD_DATA_SIZE - 12]; /* Limited data payload in USB packets */
char VersionString[PM3_CMD_DATA_SIZE - 12] = { '\0' }; char VersionString[PM3_CMD_DATA_SIZE - 12] = { '\0' };
@ -673,6 +685,10 @@ static void PacketReceived(PacketCommandNG *packet) {
setT55xxConfig(packet->oldarg[0], (t55xx_configurations_t *) packet->data.asBytes); setT55xxConfig(packet->oldarg[0], (t55xx_configurations_t *) packet->data.asBytes);
break; break;
} }
case CMD_LF_SAMPLING_GET_CONFIG: {
printConfig();
break;
}
case CMD_LF_SAMPLING_SET_CONFIG: { case CMD_LF_SAMPLING_SET_CONFIG: {
setSamplingConfig((sample_config *) packet->data.asBytes); setSamplingConfig((sample_config *) packet->data.asBytes);
break; break;
@ -1083,7 +1099,16 @@ static void PacketReceived(PacketCommandNG *packet) {
break; break;
} }
case CMD_HF_MIFARE_NESTED: { case CMD_HF_MIFARE_NESTED: {
MifareNested(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes); struct p {
uint8_t block;
uint8_t keytype;
uint8_t target_block;
uint8_t target_keytype;
bool calibrate;
uint8_t key[6];
} PACKED;
struct p *payload = (struct p *) packet->data.asBytes;
MifareNested(payload->block, payload->keytype, payload->target_block, payload->target_keytype, payload->calibrate, payload->key);
break; break;
} }
case CMD_HF_MIFARE_CHKKEYS: { case CMD_HF_MIFARE_CHKKEYS: {
@ -1452,7 +1477,7 @@ static void PacketReceived(PacketCommandNG *packet) {
break; break;
} }
case CMD_MEASURE_ANTENNA_TUNING_LF: { case CMD_MEASURE_ANTENNA_TUNING_LF: {
if (packet->length != 1) if (packet->length != 2)
reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EINVARG, NULL, 0); reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_EINVARG, NULL, 0);
switch (packet->data.asBytes[0]) { switch (packet->data.asBytes[0]) {
@ -1460,7 +1485,7 @@ static void PacketReceived(PacketCommandNG *packet) {
// Let the FPGA drive the low-frequency antenna around 125kHz // Let the FPGA drive the low-frequency antenna around 125kHz
FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, packet->data.asBytes[1]);
reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, NULL, 0); reply_ng(CMD_MEASURE_ANTENNA_TUNING_LF, PM3_SUCCESS, NULL, 0);
break; break;
case 2: case 2:
@ -1870,7 +1895,6 @@ static void PacketReceived(PacketCommandNG *packet) {
break; break;
} }
#endif #endif
case CMD_SETUP_WRITE:
case CMD_FINISH_WRITE: case CMD_FINISH_WRITE:
case CMD_HARDWARE_RESET: { case CMD_HARDWARE_RESET: {
usb_disable(); usb_disable();

View file

@ -906,11 +906,11 @@ void RAMFUNC SniffIClass(void) {
for (;;) { for (;;) {
WDT_HIT(); WDT_HIT();
if (checked == 2000) { if (checked == 1000) {
if (BUTTON_PRESS() || data_available()) break; if (BUTTON_PRESS() || data_available()) break;
checked = 0; checked = 0;
} }
checked++; ++checked;
previous_data <<= 8; previous_data <<= 8;
previous_data |= *data; previous_data |= *data;
@ -1014,11 +1014,11 @@ static bool GetIClassCommandFromReader(uint8_t *received, int *len, int maxLen)
WDT_HIT(); WDT_HIT();
if (checked == 2000) { if (checked == 1000) {
if (BUTTON_PRESS() || data_available()) return false; if (BUTTON_PRESS() || data_available()) return false;
checked = 0; checked = 0;
} }
checked++; ++checked;
// keep tx buffer in a defined state anyway. // keep tx buffer in a defined state anyway.
if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
@ -1666,11 +1666,11 @@ static int SendIClassAnswer(uint8_t *resp, int respLen, uint16_t delay) {
uint16_t checked = 0; uint16_t checked = 0;
for (;;) { for (;;) {
if (checked == 2000) { if (checked == 1000) {
if (BUTTON_PRESS() || data_available()) return 0; if (BUTTON_PRESS() || data_available()) return 0;
checked = 0; checked = 0;
} }
checked++; ++checked;
// Prevent rx holding register from overflowing // Prevent rx holding register from overflowing
if ((AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) { if ((AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) {
@ -1828,11 +1828,11 @@ static int GetIClassAnswer(uint8_t *receivedResponse, int maxLen, int *wait) {
for (;;) { for (;;) {
WDT_HIT(); WDT_HIT();
if (checked == 2000) { if (checked == 1000) {
if (BUTTON_PRESS() || data_available()) return false; if (BUTTON_PRESS() || data_available()) return false;
checked = 0; checked = 0;
} }
checked++; ++checked;
// Wait for byte be become available in rx holding register // Wait for byte be become available in rx holding register
if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
@ -2123,11 +2123,11 @@ void ReaderIClass(uint8_t arg0) {
} }
LED_B_OFF(); LED_B_OFF();
if (checked == 2000) { if (checked == 1000) {
userCancelled = BUTTON_PRESS() || data_available(); userCancelled = BUTTON_PRESS() || data_available();
checked = 0; checked = 0;
} }
checked++; ++checked;
} }
if (userCancelled) { if (userCancelled) {
@ -2326,11 +2326,11 @@ void iClass_Authentication_fast(uint64_t arg0, uint64_t arg1, uint8_t *datain) {
uint8_t startup_limit = 10; uint8_t startup_limit = 10;
while (read_status != 2) { while (read_status != 2) {
if (checked == 2000) { if (checked == 1000) {
if (BUTTON_PRESS() || !data_available()) goto out; if (BUTTON_PRESS() || !data_available()) goto out;
checked = 0; checked = 0;
} }
checked++; ++checked;
read_status = handshakeIclassTag_ext(card_data, use_credit_key); read_status = handshakeIclassTag_ext(card_data, use_credit_key);
if (startup_limit-- == 0) { if (startup_limit-- == 0) {
@ -2347,11 +2347,11 @@ void iClass_Authentication_fast(uint64_t arg0, uint64_t arg1, uint8_t *datain) {
for (i = 0; i < keyCount; i++) { for (i = 0; i < keyCount; i++) {
// Allow button press / usb cmd to interrupt device // Allow button press / usb cmd to interrupt device
if (checked == 2000) { if (checked == 1000) {
if (BUTTON_PRESS() || !data_available()) goto out; if (BUTTON_PRESS() || !data_available()) goto out;
checked = 0; checked = 0;
} }
checked++; ++checked;
WDT_HIT(); WDT_HIT();
LED_B_ON(); LED_B_ON();

View file

@ -2818,7 +2818,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype) {
WDT_HIT(); WDT_HIT();
// Test if the action was cancelled // Test if the action was cancelled
if (checkbtn_cnt == 2000) { if (checkbtn_cnt == 1000) {
if (BUTTON_PRESS() || data_available()) { if (BUTTON_PRESS() || data_available()) {
isOK = -1; isOK = -1;
return_status = PM3_EOPABORTED; return_status = PM3_EOPABORTED;
@ -2832,7 +2832,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype) {
if (!have_uid) { // need a full select cycle to get the uid first if (!have_uid) { // need a full select cycle to get the uid first
iso14a_card_select_t card_info; iso14a_card_select_t card_info;
if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
if (DBGLEVEL >= DBG_ERROR) Dbprintf("Mifare: Can't select card (ALL)"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Mifare: Can't select card (ALL)");
continue; continue;
} }
switch (card_info.uidlen) { switch (card_info.uidlen) {
@ -2851,7 +2851,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype) {
have_uid = true; have_uid = true;
} else { // no need for anticollision. We can directly select the card } else { // no need for anticollision. We can directly select the card
if (!iso14443a_fast_select_card(uid, cascade_levels)) { if (!iso14443a_fast_select_card(uid, cascade_levels)) {
if (DBGLEVEL >= DBG_ERROR) Dbprintf("Mifare: Can't select card (UID)"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Mifare: Can't select card (UID)");
continue; continue;
} }
} }
@ -3092,7 +3092,7 @@ void DetectNACKbug(void) {
WDT_HIT(); WDT_HIT();
// Test if the action was cancelled // Test if the action was cancelled
if (checkbtn_cnt == 2000) { if (checkbtn_cnt == 1000) {
if (BUTTON_PRESS() || data_available()) { if (BUTTON_PRESS() || data_available()) {
status = PM3_EOPABORTED; status = PM3_EOPABORTED;
break; break;
@ -3105,7 +3105,7 @@ void DetectNACKbug(void) {
if (!have_uid) { // need a full select cycle to get the uid first if (!have_uid) { // need a full select cycle to get the uid first
iso14a_card_select_t card_info; iso14a_card_select_t card_info;
if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) {
if (DBGLEVEL >= DBG_ERROR) Dbprintf("Mifare: Can't select card (ALL)"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Mifare: Can't select card (ALL)");
i = 0; i = 0;
continue; continue;
} }
@ -3127,7 +3127,7 @@ void DetectNACKbug(void) {
have_uid = true; have_uid = true;
} else { // no need for anticollision. We can directly select the card } else { // no need for anticollision. We can directly select the card
if (!iso14443a_fast_select_card(uid, cascade_levels)) { if (!iso14443a_fast_select_card(uid, cascade_levels)) {
if (DBGLEVEL >= DBG_ERROR) Dbprintf("Mifare: Can't select card (UID)"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Mifare: Can't select card (UID)");
i = 0; i = 0;
have_uid = false; have_uid = false;
continue; continue;

View file

@ -290,10 +290,12 @@ void setT55xxConfig(uint8_t arg0, t55xx_configurations_t *c) {
#ifdef WITH_FLASH #ifdef WITH_FLASH
// shall persist to flashmem // shall persist to flashmem
if (arg0 == 0) { if (arg0 == 0) {
BigBuf_free();
return; return;
} }
if (!FlashInit()) { if (!FlashInit()) {
BigBuf_free();
return; return;
} }
@ -370,16 +372,19 @@ void loadT55xxConfig(void) {
*/ */
void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint32_t period_1, uint8_t *command) { void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint32_t period_1, uint8_t *command) {
// start timer FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
StartTicks();
// use lf config settings // use lf config settings
sample_config *sc = getSamplingConfig(); sample_config *sc = getSamplingConfig();
// Make sure the tag is reset // Make sure the tag is reset
FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
WaitMS(500);
// start timer
StartTicks();
WaitMS(100);
// clear read buffer // clear read buffer
BigBuf_Clear_keep_EM(); BigBuf_Clear_keep_EM();
@ -387,10 +392,10 @@ void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint
LFSetupFPGAForADC(sc->divisor, true); LFSetupFPGAForADC(sc->divisor, true);
// little more time for the tag to fully power up // little more time for the tag to fully power up
WaitMS(200); WaitMS(20);
// if delay_off = 0 then just bitbang 1 = antenna on 0 = off for respective periods. // if delay_off = 0 then just bitbang 1 = antenna on 0 = off for respective periods.
bool bitbang = delay_off == 0; bool bitbang = (delay_off == 0);
// now modulate the reader field // now modulate the reader field
if (bitbang) { if (bitbang) {
// HACK it appears the loop and if statements take up about 7us so adjust waits accordingly... // HACK it appears the loop and if statements take up about 7us so adjust waits accordingly...
@ -399,6 +404,7 @@ void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint
DbpString("[!] Warning periods cannot be less than 7us in bit bang mode"); DbpString("[!] Warning periods cannot be less than 7us in bit bang mode");
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LED_D_OFF(); LED_D_OFF();
reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC, PM3_EINVARG, NULL, 0);
return; return;
} }
@ -460,6 +466,7 @@ void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint
// Turn off antenna // Turn off antenna
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
// tell client we are done // tell client we are done
reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC, PM3_SUCCESS, NULL, 0); reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC, PM3_SUCCESS, NULL, 0);
} }
@ -1691,9 +1698,8 @@ void T55xxResetRead(uint8_t flags) {
DoPartialAcquisition(0, true, BigBuf_max_traceLen(), 0); DoPartialAcquisition(0, true, BigBuf_max_traceLen(), 0);
// Turn the field off // Turn the field off
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
reply_mix(CMD_ACK, 0, 0, 0, 0, 0); reply_ng(CMD_LF_T55XX_RESET_READ, PM3_SUCCESS, NULL, 0);
LED_A_OFF(); LED_A_OFF();
} }

View file

@ -24,11 +24,12 @@ Default LF config is set to:
divisor = 95 (125kHz) divisor = 95 (125kHz)
trigger_threshold = 0 trigger_threshold = 0
*/ */
sample_config config = { 1, 8, 1, 95, 0, 0 } ; sample_config config = { 1, 8, 1, LF_DIVISOR_125, 0, 0 } ;
void printConfig() { void printConfig() {
uint32_t d = config.divisor;
DbpString(_BLUE_("LF Sampling config")); DbpString(_BLUE_("LF Sampling config"));
Dbprintf(" [q] divisor.............%d ( "_GREEN_("%d kHz")")", config.divisor, 12000 / (config.divisor + 1)); Dbprintf(" [q] divisor.............%d ( "_GREEN_("%d.%02d kHz")")", d, 12000 / (d+1), ((1200000 + (d+1)/2) / (d+1)) - ((12000 / (d+1)) * 100));
Dbprintf(" [b] bps.................%d", config.bits_per_sample); Dbprintf(" [b] bps.................%d", config.bits_per_sample);
Dbprintf(" [d] decimation..........%d", config.decimation); Dbprintf(" [d] decimation..........%d", config.decimation);
Dbprintf(" [a] averaging...........%s", (config.averaging) ? "Yes" : "No"); Dbprintf(" [a] averaging...........%s", (config.averaging) ? "Yes" : "No");
@ -148,17 +149,16 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag
uint32_t sample_total_saved = 0; uint32_t sample_total_saved = 0;
uint32_t cancel_counter = 0; uint32_t cancel_counter = 0;
uint16_t checker = 0; uint16_t checked = 0;
while (true) { while (true) {
if (checker == 1000) { if (checked == 1000) {
if (BUTTON_PRESS() || data_available()) if (BUTTON_PRESS() || data_available())
break; break;
else else
checker = 0; checked = 0;
} else {
++checker;
} }
++checked;
WDT_HIT(); WDT_HIT();

View file

@ -866,26 +866,20 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags,
// MIFARE nested authentication. // MIFARE nested authentication.
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) { void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, bool calibrate, uint8_t *key) {
// params
uint8_t blockNo = arg0 & 0xff;
uint8_t keyType = (arg0 >> 8) & 0xff;
uint8_t targetBlockNo = arg1 & 0xff;
uint8_t targetKeyType = (arg1 >> 8) & 0xff;
// calibrate = arg2
uint64_t ui64Key = 0; uint64_t ui64Key = 0;
ui64Key = bytes_to_num(key, 6);
ui64Key = bytes_to_num(datain, 6);
// variables // variables
uint16_t i, j, len; uint16_t i, j, len;
static uint16_t dmin, dmax; static uint16_t dmin, dmax;
uint8_t par[1] = {0x00};
uint8_t par_array[4] = {0x00};
uint8_t uid[10] = {0x00}; uint8_t uid[10] = {0x00};
uint32_t cuid = 0, nt1, nt2, nttest, ks1; uint32_t cuid = 0, nt1, nt2, nttest, ks1;
uint8_t par[1] = {0x00};
uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00}; uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00};
uint8_t par_array[4] = {0x00};
uint16_t ncount = 0; uint16_t ncount = 0;
struct Crypto1State mpcs = {0, 0}; struct Crypto1State mpcs = {0, 0};
struct Crypto1State *pcs; struct Crypto1State *pcs;
@ -903,13 +897,15 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
BigBuf_free(); BigBuf_free();
BigBuf_Clear_ext(false); BigBuf_Clear_ext(false);
if (arg2) clear_trace(); if (calibrate)
clear_trace();
set_tracing(true); set_tracing(true);
// statistics on nonce distance // statistics on nonce distance
int16_t isOK = 0; int16_t isOK = 0;
#define NESTED_MAX_TRIES 12 #define NESTED_MAX_TRIES 12
if (arg2) { // calibrate: for first call only. Otherwise reuse previous calibration if (calibrate) { // calibrate: for first call only. Otherwise reuse previous calibration
LED_B_ON(); LED_B_ON();
WDT_HIT(); WDT_HIT();
@ -929,31 +925,37 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
// prepare next select. No need to power down the card. // prepare next select. No need to power down the card.
if (mifare_classic_halt(pcs, cuid)) { if (mifare_classic_halt(pcs, cuid)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Halt error"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Halt error");
rtr--; rtr--;
continue; continue;
} }
if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Can't select card"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Can't select card");
rtr--; rtr--;
continue; continue;
}; };
auth1_time = 0; auth1_time = 0;
if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) { if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Auth1 error"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth1 error");
rtr--; rtr--;
continue; continue;
}; };
auth2_time = (delta_time) ? auth1_time + delta_time : 0; auth2_time = (delta_time) ? auth1_time + delta_time : 0;
if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time)) { if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Auth2 error"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth2 error");
rtr--; rtr--;
continue; continue;
}; };
// cards with fixed nonce
if (nt1 == nt2) {
Dbprintf("Nested: %08x vs %08x", nt1, nt2);
break;
}
uint32_t nttmp = prng_successor(nt1, 100); //NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160 uint32_t nttmp = prng_successor(nt1, 100); //NXP Mifare is typical around 840,but for some unlicensed/compatible mifare card this can be 160
for (i = 101; i < 1200; i++) { for (i = 101; i < 1200; i++) {
nttmp = prng_successor(nttmp, 1); nttmp = prng_successor(nttmp, 1);
@ -968,7 +970,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
} else { } else {
delta_time = auth2_time - auth1_time + 32; // allow some slack for proper timing delta_time = auth2_time - auth1_time + 32; // allow some slack for proper timing
} }
if (DBGLEVEL >= 3) Dbprintf("Nested: calibrating... ntdist=%d", i); if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nested: calibrating... ntdist=%d", i);
} else { } else {
unsuccessful_tries++; unsuccessful_tries++;
if (unsuccessful_tries > NESTED_MAX_TRIES) { // card isn't vulnerable to nested attack (random numbers are not predictable) if (unsuccessful_tries > NESTED_MAX_TRIES) { // card isn't vulnerable to nested attack (random numbers are not predictable)
@ -979,7 +981,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
davg = (davg + (rtr - 1) / 2) / (rtr - 1); davg = (davg + (rtr - 1) / 2) / (rtr - 1);
if (DBGLEVEL >= 3) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time); if (DBGLEVEL >= DBG_DEBUG) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time);
dmin = davg - 2; dmin = davg - 2;
dmax = davg + 2; dmax = davg + 2;
@ -998,18 +1000,18 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
// prepare next select. No need to power down the card. // prepare next select. No need to power down the card.
if (mifare_classic_halt(pcs, cuid)) { if (mifare_classic_halt(pcs, cuid)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Halt error"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Halt error");
continue; continue;
} }
if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Can't select card"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Can't select card");
continue; continue;
}; };
auth1_time = 0; auth1_time = 0;
if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) { if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Auth1 error"); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth1 error");
continue; continue;
}; };
@ -1018,12 +1020,12 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time); len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time);
if (len != 4) { if (len != 4) {
if (DBGLEVEL >= 2) Dbprintf("Nested: Auth2 error len=%d", len); if (DBGLEVEL >= DBG_INFO) Dbprintf("Nested: Auth2 error len=%d", len);
continue; continue;
}; };
nt2 = bytes_to_num(receivedAnswer, 4); nt2 = bytes_to_num(receivedAnswer, 4);
if (DBGLEVEL >= 3) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i + 1, nt1, nt2, par[0]); if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i + 1, nt1, nt2, par[0]);
// Parity validity check // Parity validity check
for (j = 0; j < 4; j++) { for (j = 0; j < 4; j++) {
@ -1038,7 +1040,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
if (valid_nonce(nttest, nt2, ks1, par_array)) { if (valid_nonce(nttest, nt2, ks1, par_array)) {
if (ncount > 0) { // we are only interested in disambiguous nonces, try again if (ncount > 0) { // we are only interested in disambiguous nonces, try again
if (DBGLEVEL >= 3) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i + 1, j); if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#%d: dismissed (ambiguous), ntdist=%d", i + 1, j);
target_nt[i] = 0; target_nt[i] = 0;
break; break;
} }
@ -1047,10 +1049,10 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
ncount++; ncount++;
if (i == 1 && target_nt[1] == target_nt[0]) { // we need two different nonces if (i == 1 && target_nt[1] == target_nt[0]) { // we need two different nonces
target_nt[i] = 0; target_nt[i] = 0;
if (DBGLEVEL >= 3) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j); if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#2: dismissed (= nonce#1), ntdist=%d", j);
break; break;
} }
if (DBGLEVEL >= 3) Dbprintf("Nonce#%d: valid, ntdist=%d", i + 1, j); if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Nonce#%d: valid, ntdist=%d", i + 1, j);
} }
} }
if (target_nt[i] == 0 && j == dmax + 1 && DBGLEVEL >= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i + 1); if (target_nt[i] == 0 && j == dmax + 1 && DBGLEVEL >= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i + 1);
@ -1061,15 +1063,28 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
crypto1_destroy(pcs); crypto1_destroy(pcs);
uint8_t buf[4 + 4 * 4] = {0}; struct p {
memcpy(buf, &cuid, 4); int16_t isOK;
memcpy(buf + 4, &target_nt[0], 4); uint8_t block;
memcpy(buf + 8, &target_ks[0], 4); uint8_t keytype;
memcpy(buf + 12, &target_nt[1], 4); uint8_t cuid[4];
memcpy(buf + 16, &target_ks[1], 4); uint8_t nt_a[4];
uint8_t ks_a[4];
uint8_t nt_b[4];
uint8_t ks_b[4];
} PACKED payload;
payload.isOK = isOK;
payload.block = targetBlockNo;
payload.keytype = targetKeyType;
memcpy(payload.cuid, &cuid, 4);
memcpy(payload.nt_a, &target_nt[0], 4);
memcpy(payload.ks_a, &target_ks[0], 4);
memcpy(payload.nt_b, &target_nt[1], 4);
memcpy(payload.ks_b, &target_ks[1], 4);
LED_B_ON(); LED_B_ON();
reply_mix(CMD_ACK, isOK, 0, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); reply_ng(CMD_HF_MIFARE_NESTED, PM3_SUCCESS, (uint8_t*)&payload, sizeof(payload));
LED_B_OFF(); LED_B_OFF();
if (DBGLEVEL >= 3) DbpString("NESTED FINISHED"); if (DBGLEVEL >= 3) DbpString("NESTED FINISHED");
@ -2004,7 +2019,7 @@ void MifareCIdent() {
// reset card // reset card
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
SpinDelay(100); SpinDelay(40);
iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
int res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true); int res = iso14443a_select_card(uid, NULL, &cuid, true, 0, true);
@ -2032,6 +2047,7 @@ OUT:
// turns off // turns off
OnSuccessMagic(); OnSuccessMagic();
BigBuf_free(); BigBuf_free();
BigBuf_Clear_ext(false);
} }
void OnSuccessMagic() { void OnSuccessMagic() {

View file

@ -21,8 +21,10 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain)
void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t *datain);
void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain);
//void MifareUWriteBlockCompat(uint8_t arg0,uint8_t *datain); //void MifareUWriteBlockCompat(uint8_t arg0,uint8_t *datain);
void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain);
void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8_t targetKeyType, bool calibrate, uint8_t *key);
void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain); void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain);
void MifareAcquireNonces(uint32_t arg0, uint32_t flags); void MifareAcquireNonces(uint32_t arg0, uint32_t flags);
void MifareChkKeys(uint8_t *datain); void MifareChkKeys(uint8_t *datain);

View file

@ -12,7 +12,8 @@
struct common_area common_area __attribute__((section(".commonarea"))); struct common_area common_area __attribute__((section(".commonarea")));
unsigned int start_addr, end_addr, bootrom_unlocked; unsigned int start_addr, end_addr, bootrom_unlocked;
extern char _bootrom_start, _bootrom_end, _flash_start, _flash_end; extern char _bootrom_start, _bootrom_end, _flash_end;
extern uint32_t _flash_start[AT91C_IFLASH_NB_OF_PAGES * AT91C_IFLASH_PAGE_SIZE / sizeof(uint32_t)];
extern uint32_t _osimage_entry; extern uint32_t _osimage_entry;
static int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) { static int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) {
@ -149,23 +150,12 @@ void UsbPacketReceived(uint8_t *packet, int len) {
} }
break; break;
case CMD_SETUP_WRITE: {
/* The temporary write buffer of the embedded flash controller is mapped to the
* whole memory region, only the last 8 bits are decoded.
*/
volatile uint32_t *p = (volatile uint32_t *)&_flash_start;
for (i = 0; i < 12; i++)
p[i + arg0] = c->d.asDwords[i];
}
break;
case CMD_FINISH_WRITE: { case CMD_FINISH_WRITE: {
uint32_t *flash_mem = (uint32_t *)(&_flash_start);
for (int j = 0; j < 2; j++) { for (int j = 0; j < 2; j++) {
uint32_t flash_address = arg0 + (0x100 * j); uint32_t flash_address = arg0 + (0x100 * j);
AT91PS_EFC efc_bank = AT91C_BASE_EFC0; AT91PS_EFC efc_bank = AT91C_BASE_EFC0;
int offset = 0; int offset = 0;
uint32_t page_n = (flash_address - ((uint32_t)flash_mem)) / AT91C_IFLASH_PAGE_SIZE; uint32_t page_n = (flash_address - ((uint32_t)_flash_start)) / AT91C_IFLASH_PAGE_SIZE;
if (page_n >= AT91C_IFLASH_NB_OF_PAGES / 2) { if (page_n >= AT91C_IFLASH_NB_OF_PAGES / 2) {
page_n -= AT91C_IFLASH_NB_OF_PAGES / 2; page_n -= AT91C_IFLASH_NB_OF_PAGES / 2;
efc_bank = AT91C_BASE_EFC1; efc_bank = AT91C_BASE_EFC1;
@ -173,7 +163,7 @@ void UsbPacketReceived(uint8_t *packet, int len) {
offset = (AT91C_IFLASH_NB_OF_PAGES / 2) * AT91C_IFLASH_PAGE_SIZE / sizeof(uint32_t); offset = (AT91C_IFLASH_NB_OF_PAGES / 2) * AT91C_IFLASH_PAGE_SIZE / sizeof(uint32_t);
} }
for (i = 0 + (64 * j); i < 64 + (64 * j); i++) { for (i = 0 + (64 * j); i < 64 + (64 * j); i++) {
flash_mem[offset + i] = c->d.asDwords[i]; _flash_start[offset + i] = c->d.asDwords[i];
} }
/* Check that the address that we are supposed to write to is within our allowed region */ /* Check that the address that we are supposed to write to is within our allowed region */

View file

@ -225,6 +225,7 @@ CMDSRCS = crapto1/crapto1.c \
cmdlfti.c \ cmdlfti.c \
cmdlfviking.c \ cmdlfviking.c \
cmdlfvisa2000.c \ cmdlfvisa2000.c \
cmdlfverichip.c \
cmdtrace.c \ cmdtrace.c \
cmdflashmem.c \ cmdflashmem.c \
cmdflashmemspiffs.c \ cmdflashmemspiffs.c \

View file

@ -1522,7 +1522,7 @@ struct arg_dbl *arg_dbln(
addr = (size_t)(result + 1); addr = (size_t)(result + 1);
rem = addr % sizeof(double); rem = addr % sizeof(double);
result->dval = (double *)(addr + sizeof(double) - rem); result->dval = (double *)(addr + sizeof(double) - rem);
ARG_TRACE(("addr=%p, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem)); ARG_TRACE(("addr=%zu, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem));
result->count = 0; result->count = 0;
} }

View file

@ -260,7 +260,7 @@ static int CmdAnalyseLCR(const char *Cmd) {
PrintAndLogEx(WARNING, "Invalid HEX value."); PrintAndLogEx(WARNING, "Invalid HEX value.");
return 1; return 1;
case 2: case 2:
PrintAndLogEx(WARNING, "Too many bytes. Max %d bytes", sizeof(data)); PrintAndLogEx(WARNING, "Too many bytes. Max %zu bytes", sizeof(data));
return 1; return 1;
case 3: case 3:
PrintAndLogEx(WARNING, "Hex must have even number of digits."); PrintAndLogEx(WARNING, "Hex must have even number of digits.");

View file

@ -89,6 +89,8 @@ int GetModels(char *Models[], int *count, uint8_t *width) {
memcpy(tmp, model.name, size); memcpy(tmp, model.name, size);
Models[mode] = tmp; Models[mode] = tmp;
width[mode] = plen(model.spoly); width[mode] = plen(model.spoly);
} else {
free(tmp);
} }
} }
mfree(&model); mfree(&model);

View file

@ -32,6 +32,20 @@ int g_DemodClock = 0;
static int CmdHelp(const char *Cmd); static int CmdHelp(const char *Cmd);
static int usage_data_scale(void) {
PrintAndLogEx(NORMAL, "Set cursor display scale.");
PrintAndLogEx(NORMAL, "Setting the scale makes the differential `dt` reading between the yellow and purple markers meaningful. ");
PrintAndLogEx(NORMAL, "once the scale is set, the differential reading between brackets is the time duration in seconds.");
PrintAndLogEx(NORMAL, "For example, if acquiring in 125kHz, use scale 125.");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: data scale [h] <kHz>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " <kHz> Sets scale of carrier frequency expressed in kHz");
PrintAndLogEx(NORMAL, "Samples:");
PrintAndLogEx(NORMAL, " data scale 125 - if sampled in 125kHz");
return PM3_SUCCESS;
}
static int usage_data_printdemodbuf(void) { static int usage_data_printdemodbuf(void) {
PrintAndLogEx(NORMAL, "Usage: data printdemodbuffer x o <offset> l <length>"); PrintAndLogEx(NORMAL, "Usage: data printdemodbuffer x o <offset> l <length>");
PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, "Options:");
@ -539,7 +553,7 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType,
size_t BitLen = getFromGraphBuf(bits); size_t BitLen = getFromGraphBuf(bits);
PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) #samples from graphbuff: %d", BitLen); PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) #samples from graphbuff: %zu", BitLen);
if (BitLen < 255) { if (BitLen < 255) {
free(bits); free(bits);
@ -577,18 +591,18 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType,
int errCnt = askdemod_ext(bits, &BitLen, &clk, &invert, maxErr, askamp, askType, &startIdx); int errCnt = askdemod_ext(bits, &BitLen, &clk, &invert, maxErr, askamp, askType, &startIdx);
if (errCnt < 0 || BitLen < 16) { //if fatal error (or -1) if (errCnt < 0 || BitLen < 16) { //if fatal error (or -1)
PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) No data found errors:%d, invert:%c, bitlen:%d, clock:%d", errCnt, (invert) ? 'Y' : 'N', BitLen, clk); PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) No data found errors:%d, invert:%c, bitlen:%zu, clock:%d", errCnt, (invert) ? 'Y' : 'N', BitLen, clk);
free(bits); free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
if (errCnt > maxErr) { if (errCnt > maxErr) {
PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Too many errors found, errors:%d, bits:%d, clock:%d", errCnt, BitLen, clk); PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Too many errors found, errors:%d, bits:%zu, clock:%d", errCnt, BitLen, clk);
free(bits); free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
if (verbose) PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Using clock:%d, invert:%d, bits found:%d, start index %d", clk, invert, BitLen, startIdx); if (verbose) PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Using clock:%d, invert:%d, bits found:%zu, start index %d", clk, invert, BitLen, startIdx);
//output //output
setDemodBuff(bits, BitLen, 0); setDemodBuff(bits, BitLen, 0);
@ -798,7 +812,7 @@ int AutoCorrelate(const int *in, int *out, size_t len, size_t window, bool SaveG
// sanity check // sanity check
if (window > len) window = len; if (window > len) window = len;
if (verbose) PrintAndLogEx(INFO, "performing " _YELLOW_("%d")" correlations", GraphTraceLen - window); if (verbose) PrintAndLogEx(INFO, "performing " _YELLOW_("%zu")" correlations", GraphTraceLen - window);
//test //test
double autocv = 0.0; // Autocovariance value double autocv = 0.0; // Autocovariance value
@ -854,9 +868,9 @@ int AutoCorrelate(const int *in, int *out, size_t len, size_t window, bool SaveG
if (verbose && foo < bar) { if (verbose && foo < bar) {
distance = idx_1 - idx; distance = idx_1 - idx;
PrintAndLogEx(SUCCESS, "possible 4% visible correlation %4d samples", distance); PrintAndLogEx(SUCCESS, "possible visible correlation %4d samples", distance);
} else if (verbose && (correlation > 1)) { } else if (verbose && (correlation > 1)) {
PrintAndLogEx(SUCCESS, "possible correlation %4d samples", correlation); PrintAndLogEx(SUCCESS, "possible correlation %4zu samples", correlation);
} else { } else {
PrintAndLogEx(FAILED, "no repeating pattern found, try increasing window size"); PrintAndLogEx(FAILED, "no repeating pattern found, try increasing window size");
} }
@ -898,7 +912,7 @@ static int CmdAutoCorr(const char *Cmd) {
case 'w': case 'w':
window = param_get32ex(Cmd, cmdp + 1, 4000, 10); window = param_get32ex(Cmd, cmdp + 1, 4000, 10);
if (window >= GraphTraceLen) { if (window >= GraphTraceLen) {
PrintAndLogEx(WARNING, "window must be smaller than trace (%d samples)", GraphTraceLen); PrintAndLogEx(WARNING, "window must be smaller than trace (%zu samples)", GraphTraceLen);
errors = true; errors = true;
} }
cmdp += 2; cmdp += 2;
@ -1208,17 +1222,17 @@ int PSKDemod(const char *Cmd, bool verbose) {
int startIdx = 0; int startIdx = 0;
int errCnt = pskRawDemod_ext(bits, &bitlen, &clk, &invert, &startIdx); int errCnt = pskRawDemod_ext(bits, &bitlen, &clk, &invert, &startIdx);
if (errCnt > maxErr) { if (errCnt > maxErr) {
if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, bitlen, errCnt); if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) Too many errors found, clk: %d, invert: %d, numbits: %zu, errCnt: %d", clk, invert, bitlen, errCnt);
free(bits); free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
if (errCnt < 0 || bitlen < 16) { //throw away static - allow 1 and -1 (in case of threshold command first) if (errCnt < 0 || bitlen < 16) { //throw away static - allow 1 and -1 (in case of threshold command first)
if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, bitlen, errCnt); if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) no data found, clk: %d, invert: %d, numbits: %zu, errCnt: %d", clk, invert, bitlen, errCnt);
free(bits); free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
if (verbose || g_debugMode) { if (verbose || g_debugMode) {
PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) Using Clock:%d, invert:%d, Bits Found:%d", clk, invert, bitlen); PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) Using Clock:%d, invert:%d, Bits Found:%zu", clk, invert, bitlen);
if (errCnt > 0) { if (errCnt > 0) {
PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) errors during Demoding (shown as 7 in bit stream): %d", errCnt); PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) errors during Demoding (shown as 7 in bit stream): %d", errCnt);
} }
@ -1250,7 +1264,7 @@ static int CmdIdteckDemod(const char *Cmd) {
else if (idx == -3) else if (idx == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: preamble not found");
else if (idx == -4) else if (idx == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: idx: %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: idx: %d", idx);
@ -1269,7 +1283,7 @@ static int CmdIdteckDemod(const char *Cmd) {
else if (idx == -3) else if (idx == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: preamble not found");
else if (idx == -4) else if (idx == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: idx: %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: idx: %d", idx);
@ -1332,17 +1346,17 @@ int NRZrawDemod(const char *Cmd, bool verbose) {
errCnt = nrzRawDemod(bits, &BitLen, &clk, &invert, &clkStartIdx); errCnt = nrzRawDemod(bits, &BitLen, &clk, &invert, &clkStartIdx);
if (errCnt > maxErr) { if (errCnt > maxErr) {
PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, BitLen, errCnt); PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) Too many errors found, clk: %d, invert: %d, numbits: %zu, errCnt: %d", clk, invert, BitLen, errCnt);
free(bits); free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
if (errCnt < 0 || BitLen < 16) { //throw away static - allow 1 and -1 (in case of threshold command first) if (errCnt < 0 || BitLen < 16) { //throw away static - allow 1 and -1 (in case of threshold command first)
PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, BitLen, errCnt); PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) no data found, clk: %d, invert: %d, numbits: %zu, errCnt: %d", clk, invert, BitLen, errCnt);
free(bits); free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
if (verbose || g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) Tried NRZ Demod using Clock: %d - invert: %d - Bits Found: %d", clk, invert, BitLen); if (verbose || g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) Tried NRZ Demod using Clock: %d - invert: %d - Bits Found: %zu", clk, invert, BitLen);
//prime demod buffer for output //prime demod buffer for output
setDemodBuff(bits, BitLen, 0); setDemodBuff(bits, BitLen, 0);
setClockGrid(clk, clkStartIdx); setClockGrid(clk, clkStartIdx);
@ -1640,52 +1654,69 @@ int CmdTuneSamples(const char *Cmd) {
return PM3_ETIMEOUT; return PM3_ETIMEOUT;
} }
} }
if (resp.status != PM3_SUCCESS) {
PrintAndLogEx(WARNING, "Antenna tuning failed");
return PM3_ESOFT;
}
PrintAndLogEx(NORMAL, "\n"); PrintAndLogEx(NORMAL, "\n");
// in mVolt
struct p {
uint32_t v_lf134;
uint32_t v_lf125;
uint32_t v_lfconf;
uint32_t v_hf;
uint32_t peak_v;
uint32_t peak_f;
int divisor;
uint8_t results[256];
} PACKED;
uint32_t v_lf125 = resp.oldarg[0]; struct p* package = (struct p*)resp.data.asBytes;
uint32_t v_lf134 = resp.oldarg[0] >> 32;
uint32_t v_hf = resp.oldarg[1]; if (package->v_lf125 > NON_VOLTAGE)
uint32_t peakf = resp.oldarg[2]; PrintAndLogEx(SUCCESS, "LF antenna: %5.2f V - %.2f kHz", (package->v_lf125 * ANTENNA_ERROR) / 1000.0, 12000.0 / (LF_DIVISOR_125 + 1));
uint32_t peakv = resp.oldarg[2] >> 32;
if (v_lf125 > NON_VOLTAGE) if (package->v_lf134 > NON_VOLTAGE)
PrintAndLogEx(SUCCESS, "LF antenna: %5.2f V - 125.00 kHz", (v_lf125 * ANTENNA_ERROR) / 1000.0); PrintAndLogEx(SUCCESS, "LF antenna: %5.2f V - %.2f kHz", (package->v_lf134 * ANTENNA_ERROR) / 1000.0, 12000.0 / (LF_DIVISOR_134 + 1));
if (v_lf134 > NON_VOLTAGE)
PrintAndLogEx(SUCCESS, "LF antenna: %5.2f V - 134.00 kHz", (v_lf134 * ANTENNA_ERROR) / 1000.0); if (package->v_lfconf > NON_VOLTAGE && package->divisor > 0 && package->divisor != LF_DIVISOR_125 && package->divisor != LF_DIVISOR_134)
if (peakv > NON_VOLTAGE && peakf > 0) PrintAndLogEx(SUCCESS, "LF antenna: %5.2f V - %.2f kHz", (package->v_lfconf * ANTENNA_ERROR) / 1000.0, 12000.0 / (package->divisor + 1));
PrintAndLogEx(SUCCESS, "LF optimal: %5.2f V - %6.2f kHz", (peakv * ANTENNA_ERROR) / 1000.0, 12000.0 / (peakf + 1));
if (package->peak_v > NON_VOLTAGE && package->peak_f > 0)
PrintAndLogEx(SUCCESS, "LF optimal: %5.2f V - %6.2f kHz", (package->peak_v * ANTENNA_ERROR) / 1000.0, 12000.0 / (package->peak_f + 1));
char judgement[20]; char judgement[20];
memset(judgement, 0, sizeof(judgement)); memset(judgement, 0, sizeof(judgement));
// LF evaluation // LF evaluation
if (peakv < LF_UNUSABLE_V) if (package->peak_v < LF_UNUSABLE_V)
sprintf(judgement, _RED_("UNUSABLE")); sprintf(judgement, _RED_("UNUSABLE"));
else if (peakv < LF_MARGINAL_V) else if (package->peak_v < LF_MARGINAL_V)
sprintf(judgement, _YELLOW_("MARGINAL")); sprintf(judgement, _YELLOW_("MARGINAL"));
else else
sprintf(judgement, _GREEN_("OK")); sprintf(judgement, _GREEN_("OK"));
PrintAndLogEx(NORMAL, "%sLF antenna is %s \n" PrintAndLogEx(NORMAL, "%sLF antenna is %s \n"
, (peakv < LF_UNUSABLE_V) ? _CYAN_("[!]") : _GREEN_("[+]") , (package->peak_v < LF_UNUSABLE_V) ? _CYAN_("[!]") : _GREEN_("[+]")
, judgement , judgement
); );
// HF evaluation // HF evaluation
if (v_hf > NON_VOLTAGE) if (package->v_hf > NON_VOLTAGE)
PrintAndLogEx(SUCCESS, "HF antenna: %5.2f V - 13.56 MHz", (v_hf * ANTENNA_ERROR) / 1000.0); PrintAndLogEx(SUCCESS, "HF antenna: %5.2f V - 13.56 MHz", (package->v_hf * ANTENNA_ERROR) / 1000.0);
memset(judgement, 0, sizeof(judgement)); memset(judgement, 0, sizeof(judgement));
if (v_hf < HF_UNUSABLE_V) if (package->v_hf < HF_UNUSABLE_V)
sprintf(judgement, _RED_("UNUSABLE")); sprintf(judgement, _RED_("UNUSABLE"));
else if (v_hf < HF_MARGINAL_V) else if (package->v_hf < HF_MARGINAL_V)
sprintf(judgement, _YELLOW_("MARGINAL")); sprintf(judgement, _YELLOW_("MARGINAL"));
else else
sprintf(judgement, _GREEN_("OK")); sprintf(judgement, _GREEN_("OK"));
PrintAndLogEx(NORMAL, "%sHF antenna is %s" PrintAndLogEx(NORMAL, "%sHF antenna is %s"
, (v_hf < HF_UNUSABLE_V) ? _CYAN_("[!]") : _GREEN_("[+]") , (package->v_hf < HF_UNUSABLE_V) ? _CYAN_("[!]") : _GREEN_("[+]")
, judgement , judgement
); );
@ -1693,12 +1724,13 @@ int CmdTuneSamples(const char *Cmd) {
// even here, these values has 3% error. // even here, these values has 3% error.
uint16_t test1 = 0; uint16_t test1 = 0;
for (int i = 0; i < 256; i++) { for (int i = 0; i < 256; i++) {
GraphBuffer[i] = resp.data.asBytes[i] - 128; GraphBuffer[i] = package->results[i] - 128;
test1 += resp.data.asBytes[i]; test1 += package->results[i];
} }
if (test1 > 0) { if (test1 > 0) {
PrintAndLogEx(SUCCESS, "\nDisplaying LF tuning graph. Divisor 89 is 134kHz, 95 is 125kHz.\n\n"); PrintAndLogEx(SUCCESS, "\nDisplaying LF tuning graph. Divisor %d is %.2f kHz, %d is %.2f kHz.\n\n",
LF_DIVISOR_134, 12000.0 / (LF_DIVISOR_134 + 1), LF_DIVISOR_125, 12000.0 / (LF_DIVISOR_125 + 1));
GraphTraceLen = 256; GraphTraceLen = 256;
ShowGraphWindow(); ShowGraphWindow();
RepaintGraphWindow(); RepaintGraphWindow();
@ -1747,7 +1779,7 @@ static int CmdLoad(const char *Cmd) {
fclose(f); fclose(f);
PrintAndLogEx(SUCCESS, "loaded %d samples", GraphTraceLen); PrintAndLogEx(SUCCESS, "loaded %zu samples", GraphTraceLen);
uint8_t bits[GraphTraceLen]; uint8_t bits[GraphTraceLen];
size_t size = getFromGraphBuf(bits); size_t size = getFromGraphBuf(bits);
@ -1865,6 +1897,9 @@ static int CmdSave(const char *Cmd) {
} }
static int CmdScale(const char *Cmd) { static int CmdScale(const char *Cmd) {
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_data_scale();
CursorScaleFactor = atoi(Cmd); CursorScaleFactor = atoi(Cmd);
if (CursorScaleFactor == 0) { if (CursorScaleFactor == 0) {
PrintAndLogEx(FAILED, "bad, can't have zero scale"); PrintAndLogEx(FAILED, "bad, can't have zero scale");
@ -2236,7 +2271,7 @@ static command_t CommandTable[] = {
{"samples", CmdSamples, IfPm3Present, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"}, {"samples", CmdSamples, IfPm3Present, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"},
{"save", CmdSave, AlwaysAvailable, "<filename> -- Save trace (from graph window)"}, {"save", CmdSave, AlwaysAvailable, "<filename> -- Save trace (from graph window)"},
{"setgraphmarkers", CmdSetGraphMarkers, AlwaysAvailable, "[orange_marker] [blue_marker] (in graph window)"}, {"setgraphmarkers", CmdSetGraphMarkers, AlwaysAvailable, "[orange_marker] [blue_marker] (in graph window)"},
{"scale", CmdScale, AlwaysAvailable, "<int> -- Set cursor display scale"}, {"scale", CmdScale, AlwaysAvailable, "<int> -- Set cursor display scale in carrier frequency expressed in kHz"},
{"setdebugmode", CmdSetDebugMode, AlwaysAvailable, "<0|1|2> -- Set Debugging Level on client side"}, {"setdebugmode", CmdSetDebugMode, AlwaysAvailable, "<0|1|2> -- Set Debugging Level on client side"},
{"shiftgraphzero", CmdGraphShiftZero, AlwaysAvailable, "<shift> -- Shift 0 for Graphed wave + or - shift value"}, {"shiftgraphzero", CmdGraphShiftZero, AlwaysAvailable, "<shift> -- Shift 0 for Graphed wave + or - shift value"},
{"dirthreshold", CmdDirectionalThreshold, AlwaysAvailable, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."}, {"dirthreshold", CmdDirectionalThreshold, AlwaysAvailable, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."},

View file

@ -266,7 +266,7 @@ static int CmdFlashMemLoad(const char *Cmd) {
conn.block_after_ACK = false; conn.block_after_ACK = false;
free(data); free(data);
PrintAndLogEx(SUCCESS, "Wrote "_GREEN_("%u")"bytes to offset "_GREEN_("%u"), datalen, start_index); PrintAndLogEx(SUCCESS, "Wrote "_GREEN_("%zu")"bytes to offset "_GREEN_("%u"), datalen, start_index);
return PM3_SUCCESS; return PM3_SUCCESS;
} }
static int CmdFlashMemDump(const char *Cmd) { static int CmdFlashMemDump(const char *Cmd) {

View file

@ -413,7 +413,7 @@ static int CmdFlashMemSpiFFSLoad(const char *Cmd) {
conn.block_after_ACK = false; conn.block_after_ACK = false;
free(data); free(data);
PrintAndLogEx(SUCCESS, "Wrote "_GREEN_("%u") "bytes to file "_GREEN_("%s"), datalen, destfilename); PrintAndLogEx(SUCCESS, "Wrote "_GREEN_("%zu") "bytes to file "_GREEN_("%s"), datalen, destfilename);
// We want to unmount after these to set things back to normal but more than this // We want to unmount after these to set things back to normal but more than this
// unmouting ensure that SPIFFS CACHES are all flushed so our file is actually written on memory // unmouting ensure that SPIFFS CACHES are all flushed so our file is actually written on memory

View file

@ -553,7 +553,7 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav
} }
if (resp.oldarg[0] != 1 && resp.oldarg[0] != 2) { if (resp.oldarg[0] != 1 && resp.oldarg[0] != 2) {
PrintAndLogEx(ERR, "Card not in iso14443-4. res=%d.", resp.oldarg[0]); PrintAndLogEx(ERR, "Card not in iso14443-4. res=" PRId64 ".", resp.oldarg[0]);
return 1; return 1;
} }
@ -647,7 +647,7 @@ static int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) {
} }
if (resp.oldarg[0] != 1 && resp.oldarg[0] != 2) { if (resp.oldarg[0] != 1 && resp.oldarg[0] != 2) {
PrintAndLogEx(ERR, "Card not in iso14443-4. res=%d.", resp.oldarg[0]); PrintAndLogEx(ERR, "Card not in iso14443-4. res=%" PRId64 ".", resp.oldarg[0]);
return 1; return 1;
} }
@ -1376,7 +1376,7 @@ int infoHF14A(bool verbose, bool do_nack_test) {
int16_t fsci = card.ats[1] & 0x0f; int16_t fsci = card.ats[1] & 0x0f;
PrintAndLogEx(NORMAL, " - T0 : TA1 is%s present, TB1 is%s present, " PrintAndLogEx(NORMAL, " - T0 : TA1 is%s present, TB1 is%s present, "
"TC1 is%s present, FSCI is %d (FSC = %ld)", "TC1 is%s present, FSCI is %d (FSC = %d)",
(ta1 ? "" : " NOT"), (ta1 ? "" : " NOT"),
(tb1 ? "" : " NOT"), (tb1 ? "" : " NOT"),
(tc1 ? "" : " NOT"), (tc1 ? "" : " NOT"),
@ -1408,7 +1408,7 @@ int infoHF14A(bool verbose, bool do_nack_test) {
if (tb1) { if (tb1) {
uint32_t sfgi = card.ats[pos] & 0x0F; uint32_t sfgi = card.ats[pos] & 0x0F;
uint32_t fwi = card.ats[pos] >> 4; uint32_t fwi = card.ats[pos] >> 4;
PrintAndLogEx(NORMAL, " - TB1 : SFGI = %d (SFGT = %s%ld/fc), FWI = %d (FWT = %ld/fc)", PrintAndLogEx(NORMAL, " - TB1 : SFGI = %d (SFGT = %s%d/fc), FWI = %d (FWT = %d/fc)",
(sfgi), (sfgi),
sfgi ? "" : "(not needed) ", sfgi ? "" : "(not needed) ",
sfgi ? (1 << 12) << sfgi : 0, sfgi ? (1 << 12) << sfgi : 0,

View file

@ -900,7 +900,7 @@ static int CmdHF14BDump(const char *Cmd) {
//select //select
if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
if (resp.oldarg[0]) { if (resp.oldarg[0]) {
PrintAndLogEx(INFO, "failed to select %d | %d", resp.oldarg[0], resp.oldarg[1]); PrintAndLogEx(INFO, "failed to select %" PRId64 " | %" PRId64, resp.oldarg[0], resp.oldarg[1]);
goto out; goto out;
} }
} }

View file

@ -534,7 +534,7 @@ static int CmdHF15Demod(const char *Cmd) {
} }
} }
PrintAndLogEx(NORMAL, "SOF at %d, correlation %d", maxPos, max / (ARRAYLEN(FrameSOF) / skip)); PrintAndLogEx(NORMAL, "SOF at %d, correlation %zu", maxPos, max / (ARRAYLEN(FrameSOF) / skip));
i = maxPos + ARRAYLEN(FrameSOF) / skip; i = maxPos + ARRAYLEN(FrameSOF) / skip;
int k = 0; int k = 0;
@ -1228,7 +1228,7 @@ static int CmdHF15Restore(const char *Cmd) {
cmdp++; cmdp++;
} }
PrintAndLogEx(INFO, "Blocksize: %u", blocksize); PrintAndLogEx(INFO, "Blocksize: %zu", blocksize);
if (!strlen(filename)) { if (!strlen(filename)) {
PrintAndLogEx(WARNING, "Please provide a filename"); PrintAndLogEx(WARNING, "Please provide a filename");
@ -1259,7 +1259,7 @@ static int CmdHF15Restore(const char *Cmd) {
fclose(f); fclose(f);
return 0; return 0;
} else if (bytes_read != blocksize) { } else if (bytes_read != blocksize) {
PrintAndLogEx(ERR, "File reading error (%s), %u bytes read instead of %u bytes.", filename, bytes_read, blocksize); PrintAndLogEx(ERR, "File reading error (%s), %zu bytes read instead of %zu bytes.", filename, bytes_read, blocksize);
fclose(f); fclose(f);
return 2; return 2;
} }

View file

@ -50,7 +50,7 @@ static int CmdHFEPACollectPACENonces(const char *Cmd) {
// check if command failed // check if command failed
if (resp.oldarg[0] != 0) { if (resp.oldarg[0] != 0) {
PrintAndLogEx(FAILED, "Error in step %d, Return code: %d", resp.oldarg[0], (int)resp.oldarg[1]); PrintAndLogEx(FAILED, "Error in step %" PRId64 ", Return code: %" PRId64, resp.oldarg[0], (int)resp.oldarg[1]);
} else { } else {
size_t nonce_length = resp.oldarg[1]; size_t nonce_length = resp.oldarg[1];
char *nonce = (char *) calloc(2 * nonce_length + 1, sizeof(uint8_t)); char *nonce = (char *) calloc(2 * nonce_length + 1, sizeof(uint8_t));
@ -58,7 +58,7 @@ static int CmdHFEPACollectPACENonces(const char *Cmd) {
sprintf(nonce + (2 * j), "%02X", resp.data.asBytes[j]); sprintf(nonce + (2 * j), "%02X", resp.data.asBytes[j]);
} }
// print nonce // print nonce
PrintAndLogEx(NORMAL, "Length: %d, Nonce: %s", nonce_length, nonce); PrintAndLogEx(NORMAL, "Length: %zu, Nonce: %s", nonce_length, nonce);
free(nonce); free(nonce);
} }
if (i < n - 1) { if (i < n - 1) {

View file

@ -13,6 +13,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
#include <inttypes.h>
#include "cmdparser.h" // command_t #include "cmdparser.h" // command_t
#include "comms.h" #include "comms.h"
@ -391,7 +392,7 @@ static int CmdHFFelicaDumpLite(const char *Cmd) {
return 1; return 1;
} }
uint64_t tracelen = resp.oldarg[1]; uint32_t tracelen = resp.oldarg[1];
if (tracelen == 0) if (tracelen == 0)
return 1; return 1;
@ -407,7 +408,7 @@ static int CmdHFFelicaDumpLite(const char *Cmd) {
return 0; return 0;
} }
PrintAndLogEx(SUCCESS, "Recorded Activity (trace len = %d bytes)", tracelen); PrintAndLogEx(SUCCESS, "Recorded Activity (trace len = %"PRIu64" bytes)", tracelen);
print_hex_break(trace, tracelen, 32); print_hex_break(trace, tracelen, 32);
printSep(); printSep();

View file

@ -75,14 +75,14 @@ static int CmdHFFidoInfo(const char *cmd) {
if (!strncmp((char *)buf, "U2F_V2", 7)) { if (!strncmp((char *)buf, "U2F_V2", 7)) {
if (!strncmp((char *)buf, "FIDO_2_0", 8)) { if (!strncmp((char *)buf, "FIDO_2_0", 8)) {
PrintAndLogEx(INFO, "FIDO2 authenticator detected. Version: %.*s", len, buf); PrintAndLogEx(INFO, "FIDO2 authenticator detected. Version: %.*s", (int)len, buf);
} else { } else {
PrintAndLogEx(INFO, "FIDO authenticator detected (not standard U2F)."); PrintAndLogEx(INFO, "FIDO authenticator detected (not standard U2F).");
PrintAndLogEx(INFO, "Non U2F authenticator version:"); PrintAndLogEx(INFO, "Non U2F authenticator version:");
dump_buffer((const unsigned char *)buf, len, NULL, 0); dump_buffer((const unsigned char *)buf, len, NULL, 0);
} }
} else { } else {
PrintAndLogEx(INFO, "FIDO U2F authenticator detected. Version: %.*s", len, buf); PrintAndLogEx(INFO, "FIDO U2F authenticator detected. Version: %.*s", (int)len, buf);
} }
res = FIDO2GetInfo(buf, sizeof(buf), &len, &sw); res = FIDO2GetInfo(buf, sizeof(buf), &len, &sw);
@ -274,7 +274,7 @@ static int CmdHFFidoRegister(const char *cmd) {
PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "");
if (APDULogging) if (APDULogging)
PrintAndLogEx(NORMAL, "---------------------------------------------------------------"); PrintAndLogEx(NORMAL, "---------------------------------------------------------------");
PrintAndLogEx(NORMAL, "data len: %d", len); PrintAndLogEx(NORMAL, "data len: %zu", len);
if (verbose2) { if (verbose2) {
PrintAndLogEx(NORMAL, "--------------data----------------------"); PrintAndLogEx(NORMAL, "--------------data----------------------");
dump_buffer((const unsigned char *)buf, len, NULL, 0); dump_buffer((const unsigned char *)buf, len, NULL, 0);
@ -316,7 +316,7 @@ static int CmdHFFidoRegister(const char *cmd) {
// get hash // get hash
int hashp = 1 + 65 + 1 + keyHandleLen + derLen; int hashp = 1 + 65 + 1 + keyHandleLen + derLen;
PrintAndLogEx(SUCCESS, "Hash[%d]: %s", len - hashp, sprint_hex(&buf[hashp], len - hashp)); PrintAndLogEx(SUCCESS, "Hash[%zu]: %s", len - hashp, sprint_hex(&buf[hashp], len - hashp));
// check ANSI X9.62 format ECDSA signature (on P-256) // check ANSI X9.62 format ECDSA signature (on P-256)
uint8_t rval[300] = {0}; uint8_t rval[300] = {0};
@ -543,7 +543,7 @@ static int CmdHFFidoAuthenticate(const char *cmd) {
PrintAndLogEx(SUCCESS, "User presence: %s", (buf[0] ? "verified" : "not verified")); PrintAndLogEx(SUCCESS, "User presence: %s", (buf[0] ? "verified" : "not verified"));
uint32_t cntr = (uint32_t)bytes_to_num(&buf[1], 4); uint32_t cntr = (uint32_t)bytes_to_num(&buf[1], 4);
PrintAndLogEx(SUCCESS, "Counter: %d", cntr); PrintAndLogEx(SUCCESS, "Counter: %d", cntr);
PrintAndLogEx(SUCCESS, "Hash[%d]: %s", len - 5, sprint_hex(&buf[5], len - 5)); PrintAndLogEx(SUCCESS, "Hash[%zu]: %s", len - 5, sprint_hex(&buf[5], len - 5));
// check ANSI X9.62 format ECDSA signature (on P-256) // check ANSI X9.62 format ECDSA signature (on P-256)
uint8_t rval[300] = {0}; uint8_t rval[300] = {0};
@ -736,7 +736,7 @@ static int CmdHFFido2MakeCredential(const char *cmd) {
return 0; return 0;
} }
PrintAndLogEx(SUCCESS, "MakeCredential result (%d b) OK.", len); PrintAndLogEx(SUCCESS, "MakeCredential result (%zu b) OK.", len);
if (showCBOR) { if (showCBOR) {
PrintAndLogEx(SUCCESS, "CBOR make credential response:"); PrintAndLogEx(SUCCESS, "CBOR make credential response:");
PrintAndLogEx(NORMAL, "---------------- CBOR ------------------"); PrintAndLogEx(NORMAL, "---------------- CBOR ------------------");
@ -862,7 +862,7 @@ static int CmdHFFido2GetAssertion(const char *cmd) {
return 0; return 0;
} }
PrintAndLogEx(SUCCESS, "GetAssertion result (%d b) OK.", len); PrintAndLogEx(SUCCESS, "GetAssertion result (%zu b) OK.", len);
if (showCBOR) { if (showCBOR) {
PrintAndLogEx(SUCCESS, "CBOR get assertion response:"); PrintAndLogEx(SUCCESS, "CBOR get assertion response:");
PrintAndLogEx(NORMAL, "---------------- CBOR ------------------"); PrintAndLogEx(NORMAL, "---------------- CBOR ------------------");

View file

@ -757,6 +757,7 @@ static int CmdHFiClassELoad(const char *Cmd) {
} }
default: default:
PrintAndLogEx(ERR, "No dictionary loaded"); PrintAndLogEx(ERR, "No dictionary loaded");
free(dump);
return PM3_ESOFT; return PM3_ESOFT;
} }
@ -977,6 +978,7 @@ static int CmdHFiClassEncryptBlk(const char *Cmd) {
return PM3_EINVARG; return PM3_EINVARG;
memcpy(key, keyptr, sizeof(key)); memcpy(key, keyptr, sizeof(key));
free(keyptr);
} }
iClassEncryptBlkData(blk_data, key); iClassEncryptBlkData(blk_data, key);
@ -1332,7 +1334,7 @@ static int CmdHFiClassReader_Dump(const char *Cmd) {
} }
// save the dump to .bin file // save the dump to .bin file
PrintAndLogEx(SUCCESS, "saving dump file - %d blocks read", gotBytes / 8); PrintAndLogEx(SUCCESS, "saving dump file - %zu blocks read", gotBytes / 8);
saveFile(filename, ".bin", tag_data, gotBytes); saveFile(filename, ".bin", tag_data, gotBytes);
saveFileEML(filename, tag_data, gotBytes, 8); saveFileEML(filename, tag_data, gotBytes, 8);
saveFileJSON(filename, jsfIclass, tag_data, gotBytes); saveFileJSON(filename, jsfIclass, tag_data, gotBytes);
@ -2081,7 +2083,7 @@ static int loadKeys(char *filename) {
size_t bytes_read = fread(dump, 1, fsize, f); size_t bytes_read = fread(dump, 1, fsize, f);
fclose(f); fclose(f);
if (bytes_read > ICLASS_KEYS_MAX * 8) { if (bytes_read > ICLASS_KEYS_MAX * 8) {
PrintAndLogEx(WARNING, "File is too long to load - bytes: %u", bytes_read); PrintAndLogEx(WARNING, "File is too long to load - bytes: %zu", bytes_read);
free(dump); free(dump);
return 0; return 0;
} }
@ -2502,7 +2504,7 @@ static int CmdHFiClassLookUp(const char *Cmd) {
case 'p': case 'p':
param_gethex_ex(Cmd, cmdp + 1, EPURSE, &len); param_gethex_ex(Cmd, cmdp + 1, EPURSE, &len);
if (len >> 1 != sizeof(EPURSE)) { if (len >> 1 != sizeof(EPURSE)) {
PrintAndLogEx(WARNING, "Wrong EPURSE length, expected %d got [%d] ", sizeof(EPURSE), len >> 1); PrintAndLogEx(WARNING, "Wrong EPURSE length, expected %zu got [%d] ", sizeof(EPURSE), len >> 1);
errors = true; errors = true;
} }
cmdp += 2; cmdp += 2;
@ -2652,7 +2654,7 @@ void PrintPreCalc(iclass_prekey_t *list, int itemcnt) {
for (int i = 0; i < itemcnt; i++) { for (int i = 0; i < itemcnt; i++) {
if (i < 10) { if (i < 10) {
PrintAndLogEx(NORMAL, "[%2d] | %016" PRIx64 " | %08" PRIx32, i, bytes_to_num(list[i].key, 8), bytes_to_num(list[i].mac, 4)); PrintAndLogEx(NORMAL, "[%2d] | %016" PRIx64 " | %08" PRIx64, i, bytes_to_num(list[i].key, 8), bytes_to_num(list[i].mac, 4));
} else if (i == 10) { } else if (i == 10) {
PrintAndLogEx(SUCCESS, "... skip printing the rest"); PrintAndLogEx(SUCCESS, "... skip printing the rest");
} }

View file

@ -1036,7 +1036,7 @@ static int CmdLegicRestore(const char *Cmd) {
fseek(f, 0, SEEK_SET); // seek back to beginning of file fseek(f, 0, SEEK_SET); // seek back to beginning of file
if (filesize != numofbytes) { if (filesize != numofbytes) {
PrintAndLogEx(WARNING, "Fail, filesize and cardsize is not equal. [%u != %u]", filesize, numofbytes); PrintAndLogEx(WARNING, "Fail, filesize and cardsize is not equal. [%zu != %u]", filesize, numofbytes);
free(data); free(data);
fclose(f); fclose(f);
return PM3_EFILE; return PM3_EFILE;
@ -1084,11 +1084,11 @@ static int CmdLegicRestore(const char *Cmd) {
uint8_t isOK = resp.oldarg[0] & 0xFF; uint8_t isOK = resp.oldarg[0] & 0xFF;
if (!isOK) { if (!isOK) {
PrintAndLogEx(WARNING, "Failed writing tag [msg = %u]", resp.oldarg[1] & 0xFF); PrintAndLogEx(WARNING, "Failed writing tag [msg = %u]", (uint8_t)(resp.oldarg[1] & 0xFF));
free(data); free(data);
return PM3_ERFTRANS; return PM3_ERFTRANS;
} }
PrintAndLogEx(SUCCESS, "Wrote chunk [offset %d | len %d | total %d", i, len, i + len); PrintAndLogEx(SUCCESS, "Wrote chunk [offset %zu | len %zu | total %zu", i, len, i + len);
} }
free(data); free(data);
@ -1281,7 +1281,7 @@ static int CmdLegicWipe(const char *Cmd) {
uint8_t isOK = resp.oldarg[0] & 0xFF; uint8_t isOK = resp.oldarg[0] & 0xFF;
if (!isOK) { if (!isOK) {
PrintAndLogEx(WARNING, "Failed writing tag [msg = %u]", resp.oldarg[1] & 0xFF); PrintAndLogEx(WARNING, "Failed writing tag [msg = %u]", (uint8_t)(resp.oldarg[1] & 0xFF));
free(data); free(data);
return PM3_ERFTRANS; return PM3_ERFTRANS;
} }

View file

@ -1122,7 +1122,7 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes
AuthData.ks3 = AuthData.at_enc ^ prng_successor(AuthData.nt, 96); AuthData.ks3 = AuthData.at_enc ^ prng_successor(AuthData.nt, 96);
mfLastKey = GetCrypto1ProbableKey(&AuthData); mfLastKey = GetCrypto1ProbableKey(&AuthData);
PrintAndLogEx(NORMAL, " | | * |%49s %012"PRIx64" prng %s | |", PrintAndLogEx(NORMAL, " | | * |%48s %012"PRIx64" prng %s | |",
"key", "key",
mfLastKey, mfLastKey,
validate_prng_nonce(AuthData.nt) ? _GREEN_("WEAK") : _YELLOW_("HARD")); validate_prng_nonce(AuthData.nt) ? _GREEN_("WEAK") : _YELLOW_("HARD"));

View file

@ -1296,7 +1296,7 @@ static int CmdHF14AMfNested(const char *Cmd) {
} }
uint64_t t2 = msclock() - t1; uint64_t t2 = msclock() - t1;
PrintAndLogEx(SUCCESS, "Time to check %d known keys: %.0f seconds\n", ARRAYLEN(g_mifare_default_keys), (float)t2 / 1000.0); PrintAndLogEx(SUCCESS, "Time to check %zu known keys: %.0f seconds\n", ARRAYLEN(g_mifare_default_keys), (float)t2 / 1000.0);
PrintAndLogEx(SUCCESS, "enter nested attack"); PrintAndLogEx(SUCCESS, "enter nested attack");
// nested sectors // nested sectors
@ -2607,7 +2607,10 @@ static int CmdHF14AMfChk(const char *Cmd) {
if (param_getchar(Cmd, 0) == '*') { if (param_getchar(Cmd, 0) == '*') {
blockNo = 3; blockNo = 3;
SectorsCnt = NumOfSectors(param_getchar(Cmd + 1, 0)); SectorsCnt = NumOfSectors(param_getchar(Cmd + 1, 0));
if (SectorsCnt == 0) return usage_hf14_chk(); if (SectorsCnt == 0) {
free(keyBlock);
return usage_hf14_chk();
}
} else { } else {
blockNo = param_get8(Cmd, 0); blockNo = param_get8(Cmd, 0);
} }
@ -4425,12 +4428,12 @@ static command_t CommandTable[] = {
{"ecfill", CmdHF14AMfECFill, IfPm3Iso14443a, "Fill simulator memory with help of keys from simulator"}, {"ecfill", CmdHF14AMfECFill, IfPm3Iso14443a, "Fill simulator memory with help of keys from simulator"},
{"ekeyprn", CmdHF14AMfEKeyPrn, IfPm3Iso14443a, "Print keys from simulator memory"}, {"ekeyprn", CmdHF14AMfEKeyPrn, IfPm3Iso14443a, "Print keys from simulator memory"},
{"-----------", CmdHelp, IfPm3Iso14443a, ""}, {"-----------", CmdHelp, IfPm3Iso14443a, ""},
{"csetuid", CmdHF14AMfCSetUID, IfPm3Iso14443a, "Set UID for magic Chinese card"}, {"csetuid", CmdHF14AMfCSetUID, IfPm3Iso14443a, "Set UID (magic chinese card)"},
{"csetblk", CmdHF14AMfCSetBlk, IfPm3Iso14443a, "Write block - Magic Chinese card"}, {"csetblk", CmdHF14AMfCSetBlk, IfPm3Iso14443a, "Write block (magic chinese card)"},
{"cgetblk", CmdHF14AMfCGetBlk, IfPm3Iso14443a, "Read block - Magic Chinese card"}, {"cgetblk", CmdHF14AMfCGetBlk, IfPm3Iso14443a, "Read block (magic chinese card)"},
{"cgetsc", CmdHF14AMfCGetSc, IfPm3Iso14443a, "Read sector - Magic Chinese card"}, {"cgetsc", CmdHF14AMfCGetSc, IfPm3Iso14443a, "Read sector (magic chinese card)"},
{"cload", CmdHF14AMfCLoad, IfPm3Iso14443a, "Load dump into magic Chinese card"}, {"cload", CmdHF14AMfCLoad, IfPm3Iso14443a, "Load dump (magic chinese card)"},
{"csave", CmdHF14AMfCSave, IfPm3Iso14443a, "Save dump from magic Chinese card into file or emulator"}, {"csave", CmdHF14AMfCSave, IfPm3Iso14443a, "Save dump from magic chinese card into file or emulator"},
{"-----------", CmdHelp, IfPm3Iso14443a, ""}, {"-----------", CmdHelp, IfPm3Iso14443a, ""},
{"mad", CmdHF14AMfMAD, IfPm3Iso14443a, "Checks and prints MAD"}, {"mad", CmdHF14AMfMAD, IfPm3Iso14443a, "Checks and prints MAD"},
{"ndef", CmdHFMFNDEF, IfPm3Iso14443a, "Prints NDEF records from card"}, {"ndef", CmdHFMFNDEF, IfPm3Iso14443a, "Prints NDEF records from card"},

View file

@ -2496,7 +2496,7 @@ static int CmdHF14AMfUCSetPwd(const char *Cmd) {
if ((resp.oldarg[0] & 0xff) == 1) { if ((resp.oldarg[0] & 0xff) == 1) {
PrintAndLogEx(INFO, "Ultralight-C new password: %s", sprint_hex(pwd, 16)); PrintAndLogEx(INFO, "Ultralight-C new password: %s", sprint_hex(pwd, 16));
} else { } else {
PrintAndLogEx(WARNING, "Failed writing at block %d", resp.oldarg[1] & 0xff); PrintAndLogEx(WARNING, "Failed writing at block %u", (uint8_t)(resp.oldarg[1] & 0xff));
return 1; return 1;
} }
} else { } else {

View file

@ -65,7 +65,7 @@ static int print_barcode(uint8_t *barcode, const size_t barcode_len, bool verbos
} else { } else {
PrintAndLogEx(SUCCESS, " Checksum : "_YELLOW_("too few data for checksum")"- " _RED_("fail")); PrintAndLogEx(SUCCESS, " Checksum : "_YELLOW_("too few data for checksum")"- " _RED_("fail"));
} }
PrintAndLogEx(SUCCESS, " Data len (bits) : "_YELLOW_("%i")"- %s", barcode_len * 8, (barcode_len == 16 || barcode_len == 32) ? _GREEN_("OK") : _YELLOW_("warning")); PrintAndLogEx(SUCCESS, " Data len (bits) : "_YELLOW_("%zu")"- %s", barcode_len * 8, (barcode_len == 16 || barcode_len == 32) ? _GREEN_("OK") : _YELLOW_("warning"));
PrintAndLogEx(SUCCESS, " Raw data : "_YELLOW_("%s"), sprint_hex(barcode, barcode_len)); PrintAndLogEx(SUCCESS, " Raw data : "_YELLOW_("%s"), sprint_hex(barcode, barcode_len));
if (barcode_len < 4) // too few to go to next decoding stages if (barcode_len < 4) // too few to go to next decoding stages
return PM3_ESOFT; return PM3_ESOFT;

View file

@ -13,6 +13,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
#include <inttypes.h>
#include "cmdparser.h" // command_t #include "cmdparser.h" // command_t
#include "comms.h" #include "comms.h"
@ -71,7 +72,7 @@ static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response, uint
memcpy(response, resp.data.asBytes, *response_len); memcpy(response, resp.data.asBytes, *response_len);
} }
} else { } else {
if (verbose) PrintAndLogEx(WARNING, "Wrong response length (%d != %d)", *response_len, resp.oldarg[0]); if (verbose) PrintAndLogEx(WARNING, "Wrong response length (%d != %" PRIu64 ")", *response_len, resp.oldarg[0]);
return PM3_ESOFT; return PM3_ESOFT;
} }
return PM3_SUCCESS; return PM3_SUCCESS;

View file

@ -47,6 +47,7 @@
#include "cmdlfsecurakey.h" // for securakey menu #include "cmdlfsecurakey.h" // for securakey menu
#include "cmdlfpac.h" // for pac menu #include "cmdlfpac.h" // for pac menu
#include "cmdlfkeri.h" // for keri menu #include "cmdlfkeri.h" // for keri menu
#include "cmdlfverichip.h" // for VeriChip menu
bool g_lf_threshold_set = false; bool g_lf_threshold_set = false;
@ -103,18 +104,21 @@ static int usage_lf_sniff(void) {
return PM3_SUCCESS; return PM3_SUCCESS;
} }
static int usage_lf_config(void) { static int usage_lf_config(void) {
PrintAndLogEx(NORMAL, "Usage: lf config [h] [H|<divisor>] [b <bps>] [d <decim>] [a 0|1]"); PrintAndLogEx(NORMAL, "Usage: lf config [h] [L | H | q <divisor> | f <freq>] [b <bps>] [d <decim>] [a 0|1]");
PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help"); PrintAndLogEx(NORMAL, " h This help");
PrintAndLogEx(NORMAL, " L Low frequency (125 kHz)"); PrintAndLogEx(NORMAL, " L Low frequency (125 kHz)");
PrintAndLogEx(NORMAL, " H High frequency (134 kHz)"); PrintAndLogEx(NORMAL, " H High frequency (134 kHz)");
PrintAndLogEx(NORMAL, " q <divisor> Manually set divisor. 88-> 134 kHz, 95-> 125 kHz"); PrintAndLogEx(NORMAL, " q <divisor> Manually set freq divisor. %d -> 134 kHz, %d -> 125 kHz", LF_DIVISOR_134, LF_DIVISOR_125);
PrintAndLogEx(NORMAL, " f <freq> Manually set frequency in kHz");
PrintAndLogEx(NORMAL, " b <bps> Sets resolution of bits per sample. Default (max): 8"); PrintAndLogEx(NORMAL, " b <bps> Sets resolution of bits per sample. Default (max): 8");
PrintAndLogEx(NORMAL, " d <decim> Sets decimation. A value of N saves only 1 in N samples. Default: 1"); PrintAndLogEx(NORMAL, " d <decim> Sets decimation. A value of N saves only 1 in N samples. Default: 1");
PrintAndLogEx(NORMAL, " a [0|1] Averaging - if set, will average the stored sample value when decimating. Default: 1"); PrintAndLogEx(NORMAL, " a [0|1] Averaging - if set, will average the stored sample value when decimating. Default: 1");
PrintAndLogEx(NORMAL, " t <threshold> Sets trigger threshold. 0 means no threshold (range: 0-128)"); PrintAndLogEx(NORMAL, " t <threshold> Sets trigger threshold. 0 means no threshold (range: 0-128)");
PrintAndLogEx(NORMAL, " s <samplestoskip> Sets a number of samples to skip before capture. Default: 0"); PrintAndLogEx(NORMAL, " s <samplestoskip> Sets a number of samples to skip before capture. Default: 0");
PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf config");
PrintAndLogEx(NORMAL, " Shows current config");
PrintAndLogEx(NORMAL, " lf config b 8 L"); PrintAndLogEx(NORMAL, " lf config b 8 L");
PrintAndLogEx(NORMAL, " Samples at 125 kHz, 8bps."); PrintAndLogEx(NORMAL, " Samples at 125 kHz, 8bps.");
PrintAndLogEx(NORMAL, " lf config H b 4 d 3"); PrintAndLogEx(NORMAL, " lf config H b 4 d 3");
@ -192,39 +196,78 @@ static int usage_lf_find(void) {
return PM3_SUCCESS; return PM3_SUCCESS;
} }
static int usage_lf_tune(void) { static int usage_lf_tune(void) {
PrintAndLogEx(NORMAL, "Continuously measure LF antenna tuning at 125 kHz."); PrintAndLogEx(NORMAL, "Continuously measure LF antenna tuning.");
PrintAndLogEx(NORMAL, "Press button or Enter to interrupt."); PrintAndLogEx(NORMAL, "Press button or Enter to interrupt.");
PrintAndLogEx(NORMAL, "Usage: lf tune [h] [<iter>]"); PrintAndLogEx(NORMAL, "Usage: lf tune [h] [n <iter>] [q <divisor> | f <freq>]");
PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h - This help"); PrintAndLogEx(NORMAL, " h - This help");
PrintAndLogEx(NORMAL, " <iter> - number of iterations (default: 0=infinite)"); PrintAndLogEx(NORMAL, " n <iter> - number of iterations (default: 0=infinite)");
PrintAndLogEx(NORMAL, " q <divisor> - Frequency divisor. %d -> 134 kHz, %d -> 125 kHz", LF_DIVISOR_134, LF_DIVISOR_125);
PrintAndLogEx(NORMAL, " f <freq> - Frequency in kHz");
return PM3_SUCCESS; return PM3_SUCCESS;
} }
int CmdLFTune(const char *Cmd) { int CmdLFTune(const char *Cmd) {
char cmdp = tolower(param_getchar(Cmd, 0)); int iter = 0;
if (cmdp == 'h') return usage_lf_tune(); uint8_t divisor = LF_DIVISOR_125;//Frequency divisor
int iter = param_get32ex(Cmd, 0, 0, 10); bool errors = false;
uint8_t cmdp = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (param_getchar(Cmd, cmdp)) {
case 'h':
return usage_lf_tune();
case 'q':
errors |= param_getdec(Cmd, cmdp + 1, &divisor);
cmdp += 2;
if (divisor < 19) {
PrintAndLogEx(ERR, "divisor must be between 19 and 255");
return PM3_EINVARG;
}
break;
case 'f': {
int freq = param_get32ex(Cmd, cmdp + 1, 125, 10);
divisor = LF_DIVISOR(freq);
if (divisor < 19) {
PrintAndLogEx(ERR, "freq must be between 47 and 600");
return PM3_EINVARG;
}
cmdp += 2;
break;
}
case 'n':
iter = param_get32ex(Cmd, cmdp + 1, 0, 10);
cmdp += 2;
break;
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = 1;
break;
}
}
PrintAndLogEx(SUCCESS, "Measuring LF antenna at 125kHz, click button or press Enter to exit"); //Validations
if (errors) return usage_lf_tune();
uint8_t mode[] = {1}; PrintAndLogEx(SUCCESS, "Measuring LF antenna at %.2f kHz, click button or press Enter to exit", 12000.0 / (divisor + 1));
uint8_t params[] = {1, 0};
params[1] = divisor;
PacketResponseNG resp; PacketResponseNG resp;
clearCommandBuffer(); clearCommandBuffer();
SendCommandNG(CMD_MEASURE_ANTENNA_TUNING_LF, mode, sizeof(mode)); SendCommandNG(CMD_MEASURE_ANTENNA_TUNING_LF, params, sizeof(params));
if (!WaitForResponseTimeout(CMD_MEASURE_ANTENNA_TUNING_LF, &resp, 1000)) { if (!WaitForResponseTimeout(CMD_MEASURE_ANTENNA_TUNING_LF, &resp, 1000)) {
PrintAndLogEx(WARNING, "Timeout while waiting for Proxmark LF initialization, aborting"); PrintAndLogEx(WARNING, "Timeout while waiting for Proxmark LF initialization, aborting");
return PM3_ETIMEOUT; return PM3_ETIMEOUT;
} }
mode[0] = 2; params[0] = 2;
// loop forever (till button pressed) if iter = 0 (default) // loop forever (till button pressed) if iter = 0 (default)
for (uint8_t i = 0; iter == 0 || i < iter; i++) { for (uint8_t i = 0; iter == 0 || i < iter; i++) {
if (kbd_enter_pressed()) { // abort by keyboard press if (kbd_enter_pressed()) { // abort by keyboard press
break; break;
} }
SendCommandNG(CMD_MEASURE_ANTENNA_TUNING_LF, mode, sizeof(mode)); SendCommandNG(CMD_MEASURE_ANTENNA_TUNING_LF, params, sizeof(params));
if (!WaitForResponseTimeout(CMD_MEASURE_ANTENNA_TUNING_LF, &resp, 1000)) { if (!WaitForResponseTimeout(CMD_MEASURE_ANTENNA_TUNING_LF, &resp, 1000)) {
PrintAndLogEx(WARNING, "Timeout while waiting for Proxmark LF measure, aborting"); PrintAndLogEx(WARNING, "Timeout while waiting for Proxmark LF measure, aborting");
return PM3_ETIMEOUT; return PM3_ETIMEOUT;
@ -234,8 +277,8 @@ int CmdLFTune(const char *Cmd) {
uint32_t volt = resp.data.asDwords[0]; uint32_t volt = resp.data.asDwords[0];
PrintAndLogEx(INPLACE, "%u mV / %5u V", volt, (uint32_t)(volt / 1000)); PrintAndLogEx(INPLACE, "%u mV / %5u V", volt, (uint32_t)(volt / 1000));
} }
mode[0] = 3; params[0] = 3;
SendCommandNG(CMD_MEASURE_ANTENNA_TUNING_LF, mode, sizeof(mode)); SendCommandNG(CMD_MEASURE_ANTENNA_TUNING_LF, params, sizeof(params));
if (!WaitForResponseTimeout(CMD_MEASURE_ANTENNA_TUNING_LF, &resp, 1000)) { if (!WaitForResponseTimeout(CMD_MEASURE_ANTENNA_TUNING_LF, &resp, 1000)) {
PrintAndLogEx(WARNING, "Timeout while waiting for Proxmark LF shutdown, aborting"); PrintAndLogEx(WARNING, "Timeout while waiting for Proxmark LF shutdown, aborting");
return PM3_ETIMEOUT; return PM3_ETIMEOUT;
@ -289,6 +332,14 @@ int CmdLFCommandRead(const char *Cmd) {
} }
} }
// bitbang mode
if (payload.delay == 0){
if (payload.zeros < 7 || payload.ones < 7) {
PrintAndLogEx(WARNING, "Warning periods cannot be less than 7us in bit bang mode");
return PM3_EINVARG;
}
}
//Validations //Validations
if (errors || cmdp == 0) return usage_lf_cmdread(); if (errors || cmdp == 0) return usage_lf_cmdread();
@ -297,21 +348,29 @@ int CmdLFCommandRead(const char *Cmd) {
SendCommandNG(CMD_LF_MOD_THEN_ACQ_RAW_ADC, (uint8_t *)&payload, 8 + datalen); SendCommandNG(CMD_LF_MOD_THEN_ACQ_RAW_ADC, (uint8_t *)&payload, 8 + datalen);
printf("\n"); printf("\n");
PacketResponseNG resp;
uint8_t i = 10; uint8_t i = 10;
while (!WaitForResponseTimeout(CMD_LF_MOD_THEN_ACQ_RAW_ADC, NULL, 2000) && i != 0) { while (!WaitForResponseTimeout(CMD_LF_MOD_THEN_ACQ_RAW_ADC, &resp, 2000) && i != 0) {
printf("."); printf(".");
fflush(stdout); fflush(stdout);
i--; i--;
} }
printf("\n"); printf("\n");
if (i) { if (resp.status == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Downloading response signal data"); if (i) {
getSamples(0, true); PrintAndLogEx(SUCCESS, "Downloading response signal data");
return PM3_SUCCESS; getSamples(0, true);
return PM3_SUCCESS;
} else {
PrintAndLogEx(WARNING, "timeout while waiting for reply.");
return PM3_ETIMEOUT;
}
} }
PrintAndLogEx(WARNING, "timeout while waiting for reply."); PrintAndLogEx(WARNING, "Command failed.");
return PM3_ETIMEOUT; return PM3_ESOFT;
} }
int CmdFlexdemod(const char *Cmd) { int CmdFlexdemod(const char *Cmd) {
@ -389,7 +448,7 @@ int CmdFlexdemod(const char *Cmd) {
return PM3_SUCCESS; return PM3_SUCCESS;
} }
int CmdLFSetConfig(const char *Cmd) { int CmdLFConfig(const char *Cmd) {
if (!session.pm3_present) return PM3_ENOTTY; if (!session.pm3_present) return PM3_ENOTTY;
@ -409,17 +468,31 @@ int CmdLFSetConfig(const char *Cmd) {
case 'h': case 'h':
return usage_lf_config(); return usage_lf_config();
case 'H': case 'H':
divisor = 88; divisor = LF_DIVISOR_134;
cmdp++; cmdp++;
break; break;
case 'L': case 'L':
divisor = 95; divisor = LF_DIVISOR_125;
cmdp++; cmdp++;
break; break;
case 'q': case 'q':
errors |= param_getdec(Cmd, cmdp + 1, &divisor); errors |= param_getdec(Cmd, cmdp + 1, &divisor);
if (divisor < 19) {
PrintAndLogEx(ERR, "divisor must be between 19 and 255");
return PM3_EINVARG;
}
cmdp += 2; cmdp += 2;
break; break;
case 'f': {
int freq = param_get32ex(Cmd, cmdp + 1, 125, 10);
divisor = LF_DIVISOR(freq);
if (divisor < 19) {
PrintAndLogEx(ERR, "freq must be between 47 and 600");
return PM3_EINVARG;
}
cmdp += 2;
break;
}
case 't': case 't':
errors |= param_getdec(Cmd, cmdp + 1, &unsigned_trigg); errors |= param_getdec(Cmd, cmdp + 1, &unsigned_trigg);
cmdp += 2; cmdp += 2;
@ -452,7 +525,12 @@ int CmdLFSetConfig(const char *Cmd) {
} }
//Validations //Validations
if (errors || cmdp == 0) return usage_lf_config(); if (errors) return usage_lf_config();
if (cmdp == 0) {
clearCommandBuffer();
SendCommandNG(CMD_LF_SAMPLING_GET_CONFIG, NULL, 0);
return PM3_SUCCESS;
}
//Bps is limited to 8 //Bps is limited to 8
if (bps >> 4) bps = 8; if (bps >> 4) bps = 8;
@ -573,7 +651,7 @@ int CmdLFSim(const char *Cmd) {
// convert to bitstream if necessary // convert to bitstream if necessary
ChkBitstream(); ChkBitstream();
PrintAndLogEx(DEBUG, "DEBUG: Uploading %d bytes", GraphTraceLen); PrintAndLogEx(DEBUG, "DEBUG: Uploading %zu bytes", GraphTraceLen);
struct pupload { struct pupload {
uint8_t flag; uint8_t flag;
@ -709,7 +787,7 @@ int CmdLFfskSim(const char *Cmd) {
size_t size = DemodBufferLen; size_t size = DemodBufferLen;
if (size > (PM3_CMD_DATA_SIZE - sizeof(lf_fsksim_t))) { if (size > (PM3_CMD_DATA_SIZE - sizeof(lf_fsksim_t))) {
PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %d - max: %d", size, PM3_CMD_DATA_SIZE - sizeof(lf_fsksim_t)); PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %zu - max: %zu", size, PM3_CMD_DATA_SIZE - sizeof(lf_fsksim_t));
size = PM3_CMD_DATA_SIZE - sizeof(lf_fsksim_t); size = PM3_CMD_DATA_SIZE - sizeof(lf_fsksim_t);
} }
@ -811,7 +889,7 @@ int CmdLFaskSim(const char *Cmd) {
size_t size = DemodBufferLen; size_t size = DemodBufferLen;
if (size > (PM3_CMD_DATA_SIZE - sizeof(lf_asksim_t))) { if (size > (PM3_CMD_DATA_SIZE - sizeof(lf_asksim_t))) {
PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %d - max: %d", size, PM3_CMD_DATA_SIZE - sizeof(lf_asksim_t)); PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %zu - max: %zu", size, PM3_CMD_DATA_SIZE - sizeof(lf_asksim_t));
size = PM3_CMD_DATA_SIZE - sizeof(lf_asksim_t); size = PM3_CMD_DATA_SIZE - sizeof(lf_asksim_t);
} }
@ -931,7 +1009,7 @@ int CmdLFpskSim(const char *Cmd) {
} }
size_t size = DemodBufferLen; size_t size = DemodBufferLen;
if (size > (PM3_CMD_DATA_SIZE - sizeof(lf_psksim_t))) { if (size > (PM3_CMD_DATA_SIZE - sizeof(lf_psksim_t))) {
PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %d - max: %d", size, PM3_CMD_DATA_SIZE - sizeof(lf_psksim_t)); PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %zu - max: %zu", size, PM3_CMD_DATA_SIZE - sizeof(lf_psksim_t));
size = PM3_CMD_DATA_SIZE - sizeof(lf_psksim_t); size = PM3_CMD_DATA_SIZE - sizeof(lf_psksim_t);
} }
@ -961,12 +1039,21 @@ int CmdLFSimBidir(const char *Cmd) {
// Set ADC to twice the carrier for a slight supersampling // Set ADC to twice the carrier for a slight supersampling
// HACK: not implemented in ARMSRC. // HACK: not implemented in ARMSRC.
PrintAndLogEx(INFO, "Not implemented yet."); PrintAndLogEx(INFO, "Not implemented yet.");
SendCommandMIX(CMD_LF_SIMULATE_BIDIR, 47, 384, 0, NULL, 0); // SendCommandMIX(CMD_LF_SIMULATE_BIDIR, 47, 384, 0, NULL, 0);
return PM3_SUCCESS; return PM3_SUCCESS;
} }
// ICEMAN, todo, swap from Graphbuffer. // ICEMAN, todo, swap from Graphbuffer.
// according to Westhus this demod uses decimated samples / 2.
// need to do complete rewrite. Need access to reader / chip
// should be extracted to seperate files aswell
int CmdVchDemod(const char *Cmd) { int CmdVchDemod(const char *Cmd) {
if (GraphTraceLen < 4096) {
PrintAndLogEx(DEBUG, "debug; VchDemod - too few samples");
return PM3_EINVARG;
}
// Is this the entire sync pattern, or does this also include some // Is this the entire sync pattern, or does this also include some
// data bits that happen to be the same everywhere? That would be // data bits that happen to be the same everywhere? That would be
// lovely to know. // lovely to know.
@ -1138,9 +1225,10 @@ int CmdLFfind(const char *Cmd) {
if (demodSecurakey() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Securakey ID") "found!"); goto out;} if (demodSecurakey() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Securakey ID") "found!"); goto out;}
if (demodViking() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Viking ID") "found!"); goto out;} if (demodViking() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Viking ID") "found!"); goto out;}
if (demodVisa2k() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Visa2000 ID") "found!"); goto out;} if (demodVisa2k() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Visa2000 ID") "found!"); goto out;}
if (demodTI() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Texas Instrument ID") "found!"); goto out;} // if (demodTI() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Texas Instrument ID") "found!"); goto out;}
// if (demodVerichip() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("VeriChip ID") "found!"); goto out;}
//if (demodFermax() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Fermax ID") "found!"); goto out;} //if (demodFermax() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Fermax ID") "found!"); goto out;}
//if (demodFlex() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Flex ID") "found!"); goto out;} //if (demodFlex() == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "\nValid " _GREEN_("Motorola FlexPass ID") "found!"); goto out;}
PrintAndLogEx(FAILED, _RED_("No known 125/134 kHz tags found!")); PrintAndLogEx(FAILED, _RED_("No known 125/134 kHz tags found!"));
@ -1213,11 +1301,12 @@ static command_t CommandTable[] = {
{"securakey", CmdLFSecurakey, AlwaysAvailable, "{ Securakey RFIDs... }"}, {"securakey", CmdLFSecurakey, AlwaysAvailable, "{ Securakey RFIDs... }"},
{"ti", CmdLFTI, AlwaysAvailable, "{ TI CHIPs... }"}, {"ti", CmdLFTI, AlwaysAvailable, "{ TI CHIPs... }"},
{"t55xx", CmdLFT55XX, AlwaysAvailable, "{ T55xx CHIPs... }"}, {"t55xx", CmdLFT55XX, AlwaysAvailable, "{ T55xx CHIPs... }"},
// {"verichip", CmdLFVerichip, AlwaysAvailable, "{ VeriChip RFIDs... }"},
{"viking", CmdLFViking, AlwaysAvailable, "{ Viking RFIDs... }"}, {"viking", CmdLFViking, AlwaysAvailable, "{ Viking RFIDs... }"},
{"visa2000", CmdLFVisa2k, AlwaysAvailable, "{ Visa2000 RFIDs... }"}, {"visa2000", CmdLFVisa2k, AlwaysAvailable, "{ Visa2000 RFIDs... }"},
{"config", CmdLFSetConfig, IfPm3Lf, "Set config for LF sampling, bit/sample, decimation, frequency"}, {"", CmdHelp, AlwaysAvailable, ""},
{"config", CmdLFConfig, IfPm3Lf, "Get/Set config for LF sampling, bit/sample, decimation, frequency"},
{"cmdread", CmdLFCommandRead, IfPm3Lf, "<off period> <'0' period> <'1' period> <command> ['h' 134] \n\t\t-- Modulate LF reader field to send command before read (all periods in microseconds)"}, {"cmdread", CmdLFCommandRead, IfPm3Lf, "<off period> <'0' period> <'1' period> <command> ['h' 134] \n\t\t-- Modulate LF reader field to send command before read (all periods in microseconds)"},
{"flexdemod", CmdFlexdemod, AlwaysAvailable, "Demodulate samples for FlexPass"},
{"read", CmdLFRead, IfPm3Lf, "['s' silent] Read 125/134 kHz LF ID-only tag. Do 'lf read h' for help"}, {"read", CmdLFRead, IfPm3Lf, "['s' silent] Read 125/134 kHz LF ID-only tag. Do 'lf read h' for help"},
{"search", CmdLFfind, AlwaysAvailable, "[offline] ['u'] Read and Search for valid known tag (in offline mode it you can load first then search) \n\t\t-- 'u' to search for unknown tags"}, {"search", CmdLFfind, AlwaysAvailable, "[offline] ['u'] Read and Search for valid known tag (in offline mode it you can load first then search) \n\t\t-- 'u' to search for unknown tags"},
{"sim", CmdLFSim, IfPm3Lf, "[GAP] -- Simulate LF tag from buffer with optional GAP (in microseconds)"}, {"sim", CmdLFSim, IfPm3Lf, "[GAP] -- Simulate LF tag from buffer with optional GAP (in microseconds)"},
@ -1227,7 +1316,8 @@ static command_t CommandTable[] = {
{"simbidir", CmdLFSimBidir, IfPm3Lf, "Simulate LF tag (with bidirectional data transmission between reader and tag)"}, {"simbidir", CmdLFSimBidir, IfPm3Lf, "Simulate LF tag (with bidirectional data transmission between reader and tag)"},
{"sniff", CmdLFSniff, IfPm3Lf, "Sniff LF traffic between reader and tag"}, {"sniff", CmdLFSniff, IfPm3Lf, "Sniff LF traffic between reader and tag"},
{"tune", CmdLFTune, IfPm3Lf, "Continuously measure LF antenna tuning"}, {"tune", CmdLFTune, IfPm3Lf, "Continuously measure LF antenna tuning"},
{"vchdemod", CmdVchDemod, AlwaysAvailable, "['clone'] -- Demodulate samples for VeriChip"}, // {"vchdemod", CmdVchDemod, AlwaysAvailable, "['clone'] -- Demodulate samples for VeriChip"},
{"flexdemod", CmdFlexdemod, AlwaysAvailable, "Demodulate samples for Motorola FlexPass"},
{NULL, NULL, NULL, NULL} {NULL, NULL, NULL, NULL}
}; };

View file

@ -16,6 +16,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include "commonutil.h" // ARRAYLEN
#include "cmdparser.h" // command_t #include "cmdparser.h" // command_t
#include "comms.h" #include "comms.h"
#include "graph.h" #include "graph.h"
@ -323,7 +324,7 @@ static int CmdAWIDDemod(const char *Cmd) {
} }
free(bits); free(bits);
PrintAndLogEx(DEBUG, "DEBUG: AWID idx: %d, Len: %d Printing Demod Buffer:", idx, size); PrintAndLogEx(DEBUG, "DEBUG: AWID idx: %d, Len: %zu Printing Demod Buffer:", idx, size);
if (g_debugMode) if (g_debugMode)
printDemodBuff(); printDemodBuff();
@ -385,13 +386,8 @@ static int CmdAWIDSim(const char *Cmd) {
} }
static int CmdAWIDClone(const char *Cmd) { static int CmdAWIDClone(const char *Cmd) {
uint32_t blocks[4] = {T55x7_MODULATION_FSK2a | T55x7_BITRATE_RF_50 | 3 << T55x7_MAXBLOCK_SHIFT, 0, 0, 0};
uint32_t fc = 0, cn = 0; uint32_t fc = 0, cn = 0;
uint8_t fmtlen = 0; uint8_t fmtlen = 0;
uint8_t bits[96];
uint8_t *bs = bits;
memset(bs, 0, sizeof(bits));
char cmdp = tolower(param_getchar(Cmd, 0)); char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_awid_clone(); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_awid_clone();
@ -401,63 +397,32 @@ static int CmdAWIDClone(const char *Cmd) {
if (!fc || !cn) return usage_lf_awid_clone(); if (!fc || !cn) return usage_lf_awid_clone();
uint32_t blocks[4] = {T55x7_MODULATION_FSK2a | T55x7_BITRATE_RF_50 | 3 << T55x7_MAXBLOCK_SHIFT, 0, 0, 0};
if (tolower(param_getchar(Cmd, 3)) == 'q') if (tolower(param_getchar(Cmd, 3)) == 'q')
//t5555 (Q5) BITRATE = (RF-2)/2 (iceman) //t5555 (Q5) BITRATE = (RF-2)/2 (iceman)
blocks[0] = T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | T5555_SET_BITRATE(50) | 3 << T5555_MAXBLOCK_SHIFT; blocks[0] = T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | T5555_SET_BITRATE(50) | 3 << T5555_MAXBLOCK_SHIFT;
verify_values(&fmtlen, &fc, &cn); verify_values(&fmtlen, &fc, &cn);
if (getAWIDBits(fmtlen, fc, cn, bs) != PM3_SUCCESS) { uint8_t *bits = calloc(96, sizeof(uint8_t));
if (getAWIDBits(fmtlen, fc, cn, bits) != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Error with tag bitstream generation."); PrintAndLogEx(ERR, "Error with tag bitstream generation.");
free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }
blocks[1] = bytebits_to_byte(bs, 32); blocks[1] = bytebits_to_byte(bits, 32);
blocks[2] = bytebits_to_byte(bs + 32, 32); blocks[2] = bytebits_to_byte(bits + 32, 32);
blocks[3] = bytebits_to_byte(bs + 64, 32); blocks[3] = bytebits_to_byte(bits + 64, 32);
free(bits);
PrintAndLogEx(INFO, "Preparing to clone AWID %u to T55x7 with FC: %u, CN: %u", fmtlen, fc, cn); PrintAndLogEx(INFO, "Preparing to clone AWID %u to T55x7 with FC: %u, CN: %u", fmtlen, fc, cn);
print_blocks(blocks, 4); print_blocks(blocks, ARRAYLEN(blocks));
uint8_t res = 0; return clone_t55xx_tag(blocks, ARRAYLEN(blocks));
PacketResponseNG resp;
// fast push mode
conn.block_after_ACK = true;
for (uint8_t i = 0; i < 4; i++) {
if (i == 3) {
// Disable fast mode on last packet
conn.block_after_ACK = false;
}
clearCommandBuffer();
t55xx_write_block_t ng;
ng.data = blocks[i];
ng.pwd = 0;
ng.blockno = i;
ng.flags = 0;
SendCommandNG(CMD_LF_T55XX_WRITEBL, (uint8_t *)&ng, sizeof(ng));
if (!WaitForResponseTimeout(CMD_LF_T55XX_WRITEBL, &resp, T55XX_WRITE_TIMEOUT)) {
PrintAndLogEx(ERR, "Error occurred, device did not respond during write operation.");
return PM3_ETIMEOUT;
}
if (i == 0) {
SetConfigWithBlock0(blocks[0]);
if (t55xxAquireAndCompareBlock0(false, 0, blocks[0], false))
continue;
}
if (t55xxVerifyWrite(i, 0, false, false, 0, 0xFF, blocks[i]) == false)
res++;
}
if (res == 0)
PrintAndLogEx(SUCCESS, "Success writing to tag");
return PM3_SUCCESS;
} }
static int CmdAWIDBrute(const char *Cmd) { static int CmdAWIDBrute(const char *Cmd) {

View file

@ -416,7 +416,7 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo) {
setDemodBuff(DemodBuffer, (size == 40) ? 64 : 128, idx + 1); setDemodBuff(DemodBuffer, (size == 40) ? 64 : 128, idx + 1);
setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx + 1)*g_DemodClock)); setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx + 1)*g_DemodClock));
PrintAndLogEx(DEBUG, "DEBUG: Em410x idx: %d, Len: %d, Printing Demod Buffer:", idx, size); PrintAndLogEx(DEBUG, "DEBUG: Em410x idx: %zu, Len: %zu, Printing Demod Buffer:", idx, size);
if (g_debugMode) if (g_debugMode)
printDemodBuff(); printDemodBuff();
@ -1085,7 +1085,7 @@ static bool doPreambleSearch(size_t *startIdx) {
uint8_t preamble[EM_PREAMBLE_LEN] = {0, 0, 1, 0, 1, 0}; uint8_t preamble[EM_PREAMBLE_LEN] = {0, 0, 1, 0, 1, 0};
if (!preambleSearchEx(DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, startIdx, true)) { if (!preambleSearchEx(DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, startIdx, true)) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 preamble not found :: %d", *startIdx); PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 preamble not found :: %zu", *startIdx);
return false; return false;
} }
return true; return true;

View file

@ -245,7 +245,7 @@ static int CmdFdxDemod(const char *Cmd) {
PrintAndLogEx(SUCCESS, "CRC-16 0x%04X - 0x%04X [%s]", crc_16, calcCrc, (calcCrc == crc_16) ? _GREEN_("Ok") : _RED_("Fail")); PrintAndLogEx(SUCCESS, "CRC-16 0x%04X - 0x%04X [%s]", crc_16, calcCrc, (calcCrc == crc_16) ? _GREEN_("Ok") : _RED_("Fail"));
if (g_debugMode) { if (g_debugMode) {
PrintAndLogEx(DEBUG, "Start marker %d; Size %d", preambleIndex, size); PrintAndLogEx(DEBUG, "Start marker %d; Size %zu", preambleIndex, size);
char *bin = sprint_bin_break(DemodBuffer, size, 16); char *bin = sprint_bin_break(DemodBuffer, size, 16);
PrintAndLogEx(DEBUG, "DEBUG bin stream:\n%s", bin); PrintAndLogEx(DEBUG, "DEBUG bin stream:\n%s", bin);
} }

View file

@ -84,7 +84,7 @@ static int CmdGuardDemod(const char *Cmd) {
else if (preambleIndex == -2) else if (preambleIndex == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII preamble not found");
else if (preambleIndex == -3) else if (preambleIndex == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII size not correct: %zu", size);
else if (preambleIndex == -5) else if (preambleIndex == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII wrong spacerbits"); PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII wrong spacerbits");
else else
@ -103,14 +103,14 @@ static int CmdGuardDemod(const char *Cmd) {
// remove the 18 (90/5=18) parity bits (down to 72 bits (96-6-18=72)) // remove the 18 (90/5=18) parity bits (down to 72 bits (96-6-18=72))
size_t len = removeParity(bits_no_spacer, 0, 5, 3, 90); //source, startloc, paritylen, ptype, length_to_run size_t len = removeParity(bits_no_spacer, 0, 5, 3, 90); //source, startloc, paritylen, ptype, length_to_run
if (len != 72) { if (len != 72) {
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII spacer removal did not produce 72 bits: %u, start: %u", len, startIdx); PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII spacer removal did not produce 72 bits: %zu, start: %zu", len, startIdx);
return PM3_ESOFT; return PM3_ESOFT;
} }
// get key and then get all 8 bytes of payload decoded // get key and then get all 8 bytes of payload decoded
xorKey = (uint8_t)bytebits_to_byteLSBF(bits_no_spacer, 8); xorKey = (uint8_t)bytebits_to_byteLSBF(bits_no_spacer, 8);
for (size_t idx = 0; idx < 8; idx++) { for (size_t idx = 0; idx < 8; idx++) {
ByteStream[idx] = ((uint8_t)bytebits_to_byteLSBF(bits_no_spacer + 8 + (idx * 8), 8)) ^ xorKey; ByteStream[idx] = ((uint8_t)bytebits_to_byteLSBF(bits_no_spacer + 8 + (idx * 8), 8)) ^ xorKey;
PrintAndLogEx(DEBUG, "DEBUG: gProxII byte %u after xor: %02x", (unsigned int)idx, ByteStream[idx]); PrintAndLogEx(DEBUG, "DEBUG: gProxII byte %zu after xor: %02x", idx, ByteStream[idx]);
} }
setDemodBuff(DemodBuffer, 96, preambleIndex); setDemodBuff(DemodBuffer, 96, preambleIndex);

View file

@ -123,7 +123,7 @@ static int sendTry(uint8_t format_idx, wiegand_card_t *card, uint32_t delay, boo
} }
if (verbose) if (verbose)
PrintAndLogEx(INFO, "Trying FC: %u; CN: %u; Issue level: %u; OEM: %u", card->FacilityCode, card->CardNumber, card->IssueLevel, card->OEM); PrintAndLogEx(INFO, "Trying FC: %u; CN: %"PRIu64"; Issue level: %u; OEM: %u", card->FacilityCode, card->CardNumber, card->IssueLevel, card->OEM);
lf_hidsim_t payload; lf_hidsim_t payload;
payload.hi2 = packed.Top; payload.hi2 = packed.Top;
@ -177,7 +177,7 @@ static int CmdHIDDemod(const char *Cmd) {
else if (idx == -4) else if (idx == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - HID preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - HID preamble not found");
else if (idx == -5) else if (idx == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - HID error in Manchester data, size %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - HID error in Manchester data, size %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - HID error demoding fsk %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - HID error demoding fsk %d", idx);
@ -239,7 +239,7 @@ static int CmdHIDDemod(const char *Cmd) {
fc = ((hi & 0xF) << 12) | (lo >> 20); fc = ((hi & 0xF) << 12) | (lo >> 20);
} }
if (fmtLen == 32 && (lo & 0x40000000)) { //if 32 bit and Kastle bit set if (fmtLen == 32 && (lo & 0x40000000)) { //if 32 bit and Kastle bit set
PrintAndLogEx(SUCCESS, "HID Prox TAG (Kastle format) ID: %08x (%u) - Format Len: 32bit - CC: %u - FC: %u - Card: %u", lo, (lo >> 1) & 0xFFFF, cc, fc, cardnum); PrintAndLogEx(SUCCESS, "HID Prox TAG (Kastle format) ID: %x%08x (%u) - Format Len: 32bit - CC: %u - FC: %u - Card: %u", hi, lo, (lo >> 1) & 0xFFFF, cc, fc, cardnum);
} else { } else {
PrintAndLogEx(SUCCESS, "HID Prox TAG ID: %x%08x (%u) - Format Len: %ubit - OEM: %03u - FC: %u - Card: %u", PrintAndLogEx(SUCCESS, "HID Prox TAG ID: %x%08x (%u) - Format Len: %ubit - OEM: %03u - FC: %u - Card: %u",
hi, lo, cardnum, fmtLen, oem, fc, cardnum); hi, lo, cardnum, fmtLen, oem, fc, cardnum);

View file

@ -98,7 +98,7 @@ static int CmdIndalaDemod(const char *Cmd) {
else if (idx == -4) else if (idx == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: preamble not found");
else if (idx == -5) else if (idx == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: error demoding psk idx: %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - Indala: error demoding psk idx: %d", idx);
return PM3_ESOFT; return PM3_ESOFT;
@ -114,7 +114,7 @@ static int CmdIndalaDemod(const char *Cmd) {
if (DemodBufferLen == 64) { if (DemodBufferLen == 64) {
PrintAndLogEx( PrintAndLogEx(
SUCCESS SUCCESS
, "Indala Found - bitlength %d, Raw %x%08x" , "Indala Found - bitlength %zu, Raw %x%08x"
, DemodBufferLen , DemodBufferLen
, uid1 , uid1
, uid2 , uid2
@ -161,7 +161,7 @@ static int CmdIndalaDemod(const char *Cmd) {
uint32_t uid7 = bytebits_to_byte(DemodBuffer + 192, 32); uint32_t uid7 = bytebits_to_byte(DemodBuffer + 192, 32);
PrintAndLogEx( PrintAndLogEx(
SUCCESS SUCCESS
, "Indala Found - bitlength %d, Raw 0x%x%08x%08x%08x%08x%08x%08x" , "Indala Found - bitlength %zu, Raw 0x%x%08x%08x%08x%08x%08x%08x"
, DemodBufferLen , DemodBufferLen
, uid1 , uid1
, uid2 , uid2
@ -237,7 +237,7 @@ static int CmdIndalaDemodAlt(const char *Cmd) {
} }
if (rawbit > 0) { if (rawbit > 0) {
PrintAndLogEx(INFO, "Recovered %d raw bits, expected: %d", rawbit, GraphTraceLen / 32); PrintAndLogEx(INFO, "Recovered %d raw bits, expected: %zu", rawbit, GraphTraceLen / 32);
PrintAndLogEx(INFO, "worst metric (0=best..7=worst): %d at pos %d", worst, worstPos); PrintAndLogEx(INFO, "worst metric (0=best..7=worst): %d at pos %d", worst, worstPos);
} else { } else {
return PM3_ESOFT; return PM3_ESOFT;
@ -629,7 +629,7 @@ out:
//PrintAndLogEx(INFO, "DEBUG: detectindala RES = %d | %d | %d", res, found_size, idx); //PrintAndLogEx(INFO, "DEBUG: detectindala RES = %d | %d | %d", res, found_size, idx);
if (found_size != 224 && found_size != 64) { if (found_size != 224 && found_size != 64) {
PrintAndLogEx(INFO, "DEBUG: detectindala | %d", found_size); PrintAndLogEx(INFO, "DEBUG: detectindala | %zu", found_size);
return -5; return -5;
} }

View file

@ -109,7 +109,7 @@ static int CmdIOProxDemod(const char *Cmd) {
} else if (idx == -4) { } else if (idx == -4) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox preamble not found");
} else if (idx == -5) { } else if (idx == -5) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO size not correct, size %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - IO size not correct, size %zu", size);
} else if (idx == -6) { } else if (idx == -6) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox separator bits not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox separator bits not found");
} else { } else {
@ -123,7 +123,7 @@ static int CmdIOProxDemod(const char *Cmd) {
if (idx == 0) { if (idx == 0) {
if (g_debugMode) { if (g_debugMode) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox data not found - FSK Bits: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox data not found - FSK Bits: %zu", size);
if (size > 92) PrintAndLogEx(DEBUG, "%s", sprint_bin_break(bits, 92, 16)); if (size > 92) PrintAndLogEx(DEBUG, "%s", sprint_bin_break(bits, 92, 16));
} }
return PM3_ESOFT; return PM3_ESOFT;
@ -176,7 +176,7 @@ static int CmdIOProxDemod(const char *Cmd) {
PrintAndLogEx(SUCCESS, "IO Prox XSF(%02d)%02x:%05d (%08x%08x) [crc %s]", version, facilitycode, number, code, code2, crcStr); PrintAndLogEx(SUCCESS, "IO Prox XSF(%02d)%02x:%05d (%08x%08x) [crc %s]", version, facilitycode, number, code, code2, crcStr);
if (g_debugMode) { if (g_debugMode) {
PrintAndLogEx(DEBUG, "DEBUG: IO prox idx: %d, Len: %d, Printing demod buffer:", idx, size); PrintAndLogEx(DEBUG, "DEBUG: IO prox idx: %d, Len: %zu, Printing demod buffer:", idx, size);
printDemodBuff(); printDemodBuff();
} }
return retval; return retval;

View file

@ -94,7 +94,7 @@ static int CmdJablotronDemod(const char *Cmd) {
else if (ans == -2) else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - Jablotron preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Jablotron preamble not found");
else if (ans == -3) else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Jablotron size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Jablotron size not correct: %zu", size);
else if (ans == -5) else if (ans == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - Jablotron checksum failed"); PrintAndLogEx(DEBUG, "DEBUG: Error - Jablotron checksum failed");
else else

View file

@ -70,7 +70,7 @@ static int CmdKeriDemod(const char *Cmd) {
else if (idx == -2) else if (idx == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: preamble not found");
else if (idx == -3) else if (idx == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: Size not correct: 64 != %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: Size not correct: 64 != %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: ans: %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: ans: %d", idx);
@ -154,7 +154,7 @@ static int CmdKeriClone(const char *Cmd) {
// 3 LSB is ONE // 3 LSB is ONE
uint64_t data = ((uint64_t)internalid << 3) + 7; uint64_t data = ((uint64_t)internalid << 3) + 7;
PrintAndLogEx(INFO, "Preparing to clone KERI to T55x7 with Internal Id: %" PRIx64, internalid); PrintAndLogEx(INFO, "Preparing to clone KERI to T55x7 with Internal Id: %" PRIx32, internalid);
blocks[1] = data >> 32; blocks[1] = data >> 32;
blocks[2] = data & 0xFFFFFFFF; blocks[2] = data & 0xFFFFFFFF;
@ -182,7 +182,7 @@ static int CmdKeriSim(const char *Cmd) {
bs[j++] = ((internalid >> i) & 1); bs[j++] = ((internalid >> i) & 1);
} }
PrintAndLogEx(SUCCESS, "Simulating KERI - Internal Id: %u", internalid); PrintAndLogEx(SUCCESS, "Simulating KERI - Internal Id: %" PRIu64, internalid);
lf_psksim_t *payload = calloc(1, sizeof(lf_psksim_t) + sizeof(bs)); lf_psksim_t *payload = calloc(1, sizeof(lf_psksim_t) + sizeof(bs));
payload->carrier = 2; payload->carrier = 2;

View file

@ -124,7 +124,7 @@ static int CmdLFNedapDemod(const char *Cmd) {
// sanity checks // sanity checks
if ((size != 128) && (size != 64)) { if ((size != 128) && (size != 64)) {
PrintAndLogEx(DEBUG, "DEBUG: Error - NEDAP: Size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - NEDAP: Size not correct: %zu", size);
return PM3_ESOFT; return PM3_ESOFT;
} }

View file

@ -85,7 +85,7 @@ static int CmdNoralsyDemod(const char *Cmd) {
else if (ans == -2) else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: preamble not found");
else if (ans == -3) else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: Size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: Size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: ans: %d", ans); PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: ans: %d", ans);
} }
@ -142,7 +142,6 @@ static int CmdNoralsyClone(const char *Cmd) {
uint16_t year = 0; uint16_t year = 0;
uint32_t id = 0; uint32_t id = 0;
uint32_t blocks[4] = {T55x7_MODULATION_MANCHESTER | T55x7_BITRATE_RF_32 | T55x7_ST_TERMINATOR | 3 << T55x7_MAXBLOCK_SHIFT, 0, 0}; uint32_t blocks[4] = {T55x7_MODULATION_MANCHESTER | T55x7_BITRATE_RF_32 | T55x7_ST_TERMINATOR | 3 << T55x7_MAXBLOCK_SHIFT, 0, 0};
uint8_t *bits = calloc(96, sizeof(uint8_t));
char cmdp = tolower(param_getchar(Cmd, 0)); char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_noralsy_clone(); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_noralsy_clone();
@ -154,8 +153,10 @@ static int CmdNoralsyClone(const char *Cmd) {
if (tolower(param_getchar(Cmd, 2) == 'q')) if (tolower(param_getchar(Cmd, 2) == 'q'))
blocks[0] = T5555_MODULATION_MANCHESTER | T5555_SET_BITRATE(32) | T5555_ST_TERMINATOR | 3 << T5555_MAXBLOCK_SHIFT; blocks[0] = T5555_MODULATION_MANCHESTER | T5555_SET_BITRATE(32) | T5555_ST_TERMINATOR | 3 << T5555_MAXBLOCK_SHIFT;
uint8_t *bits = calloc(96, sizeof(uint8_t));
if (getnoralsyBits(id, year, bits) != PM3_SUCCESS) { if (getnoralsyBits(id, year, bits) != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Error with tag bitstream generation."); PrintAndLogEx(ERR, "Error with tag bitstream generation.");
free(bits);
return PM3_ESOFT; return PM3_ESOFT;
} }

View file

@ -53,7 +53,7 @@ static int CmdPacDemod(const char *Cmd) {
else if (ans == -2) else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: preamble not found");
else if (ans == -3) else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: Size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: Size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: ans: %d", ans); PrintAndLogEx(DEBUG, "DEBUG: Error - PAC: ans: %d", ans);

View file

@ -86,7 +86,7 @@ static int CmdParadoxDemod(const char *Cmd) {
else if (idx == -4) else if (idx == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox preamble not found");
else if (idx == -5) else if (idx == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox error in Manchester data, size %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox error in Manchester data, size %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox error demoding fsk %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox error demoding fsk %d", idx);
@ -117,7 +117,7 @@ static int CmdParadoxDemod(const char *Cmd) {
rawLo rawLo
); );
PrintAndLogEx(DEBUG, "DEBUG: Paradox idx: %d, len: %d, Printing Demod Buffer:", idx, size); PrintAndLogEx(DEBUG, "DEBUG: Paradox idx: %d, len: %zu, Printing Demod Buffer:", idx, size);
if (g_debugMode) if (g_debugMode)
printDemodBuff(); printDemodBuff();

View file

@ -72,7 +72,7 @@ static int CmdPrescoDemod(const char *Cmd) {
else if (ans == -2) else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: preamble not found");
else if (ans == -3) else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: Size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: Size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: ans: %d", ans); PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: ans: %d", ans);
return PM3_ESOFT; return PM3_ESOFT;

View file

@ -87,7 +87,7 @@ static int CmdPyramidDemod(const char *Cmd) {
else if (idx == -4) else if (idx == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: preamble not found");
else if (idx == -5) else if (idx == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: error demoding fsk idx: %d", idx); PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: error demoding fsk idx: %d", idx);
return PM3_ESOFT; return PM3_ESOFT;
@ -137,7 +137,7 @@ static int CmdPyramidDemod(const char *Cmd) {
if (size == 0) if (size == 0)
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: parity check failed - IDX: %d, hi3: %08X", idx, rawHi3); PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: parity check failed - IDX: %d, hi3: %08X", idx, rawHi3);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: at parity check - tag size does not match Pyramid format, SIZE: %d, IDX: %d, hi3: %08X", size, idx, rawHi3); PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: at parity check - tag size does not match Pyramid format, SIZE: %zu, IDX: %d, hi3: %08X", size, idx, rawHi3);
return PM3_ESOFT; return PM3_ESOFT;
} }
@ -217,16 +217,14 @@ static int CmdPyramidClone(const char *Cmd) {
char cmdp = tolower(param_getchar(Cmd, 0)); char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_pyramid_clone(); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_pyramid_clone();
uint32_t facilitycode = 0, cardnumber = 0, fc = 0, cn = 0; uint32_t facilitycode = 0, cardnumber = 0, fc = 0, cn = 0;
if (sscanf(Cmd, "%u %u", &fc, &cn) != 2) return usage_lf_pyramid_clone();
uint32_t blocks[5]; uint32_t blocks[5];
uint8_t *bs = calloc(128, sizeof(uint8_t)); uint8_t *bs = calloc(128, sizeof(uint8_t));
if (bs == NULL) { if (bs == NULL) {
return PM3_EMALLOC; return PM3_EMALLOC;
} }
if (sscanf(Cmd, "%u %u", &fc, &cn) != 2) return usage_lf_pyramid_clone();
facilitycode = (fc & 0x000000FF); facilitycode = (fc & 0x000000FF);
cardnumber = (cn & 0x0000FFFF); cardnumber = (cn & 0x0000FFFF);

View file

@ -59,7 +59,7 @@ static int CmdSecurakeyDemod(const char *Cmd) {
else if (ans == -2) else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: preamble not found");
else if (ans == -3) else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: Size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: Size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: ans: %d", ans); PrintAndLogEx(DEBUG, "DEBUG: Error - Securakey: ans: %d", ans);
return PM3_ESOFT; return PM3_ESOFT;
@ -90,7 +90,7 @@ static int CmdSecurakeyDemod(const char *Cmd) {
// remove marker bits (0's every 9th digit after preamble) (pType = 3 (always 0s)) // remove marker bits (0's every 9th digit after preamble) (pType = 3 (always 0s))
size = removeParity(bits_no_spacer, 0, 9, 3, 85); size = removeParity(bits_no_spacer, 0, 9, 3, 85);
if (size != 85 - 9) { if (size != 85 - 9) {
PrintAndLogEx(DEBUG, "DEBUG: Error removeParity: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error removeParity: %zu", size);
return 0; return 0;
} }

View file

@ -83,7 +83,7 @@ static int usage_t55xx_config() {
PrintAndLogEx(NORMAL, " d <FSK|FSK1|FSK1a|FSK2|FSK2a|ASK|PSK1|PSK2|NRZ|BI|BIa> - Set demodulation FSK / ASK / PSK / NRZ / Biphase / Biphase A"); PrintAndLogEx(NORMAL, " d <FSK|FSK1|FSK1a|FSK2|FSK2a|ASK|PSK1|PSK2|NRZ|BI|BIa> - Set demodulation FSK / ASK / PSK / NRZ / Biphase / Biphase A");
PrintAndLogEx(NORMAL, " i [0/1] - Set/reset data signal inversion"); PrintAndLogEx(NORMAL, " i [0/1] - Set/reset data signal inversion");
PrintAndLogEx(NORMAL, " o [offset] - Set offset, where data should start decode in bitstream"); PrintAndLogEx(NORMAL, " o [offset] - Set offset, where data should start decode in bitstream");
PrintAndLogEx(NORMAL, " Q5 [0/1] - Set/reset as Q5(T5555) chip instead of T55x7"); PrintAndLogEx(NORMAL, " Q5 [0/1] - Set/reset as T5555 ( Q5 ) chip instead of T55x7");
PrintAndLogEx(NORMAL, " ST [0/1] - Set/reset Sequence Terminator on"); PrintAndLogEx(NORMAL, " ST [0/1] - Set/reset Sequence Terminator on");
PrintAndLogEx(NORMAL, ""); // layout is a little differnet, so seperate until a better fix PrintAndLogEx(NORMAL, ""); // layout is a little differnet, so seperate until a better fix
print_usage_t55xx_downloadlink(T55XX_DLMODE_SINGLE); print_usage_t55xx_downloadlink(T55XX_DLMODE_SINGLE);
@ -103,9 +103,10 @@ static int usage_t55xx_read() {
PrintAndLogEx(NORMAL, " o - OPTIONAL override safety check"); PrintAndLogEx(NORMAL, " o - OPTIONAL override safety check");
PrintAndLogEx(NORMAL, " 1 - OPTIONAL 0|1 read Page 1 instead of Page 0"); PrintAndLogEx(NORMAL, " 1 - OPTIONAL 0|1 read Page 1 instead of Page 0");
print_usage_t55xx_downloadlink(T55XX_DLMODE_SINGLE); print_usage_t55xx_downloadlink(T55XX_DLMODE_SINGLE);
PrintAndLogEx(NORMAL, " ****WARNING****"); PrintAndLogEx(NORMAL, " " _RED_("**** WARNING ****"));
PrintAndLogEx(NORMAL, " Use of read with password on a tag not configured for a pwd"); PrintAndLogEx(NORMAL, " Use of read with password on a tag not configured");
PrintAndLogEx(NORMAL, " can damage the tag"); PrintAndLogEx(NORMAL, " for a password can damage the tag");
PrintAndLogEx(NORMAL, " " _RED_("*****************"));
PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf t55xx read b 0 - read data from block 0"); PrintAndLogEx(NORMAL, " lf t55xx read b 0 - read data from block 0");
@ -232,7 +233,7 @@ static int usage_t55xx_wakup() {
static int usage_t55xx_chk() { static int usage_t55xx_chk() {
PrintAndLogEx(NORMAL, "This command uses a dictionary attack"); PrintAndLogEx(NORMAL, "This command uses a dictionary attack");
PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command"); PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command");
PrintAndLogEx(NORMAL, "WARNING: this may brick non-password protected chips!"); PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!");
PrintAndLogEx(NORMAL, "Try to reading block 7 before\n"); PrintAndLogEx(NORMAL, "Try to reading block 7 before\n");
PrintAndLogEx(NORMAL, "Usage: lf t55xx chk [h] [m] [r <mode>] [i <*.dic>]"); PrintAndLogEx(NORMAL, "Usage: lf t55xx chk [h] [m] [r <mode>] [i <*.dic>]");
PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, "Options:");
@ -250,7 +251,7 @@ static int usage_t55xx_chk() {
static int usage_t55xx_bruteforce() { static int usage_t55xx_bruteforce() {
PrintAndLogEx(NORMAL, "This command uses bruteforce to scan a number range"); PrintAndLogEx(NORMAL, "This command uses bruteforce to scan a number range");
PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command"); PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command");
PrintAndLogEx(NORMAL, "WARNING: this may brick non-password protected chips!"); PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!");
PrintAndLogEx(NORMAL, "Try reading block 7 before\n"); PrintAndLogEx(NORMAL, "Try reading block 7 before\n");
PrintAndLogEx(NORMAL, "Usage: lf t55xx bruteforce [h] [r <mode>] [s <start password>] [e <end password>]"); PrintAndLogEx(NORMAL, "Usage: lf t55xx bruteforce [h] [r <mode>] [s <start password>] [e <end password>]");
PrintAndLogEx(NORMAL, " password must be 4 bytes (8 hex symbols)"); PrintAndLogEx(NORMAL, " password must be 4 bytes (8 hex symbols)");
@ -268,7 +269,7 @@ static int usage_t55xx_bruteforce() {
static int usage_t55xx_recoverpw() { static int usage_t55xx_recoverpw() {
PrintAndLogEx(NORMAL, "This command uses a few tricks to try to recover mangled password"); PrintAndLogEx(NORMAL, "This command uses a few tricks to try to recover mangled password");
PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command"); PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command");
PrintAndLogEx(NORMAL, "WARNING: this may brick non-password protected chips!"); PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!");
PrintAndLogEx(NORMAL, "Try reading block 7 before\n"); PrintAndLogEx(NORMAL, "Try reading block 7 before\n");
PrintAndLogEx(NORMAL, "Usage: lf t55xx recoverpw [r <mode>] [p <password>]"); PrintAndLogEx(NORMAL, "Usage: lf t55xx recoverpw [r <mode>] [p <password>]");
PrintAndLogEx(NORMAL, " password must be 4 bytes (8 hex symbols)"); PrintAndLogEx(NORMAL, " password must be 4 bytes (8 hex symbols)");
@ -292,11 +293,11 @@ static int usage_t55xx_wipe() {
PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h - this help"); PrintAndLogEx(NORMAL, " h - this help");
PrintAndLogEx(NORMAL, " c <block0> - set configuration from a block0"); PrintAndLogEx(NORMAL, " c <block0> - set configuration from a block0");
PrintAndLogEx(NORMAL, " q - indicates to use the T5555 (Q5) default configuration block"); PrintAndLogEx(NORMAL, " q - indicates to use T5555 ( Q5 ) default configuration block");
PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf t55xx wipe - wipes a t55x7 tag, config block 0x000880E0"); PrintAndLogEx(NORMAL, " lf t55xx wipe - wipes a T55x7 tag, config block 0x000880E0");
PrintAndLogEx(NORMAL, " lf t55xx wipe q - wipes a t5555 Q5 tag, config block 0x6001F004"); PrintAndLogEx(NORMAL, " lf t55xx wipe q - wipes a T5555 ( Q5 ) tag, config block 0x6001F004");
return PM3_SUCCESS; return PM3_SUCCESS;
} }
static int usage_t55xx_deviceconfig() { static int usage_t55xx_deviceconfig() {
@ -342,7 +343,7 @@ int clone_t55xx_tag(uint32_t *blockdata, uint8_t numblocks) {
if (blockdata == NULL) if (blockdata == NULL)
return PM3_EINVARG; return PM3_EINVARG;
if (numblocks < 1 || numblocks > 7) if (numblocks < 1 || numblocks > 8)
return PM3_EINVARG; return PM3_EINVARG;
PacketResponseNG resp; PacketResponseNG resp;
@ -1256,7 +1257,7 @@ bool GetT55xxBlockData(uint32_t *blockdata) {
uint8_t idx = config.offset; uint8_t idx = config.offset;
if (idx + 32 > DemodBufferLen) { if (idx + 32 > DemodBufferLen) {
PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %d)", idx, DemodBufferLen - 32); PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %zu)", idx, DemodBufferLen - 32);
return false; return false;
} }
@ -1473,7 +1474,7 @@ int special(const char *Cmd) {
} }
int printConfiguration(t55xx_conf_block_t b) { int printConfiguration(t55xx_conf_block_t b) {
PrintAndLogEx(NORMAL, " Chip Type : %s", (b.Q5) ? "T5555(Q5)" : "T55x7"); PrintAndLogEx(NORMAL, " Chip Type : %s", (b.Q5) ? "T5555 ( Q5 )" : "T55x7");
PrintAndLogEx(NORMAL, " Modulation : %s", GetSelectedModulationStr(b.modulation)); PrintAndLogEx(NORMAL, " Modulation : %s", GetSelectedModulationStr(b.modulation));
PrintAndLogEx(NORMAL, " Bit Rate : %s", GetBitRateStr(b.bitrate, (b.block0 & T55x7_X_MODE && (b.block0 >> 28 == 6 || b.block0 >> 28 == 9)))); PrintAndLogEx(NORMAL, " Bit Rate : %s", GetBitRateStr(b.bitrate, (b.block0 & T55x7_X_MODE && (b.block0 >> 28 == 6 || b.block0 >> 28 == 9))));
PrintAndLogEx(NORMAL, " Inverted : %s", (b.inverted) ? _GREEN_("Yes") : "No"); PrintAndLogEx(NORMAL, " Inverted : %s", (b.inverted) ? _GREEN_("Yes") : "No");
@ -1682,7 +1683,7 @@ static int CmdT55xxReadTrace(const char *Cmd) {
si += 9; si += 9;
if (hdr != 0x1FF) { if (hdr != 0x1FF) {
PrintAndLogEx(FAILED, "Invalid Q5 Trace data header (expected 0x1FF, found %X)", hdr); PrintAndLogEx(FAILED, "Invalid T555 ( Q5 ) Trace data header (expected 0x1FF, found %X)", hdr);
return PM3_ESOFT; return PM3_ESOFT;
} }
@ -1809,7 +1810,7 @@ void printT55x7Trace(t55x7_tracedata_t data, uint8_t repeat) {
} }
void printT5555Trace(t5555_tracedata_t data, uint8_t repeat) { void printT5555Trace(t5555_tracedata_t data, uint8_t repeat) {
PrintAndLogEx(NORMAL, "-- T5555 (Q5) Trace Information -----------------------------"); PrintAndLogEx(NORMAL, "-- T5555 ( Q5 ) Trace Information ---------------------------");
PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
PrintAndLogEx(NORMAL, " ICR IC Revision : %d", data.icr); PrintAndLogEx(NORMAL, " ICR IC Revision : %d", data.icr);
PrintAndLogEx(NORMAL, " Lot : %c%d", data.lotidc, data.lotid); PrintAndLogEx(NORMAL, " Lot : %c%d", data.lotidc, data.lotid);
@ -1976,7 +1977,7 @@ static int CmdT55xxInfo(const char *Cmd) {
uint32_t inv = (block0 >> (32 - 25)) & 0x01; uint32_t inv = (block0 >> (32 - 25)) & 0x01;
uint32_t datamod = (block0 >> (32 - 28)) & 0x07; uint32_t datamod = (block0 >> (32 - 28)) & 0x07;
uint32_t maxblk = (block0 >> (32 - 31)) & 0x07; uint32_t maxblk = (block0 >> (32 - 31)) & 0x07;
uint32_t st = (block0 >> (32 - 32)) & 0x01; uint32_t st = block0 & 0x01;
PrintAndLogEx(NORMAL, "-- Q5 Configuration & Tag Information -----------------------"); PrintAndLogEx(NORMAL, "-- Q5 Configuration & Tag Information -----------------------");
PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
PrintAndLogEx(NORMAL, " Header : 0x%03X%s", header, (header != 0x600) ? _RED_(" - Warning") : ""); PrintAndLogEx(NORMAL, " Header : 0x%03X%s", header, (header != 0x600) ? _RED_(" - Warning") : "");
@ -2388,7 +2389,7 @@ static void t55x7_create_config_block(int tagtype) {
snprintf(retStr, sizeof(buf), "%08X - T55X7 Raw", T55X7_RAW_CONFIG_BLOCK); snprintf(retStr, sizeof(buf), "%08X - T55X7 Raw", T55X7_RAW_CONFIG_BLOCK);
break; break;
case 2: case 2:
snprintf(retStr, sizeof(buf), "%08X - T5555 Q5 Default", T5555_DEFAULT_CONFIG_BLOCK); snprintf(retStr, sizeof(buf), "%08X - T5555 ( Q5 ) Default", T5555_DEFAULT_CONFIG_BLOCK);
break; break;
default: default:
break; break;
@ -2426,19 +2427,31 @@ static int CmdResetRead(const char *Cmd) {
flags = downlink_mode << 3; flags = downlink_mode << 3;
PacketResponseNG resp;
clearCommandBuffer(); clearCommandBuffer();
SendCommandNG(CMD_LF_T55XX_RESET_READ, &flags, sizeof(flags)); SendCommandNG(CMD_LF_T55XX_RESET_READ, &flags, sizeof(flags));
if (!WaitForResponseTimeout(CMD_ACK, NULL, 2500)) { if (!WaitForResponseTimeout(CMD_LF_T55XX_RESET_READ, &resp, 2500)) {
PrintAndLogEx(WARNING, "command execution time out"); PrintAndLogEx(WARNING, "command execution time out");
return PM3_ETIMEOUT; return PM3_ETIMEOUT;
} }
uint8_t got[BIGBUF_SIZE - 1]; if (resp.status == PM3_SUCCESS) {
if (!GetFromDevice(BIG_BUF, got, sizeof(got), 0, NULL, 0, NULL, 2500, false)) {
PrintAndLogEx(WARNING, "command execution time out"); uint8_t *got = calloc(BIGBUF_SIZE - 1, sizeof(uint8_t));
return PM3_ETIMEOUT; if (got == NULL) {
PrintAndLogEx(WARNING, "failed to allocate memory");
return PM3_EMALLOC;
}
if (!GetFromDevice(BIG_BUF, got, sizeof(got), 0, NULL, 0, NULL, 2500, false)) {
PrintAndLogEx(WARNING, "command execution time out");
free(got);
return PM3_ETIMEOUT;
}
setGraphBuf(got, sizeof(got));
free(got);
} }
setGraphBuf(got, sizeof(got));
return PM3_SUCCESS; return PM3_SUCCESS;
} }
@ -2480,7 +2493,7 @@ static int CmdT55xxWipe(const char *Cmd) {
if (errors) return usage_t55xx_wipe(); if (errors) return usage_t55xx_wipe();
PrintAndLogEx(INFO, "\nBegin wiping %s", (Q5) ? "Q5 / T5555 tag" : "T55x7 tag"); PrintAndLogEx(INFO, "\nBegin wiping %s", (Q5) ? "T5555 ( Q5 ) tag" : "T55x7 tag");
// default config blocks. // default config blocks.
if (gotconf == false) { if (gotconf == false) {
@ -2612,12 +2625,12 @@ static int CmdT55xxChkPwds(const char *Cmd) {
} }
if (resp.oldarg[0]) { if (resp.oldarg[0]) {
PrintAndLogEx(SUCCESS, "\nFound a candidate [ " _YELLOW_("%08X") " ]. Trying to validate", resp.oldarg[1]); PrintAndLogEx(SUCCESS, "\nFound a candidate [ " _YELLOW_("%08"PRIX64) " ]. Trying to validate", resp.oldarg[1]);
if (AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, resp.oldarg[1], downlink_mode)) { if (AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, resp.oldarg[1], downlink_mode)) {
found = tryDetectModulation(downlink_mode, T55XX_PrintConfig); found = tryDetectModulation(downlink_mode, T55XX_PrintConfig);
if (found) { if (found) {
PrintAndLogEx(SUCCESS, "Found valid password: [ " _GREEN_("%08X") " ]", resp.oldarg[1]); PrintAndLogEx(SUCCESS, "Found valid password: [ " _GREEN_("%08"PRIX64) " ]", resp.oldarg[1]);
} else { } else {
PrintAndLogEx(WARNING, "Check pwd failed"); PrintAndLogEx(WARNING, "Check pwd failed");
@ -2660,7 +2673,7 @@ static int CmdT55xxChkPwds(const char *Cmd) {
curr_password = bytes_to_num(keyBlock + 4 * c, 4); curr_password = bytes_to_num(keyBlock + 4 * c, 4);
PrintAndLogEx(INFO, "Testing %08X", curr_password); PrintAndLogEx(INFO, "Testing %08"PRIX64, curr_password);
for (dl_mode = downlink_mode; dl_mode <= 3; dl_mode++) { for (dl_mode = downlink_mode; dl_mode <= 3; dl_mode++) {
if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, curr_password, dl_mode)) { if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, curr_password, dl_mode)) {
@ -2669,7 +2682,7 @@ static int CmdT55xxChkPwds(const char *Cmd) {
found = tryDetectModulation(dl_mode, T55XX_PrintConfig); found = tryDetectModulation(dl_mode, T55XX_PrintConfig);
if (found) { if (found) {
PrintAndLogEx(SUCCESS, "Found valid password: [ " _GREEN_("%08X") " ]", curr_password); PrintAndLogEx(SUCCESS, "Found valid password: [ " _GREEN_("%08"PRIX64) " ]", curr_password);
dl_mode = 4; // Exit other downlink mode checks dl_mode = 4; // Exit other downlink mode checks
c = keycount; // Exit loop c = keycount; // Exit loop
} }

170
client/cmdlfverichip.c Normal file
View file

@ -0,0 +1,170 @@
//-----------------------------------------------------------------------------
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Low frequency Verichip tag commands
//NRZ, RF/32, 128 bits long
//-----------------------------------------------------------------------------
#include "cmdlfverichip.h"
#include <ctype.h> //tolower
#include "commonutil.h" // ARRAYLEN
#include "common.h"
#include "cmdparser.h" // command_t
#include "comms.h"
#include "ui.h"
#include "cmddata.h"
#include "cmdlf.h"
#include "lfdemod.h" // preamble test
#include "protocols.h" // t55xx defines
#include "cmdlft55xx.h" // clone..
static int CmdHelp(const char *Cmd);
static int usage_lf_verichip_clone(void) {
PrintAndLogEx(NORMAL, "clone a verichip tag to a T55x7 tag.");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: lf verichip clone [h] [b <raw hex>]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " b <raw hex> : raw hex data. 12 bytes max");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf verichip clone b FF2049906D8511C593155B56D5B2649F ");
return PM3_SUCCESS;
}
//see NRZDemod for what args are accepted
static int CmdVerichipDemod(const char *Cmd) {
//NRZ
if (NRZrawDemod(Cmd, false) != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "DEBUG: Error - VERICHIP: NRZ Demod failed");
return PM3_ESOFT;
}
size_t size = DemodBufferLen;
int ans = detectVerichip(DemodBuffer, &size);
if (ans < 0) {
if (ans == -1)
PrintAndLogEx(DEBUG, "DEBUG: Error - VERICHIP: too few bits found");
else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - VERICHIP: preamble not found");
else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - VERICHIP: Size not correct: %zu", size);
else
PrintAndLogEx(DEBUG, "DEBUG: Error - VERICHIP: ans: %d", ans);
return PM3_ESOFT;
}
setDemodBuff(DemodBuffer, 128, ans);
setClockGrid(g_DemodClock, g_DemodStartIdx + (ans * g_DemodClock));
//got a good demod
uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32);
uint32_t raw2 = bytebits_to_byte(DemodBuffer + 32, 32);
uint32_t raw3 = bytebits_to_byte(DemodBuffer + 64, 32);
uint32_t raw4 = bytebits_to_byte(DemodBuffer + 96, 32);
// preamble then appears to have marker bits of "10" CS?
// 11111111001000000 10 01001100 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 10001100 10 100000001
// unknown checksum 9 bits at the end
PrintAndLogEx(SUCCESS, "VERICHIP Tag Found -- Raw: %08X%08X%08X%08X", raw1, raw2, raw3, raw4);
PrintAndLogEx(INFO, "How the Raw ID is translated by the reader is unknown. Share your trace file on forum");
return PM3_SUCCESS;
}
static int CmdVerichipRead(const char *Cmd) {
lf_read(true, 4096 * 2 + 20);
return CmdVerichipDemod(Cmd);
}
static int CmdVerichipClone(const char *Cmd) {
uint32_t blocks[5];
bool errors = false;
uint8_t cmdp = 0;
int datalen = 0;
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return usage_lf_verichip_clone();
case 'b': {
// skip first block, 4*4 = 16 bytes left
uint8_t rawhex[16] = {0};
int res = param_gethex_to_eol(Cmd, cmdp + 1, rawhex, sizeof(rawhex), &datalen);
if ( res != 0 )
errors = true;
for(uint8_t i = 1; i < ARRAYLEN(blocks); i++) {
blocks[i] = bytes_to_num(rawhex + ( (i - 1) * 4 ), sizeof(uint32_t));
}
cmdp += 2;
break;
}
default:
PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp));
errors = true;
break;
}
}
if (errors || cmdp == 0) return usage_lf_verichip_clone();
//Pac - compat mode, NRZ, data rate 40, 3 data blocks
blocks[0] = T55x7_MODULATION_DIRECT | T55x7_BITRATE_RF_40 | 4 << T55x7_MAXBLOCK_SHIFT;
PrintAndLogEx(INFO, "Preparing to clone Verichip to T55x7 with raw hex");
print_blocks(blocks, ARRAYLEN(blocks));
return clone_t55xx_tag(blocks, ARRAYLEN(blocks));
}
static int CmdVerichipSim(const char *Cmd) {
// NRZ sim.
PrintAndLogEx(INFO, " To be implemented, feel free to contribute!");
return PM3_SUCCESS;
}
static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"demod", CmdVerichipDemod, AlwaysAvailable, "Demodulate an VERICHIP tag from the GraphBuffer"},
{"read", CmdVerichipRead, IfPm3Lf, "Attempt to read and extract tag data from the antenna"},
{"clone", CmdVerichipClone, IfPm3Lf, "clone VERICHIP tag"},
{"sim", CmdVerichipSim, IfPm3Lf, "simulate VERICHIP tag"},
{NULL, NULL, NULL, NULL}
};
static int CmdHelp(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
CmdsHelp(CommandTable);
return PM3_SUCCESS;
}
int CmdLFVerichip(const char *Cmd) {
clearCommandBuffer();
return CmdsParse(CommandTable, Cmd);
}
// by marshmellow
// find PAC preamble in already demoded data
int detectVerichip(uint8_t *dest, size_t *size) {
if (*size < 128) return -1; //make sure buffer has data
size_t startIdx = 0;
uint8_t preamble[] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0};
if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx))
return -2; //preamble not found
if (*size != 128) return -3; //wrong demoded size
//return start position
return (int)startIdx;
}
int demodVerichip(void) {
return CmdVerichipDemod("");
}

19
client/cmdlfverichip.h Normal file
View file

@ -0,0 +1,19 @@
//-----------------------------------------------------------------------------
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Low frequency Verichip tag commands
//-----------------------------------------------------------------------------
#ifndef CMDLFVERICHIP_H__
#define CMDLFVERICHIP_H__
#include "common.h"
int CmdLFVerichip(const char *Cmd);
int demodVerichip(void);
int detectVerichip(uint8_t *dest, size_t *size);
#endif

View file

@ -14,6 +14,7 @@
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
#include <stdlib.h> #include <stdlib.h>
#include <inttypes.h>
#include "commonutil.h" // ARRAYLEN #include "commonutil.h" // ARRAYLEN
#include "common.h" #include "common.h"
@ -119,7 +120,7 @@ static int CmdVisa2kDemod(const char *Cmd) {
else if (ans == -2) else if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: preamble not found"); PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: preamble not found");
else if (ans == -3) else if (ans == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: Size not correct: %d", size); PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: Size not correct: %zu", size);
else else
PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ans: %d", ans); PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ans: %d", ans);
@ -180,7 +181,7 @@ static int CmdVisa2kClone(const char *Cmd) {
blocks[2] = id; blocks[2] = id;
blocks[3] = (visa_parity(id) << 4) | visa_chksum(id); blocks[3] = (visa_parity(id) << 4) | visa_chksum(id);
PrintAndLogEx(INFO, "Preparing to clone Visa2000 to T55x7 with CardId: %u", id); PrintAndLogEx(INFO, "Preparing to clone Visa2000 to T55x7 with CardId: %"PRIu64, id);
print_blocks(blocks, ARRAYLEN(blocks)); print_blocks(blocks, ARRAYLEN(blocks));
return clone_t55xx_tag(blocks, ARRAYLEN(blocks)); return clone_t55xx_tag(blocks, ARRAYLEN(blocks));

View file

@ -92,19 +92,20 @@ static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help. Use '<command> help' for details of a particular command."}, {"help", CmdHelp, AlwaysAvailable, "This help. Use '<command> help' for details of a particular command."},
{"analyse", CmdAnalyse, AlwaysAvailable, "{ Analyse utils... }"}, {"analyse", CmdAnalyse, AlwaysAvailable, "{ Analyse utils... }"},
{"data", CmdData, AlwaysAvailable, "{ Plot window / data buffer manipulation... }"}, {"data", CmdData, AlwaysAvailable, "{ Plot window / data buffer manipulation... }"},
{"emv", CmdEMV, AlwaysAvailable, "{ EMV iso14443 and iso7816... }"}, {"emv", CmdEMV, AlwaysAvailable, "{ EMV ISO-14443 / ISO-7816... }"},
{"hf", CmdHF, AlwaysAvailable, "{ High Frequency commands... }"}, {"hf", CmdHF, AlwaysAvailable, "{ High frequency commands... }"},
{"hw", CmdHW, AlwaysAvailable, "{ Hardware commands... }"}, {"hw", CmdHW, AlwaysAvailable, "{ Hardware commands... }"},
{"lf", CmdLF, AlwaysAvailable, "{ Low Frequency commands... }"}, {"lf", CmdLF, AlwaysAvailable, "{ Low frequency commands... }"},
{"mem", CmdFlashMem, IfPm3Flash, "{ Flash Memory manipulation... }"}, {"mem", CmdFlashMem, IfPm3Flash, "{ Flash Memory manipulation... }"},
{"msleep", CmdMsleep, AlwaysAvailable, "Add a pause in milliseconds"},
{"rem", CmdRem, AlwaysAvailable, "Add text to row in log file"},
{"reveng", CmdRev, AlwaysAvailable, "{ CRC calculations from RevEng software }"}, {"reveng", CmdRev, AlwaysAvailable, "{ CRC calculations from RevEng software }"},
{"sc", CmdSmartcard, IfPm3Smartcard, "{ Smart card ISO7816 commands... }"}, {"sc", CmdSmartcard, IfPm3Smartcard, "{ Smart card ISO-7816 commands... }"},
{"script", CmdScript, AlwaysAvailable, "{ Scripting commands }"}, {"script", CmdScript, AlwaysAvailable, "{ Scripting commands }"},
{"trace", CmdTrace, AlwaysAvailable, "{ Trace manipulation... }"}, {"trace", CmdTrace, AlwaysAvailable, "{ Trace manipulation... }"},
{"usart", CmdUsart, IfPm3FpcUsartFromUsb, "{ USART commands... }"}, {"usart", CmdUsart, IfPm3FpcUsartFromUsb, "{ USART commands... }"},
{"wiegand", CmdWiegand, AlwaysAvailable, "{ Wiegand format manipulation... }"}, {"wiegand", CmdWiegand, AlwaysAvailable, "{ Wiegand format manipulation... }"},
{"", CmdHelp, AlwaysAvailable, ""},
{"msleep", CmdMsleep, AlwaysAvailable, "Add a pause in milliseconds"},
{"rem", CmdRem, AlwaysAvailable, "Add a text line in log file"},
{"quit", CmdQuit, AlwaysAvailable, ""}, {"quit", CmdQuit, AlwaysAvailable, ""},
{"exit", CmdQuit, AlwaysAvailable, "Exit program"}, {"exit", CmdQuit, AlwaysAvailable, "Exit program"},
{NULL, NULL, NULL, NULL} {NULL, NULL, NULL, NULL}

View file

@ -155,7 +155,8 @@ void CmdsHelp(const command_t Commands[]) {
int i = 0; int i = 0;
while (Commands[i].Name) { while (Commands[i].Name) {
if (Commands[i].IsAvailable()) if (Commands[i].IsAvailable())
PrintAndLogEx(NORMAL, _GREEN_("%-16s")" %s", Commands[i].Name, Commands[i].Help); // PrintAndLogEx(NORMAL, _GREEN_("%-16s")" %s", Commands[i].Name, Commands[i].Help);
printf(_GREEN_("%-16s")" %s\n", Commands[i].Name, Commands[i].Help);
++i; ++i;
} }
} }

View file

@ -60,6 +60,7 @@ static int CmdScriptRun(const char *Cmd) {
int error; int error;
if (luascriptfile_idx == MAX_NESTED_LUASCRIPT) { if (luascriptfile_idx == MAX_NESTED_LUASCRIPT) {
PrintAndLogEx(ERR, "Too many nested scripts, skipping %s\n", script_path); PrintAndLogEx(ERR, "Too many nested scripts, skipping %s\n", script_path);
free(script_path);
return PM3_EMALLOC; return PM3_EMALLOC;
} }
PrintAndLogEx(SUCCESS, "Executing Lua script: %s, args '%s'\n", script_path, arguments); PrintAndLogEx(SUCCESS, "Executing Lua script: %s, args '%s'\n", script_path, arguments);

View file

@ -311,7 +311,7 @@ static int PrintATR(uint8_t *atr, size_t atrlen) {
uint8_t calen = 2 + T1len + TD1len + TDilen + K; uint8_t calen = 2 + T1len + TD1len + TDilen + K;
if (atrlen != calen && atrlen != calen + 1) // may be CRC if (atrlen != calen && atrlen != calen + 1) // may be CRC
PrintAndLogEx(WARNING, "Invalid ATR length. len: %d, T1len: %d, TD1len: %d, TDilen: %d, K: %d", atrlen, T1len, TD1len, TDilen, K); PrintAndLogEx(WARNING, "Invalid ATR length. len: %zu, T1len: %d, TD1len: %d, TDilen: %d, K: %d", atrlen, T1len, TD1len, TDilen, K);
if (K > 0) if (K > 0)
PrintAndLogEx(INFO, "\nHistorical bytes | len 0x%02d | format %02x", K, atr[2 + T1len + TD1len + TDilen]); PrintAndLogEx(INFO, "\nHistorical bytes | len 0x%02d | format %02x", K, atr[2 + T1len + TD1len + TDilen]);
@ -443,7 +443,7 @@ static int CmdSmartRaw(const char *Cmd) {
PrintAndLogEx(WARNING, "Invalid HEX value."); PrintAndLogEx(WARNING, "Invalid HEX value.");
return 1; return 1;
case 2: case 2:
PrintAndLogEx(WARNING, "Too many bytes. Max %d bytes", sizeof(data)); PrintAndLogEx(WARNING, "Too many bytes. Max %zu bytes", sizeof(data));
return 1; return 1;
case 3: case 3:
PrintAndLogEx(WARNING, "Hex must have even number of digits."); PrintAndLogEx(WARNING, "Hex must have even number of digits.");

View file

@ -665,7 +665,7 @@ static int CmdTraceLoad(const char *Cmd) {
size_t bytes_read = fread(trace, 1, fsize, f); size_t bytes_read = fread(trace, 1, fsize, f);
traceLen = bytes_read; traceLen = bytes_read;
fclose(f); fclose(f);
PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %d bytes) loaded from file %s", traceLen, filename); PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %lu bytes) loaded from file %s", traceLen, filename);
return 0; return 0;
} }
@ -815,7 +815,7 @@ int CmdTraceList(const char *Cmd) {
} }
} }
PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %d bytes)", traceLen); PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %lu bytes)", traceLen);
PrintAndLogEx(INFO, ""); PrintAndLogEx(INFO, "");
if (protocol == FELICA) { if (protocol == FELICA) {
printFelica(traceLen, trace); printFelica(traceLen, trace);

View file

@ -278,13 +278,13 @@ static int usart_bt_testcomm(uint32_t baudrate, uint8_t parity) {
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00}; uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0; size_t len = 0;
PrintAndLogEx(SUCCESS, "TX (%3u):%.*s at %u 8%c1", strlen(string), strlen(string), string, baudrate, parity); PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s at %u 8%c1", strlen(string), (int)strlen(string), string, baudrate, parity);
ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); // such large timeout needed ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); // such large timeout needed
if (ret == PM3_SUCCESS) { if (ret == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "hc01.comV2.0") == 0) { if (strcmp((char *)data, "hc01.comV2.0") == 0) {
PrintAndLogEx(SUCCESS, "Add-on " _GREEN_("found!"), len, len, data); PrintAndLogEx(SUCCESS, "Add-on " _GREEN_("found!"));
return PM3_SUCCESS; return PM3_SUCCESS;
} }
} }
@ -365,11 +365,11 @@ static int CmdUsartBtFactory(const char *Cmd) {
memset(data, 0, sizeof(data)); memset(data, 0, sizeof(data));
string = "AT+NAMEPM3_RDV4.0"; string = "AT+NAMEPM3_RDV4.0";
PrintAndLogEx(SUCCESS, "TX (%3u):%.*s", strlen(string), strlen(string), string); PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s", strlen(string), (int)strlen(string), string);
int ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); int ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000);
if (ret == PM3_SUCCESS) { if (ret == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "OKsetname") == 0) { if (strcmp((char *)data, "OKsetname") == 0) {
PrintAndLogEx(SUCCESS, "Name set to " _GREEN_("PM3_RDV4.0")); PrintAndLogEx(SUCCESS, "Name set to " _GREEN_("PM3_RDV4.0"));
} else { } else {
@ -383,11 +383,11 @@ static int CmdUsartBtFactory(const char *Cmd) {
memset(data, 0, sizeof(data)); memset(data, 0, sizeof(data));
len = 0; len = 0;
string = "AT+ROLE=S"; string = "AT+ROLE=S";
PrintAndLogEx(SUCCESS, "TX (%3u):%.*s", strlen(string), strlen(string), string); PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s", strlen(string), (int)strlen(string), string);
ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000);
if (ret == PM3_SUCCESS) { if (ret == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "OK+ROLE:S") == 0) { if (strcmp((char *)data, "OK+ROLE:S") == 0) {
PrintAndLogEx(SUCCESS, "Role set to " _GREEN_("Slave")); PrintAndLogEx(SUCCESS, "Role set to " _GREEN_("Slave"));
} else { } else {
@ -401,11 +401,11 @@ static int CmdUsartBtFactory(const char *Cmd) {
memset(data, 0, sizeof(data)); memset(data, 0, sizeof(data));
len = 0; len = 0;
string = "AT+PIN1234"; string = "AT+PIN1234";
PrintAndLogEx(SUCCESS, "TX (%3u):%.*s", strlen(string), strlen(string), string); PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s", strlen(string), (int)strlen(string), string);
ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000);
if (ret == PM3_SUCCESS) { if (ret == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "OKsetPIN") == 0) { if (strcmp((char *)data, "OKsetPIN") == 0) {
PrintAndLogEx(SUCCESS, "PIN set to " _GREEN_("1234")); PrintAndLogEx(SUCCESS, "PIN set to " _GREEN_("1234"));
} else { } else {
@ -421,11 +421,11 @@ static int CmdUsartBtFactory(const char *Cmd) {
memset(data, 0, sizeof(data)); memset(data, 0, sizeof(data));
len = 0; len = 0;
string = "AT+PN"; string = "AT+PN";
PrintAndLogEx(SUCCESS, "TX (%3u):%.*s", strlen(string), strlen(string), string); PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s", strlen(string), (int)strlen(string), string);
ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000);
if (ret == PM3_SUCCESS) { if (ret == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "OK None") == 0) { if (strcmp((char *)data, "OK None") == 0) {
PrintAndLogEx(SUCCESS, "Parity set to " _GREEN_("None")); PrintAndLogEx(SUCCESS, "Parity set to " _GREEN_("None"));
} else { } else {
@ -441,11 +441,11 @@ static int CmdUsartBtFactory(const char *Cmd) {
memset(data, 0, sizeof(data)); memset(data, 0, sizeof(data));
len = 0; len = 0;
string = BTADDON_BAUD_AT; string = BTADDON_BAUD_AT;
PrintAndLogEx(SUCCESS, "TX (%3u):%.*s", strlen(string), strlen(string), string); PrintAndLogEx(SUCCESS, "TX (%3zu):%.*s", strlen(string), (int)strlen(string), string);
ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000); ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 1000);
if (ret == PM3_SUCCESS) { if (ret == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(SUCCESS, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "OK" BTADDON_BAUD_NUM) == 0) { if (strcmp((char *)data, "OK" BTADDON_BAUD_NUM) == 0) {
PrintAndLogEx(SUCCESS, "Baudrate set to " _GREEN_(BTADDON_BAUD_NUM)); PrintAndLogEx(SUCCESS, "Baudrate set to " _GREEN_(BTADDON_BAUD_NUM));
} else { } else {
@ -514,7 +514,7 @@ static int CmdUsartBtPin(const char *Cmd) {
sprintf(string, "AT+PIN%s", pin); sprintf(string, "AT+PIN%s", pin);
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00}; uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0; size_t len = 0;
// PrintAndLogEx(NORMAL, "TX (%3u):%.*s", strlen(string), strlen(string), string); // PrintAndLogEx(NORMAL, "TX (%3zu):%.*s", strlen(string), (int)strlen(string), string);
int ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 600); int ret = usart_txrx((uint8_t *)string, strlen(string), data, &len, 600);
if (ret == PM3_ENODATA) { if (ret == PM3_ENODATA) {
PrintAndLogEx(FAILED, "No response from add-on, is it ON and blinking?"); PrintAndLogEx(FAILED, "No response from add-on, is it ON and blinking?");
@ -524,7 +524,7 @@ static int CmdUsartBtPin(const char *Cmd) {
PrintAndLogEx(FAILED, "Command failed, ret=%i", ret); PrintAndLogEx(FAILED, "Command failed, ret=%i", ret);
return ret; return ret;
} }
// PrintAndLogEx(NORMAL, "RX (%3u):%.*s", len, len, data); // PrintAndLogEx(NORMAL, "RX (%3zu):%.*s", len, (int)len, data);
if (strcmp((char *)data, "OKsetPIN") == 0) { if (strcmp((char *)data, "OKsetPIN") == 0) {
PrintAndLogEx(NORMAL, "PIN changed " _GREEN_("successfully")); PrintAndLogEx(NORMAL, "PIN changed " _GREEN_("successfully"));
} else { } else {
@ -688,11 +688,11 @@ static int CmdUsartTXRX(const char *Cmd) {
} }
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00}; uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0; size_t len = 0;
PrintAndLogEx(NORMAL, "TX (%3u):%.*s", strlen(string2), strlen(string2), string2); PrintAndLogEx(NORMAL, "TX (%3zu):%.*s", strlen(string2), (int)strlen(string2), string2);
int ret = usart_txrx((uint8_t *)string2, strlen(string2), data, &len, waittime); int ret = usart_txrx((uint8_t *)string2, strlen(string2), data, &len, waittime);
if (ret != PM3_SUCCESS) if (ret != PM3_SUCCESS)
return ret; return ret;
PrintAndLogEx(NORMAL, "RX (%3u):%.*s", len, len, data); PrintAndLogEx(NORMAL, "RX (%3zu):%.*s", len, (int)len, data);
return PM3_SUCCESS; return PM3_SUCCESS;
} }

View file

@ -123,7 +123,7 @@ static void SendCommandNG_internal(uint16_t cmd, uint8_t *data, size_t len, bool
return; return;
} }
if (len > PM3_CMD_DATA_SIZE) { if (len > PM3_CMD_DATA_SIZE) {
PrintAndLogEx(WARNING, "Sending %d bytes of payload is too much, abort", len); PrintAndLogEx(WARNING, "Sending %zu bytes of payload is too much, abort", len);
return; return;
} }
@ -183,7 +183,7 @@ void SendCommandNG(uint16_t cmd, uint8_t *data, size_t len) {
void SendCommandMIX(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) { void SendCommandMIX(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) {
uint64_t arg[3] = {arg0, arg1, arg2}; uint64_t arg[3] = {arg0, arg1, arg2};
if (len > PM3_CMD_DATA_SIZE_MIX) { if (len > PM3_CMD_DATA_SIZE_MIX) {
PrintAndLogEx(WARNING, "Sending %d bytes of payload is too much for MIX frames, abort", len); PrintAndLogEx(WARNING, "Sending %zu bytes of payload is too much for MIX frames, abort", len);
return; return;
} }
uint8_t cmddata[PM3_CMD_DATA_SIZE]; uint8_t cmddata[PM3_CMD_DATA_SIZE];
@ -302,7 +302,8 @@ static void PacketResponseReceived(PacketResponseNG *packet) {
break; break;
} }
case CMD_DEBUG_PRINT_INTEGERS: { case CMD_DEBUG_PRINT_INTEGERS: {
PrintAndLogEx(NORMAL, "#db# %" PRIx64 ", %" PRIx64 ", %" PRIx64 "", packet->oldarg[0], packet->oldarg[1], packet->oldarg[2]); if (! packet->ng)
PrintAndLogEx(NORMAL, "#db# %" PRIx64 ", %" PRIx64 ", %" PRIx64 "", packet->oldarg[0], packet->oldarg[1], packet->oldarg[2]);
break; break;
} }
// iceman: hw status - down the path on device, runs printusbspeed which starts sending a lot of // iceman: hw status - down the path on device, runs printusbspeed which starts sending a lot of
@ -434,7 +435,7 @@ __attribute__((force_align_arg_pointer))
res = uart_receive(sp, ((uint8_t *)&rx_old) + sizeof(PacketResponseNGPreamble), sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble), &rxlen); res = uart_receive(sp, ((uint8_t *)&rx_old) + sizeof(PacketResponseNGPreamble), sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble), &rxlen);
if ((res != PM3_SUCCESS) || (rxlen != sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble))) { if ((res != PM3_SUCCESS) || (rxlen != sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble))) {
PrintAndLogEx(WARNING, "Received packet OLD frame with payload too short? %d/%d", rxlen, sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble)); PrintAndLogEx(WARNING, "Received packet OLD frame with payload too short? %d/%zu", rxlen, sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble));
error = true; error = true;
} }
if (!error) { if (!error) {
@ -464,7 +465,7 @@ __attribute__((force_align_arg_pointer))
} }
} else { } else {
if (rxlen > 0) { if (rxlen > 0) {
PrintAndLogEx(WARNING, "Received packet frame preamble too short: %d/%d", rxlen, sizeof(PacketResponseNGPreamble)); PrintAndLogEx(WARNING, "Received packet frame preamble too short: %d/%zu", rxlen, sizeof(PacketResponseNGPreamble));
error = true; error = true;
} }
if (res == PM3_ENOTTY) { if (res == PM3_ENOTTY) {
@ -733,6 +734,8 @@ bool WaitForResponseTimeoutW(uint32_t cmd, PacketResponseNG *response, size_t ms
PrintAndLogEx(INFO, "You can cancel this operation by pressing the pm3 button"); PrintAndLogEx(INFO, "You can cancel this operation by pressing the pm3 button");
show_warning = false; show_warning = false;
} }
// just to avoid CPU busy loop:
msleep(10);
} }
return false; return false;
} }

View file

@ -301,7 +301,7 @@ static int CmdEMVGPO(const char *Cmd) {
free(pdol_data_tlv); free(pdol_data_tlv);
return PM3_ESOFT; return PM3_ESOFT;
} }
PrintAndLogEx(INFO, "PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
// exec // exec
uint8_t buf[APDU_RES_LEN] = {0}; uint8_t buf[APDU_RES_LEN] = {0};
@ -477,7 +477,7 @@ static int CmdEMVAC(const char *Cmd) {
cdol_data_tlv = &data_tlv; cdol_data_tlv = &data_tlv;
} }
PrintAndLogEx(INFO, "CDOL data[%d]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len)); PrintAndLogEx(INFO, "CDOL data[%zu]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len));
// exec // exec
uint8_t buf[APDU_RES_LEN] = {0}; uint8_t buf[APDU_RES_LEN] = {0};
@ -543,7 +543,7 @@ static int CmdEMVGenerateChallenge(const char *Cmd) {
PrintAndLogEx(SUCCESS, "Challenge: %s", sprint_hex(buf, len)); PrintAndLogEx(SUCCESS, "Challenge: %s", sprint_hex(buf, len));
if (len != 4 && len != 8) if (len != 4 && len != 8)
PrintAndLogEx(WARNING, "Length of challenge must be 4 or 8, but it %d", len); PrintAndLogEx(WARNING, "Length of challenge must be 4 or 8, but it %zu", len);
return PM3_SUCCESS; return PM3_SUCCESS;
} }
@ -624,7 +624,7 @@ static int CmdEMVInternalAuthenticate(const char *Cmd) {
ddol_data_tlv = &data_tlv; ddol_data_tlv = &data_tlv;
} }
PrintAndLogEx(INFO, "DDOL data[%d]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len)); PrintAndLogEx(INFO, "DDOL data[%zu]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len));
// exec // exec
uint8_t buf[APDU_RES_LEN] = {0}; uint8_t buf[APDU_RES_LEN] = {0};
@ -693,7 +693,7 @@ static void ProcessGPOResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_
} }
if (len < 4 || (len - 4) % 4) { if (len < 4 || (len - 4) % 4) {
PrintAndLogEx(ERR, "GPO response format 1 parsing error. length = %d", len); PrintAndLogEx(ERR, "GPO response format 1 parsing error. length = %zu", len);
} else { } else {
// AIP // AIP
struct tlvdb *f1AIP = tlvdb_fixed(0x82, 2, buf + 2); struct tlvdb *f1AIP = tlvdb_fixed(0x82, 2, buf + 2);
@ -725,7 +725,7 @@ static void ProcessACResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t
uint8_t elmlen = len - 2; // wo 0x80XX uint8_t elmlen = len - 2; // wo 0x80XX
if (len < 4 + 2 || (elmlen - 2) % 4 || elmlen != buf[1]) { if (len < 4 + 2 || (elmlen - 2) % 4 || elmlen != buf[1]) {
PrintAndLogEx(ERR, "GPO response format1 parsing error. length=%d", len); PrintAndLogEx(ERR, "GPO response format1 parsing error. length=%zu", len);
} else { } else {
struct tlvdb *tlvElm = NULL; struct tlvdb *tlvElm = NULL;
if (decodeTLV) if (decodeTLV)
@ -752,6 +752,7 @@ static void ProcessACResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t
if (decodeTLV) if (decodeTLV)
TLVPrintFromTLV(tlvElm); TLVPrintFromTLV(tlvElm);
} }
tlvdb_free(tlvElm);
} }
} else { } else {
if (decodeTLV) if (decodeTLV)
@ -907,7 +908,7 @@ static int CmdEMVExec(const char *Cmd) {
PrintAndLogEx(ERR, "Error: can't create PDOL data."); PrintAndLogEx(ERR, "Error: can't create PDOL data.");
dreturn(PM3_ESOFT); dreturn(PM3_ESOFT);
} }
PrintAndLogEx(NORMAL, "PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); PrintAndLogEx(NORMAL, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
PrintAndLogEx(NORMAL, "\n* GPO."); PrintAndLogEx(NORMAL, "\n* GPO.");
res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
@ -947,7 +948,7 @@ static int CmdEMVExec(const char *Cmd) {
while (AFL && AFL->len) { while (AFL && AFL->len) {
if (AFL->len % 4) { if (AFL->len % 4) {
PrintAndLogEx(WARNING, "Warning: Wrong AFL length: %d", AFL->len); PrintAndLogEx(WARNING, "Warning: Wrong AFL length: %zu", AFL->len);
break; break;
} }
@ -1007,7 +1008,7 @@ static int CmdEMVExec(const char *Cmd) {
if (ODAiListLen) { if (ODAiListLen) {
struct tlvdb *oda = tlvdb_fixed(0x21, ODAiListLen, ODAiList); // not a standard tag struct tlvdb *oda = tlvdb_fixed(0x21, ODAiListLen, ODAiList); // not a standard tag
tlvdb_add(tlvRoot, oda); tlvdb_add(tlvRoot, oda);
PrintAndLogEx(NORMAL, "* Input list for Offline Data Authentication added to TLV. len=%d \n", ODAiListLen); PrintAndLogEx(NORMAL, "* Input list for Offline Data Authentication added to TLV. len=%zu \n", ODAiListLen);
} }
// get AIP // get AIP
@ -1058,7 +1059,7 @@ static int CmdEMVExec(const char *Cmd) {
if (IAD->len >= IAD->value[0] + 1) { if (IAD->len >= IAD->value[0] + 1) {
PrintAndLogEx(NORMAL, "\tKey index: 0x%02x", IAD->value[1]); PrintAndLogEx(NORMAL, "\tKey index: 0x%02x", IAD->value[1]);
PrintAndLogEx(NORMAL, "\tCrypto ver: 0x%02x(%03d)", IAD->value[2], IAD->value[2]); PrintAndLogEx(NORMAL, "\tCrypto ver: 0x%02x(%03d)", IAD->value[2], IAD->value[2]);
PrintAndLogEx(NORMAL, "\tCVR:", sprint_hex(&IAD->value[3], IAD->value[0] - 2)); PrintAndLogEx(NORMAL, "\tCVR: %s", sprint_hex(&IAD->value[3], IAD->value[0] - 2));
struct tlvdb *cvr = tlvdb_fixed(0x20, IAD->value[0] - 2, &IAD->value[3]); struct tlvdb *cvr = tlvdb_fixed(0x20, IAD->value[0] - 2, &IAD->value[3]);
TLVPrintFromTLVLev(cvr, 1); TLVPrintFromTLVLev(cvr, 1);
} }
@ -1085,7 +1086,7 @@ static int CmdEMVExec(const char *Cmd) {
dreturn(PM3_ERFTRANS); dreturn(PM3_ERFTRANS);
} }
if (len < 4) { if (len < 4) {
PrintAndLogEx(ERR, "Error GetChallenge. Wrong challenge length %d", len); PrintAndLogEx(ERR, "Error GetChallenge. Wrong challenge length %zu", len);
dreturn(PM3_ESOFT); dreturn(PM3_ESOFT);
} }
@ -1104,7 +1105,7 @@ static int CmdEMVExec(const char *Cmd) {
dreturn(PM3_ESOFT); dreturn(PM3_ESOFT);
} }
PrintAndLogEx(NORMAL, "CDOL1 data[%d]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len)); PrintAndLogEx(NORMAL, "CDOL1 data[%zu]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len));
PrintAndLogEx(NORMAL, "* * AC1"); PrintAndLogEx(NORMAL, "* * AC1");
// EMVAC_TC + EMVAC_CDAREQ --- to get SDAD // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD
@ -1151,7 +1152,7 @@ static int CmdEMVExec(const char *Cmd) {
break; break;
} }
} else { } else {
PrintAndLogEx(WARNING, "Warning: Wrong CID length %d", CID->len); PrintAndLogEx(WARNING, "Warning: Wrong CID length %zu", CID->len);
} }
} else { } else {
PrintAndLogEx(WARNING, "Warning: CID(9F27) not found."); PrintAndLogEx(WARNING, "Warning: CID(9F27) not found.");
@ -1194,7 +1195,7 @@ static int CmdEMVExec(const char *Cmd) {
dreturn(PM3_ESOFT); dreturn(PM3_ESOFT);
} }
PrintAndLogEx(NORMAL, "UDOL data[%d]: %s", udol_data_tlv->len, sprint_hex(udol_data_tlv->value, udol_data_tlv->len)); PrintAndLogEx(NORMAL, "UDOL data[%zu]: %s", udol_data_tlv->len, sprint_hex(udol_data_tlv->value, udol_data_tlv->len));
PrintAndLogEx(NORMAL, "\n* Mastercard compute cryptographic checksum(UDOL)"); PrintAndLogEx(NORMAL, "\n* Mastercard compute cryptographic checksum(UDOL)");
@ -1228,7 +1229,7 @@ static int CmdEMVExec(const char *Cmd) {
dreturn(PM3_ESOFT); dreturn(PM3_ESOFT);
} }
PrintAndLogEx(NORMAL, "CDOL1 data[%d]: %s", cdol1_data_tlv->len, sprint_hex(cdol1_data_tlv->value, cdol1_data_tlv->len)); PrintAndLogEx(NORMAL, "CDOL1 data[%zu]: %s", cdol1_data_tlv->len, sprint_hex(cdol1_data_tlv->value, cdol1_data_tlv->len));
PrintAndLogEx(NORMAL, "* * AC1"); PrintAndLogEx(NORMAL, "* * AC1");
// EMVAC_TC + EMVAC_CDAREQ --- to get SDAD // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD
@ -1260,7 +1261,7 @@ static int CmdEMVExec(const char *Cmd) {
PrintAndLogEx(NORMAL, "\n* * Issuer Application Data (IAD):"); PrintAndLogEx(NORMAL, "\n* * Issuer Application Data (IAD):");
uint8_t VDDlen = IAD->value[0]; // Visa discretionary data length uint8_t VDDlen = IAD->value[0]; // Visa discretionary data length
uint8_t IDDlen = 0; // Issuer discretionary data length uint8_t IDDlen = 0; // Issuer discretionary data length
PrintAndLogEx(NORMAL, "IAD length: %d", IAD->len); PrintAndLogEx(NORMAL, "IAD length: %zu", IAD->len);
PrintAndLogEx(NORMAL, "VDDlen: %d", VDDlen); PrintAndLogEx(NORMAL, "VDDlen: %d", VDDlen);
if (VDDlen < IAD->len - 1) if (VDDlen < IAD->len - 1)
IDDlen = IAD->value[VDDlen + 1]; IDDlen = IAD->value[VDDlen + 1];
@ -1331,7 +1332,7 @@ static int CmdEMVExec(const char *Cmd) {
dreturn(PM3_ESOFT); dreturn(PM3_ESOFT);
} }
PrintAndLogEx(NORMAL, "CDOL2 data[%d]: %s", cdol2_data_tlv->len, sprint_hex(cdol2_data_tlv->value, cdol2_data_tlv->len)); PrintAndLogEx(NORMAL, "CDOL2 data[%zu]: %s", cdol2_data_tlv->len, sprint_hex(cdol2_data_tlv->value, cdol2_data_tlv->len));
//PrintAndLogEx(NORMAL, "* * AC2"); //PrintAndLogEx(NORMAL, "* * AC2");
// here must be AC2, but we dont make external authenticate ( // here must be AC2, but we dont make external authenticate (
/* // AC2 /* // AC2
@ -1590,7 +1591,7 @@ static int CmdEMVScan(const char *Cmd) {
DropFieldEx(channel); DropFieldEx(channel);
return PM3_ESOFT; return PM3_ESOFT;
} }
PrintAndLogEx(INFO, "PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
PrintAndLogEx(INFO, "-->GPO."); PrintAndLogEx(INFO, "-->GPO.");
res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
@ -1622,7 +1623,7 @@ static int CmdEMVScan(const char *Cmd) {
while (AFL && AFL->len) { while (AFL && AFL->len) {
if (AFL->len % 4) { if (AFL->len % 4) {
PrintAndLogEx(ERR, "Wrong AFL length: %d", AFL->len); PrintAndLogEx(ERR, "Wrong AFL length: %zu", AFL->len);
break; break;
} }
@ -1850,7 +1851,7 @@ static int CmdEMVRoca(const char *Cmd) {
free(pdol_data_tlv); free(pdol_data_tlv);
return PM3_ESOFT; return PM3_ESOFT;
} }
PrintAndLogEx(INFO, "PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
PrintAndLogEx(INFO, "-->GPO."); PrintAndLogEx(INFO, "-->GPO.");
res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
@ -1871,7 +1872,7 @@ static int CmdEMVRoca(const char *Cmd) {
while (AFL && AFL->len) { while (AFL && AFL->len) {
if (AFL->len % 4) { if (AFL->len % 4) {
PrintAndLogEx(ERR, "Wrong AFL length: %d", AFL->len); PrintAndLogEx(ERR, "Wrong AFL length: %zu", AFL->len);
break; break;
} }

View file

@ -495,7 +495,7 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO
if (tsfi) { if (tsfi) {
struct tlvdb *tsfitmp = tlvdb_find_path(tsfi, (tlv_tag_t[]) {0x70, 0x61, 0x00}); struct tlvdb *tsfitmp = tlvdb_find_path(tsfi, (tlv_tag_t[]) {0x70, 0x61, 0x00});
if (!tsfitmp) { if (!tsfitmp) {
PrintAndLogEx(FAILED, "SFI 0x%02d doesn't have any records.", sfidatalen[ui]); PrintAndLogEx(FAILED, "SFI 0x%02zu doesn't have any records.", sfidatalen[ui]);
continue; continue;
} }
res = EMVCheckAID(channel, decodeTLV, tsfitmp, tlv); res = EMVCheckAID(channel, decodeTLV, tsfitmp, tlv);
@ -863,7 +863,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) {
return 5; return 5;
} }
PrintAndLogEx(NORMAL, "DDOL data[%d]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len)); PrintAndLogEx(NORMAL, "DDOL data[%zu]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len));
PrintAndLogEx(NORMAL, "\n* Internal Authenticate"); PrintAndLogEx(NORMAL, "\n* Internal Authenticate");
int res = EMVInternalAuthenticate(channel, true, (uint8_t *)ddol_data_tlv->value, ddol_data_tlv->len, buf, sizeof(buf), &len, &sw, NULL); int res = EMVInternalAuthenticate(channel, true, (uint8_t *)ddol_data_tlv->value, ddol_data_tlv->len, buf, sizeof(buf), &len, &sw, NULL);
@ -879,7 +879,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) {
struct tlvdb *dda_db = NULL; struct tlvdb *dda_db = NULL;
if (buf[0] == 0x80) { if (buf[0] == 0x80) {
if (len < 3) { if (len < 3) {
PrintAndLogEx(WARNING, "Warning: Internal Authenticate format1 parsing error. length=%d", len); PrintAndLogEx(WARNING, "Warning: Internal Authenticate format1 parsing error. length=%zu", len);
} else { } else {
// parse response 0x80 // parse response 0x80
struct tlvdb *t80 = tlvdb_parse_multi(buf, len); struct tlvdb *t80 = tlvdb_parse_multi(buf, len);

View file

@ -255,7 +255,7 @@ static bool HexToBuffer(const char *errormsg, const char *hexvalue, uint8_t *buf
} }
if (buflen > maxbufferlen) { if (buflen > maxbufferlen) {
PrintAndLogEx(ERR, "%s HEX length (%d) more than %d", errormsg, (bufferlen) ? *bufferlen : -1, maxbufferlen); PrintAndLogEx(ERR, "%s HEX length (%zu) more than %zu", errormsg, (bufferlen) ? *bufferlen : -1, maxbufferlen);
return false; return false;
} }
@ -321,7 +321,7 @@ bool ParamLoadFromJson(struct tlvdb *tlv) {
return false; return false;
} }
PrintAndLogEx(SUCCESS, "Load params: json(%d) " _GREEN_("OK"), json_array_size(root)); PrintAndLogEx(SUCCESS, "Load params: json(%zu) " _GREEN_("OK"), json_array_size(root));
for (int i = 0; i < json_array_size(root); i++) { for (int i = 0; i < json_array_size(root); i++) {
json_t *data, *jtag, *jlength, *jvalue; json_t *data, *jtag, *jlength, *jvalue;
@ -382,7 +382,7 @@ bool ParamLoadFromJson(struct tlvdb *tlv) {
} }
if (buflen != tlvLength) { if (buflen != tlvLength) {
PrintAndLogEx(ERR, "Load params: data [%d] length of HEX must(%d) be identical to length in TLV param(%d)", i + 1, buflen, tlvLength); PrintAndLogEx(ERR, "Load params: data [%d] length of HEX must(%zu) be identical to length in TLV param(%d)", i + 1, buflen, tlvLength);
json_decref(root); json_decref(root);
return false; return false;
} }

View file

@ -206,7 +206,7 @@ int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public
res = CborGetBinStringValue(&map, &public_key[1], 32, &len); res = CborGetBinStringValue(&map, &public_key[1], 32, &len);
cbor_check(res); cbor_check(res);
if (verbose) if (verbose)
PrintAndLogEx(SUCCESS, "x - coordinate [%d]: %s", len, sprint_hex(&public_key[1], 32)); PrintAndLogEx(SUCCESS, "x - coordinate [%zu]: %s", len, sprint_hex(&public_key[1], 32));
if (len != 32) if (len != 32)
PrintAndLogEx(ERR, "ERROR: x - coordinate length must be 32."); PrintAndLogEx(ERR, "ERROR: x - coordinate length must be 32.");
} }
@ -217,7 +217,7 @@ int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public
res = CborGetBinStringValue(&map, &public_key[33], 32, &len); res = CborGetBinStringValue(&map, &public_key[33], 32, &len);
cbor_check(res); cbor_check(res);
if (verbose) if (verbose)
PrintAndLogEx(SUCCESS, "y - coordinate [%d]: %s", len, sprint_hex(&public_key[33], 32)); PrintAndLogEx(SUCCESS, "y - coordinate [%zu]: %s", len, sprint_hex(&public_key[33], 32));
if (len != 32) if (len != 32)
PrintAndLogEx(ERR, "ERROR: y - coordinate length must be 32."); PrintAndLogEx(ERR, "ERROR: y - coordinate length must be 32.");
} }
@ -229,7 +229,7 @@ int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public
res = CborGetBinStringValue(&map, private_key, sizeof(private_key), &len); res = CborGetBinStringValue(&map, private_key, sizeof(private_key), &len);
cbor_check(res); cbor_check(res);
if (verbose) if (verbose)
PrintAndLogEx(SUCCESS, "d - private key [%d]: %s", len, sprint_hex(private_key, len)); PrintAndLogEx(SUCCESS, "d - private key [%zu]: %s", len, sprint_hex(private_key, len));
} }
if (verbose) if (verbose)

View file

@ -434,9 +434,9 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b
memcpy(authData, ubuf, authDataLen); memcpy(authData, ubuf, authDataLen);
if (verbose2) { if (verbose2) {
PrintAndLogEx(INFO, "authData[%d]: %s", n, sprint_hex_inrow(authData, authDataLen)); PrintAndLogEx(INFO, "authData[%zu]: %s", n, sprint_hex_inrow(authData, authDataLen));
} else { } else {
PrintAndLogEx(INFO, "authData[%d]: %s...", n, sprint_hex(authData, MIN(authDataLen, 16))); PrintAndLogEx(INFO, "authData[%zu]: %s...", n, sprint_hex(authData, MIN(authDataLen, 16)));
} }
PrintAndLogEx(INFO, "RP ID Hash: %s", sprint_hex(ubuf, 32)); PrintAndLogEx(INFO, "RP ID Hash: %s", sprint_hex(ubuf, 32));
@ -530,9 +530,9 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b
res = CborGetBinStringValue(&mapsmt, sign, sizeof(sign), &signLen); res = CborGetBinStringValue(&mapsmt, sign, sizeof(sign), &signLen);
cbor_check(res); cbor_check(res);
if (verbose2) { if (verbose2) {
PrintAndLogEx(INFO, "signature [%d]: %s", signLen, sprint_hex_inrow(sign, signLen)); PrintAndLogEx(INFO, "signature [%zu]: %s", signLen, sprint_hex_inrow(sign, signLen));
} else { } else {
PrintAndLogEx(INFO, "signature [%d]: %s...", signLen, sprint_hex(sign, MIN(signLen, 16))); PrintAndLogEx(INFO, "signature [%zu]: %s...", signLen, sprint_hex(sign, MIN(signLen, 16)));
} }
} }
@ -540,11 +540,11 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b
res = CborGetArrayBinStringValue(&mapsmt, der, sizeof(der), &derLen); res = CborGetArrayBinStringValue(&mapsmt, der, sizeof(der), &derLen);
cbor_check(res); cbor_check(res);
if (verbose2) { if (verbose2) {
PrintAndLogEx(NORMAL, "DER certificate[%d]:\n------------------DER-------------------", derLen); PrintAndLogEx(NORMAL, "DER certificate[%zu]:\n------------------DER-------------------", derLen);
dump_buffer_simple((const unsigned char *)der, derLen, NULL); dump_buffer_simple((const unsigned char *)der, derLen, NULL);
PrintAndLogEx(NORMAL, "\n----------------DER---------------------"); PrintAndLogEx(NORMAL, "\n----------------DER---------------------");
} else { } else {
PrintAndLogEx(NORMAL, "DER [%d]: %s...", derLen, sprint_hex(der, MIN(derLen, 16))); PrintAndLogEx(NORMAL, "DER [%zu]: %s...", derLen, sprint_hex(der, MIN(derLen, 16)));
} }
JsonSaveBufAsHexCompact(root, "$.AppData.DER", der, derLen); JsonSaveBufAsHexCompact(root, "$.AppData.DER", der, derLen);
} }
@ -674,7 +674,7 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool
uint8_t cid[200] = {0}; uint8_t cid[200] = {0};
res = CborGetBinStringValue(&mapint, cid, sizeof(cid), &n); res = CborGetBinStringValue(&mapint, cid, sizeof(cid), &n);
cbor_check(res); cbor_check(res);
PrintAndLogEx(SUCCESS, "credential id [%d]: %s", n, sprint_hex(cid, n)); PrintAndLogEx(SUCCESS, "credential id [%zu]: %s", n, sprint_hex(cid, n));
} }
} }
res = cbor_value_leave_container(&map, &mapint); res = cbor_value_leave_container(&map, &mapint);
@ -693,9 +693,9 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool
memcpy(authData, ubuf, authDataLen); memcpy(authData, ubuf, authDataLen);
if (verbose2) { if (verbose2) {
PrintAndLogEx(INFO, "authData[%d]: %s", n, sprint_hex_inrow(authData, authDataLen)); PrintAndLogEx(INFO, "authData[%zu]: %s", n, sprint_hex_inrow(authData, authDataLen));
} else { } else {
PrintAndLogEx(INFO, "authData[%d]: %s...", n, sprint_hex(authData, MIN(authDataLen, 16))); PrintAndLogEx(INFO, "authData[%zu]: %s...", n, sprint_hex(authData, MIN(authDataLen, 16)));
} }
PrintAndLogEx(INFO, "RP ID Hash: %s", sprint_hex(ubuf, 32)); PrintAndLogEx(INFO, "RP ID Hash: %s", sprint_hex(ubuf, 32));
@ -749,7 +749,7 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool
uint8_t cid[200] = {0}; uint8_t cid[200] = {0};
res = CborGetBinStringValue(&mapint, cid, sizeof(cid), &n); res = CborGetBinStringValue(&mapint, cid, sizeof(cid), &n);
cbor_check(res); cbor_check(res);
PrintAndLogEx(SUCCESS, "UserEntity id [%d]: %s", n, sprint_hex(cid, n)); PrintAndLogEx(SUCCESS, "UserEntity id [%zu]: %s", n, sprint_hex(cid, n));
// check // check
uint8_t idbuf[100] = {0}; uint8_t idbuf[100] = {0};
@ -781,9 +781,9 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool
cbor_check(res); cbor_check(res);
if (verbose2) { if (verbose2) {
PrintAndLogEx(SUCCESS, "signature [%d]: %s", signLen, sprint_hex_inrow(sign, signLen)); PrintAndLogEx(SUCCESS, "signature [%zu]: %s", signLen, sprint_hex_inrow(sign, signLen));
} else { } else {
PrintAndLogEx(SUCCESS, "signature [%d]: %s...", signLen, sprint_hex(sign, MIN(signLen, 16))); PrintAndLogEx(SUCCESS, "signature [%zu]: %s...", signLen, sprint_hex(sign, MIN(signLen, 16)));
} }
// get public key from json // get public key from json

View file

@ -153,7 +153,7 @@ int saveFile(const char *preferredName, const char *suffix, const void *data, si
fwrite(data, 1, datalen, f); fwrite(data, 1, datalen, f);
fflush(f); fflush(f);
fclose(f); fclose(f);
PrintAndLogEx(SUCCESS, "saved %u bytes to binary file " _YELLOW_("%s"), datalen, fileName); PrintAndLogEx(SUCCESS, "saved %zu bytes to binary file " _YELLOW_("%s"), datalen, fileName);
free(fileName); free(fileName);
return PM3_SUCCESS; return PM3_SUCCESS;
} }
@ -410,7 +410,6 @@ int loadFile(const char *preferredName, const char *suffix, void *data, size_t m
} }
size_t bytes_read = fread(dump, 1, fsize, f); size_t bytes_read = fread(dump, 1, fsize, f);
fclose(f);
if (bytes_read != fsize) { if (bytes_read != fsize) {
PrintAndLogEx(FAILED, "error, bytes read mismatch file size"); PrintAndLogEx(FAILED, "error, bytes read mismatch file size");
@ -420,18 +419,19 @@ int loadFile(const char *preferredName, const char *suffix, void *data, size_t m
} }
if (bytes_read > maxdatalen) { if (bytes_read > maxdatalen) {
PrintAndLogEx(WARNING, "Warning, bytes read exceed calling array limit. Max bytes is %d bytes", maxdatalen); PrintAndLogEx(WARNING, "Warning, bytes read exceed calling array limit. Max bytes is %zu bytes", maxdatalen);
bytes_read = maxdatalen; bytes_read = maxdatalen;
} }
memcpy((data), dump, bytes_read); memcpy((data), dump, bytes_read);
free(dump); free(dump);
PrintAndLogEx(SUCCESS, "loaded %d bytes from binary file " _YELLOW_("%s"), bytes_read, fileName); PrintAndLogEx(SUCCESS, "loaded %zu bytes from binary file " _YELLOW_("%s"), bytes_read, fileName);
*datalen = bytes_read; *datalen = bytes_read;
out: out:
fclose(f);
free(fileName); free(fileName);
return retval; return retval;
} }
@ -444,8 +444,6 @@ int loadFile_safe(const char *preferredName, const char *suffix, void **pdata, s
return PM3_EFILE; return PM3_EFILE;
} }
int retval = PM3_SUCCESS;
FILE *f = fopen(path, "rb"); FILE *f = fopen(path, "rb");
if (!f) { if (!f) {
PrintAndLogEx(WARNING, "file not found or locked. '" _YELLOW_("%s")"'", path); PrintAndLogEx(WARNING, "file not found or locked. '" _YELLOW_("%s")"'", path);
@ -478,13 +476,14 @@ int loadFile_safe(const char *preferredName, const char *suffix, void **pdata, s
if (bytes_read != fsize) { if (bytes_read != fsize) {
PrintAndLogEx(FAILED, "error, bytes read mismatch file size"); PrintAndLogEx(FAILED, "error, bytes read mismatch file size");
free(*pdata);
return PM3_EFILE; return PM3_EFILE;
} }
*datalen = bytes_read; *datalen = bytes_read;
PrintAndLogEx(SUCCESS, "loaded %d bytes from binary file " _YELLOW_("%s"), bytes_read, preferredName); PrintAndLogEx(SUCCESS, "loaded %zu bytes from binary file " _YELLOW_("%s"), bytes_read, preferredName);
return retval; return PM3_SUCCESS;
} }
int loadFileEML(const char *preferredName, void *data, size_t *datalen) { int loadFileEML(const char *preferredName, void *data, size_t *datalen) {
@ -531,7 +530,7 @@ int loadFileEML(const char *preferredName, void *data, size_t *datalen) {
} }
} }
fclose(f); fclose(f);
PrintAndLogEx(SUCCESS, "loaded %d bytes from text file " _YELLOW_("%s"), counter, fileName); PrintAndLogEx(SUCCESS, "loaded %zu bytes from text file " _YELLOW_("%s"), counter, fileName);
if (datalen) if (datalen)
*datalen = counter; *datalen = counter;
@ -782,7 +781,9 @@ int loadFileDICTIONARY_safe(const char *preferredName, void **pdata, uint8_t key
*pdata = realloc(*pdata, mem_size); *pdata = realloc(*pdata, mem_size);
if (*pdata == NULL) { if (*pdata == NULL) {
return PM3_EFILE; retval = PM3_EFILE;
fclose(f);
goto out;
} else { } else {
memset(*pdata + (mem_size - block_size), 0, block_size); memset(*pdata + (mem_size - block_size), 0, block_size);
} }
@ -1058,8 +1059,12 @@ int searchFile(char **foundpath, const char *pm3dir, const char *searchname, con
char *filename = filenamemcopy(searchname, suffix); char *filename = filenamemcopy(searchname, suffix);
if (filename == NULL || strlen(filename) == 0) if (filename == NULL)
return PM3_EMALLOC; return PM3_EMALLOC;
if (strlen(filename) == 0) {
free(filename);
return PM3_EFILE;
}
int res = searchFinalFile(foundpath, pm3dir, filename, silent); int res = searchFinalFile(foundpath, pm3dir, filename, silent);
if (res != PM3_SUCCESS) { if (res != PM3_SUCCESS) {
if ((res == PM3_EFILE) && (!silent)) if ((res == PM3_EFILE) && (!silent))

View file

@ -210,14 +210,13 @@ uint8_t GetPskCarrier(const char *str, bool printAns) {
} }
uint16_t fc = countFC(bits, size, false); uint16_t fc = countFC(bits, size, false);
free(bits);
carrier = fc & 0xFF; carrier = fc & 0xFF;
if (carrier != 2 && carrier != 4 && carrier != 8) return 0; if (carrier != 2 && carrier != 4 && carrier != 8) return 0;
if ((fc >> 8) == 10 && carrier == 8) return 0; if ((fc >> 8) == 10 && carrier == 8) return 0;
// Only print this message if we're not looping something // Only print this message if we're not looping something
if (printAns) if (printAns)
PrintAndLogEx(SUCCESS, "Auto-detected PSK carrier rate: %d", carrier); PrintAndLogEx(SUCCESS, "Auto-detected PSK carrier rate: %d", carrier);
free(bits);
return carrier; return carrier;
} }

View file

@ -20,7 +20,7 @@
place your empty tag onto the PM3 to read and display the MCD & MSN0..2 place your empty tag onto the PM3 to read and display the MCD & MSN0..2
the values will be shown below the values will be shown below
confirm whnen ready [y/n] ?y confirm when ready [y/n] ?y
#db# setting up legic card #db# setting up legic card
#db# MIM 256 card found, reading card ... #db# MIM 256 card found, reading card ...
#db# Card read, use 'hf legic decode' or #db# Card read, use 'hf legic decode' or
@ -88,7 +88,7 @@ copyright = ''
author = 'Mosci' author = 'Mosci'
version = 'v1.0.1' version = 'v1.0.1'
desc = [[ desc = [[
This is a script which create a clone-dump of a dump from a Legic Prime Tag (MIM256 or MIM1024) This is a script which creates a clone-dump of a dump from a Legic Prime Tag (MIM256 or MIM1024)
(created with 'hf legic save my_dump.hex') (created with 'hf legic save my_dump.hex')
]] ]]
example = [[ example = [[
@ -98,13 +98,13 @@ example = [[
usage = [[ usage = [[
script run legic_clone -h -i <file> -o <file> -c <crc> -d -s -w script run legic_clone -h -i <file> -o <file> -c <crc> -d -s -w
requiered arguments: required arguments:
-i <input file> (file to read data from) -i <input file> (file to read data from)
optional arguments : optional arguments :
-h - Help text -h - Help text
-o <output file> - requieres option -c to be given -o <output file> - requires option -c to be given
-c <new-tag crc> - requieres option -o to be given -c <new-tag crc> - requires option -o to be given
-d - Display content of found Segments -d - Display content of found Segments
-s - Display summary at the end -s - Display summary at the end
-w - write directly to Tag - a file myLegicClone.hex wille be generated also -w - write directly to Tag - a file myLegicClone.hex wille be generated also
@ -472,7 +472,7 @@ function main(args)
outfile = a outfile = a
ofs = true ofs = true
if (file_check(a)) then if (file_check(a)) then
local answer = utils.confirm('\nthe output-file '..a..' alredy exists!\nthis will delete the previous content!\ncontinue?') local answer = utils.confirm('\nthe output-file '..a..' already exists!\nthis will delete the previous content!\ncontinue?')
if (answer==false) then return oops('quiting') end if (answer==false) then return oops('quiting') end
end end
end end

View file

@ -339,27 +339,63 @@ __attribute__((force_align_arg_pointer))
int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) { int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) {
uint16_t i; uint16_t i;
uint32_t uid; uint32_t uid;
PacketResponseNG resp;
StateList_t statelists[2]; StateList_t statelists[2];
struct Crypto1State *p1, *p2, *p3, *p4; struct Crypto1State *p1, *p2, *p3, *p4;
struct {
uint8_t block;
uint8_t keytype;
uint8_t target_block;
uint8_t target_keytype;
bool calibrate;
uint8_t key[6];
} PACKED payload;
payload.block = blockNo;
payload.keytype = keyType;
payload.target_block = trgBlockNo;
payload.target_keytype = trgKeyType;
payload.calibrate = calibrate;
memcpy(payload.key, key, sizeof(payload.key));
PacketResponseNG resp;
clearCommandBuffer(); clearCommandBuffer();
SendCommandOLD(CMD_HF_MIFARE_NESTED, blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate, key, 6); SendCommandNG(CMD_HF_MIFARE_NESTED, (uint8_t*)&payload, sizeof(payload));
if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return PM3_ETIMEOUT;
if (!WaitForResponseTimeout(CMD_HF_MIFARE_NESTED, &resp, 1500)) return PM3_ETIMEOUT;
if (resp.status != PM3_SUCCESS)
return PM3_ESOFT;
struct p {
int16_t isOK;
uint8_t block;
uint8_t keytype;
uint8_t cuid[4];
uint8_t nt_a[4];
uint8_t ks_a[4];
uint8_t nt_b[4];
uint8_t ks_b[4];
} PACKED;
struct p* package = (struct p*)resp.data.asBytes;
// error during nested // error during nested
if (resp.oldarg[0]) return resp.oldarg[0]; if (package->isOK) return package->isOK;
memcpy(&uid, resp.data.asBytes, 4); memcpy(&uid, package->cuid, sizeof(package->cuid));
for (i = 0; i < 2; i++) { for (i = 0; i < 2; i++) {
statelists[i].blockNo = resp.oldarg[2] & 0xff; statelists[i].blockNo = package->block;
statelists[i].keyType = (resp.oldarg[2] >> 8) & 0xff; statelists[i].keyType = package->keytype;
statelists[i].uid = uid; statelists[i].uid = uid;
memcpy(&statelists[i].nt, (void *)(resp.data.asBytes + 4 + i * 8 + 0), 4);
memcpy(&statelists[i].ks1, (void *)(resp.data.asBytes + 4 + i * 8 + 4), 4);
} }
memcpy(&statelists[0].nt, package->nt_a, sizeof(package->nt_a));
memcpy(&statelists[0].ks1, package->ks_a, sizeof(package->ks_a));
memcpy(&statelists[1].nt, package->nt_b, sizeof(package->nt_b));
memcpy(&statelists[1].ks1, package->ks_b, sizeof(package->ks_b));
// calc keys // calc keys
pthread_t thread_id[2]; pthread_t thread_id[2];
@ -541,6 +577,7 @@ int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidt
clearCommandBuffer(); clearCommandBuffer();
SendCommandNG(CMD_HF_MIFARE_EML_MEMSET, (uint8_t *)payload, sizeof(payload) + size); SendCommandNG(CMD_HF_MIFARE_EML_MEMSET, (uint8_t *)payload, sizeof(payload) + size);
free(payload);
return PM3_SUCCESS; return PM3_SUCCESS;
} }
@ -969,7 +1006,7 @@ int detect_classic_prng(void) {
// check respA // check respA
if (respA.oldarg[0] != 4) { if (respA.oldarg[0] != 4) {
PrintAndLogEx(ERR, "PRNG data error: Wrong length: %d", respA.oldarg[0]); PrintAndLogEx(ERR, "PRNG data error: Wrong length: %"PRIu64, respA.oldarg[0]);
return PM3_ESOFT; return PM3_ESOFT;
} }
@ -1063,19 +1100,18 @@ void detect_classic_magic(void) {
switch (isGeneration) { switch (isGeneration) {
case MAGIC_GEN_1A: case MAGIC_GEN_1A:
PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1a): " _GREEN_("YES")); PrintAndLogEx(SUCCESS, "Magic capabilities : " _GREEN_("Gen 1a"));
break; break;
case MAGIC_GEN_1B: case MAGIC_GEN_1B:
PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1b): " _GREEN_("YES")); PrintAndLogEx(SUCCESS, "Magic capabilities : " _GREEN_("Gen 1b"));
break; break;
case MAGIC_GEN_2: case MAGIC_GEN_2:
PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 2 / CUID): " _GREEN_("YES")); PrintAndLogEx(SUCCESS, "Magic capabilities : " _GREEN_("Gen 2 / CUID"));
break; break;
case MAGIC_GEN_UNFUSED: case MAGIC_GEN_UNFUSED:
PrintAndLogEx(SUCCESS, "Answers to magic commands (Write Once / FUID): " _GREEN_("YES")); PrintAndLogEx(SUCCESS, "Magic capabilities : " _GREEN_("Write Once / FUID"));
break; break;
default: default:
PrintAndLogEx(INFO, "Answers to magic commands: " _YELLOW_("NO"));
break; break;
} }
} }

View file

@ -143,11 +143,11 @@ static int ndefPrintHeader(NDEFHeader_t *header) {
PrintAndLogEx(NORMAL, "\tID Len Present: %s", STRBOOL(header->IDLenPresent)); PrintAndLogEx(NORMAL, "\tID Len Present: %s", STRBOOL(header->IDLenPresent));
PrintAndLogEx(NORMAL, "\tType Name Format: [0x%02x] %s", header->TypeNameFormat, TypeNameFormat_s[header->TypeNameFormat]); PrintAndLogEx(NORMAL, "\tType Name Format: [0x%02x] %s", header->TypeNameFormat, TypeNameFormat_s[header->TypeNameFormat]);
PrintAndLogEx(NORMAL, "\tHeader length : %d", header->len); PrintAndLogEx(NORMAL, "\tHeader length : %zu", header->len);
PrintAndLogEx(NORMAL, "\tType length : %d", header->TypeLen); PrintAndLogEx(NORMAL, "\tType length : %zu", header->TypeLen);
PrintAndLogEx(NORMAL, "\tPayload length : %d", header->PayloadLen); PrintAndLogEx(NORMAL, "\tPayload length : %zu", header->PayloadLen);
PrintAndLogEx(NORMAL, "\tID length : %d", header->IDLen); PrintAndLogEx(NORMAL, "\tID length : %zu", header->IDLen);
PrintAndLogEx(NORMAL, "\tRecord length : %d", header->RecLen); PrintAndLogEx(NORMAL, "\tRecord length : %zu", header->RecLen);
return 0; return 0;
} }
@ -171,7 +171,7 @@ static int ndefDecodeSig(uint8_t *sig, size_t siglen) {
// ecdsa 0x04 // ecdsa 0x04
if (sigType == stECDSA) { if (sigType == stECDSA) {
indx += 3; indx += 3;
PrintAndLogEx(NORMAL, "\tsignature [%d]: %s", intsiglen, sprint_hex_inrow(&sig[indx], intsiglen)); PrintAndLogEx(NORMAL, "\tsignature [%zu]: %s", intsiglen, sprint_hex_inrow(&sig[indx], intsiglen));
uint8_t rval[300] = {0}; uint8_t rval[300] = {0};
uint8_t sval[300] = {0}; uint8_t sval[300] = {0};
@ -186,7 +186,7 @@ static int ndefDecodeSig(uint8_t *sig, size_t siglen) {
if (sigURI) { if (sigURI) {
size_t intsigurilen = (sig[indx] << 8) + sig[indx + 1]; size_t intsigurilen = (sig[indx] << 8) + sig[indx + 1];
indx += 2; indx += 2;
PrintAndLogEx(NORMAL, "\tsignature uri [%d]: %.*s", intsigurilen, intsigurilen, &sig[indx]); PrintAndLogEx(NORMAL, "\tsignature uri [%zu]: %.*s", intsigurilen, intsigurilen, &sig[indx]);
indx += intsigurilen; indx += intsigurilen;
} }
@ -203,7 +203,7 @@ static int ndefDecodeSig(uint8_t *sig, size_t siglen) {
size_t intcertlen = (sig[indx + 1] << 8) + sig[indx + 2]; size_t intcertlen = (sig[indx + 1] << 8) + sig[indx + 2];
indx += 2; indx += 2;
PrintAndLogEx(NORMAL, "\tcertificate %d [%d]: %s", i + 1, intcertlen, sprint_hex_inrow(&sig[indx], intcertlen)); PrintAndLogEx(NORMAL, "\tcertificate %d [%zu]: %s", i + 1, intcertlen, sprint_hex_inrow(&sig[indx], intcertlen));
indx += intcertlen; indx += intcertlen;
} }
@ -211,7 +211,7 @@ static int ndefDecodeSig(uint8_t *sig, size_t siglen) {
if ((indx <= siglen) && certURI) { if ((indx <= siglen) && certURI) {
size_t inturilen = (sig[indx] << 8) + sig[indx + 1]; size_t inturilen = (sig[indx] << 8) + sig[indx + 1];
indx += 2; indx += 2;
PrintAndLogEx(NORMAL, "\tcertificate uri [%d]: %.*s", inturilen, inturilen, &sig[indx]); PrintAndLogEx(NORMAL, "\tcertificate uri [%zu]: %.*s", inturilen, inturilen, &sig[indx]);
} }
return 0; return 0;
@ -222,17 +222,17 @@ static int ndefDecodePayload(NDEFHeader_t *ndef) {
switch (ndef->TypeNameFormat) { switch (ndef->TypeNameFormat) {
case tnfWellKnownRecord: case tnfWellKnownRecord:
PrintAndLogEx(INFO, "Well Known Record"); PrintAndLogEx(INFO, "Well Known Record");
PrintAndLogEx(NORMAL, "\ttype: %.*s", ndef->TypeLen, ndef->Type); PrintAndLogEx(NORMAL, "\ttype: %.*s", (int)ndef->TypeLen, ndef->Type);
if (!strncmp((char *)ndef->Type, "T", ndef->TypeLen)) { if (!strncmp((char *)ndef->Type, "T", ndef->TypeLen)) {
PrintAndLogEx(NORMAL, "\ttext : %.*s", ndef->PayloadLen, ndef->Payload); PrintAndLogEx(NORMAL, "\ttext : %.*s", (int)ndef->PayloadLen, ndef->Payload);
} }
if (!strncmp((char *)ndef->Type, "U", ndef->TypeLen)) { if (!strncmp((char *)ndef->Type, "U", ndef->TypeLen)) {
PrintAndLogEx(NORMAL PrintAndLogEx(NORMAL
, "\turi : %s%.*s" , "\turi : %s%.*s"
, (ndef->Payload[0] <= 0x23 ? URI_s[ndef->Payload[0]] : "[err]") , (ndef->Payload[0] <= 0x23 ? URI_s[ndef->Payload[0]] : "[err]")
, ndef->PayloadLen - 1 , (int)(ndef->PayloadLen - 1)
, &ndef->Payload[1] , &ndef->Payload[1]
); );
} }
@ -244,8 +244,8 @@ static int ndefDecodePayload(NDEFHeader_t *ndef) {
break; break;
case tnfAbsoluteURIRecord: case tnfAbsoluteURIRecord:
PrintAndLogEx(INFO, "Absolute URI Record"); PrintAndLogEx(INFO, "Absolute URI Record");
PrintAndLogEx(NORMAL, "\ttype: %.*s", ndef->TypeLen, ndef->Type); PrintAndLogEx(NORMAL, "\ttype: %.*s", (int)ndef->TypeLen, ndef->Type);
PrintAndLogEx(NORMAL, "\tpayload: %.*s", ndef->PayloadLen, ndef->Payload); PrintAndLogEx(NORMAL, "\tpayload: %.*s", (int)ndef->PayloadLen, ndef->Payload);
break; break;
case tnfEmptyRecord: case tnfEmptyRecord:
case tnfMIMEMediaRecord: case tnfMIMEMediaRecord:
@ -302,7 +302,7 @@ static int ndefRecordsDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen)
} }
if (NDEFHeader.MessageEnd && len + NDEFHeader.RecLen != ndefRecordLen) { if (NDEFHeader.MessageEnd && len + NDEFHeader.RecLen != ndefRecordLen) {
PrintAndLogEx(ERR, "NDEF records have wrong length. Must be %d, calculated %d", ndefRecordLen, len + NDEFHeader.RecLen); PrintAndLogEx(ERR, "NDEF records have wrong length. Must be %zu, calculated %zu", ndefRecordLen, len + NDEFHeader.RecLen);
return 1; return 1;
} }

View file

@ -261,9 +261,11 @@ check_script:
} }
} // end while } // end while
clearCommandBuffer(); if (session.pm3_present) {
SendCommandNG(CMD_QUIT_SESSION, NULL, 0); clearCommandBuffer();
msleep(100); // Make sure command is sent before killing client SendCommandNG(CMD_QUIT_SESSION, NULL, 0);
msleep(100); // Make sure command is sent before killing client
}
while (current_cmdscriptfile()) while (current_cmdscriptfile())
pop_cmdscriptfile(); pop_cmdscriptfile();
@ -384,7 +386,7 @@ static int flash_pm3(char *serial_port_name, uint8_t num_files, char *filenames[
int ret = PM3_EUNDEF; int ret = PM3_EUNDEF;
flash_file_t files[FLASH_MAX_FILES]; flash_file_t files[FLASH_MAX_FILES];
memset(files, 0, sizeof(files)); memset(files, 0, sizeof(files));
char *filepaths[FLASH_MAX_FILES]; char *filepaths[FLASH_MAX_FILES] = {0};
if (serial_port_name == NULL) { if (serial_port_name == NULL) {
PrintAndLogEx(ERR, "You must specify a port.\n"); PrintAndLogEx(ERR, "You must specify a port.\n");

View file

@ -1074,6 +1074,7 @@ static int l_searchfile(lua_State *L) {
} }
lua_pushstring(L, path); lua_pushstring(L, path);
free(path);
return 1; return 1;
} }

View file

@ -200,7 +200,7 @@ Bootrom code will still use the old frame format to remain compatible with other
(`bootrom/bootrom.c`) (`bootrom/bootrom.c`)
usb_read (common/usb_cdc.c) ⇒ UsbPacketReceived (bootrom.c) usb_read (common/usb_cdc.c) ⇒ UsbPacketReceived (bootrom.c)
⇒ CMD_DEVICE_INFO / CMD_START_FLASH / CMD_FINISH_WRITE / CMD_HARDWARE_RESET / CMD_SETUP_WRITE ⇒ CMD_DEVICE_INFO / CMD_START_FLASH / CMD_FINISH_WRITE / CMD_HARDWARE_RESET
also `usb_enable`, `usb_disable` (`common/usb_cdc.c`) also `usb_enable`, `usb_disable` (`common/usb_cdc.c`)

View file

@ -253,7 +253,7 @@ typedef struct {
// For the bootloader // For the bootloader
#define CMD_DEVICE_INFO 0x0000 #define CMD_DEVICE_INFO 0x0000
#define CMD_SETUP_WRITE 0x0001 //#define CMD_SETUP_WRITE 0x0001
#define CMD_FINISH_WRITE 0x0003 #define CMD_FINISH_WRITE 0x0003
#define CMD_HARDWARE_RESET 0x0004 #define CMD_HARDWARE_RESET 0x0004
#define CMD_START_FLASH 0x0005 #define CMD_START_FLASH 0x0005
@ -373,6 +373,7 @@ typedef struct {
#define CMD_LF_T55XX_WAKEUP 0x0224 #define CMD_LF_T55XX_WAKEUP 0x0224
#define CMD_LF_COTAG_READ 0x0225 #define CMD_LF_COTAG_READ 0x0225
#define CMD_LF_T55XX_SET_CONFIG 0x0226 #define CMD_LF_T55XX_SET_CONFIG 0x0226
#define CMD_LF_SAMPLING_GET_CONFIG 0x0227
#define CMD_LF_T55XX_CHK_PWDS 0x0230 #define CMD_LF_T55XX_CHK_PWDS 0x0230
@ -578,6 +579,10 @@ typedef struct {
// Quit program client: reserved, order to quit the program // Quit program client: reserved, order to quit the program
#define PM3_EFATAL -99 #define PM3_EFATAL -99
// LF
#define LF_DIVISOR(f) (((12000 + (f)/2)/(f))-1)
#define LF_DIVISOR_125 LF_DIVISOR(125)
#define LF_DIVISOR_134 LF_DIVISOR(134)
// Receiving from USART need more than 30ms as we used on USB // Receiving from USART need more than 30ms as we used on USB
// else we get errors about partial packet reception // else we get errors about partial packet reception

154
pm3
View file

@ -16,66 +16,46 @@ else
CLIENT="proxmark3" CLIENT="proxmark3"
fi fi
function wait4proxmark_Linux { PM3LIST=()
echo >&2 "[=] Waiting for Proxmark3 to appear..."
while true; do function get_pm3_list_Linux {
PM3=$(find /dev/pm3-* /dev/ttyACM* 2>/dev/null | head -1) PM3LIST=()
if [[ $PM3 != "" ]]; then for DEV in $(find /dev/ttyACM* 2>/dev/null); do
break if udevadm info -q property -n "$DEV" |grep -q "ID_MODEL=proxmark3"; then
PM3LIST+=("$DEV")
fi fi
sleep .1
done done
echo "$PM3"
} }
function wait4proxmark_macOS { function get_pm3_list_macOS {
echo >&2 "[=] Waiting for Proxmark3 to appear..." PM3LIST=()
while true; do for DEV in $(ioreg -r -n proxmark3 -l|awk -F '"' '/IODialinDevice/{print $4}'); do
PM3=$(find /dev/pm3-* /dev/tty.usbmodem* 2>/dev/null | head -1) PM3LIST+=("$DEV")
if [[ $PM3 != "" ]]; then
break
fi
sleep .1
done done
echo "$PM3"
} }
function wait4proxmark_Windows { function get_pm3_list_Windows {
echo >&2 "[=] Waiting for Proxmark3 to appear..." PM3LIST=()
while true; do for DEV in $(wmic path Win32_SerialPort where "PNPDeviceID like '%VID_9AC4&PID_4B8F%'" get DeviceID,PNPDeviceID 2>/dev/null|awk '/^COM/{print $1}'); do
device=$(wmic path Win32_SerialPort where "PNPDeviceID like '%VID_9AC4&PID_4B8F%'" get DeviceID,PNPDeviceID 2>/dev/null | awk 'NR==2') DEV=${DEV/ */}
if [[ $device != "" ]]; then PM3LIST+=("$DEV")
PM3=${device/ */}
break
fi
sleep .1
done done
echo "$PM3"
} }
function wait4proxmark_WSL { function get_pm3_list_WSL {
# Test presence of wmic PM3LIST=()
wmic.exe computersystem get name >/dev/null 2>&1 for DEV in $(wmic.exe path Win32_SerialPort where "PNPDeviceID like '%VID_9AC4&PID_4B8F%'" get DeviceID,PNPDeviceID 2>/dev/null|awk '/^COM/{print $1}'); do
if [ $? -ne 0 ]; then DEV=${DEV/ */}
echo "[!] Cannot run wmic.exe, are you sure your WSL is authorized to run Windows processes? (cf WSL interop flag)" DEV="/dev/ttyS${DEV#COM}"
exit 1 # ttyS counterpart takes some more time to appear
fi if [ -e "$DEV" ]; then
PM3LIST+=("$DEV")
echo >&2 "[=] Waiting for Proxmark3 to appear..." if [ ! -w "$DEV" ]; then
while true; do echo "[!!] Let's give users read/write access to $DEV"
device=$(wmic.exe path Win32_SerialPort where "PNPDeviceID like '%VID_9AC4&PID_4B8F%'" get DeviceID,PNPDeviceID 2>/dev/null | awk 'NR==2') sudo chmod 666 "$DEV"
if [[ $device != "" ]]; then fi
PM3=${device/ */}
PM3="/dev/ttyS${PM3#COM}"
break
fi fi
sleep .1
done done
if [ -e "$PM3" ] && [ ! -w "$PM3" ]; then
echo "[!!] We need to give current user read/write access to $PM3"
sudo chmod 666 "$PM3"
fi
echo "$PM3"
} }
SCRIPT=$(basename -- "$0") SCRIPT=$(basename -- "$0")
@ -84,23 +64,24 @@ if [ "$SCRIPT" = "pm3" ]; then
CMD() { $CLIENT "$@"; } CMD() { $CLIENT "$@"; }
HELP() { HELP() {
cat << EOF cat << EOF
Quick helper script for proxmark3 client when working with a Proxmark device connected via USB Quick helper script for proxmark3 client when working with a Proxmark3 device connected via USB
Description: Description:
The usage is the same as for the proxmark3 client, with the following differences: The usage is the same as for the proxmark3 client, with the following differences:
* the correct port name will be automatically guessed; * the correct port name will be automatically guessed;
* the script will wait for a Proxmark to be connected (same as option -w of the client). * the script will wait for a Proxmark to be connected (same as option -w of the client).
You can also specify a first option -n N to access the Nth Proxmark3 connected on USB.
Don't use this script if you want to work offline or with the BT addon. Don't use this script if you want to work offline or with the BT addon.
Usage: Usage:
$SCRIPT [-f] [-c <command>]|[-l <lua_script_file>]|[-s <cmd_script_file>] [-i] $SCRIPT [-n <N>] [-f] [-c <command>]|[-l <lua_script_file>]|[-s <cmd_script_file>] [-i]
See "$CLIENT -h" for more details on options. See "$CLIENT -h" for more details on options.
EOF EOF
} }
elif [ "$SCRIPT" = "pm3-flash" ]; then elif [ "$SCRIPT" = "pm3-flash" ]; then
CMD() { CMD() {
ARGS=("$1" "--flash") ARGS=("--port" "$1" "--flash")
shift; shift;
while [ "$1" != "" ]; do while [ "$1" != "" ]; do
if [ "$1" == "-b" ]; then if [ "$1" == "-b" ]; then
@ -118,10 +99,11 @@ Quick helper script for flashing a Proxmark device via USB
Description: Description:
The usage is similar to the old proxmark3-flasher binary, except that the correct port name will be automatically guessed. The usage is similar to the old proxmark3-flasher binary, except that the correct port name will be automatically guessed.
You can also specify a first option -n N to access the Nth Proxmark3 connected on USB.
If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h". If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h".
Usage: Usage:
$SCRIPT [-b] image.elf [image.elf...] $SCRIPT [-n <N>] [-b] image.elf [image.elf...]
Options: Options:
-b Enable flashing of bootloader area (DANGEROUS) -b Enable flashing of bootloader area (DANGEROUS)
@ -131,45 +113,48 @@ Example:
EOF EOF
} }
elif [ "$SCRIPT" = "pm3-flash-all" ]; then elif [ "$SCRIPT" = "pm3-flash-all" ]; then
CMD() { $CLIENT "$1" "--flash" "--unlock-bootloader" "--image" "$BOOTIMAGE" "--image" "$FULLIMAGE"; } CMD() { $CLIENT "--port" "$1" "--flash" "--unlock-bootloader" "--image" "$BOOTIMAGE" "--image" "$FULLIMAGE"; }
HELP() { HELP() {
cat << EOF cat << EOF
Quick helper script for flashing a Proxmark device via USB Quick helper script for flashing a Proxmark device via USB
Description: Description:
The correct port name will be automatically guessed and the stock bootloader and firmware image will be flashed. The correct port name will be automatically guessed and the stock bootloader and firmware image will be flashed.
You can also specify a first option -n N to access the Nth Proxmark3 connected on USB.
If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h". If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h".
Usage: Usage:
$SCRIPT $SCRIPT [-n <N>]
EOF EOF
} }
elif [ "$SCRIPT" = "pm3-flash-fullimage" ]; then elif [ "$SCRIPT" = "pm3-flash-fullimage" ]; then
CMD() { $CLIENT "$1" "--flash" "--image" "$FULLIMAGE"; } CMD() { $CLIENT "--port" "$1" "--flash" "--image" "$FULLIMAGE"; }
HELP() { HELP() {
cat << EOF cat << EOF
Quick helper script for flashing a Proxmark device via USB Quick helper script for flashing a Proxmark device via USB
Description: Description:
The correct port name will be automatically guessed and the stock firmware image will be flashed. The correct port name will be automatically guessed and the stock firmware image will be flashed.
You can also specify a first option -n N to access the Nth Proxmark3 connected on USB.
If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h". If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h".
Usage: Usage:
$SCRIPT $SCRIPT [-n <N>]
EOF EOF
} }
elif [ "$SCRIPT" = "pm3-flash-bootrom" ]; then elif [ "$SCRIPT" = "pm3-flash-bootrom" ]; then
CMD() { $CLIENT "$1" "--flash" "--unlock-bootloader" "--image" "$BOOTIMAGE"; } CMD() { $CLIENT "--port" "$1" "--flash" "--unlock-bootloader" "--image" "$BOOTIMAGE"; }
HELP() { HELP() {
cat << EOF cat << EOF
Quick helper script for flashing a Proxmark device via USB Quick helper script for flashing a Proxmark device via USB
Description: Description:
The correct port name will be automatically guessed and the stock bootloader will be flashed. The correct port name will be automatically guessed and the stock bootloader will be flashed.
You can also specify a first option -n N to access the Nth Proxmark3 connected on USB.
If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h". If this doesn't work, you'll have to use manually the proxmark3 client, see "$CLIENT -h".
Usage: Usage:
$SCRIPT $SCRIPT [-n <N>]
EOF EOF
} }
else else
@ -180,25 +165,64 @@ if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
HELP HELP
exit 0 exit 0
fi fi
# if a port is already provided, let's just run the command as such
for ARG in "$@"; do
if [ "$ARG" == "-p" ]; then
CMD "$@"
exit $?
fi
done
# Number of the proxmark3 we're interested in
N=1
if [ "$1" == "-n" ]; then
shift
if [ "$1" -ge 1 ] && [ "$1" -lt 10 ]; then
N=$1
shift
else
echo "Option -n requires a number between 1 and 9, got \"$1\""
exit 1
fi
fi
echo >&2 "[=] Waiting for Proxmark3 to appear..."
HOSTOS=$(uname | awk '{print toupper($0)}') HOSTOS=$(uname | awk '{print toupper($0)}')
if [ "$HOSTOS" = "LINUX" ]; then if [ "$HOSTOS" = "LINUX" ]; then
if uname -a|grep -q Microsoft; then if uname -a|grep -q Microsoft; then
PORT=$(wait4proxmark_WSL) # Test presence of wmic
wmic.exe computersystem get name >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "[!] Cannot run wmic.exe, are you sure your WSL is authorized to run Windows processes? (cf WSL interop flag)"
exit 1
fi
GETPM3LIST=get_pm3_list_WSL
else else
PORT=$(wait4proxmark_Linux) GETPM3LIST=get_pm3_list_Linux
fi fi
elif [ "$HOSTOS" = "DARWIN" ]; then elif [ "$HOSTOS" = "DARWIN" ]; then
PORT=$(wait4proxmark_macOS) GETPM3LIST=get_pm3_list_macOS
elif [[ "$HOSTOS" =~ MINGW(32|64)_NT* ]]; then elif [[ "$HOSTOS" =~ MINGW(32|64)_NT* ]]; then
PORT=$(wait4proxmark_Windows) GETPM3LIST=get_pm3_list_Windows
else else
echo "[!!] Host OS not recognized, abort: $HOSTOS" echo "[!!] Host OS not recognized, abort: $HOSTOS"
exit 1 exit 1
fi fi
if [ "$PORT" = "" ]; then
echo "[!!] No port, abort" # Wait till we get at least N proxmark3 devices
while true; do
$GETPM3LIST $N
if [ ${#PM3LIST[*]} -ge $N ]; then
break
fi
sleep .1
done
if [ ${#PM3LIST} -lt $N ]; then
echo "[!!] No port found, abort"
exit 1 exit 1
fi fi
CMD "$PORT" "$@" CMD "${PM3LIST[$((N-1))]}" "$@"
exit $? exit $?

View file

@ -275,11 +275,15 @@ static int bitparse_find_section(FILE *infile, char section_name, unsigned int *
/* Four byte length field */ /* Four byte length field */
current_length += fgetc(infile) << 24; current_length += fgetc(infile) << 24;
current_length += fgetc(infile) << 16; current_length += fgetc(infile) << 16;
numbytes += 2; current_length += fgetc(infile) << 8;
current_length += fgetc(infile) << 0;
numbytes += 4;
break;
default: /* Fall through, two byte length field */ default: /* Fall through, two byte length field */
current_length += fgetc(infile) << 8; current_length += fgetc(infile) << 8;
current_length += fgetc(infile) << 0; current_length += fgetc(infile) << 0;
numbytes += 2; numbytes += 2;
break;
} }
if (current_name != 'e' && current_length > 255) { if (current_name != 'e' && current_length > 255) {