Merge branch 'master' of github.com:merlokk/proxmark3i into mf_mad

# Conflicts:
#	client/cmdhfmf.c
#	client/mifare/mifarehost.c
This commit is contained in:
merlokk 2019-03-01 19:37:43 +02:00
commit ee9daac029
63 changed files with 1216 additions and 862 deletions

View file

@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file.
This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log...
## [unreleased][unreleased]
- Chg 'data autocorrelate' - better visual representation and added extra peak detection (@iceman)
- Fix 'lf search' - false positive indala identification fixed (@iceman)
- Add 'lf keri' - basic support for Keri tags (@iceman)
- Add 'hf mf list' - re-added it again (@iceman)
- Fix - A lot of bugfixes, like memory leaks (@iceman)
- Change 'hf 14a antifuzz' - original implementation (@asfabw), reworked a bit
- Fix 'hf mf fchk' (@iceman)
- Fix 'usb slow on posix based systems' (@fl0-0)

View file

@ -1253,11 +1253,11 @@ void UsbPacketReceived(uint8_t *packet, int len) {
size_t size = MIN(USB_CMD_DATA_SIZE, len);
uint8_t *mem = BigBuf_malloc(size);
if (!FlashInit()) {
if (!FlashInit()) {
break;
}
uint8_t *mem = BigBuf_malloc(size);
for(size_t i = 0; i < len; i += size) {
len = MIN((len - i), size);
@ -1271,6 +1271,7 @@ void UsbPacketReceived(uint8_t *packet, int len) {
break;
}
}
BigBuf_free();
FlashStop();
LED_B_OFF();
break;

View file

@ -188,6 +188,7 @@ CMDSRCS = crapto1/crapto1.c \
cmdlfio.c \
cmdlfindala.c \
cmdlfjablotron.c \
cmdlfkeri.c \
cmdlfnexwatch.c \
cmdlfnedap.c \
cmdlfnoralsy.c \

View file

@ -754,19 +754,53 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph
lastmax = i;
}
}
if (verbose && ( correlation > 1 ) ) {
PrintAndLogEx(SUCCESS, "possible correlation %4d samples", correlation);
} else {
PrintAndLogEx(FAILED, "no repeating pattern found");
//
int hi = 0, idx = 0;
int distance = 0, hi_1 = 0, idx_1 = 0;
for (int i = 0; i <= len; ++i){
if ( CorrelBuffer[i] > hi) {
hi = CorrelBuffer[i];
idx = i;
}
}
if (SaveGrph){
for (int i = idx+1; i <= window; ++i){
if ( CorrelBuffer[i] > hi_1 ) {
hi_1 = CorrelBuffer[i];
idx_1 = i;
}
}
int foo = ABS(hi-hi_1);
int bar = (int)(((hi+hi_1) / 2) * 0.03);
if ( verbose && foo < bar ) {
distance = idx_1 - idx;
PrintAndLogEx(SUCCESS, "possible 3% visible correlation %4d samples", distance);
} else if (verbose && ( correlation > 1 ) ) {
PrintAndLogEx(SUCCESS, "possible correlation %4d samples", correlation);
} else {
PrintAndLogEx(FAILED, "no repeating pattern found, try increasing window size");
}
int retval = correlation;
if (SaveGrph) {
//GraphTraceLen = GraphTraceLen - window;
memcpy(out, CorrelBuffer, len * sizeof(int));
if ( distance > 0) {
setClockGrid(distance, idx);
retval = distance;
}
else
setClockGrid(correlation, idx);
CursorCPos = idx_1;
CursorDPos = idx_1+retval;
DemodBufferLen = 0;
RepaintGraphWindow();
}
return correlation;
return retval;
}
int CmdAutoCorr(const char *Cmd) {

View file

@ -13,6 +13,7 @@
#include "mbedtls/rsa.h"
#include "mbedtls/sha1.h"
#include "mbedtls/base64.h"
#define MCK 48000000
//#define FLASH_BAUD 24000000
@ -247,7 +248,6 @@ int CmdFlashMemLoad(const char *Cmd){
res = loadFile(filename, "bin", data, &datalen);
//int res = loadFileEML( filename, "eml", data, &datalen);
if ( res ) {
free(data);
return 1;
}

View file

@ -579,11 +579,11 @@ int CmdHF14AInfo(const char *Cmd) {
if (isMifareClassic) {
int res = detect_classic_prng();
if ( res == 1 )
PrintAndLogEx(SUCCESS, "Prng detection: WEAK");
PrintAndLogEx(SUCCESS, "Prng detection: " _GREEN_(WEAK));
else if (res == 0 )
PrintAndLogEx(SUCCESS, "Prng detection: HARD");
PrintAndLogEx(SUCCESS, "Prng detection: " _YELLOW_(HARD));
else
PrintAndLogEx(FAILED, "prng detection: failed");
PrintAndLogEx(FAILED, "prng detection: " _RED_(failed));
if ( do_nack_test )
detect_classic_nackbug(silent);

View file

@ -246,7 +246,7 @@ static bool get_14b_UID(iso14b_card_select_t *card) {
if (!card)
return false;
uint8_t retry = 3;
int8_t retry = 3;
UsbCommand resp;
UsbCommand c = {CMD_ISO_14443B_COMMAND, {ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT, 0, 0}};
@ -283,7 +283,7 @@ static bool get_14b_UID(iso14b_card_select_t *card) {
}
} // retry
if ( !retry )
if ( retry <= 0 )
PrintAndLogEx(WARNING, "timeout while waiting for reply.");
return false;
@ -461,6 +461,7 @@ bool HF14B_Std_Info(bool verbose){
PrintAndLogEx(NORMAL, " CHIPID : %02X", card.chipid);
print_atqb_resp(card.atqb, card.cid);
isSuccess = true;
break;
case 2:
if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ATTRIB fail");
break;

View file

@ -834,6 +834,7 @@ int CmdHF15Restore(const char*Cmd) {
if (!getUID(uid)) {
PrintAndLogEx(WARNING, "No tag found");
fclose(f);
return 3;
}

View file

@ -242,7 +242,7 @@ static void printSep() {
PrintAndLogEx(NORMAL, "------------------------------------------------------------------------------------");
}
uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace,uint16_t tracelen) {
uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace, uint16_t tracelen) {
if (tracepos+19 >= tracelen)
return tracelen;
@ -253,7 +253,7 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace,uint16_t tracelen) {
char line[110] = {0};
for (int j = 0; j < 16; j++) {
snprintf(line+( j * 4),110, "%02x ", trace[j+3]);
snprintf(line + (j * 4), sizeof(line) - 1 - (j*4) , "%02x ", trace[j+3]);
}
PrintAndLogEx(NORMAL, "block number %02x, status: %02x %02x",blocknum,status1, status2);
@ -273,11 +273,12 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace,uint16_t tracelen) {
case 0x0c: PrintAndLogEx(NORMAL, "S_PAD12: %s",line);break;
case 0x0d: PrintAndLogEx(NORMAL, "S_PAD13: %s",line);break;
case 0x0E: {
uint32_t regA = trace[3] + (trace[4]>>8) + (trace[5]>>16) + (trace[6]>>24);
uint32_t regB = trace[7] + (trace[8]>>8) + (trace[9]>>16) + (trace[10]>>24);
uint32_t regA = trace[3] | trace[4] << 8 | trace[5] << 16 | trace[ 6] << 24;
uint32_t regB = trace[7] | trace[8] << 8 | trace[9] << 16 | trace[10] << 24;
line[0] = 0;
for (int j = 0; j < 8; j++)
snprintf(line+( j * 2),110, "%02x", trace[j+11]);
snprintf(line + (j*2), sizeof(line)-1-(j*2), "%02x", trace[j+11]);
PrintAndLogEx(NORMAL, "REG: regA: %d regB: %d regC: %s ", regA, regB, line);
}
break;
@ -287,10 +288,10 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace,uint16_t tracelen) {
char idd[20];
char idm[20];
for (int j = 0; j < 8; j++)
snprintf(idd+( j * 2),20, "%02x", trace[j+3]);
snprintf(idd + (j*2), sizeof(idd)-1-(j*2), "%02x", trace[j+3]);
for (int j = 0; j < 6; j++)
snprintf(idm+( j * 2),20, "%02x", trace[j+13]);
snprintf(idm + (j*2), sizeof(idm)-1-(j*2), "%02x", trace[j+13]);
PrintAndLogEx(NORMAL, "ID Block, IDd: 0x%s DFC: 0x%02x%02x Arb: %s ", idd, trace[11], trace [12], idm);
}
@ -299,10 +300,10 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace,uint16_t tracelen) {
char idm[20];
char pmm[20];
for (int j = 0; j < 8; j++)
snprintf(idm+( j * 2),20, "%02x", trace[j+3]);
snprintf(idm + (j*2), sizeof(idm)-1-(j*2), "%02x", trace[j+3]);
for (int j = 0; j < 8; j++)
snprintf(pmm+( j * 2),20, "%02x", trace[j+11]);
snprintf(pmm + (j*2), sizeof(pmm)-1-(j*2), "%02x", trace[j+11]);
PrintAndLogEx(NORMAL, "DeviceId: IDm: 0x%s PMm: 0x%s ", idm, pmm);
}

View file

@ -626,7 +626,7 @@ int CmdHFiClassELoad(const char *Cmd) {
f = fopen(filename, "rb");
if ( !f ){
PrintAndLogEx(FAILED, "File: %s: not found or locked.", filename);
PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename);
return 1;
}
@ -2162,10 +2162,10 @@ static int cmp_uint32( const void *a, const void *b) {
int CmdHFiClassLookUp(const char *Cmd) {
uint8_t CSN[8];
uint8_t EPURSE[8];
uint8_t MACS[8];
uint8_t EPURSE[8] = { 0,0,0,0,0,0,0,0 };
uint8_t MACS[8]= { 0,0,0,0,0,0,0,0 };
uint8_t CCNR[12];
uint8_t MAC_TAG[4] = {0x00,0x00,0x00,0x00};
uint8_t MAC_TAG[4] = { 0,0,0,0 };
// elite key, raw key, standard key
bool use_elite = false;
@ -2304,7 +2304,7 @@ int LoadDictionaryKeyFile( char* filename, uint8_t **keys, int *keycnt) {
int keyitems = 0;
if ( !(f = fopen( filename , "r")) ) {
PrintAndLogEx(ERR, "file: %s: not found or locked.", filename);
PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename);
return 1;
}

View file

@ -1022,6 +1022,7 @@ int CmdLegicRestore(const char *Cmd){
f = fopen(filename,"rb");
if (!f) {
PrintAndLogEx(WARNING, "File %s not found or locked", filename);
free(data);
return 3;
}

View file

@ -686,7 +686,7 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes
PrintAndLogEx(NORMAL, " | | * |%49s %012"PRIx64" prng %s | |",
"key",
mfLastKey,
validate_prng_nonce(AuthData.nt) ? "WEAK": "HARD");
validate_prng_nonce(AuthData.nt) ? _GREEN_(WEAK): _YELLOW_(HARD));
AuthData.first_auth = false;

View file

@ -12,6 +12,9 @@
#include "mifare/mifare4.h"
#include "mifare/mad.h"
#define MFBLOCK_SIZE 16
#define MIFARE_4K_MAXBLOCK 256
#define MIFARE_2K_MAXBLOCK 128
#define MIFARE_1K_MAXBLOCK 64
@ -426,6 +429,7 @@ char * GenerateFilename(const char *prefix, const char *suffix){
GetHFMF14AUID(uid, &uidlen);
if (!uidlen) {
PrintAndLogEx(WARNING, "No tag found.");
free(fptr);
return NULL;
}
@ -434,7 +438,7 @@ char * GenerateFilename(const char *prefix, const char *suffix){
return fptr;
}
int CmdHF14ADarkside(const char *Cmd) {
int CmdHF14AMfDarkside(const char *Cmd) {
uint8_t blockno = 0, key_type = MIFARE_AUTH_KEYA;
uint64_t key = 0;
@ -697,10 +701,13 @@ int CmdHF14AMfDump(const char *Cmd) {
uint8_t cmdp = 0;
char keyFilename[FILE_PATH_SIZE] = {0};
char dataFilename[FILE_PATH_SIZE] = {0};
char dataFilename[FILE_PATH_SIZE];
char * fptr;
FILE *fin, *fout;
memset(keyFilename, 0, sizeof(keyFilename));
memset(dataFilename, 0, sizeof(dataFilename));
FILE *f;
UsbCommand resp;
while(param_getchar(Cmd, cmdp) != 0x00) {
@ -734,7 +741,7 @@ int CmdHF14AMfDump(const char *Cmd) {
strcpy(keyFilename, fptr);
}
if ((fin = fopen(keyFilename, "rb")) == NULL) {
if ((f = fopen(keyFilename, "rb")) == NULL) {
PrintAndLogEx(WARNING, "Could not find file " _YELLOW_(%s), keyFilename);
return 1;
}
@ -742,29 +749,29 @@ int CmdHF14AMfDump(const char *Cmd) {
// Read keys A from file
size_t bytes_read;
for (sectorNo=0; sectorNo<numSectors; sectorNo++) {
bytes_read = fread( keyA[sectorNo], 1, 6, fin );
bytes_read = fread( keyA[sectorNo], 1, 6, f );
if ( bytes_read != 6) {
PrintAndLogEx(WARNING, "File reading error.");
fclose(fin);
fclose(f);
return 2;
}
}
// Read keys B from file
for (sectorNo=0; sectorNo<numSectors; sectorNo++) {
bytes_read = fread( keyB[sectorNo], 1, 6, fin );
bytes_read = fread( keyB[sectorNo], 1, 6, f );
if ( bytes_read != 6) {
PrintAndLogEx(WARNING, "File reading error.");
fclose(fin);
fclose(f);
return 2;
}
}
fclose(fin);
fclose(f);
PrintAndLogEx(NORMAL, "|-----------------------------------------|");
PrintAndLogEx(NORMAL, "|------ Reading sector access bits...-----|");
PrintAndLogEx(NORMAL, "|-----------------------------------------|");
PrintAndLogEx(INFO, "Reading sector access bits...");
uint8_t tries = 0;
for (sectorNo = 0; sectorNo < numSectors; sectorNo++) {
for (tries = 0; tries < MIFARE_SECTOR_RETRY; tries++) {
@ -796,9 +803,8 @@ int CmdHF14AMfDump(const char *Cmd) {
}
}
PrintAndLogEx(NORMAL, "|-----------------------------------------|");
PrintAndLogEx(NORMAL, "|----- Dumping all blocks to file... -----|");
PrintAndLogEx(NORMAL, "|-----------------------------------------|");
PrintAndLogEx(SUCCESS, "Finished reading sector access bits");
PrintAndLogEx(INFO, "Dumping all blocks from card...");
bool isOK = true;
for (sectorNo = 0; isOK && sectorNo < numSectors; sectorNo++) {
@ -870,24 +876,24 @@ int CmdHF14AMfDump(const char *Cmd) {
}
}
if (isOK) {
if (dataFilename[0] == 0x00) {
fptr = GenerateFilename("hf-mf-", "-data.bin");
if (fptr == NULL)
return 1;
strcpy(dataFilename, fptr);
}
if ((fout = fopen(dataFilename,"wb")) == NULL) {
PrintAndLogEx(WARNING, "could not create file name " _YELLOW_(%s), dataFilename);
return 1;
}
uint16_t numblocks = FirstBlockOfSector(numSectors - 1) + NumBlocksPerSector(numSectors - 1);
fwrite(carddata, 1, 16*numblocks, fout);
fclose(fout);
PrintAndLogEx(SUCCESS, "dumped %d blocks (%d bytes) to file " _YELLOW_(%s), numblocks, 16*numblocks, dataFilename);
if (isOK == 0) {
PrintAndLogEx(FAILED, "Something went wrong");
return 0;
}
PrintAndLogEx(SUCCESS, "\nSuccedded in dumping all blocks");
if ( strlen(dataFilename) < 1 ) {
fptr = dataFilename;
fptr += sprintf(fptr, "hf-mf-");
FillFileNameByUID(fptr, (uint8_t *)carddata, "-data", 4);
}
uint16_t bytes = 16*(FirstBlockOfSector(numSectors - 1) + NumBlocksPerSector(numSectors - 1));
saveFile(dataFilename, "bin", (uint8_t *)carddata, bytes);
saveFileEML(dataFilename, "eml", (uint8_t *)carddata, bytes, MFBLOCK_SIZE);
saveFileJSON(dataFilename, "json", jsfCardMemory, (uint8_t *)carddata, bytes);
return 0;
}
@ -1083,19 +1089,21 @@ int CmdHF14AMfNested(const char *Cmd) {
} else {
SectorsCnt = NumOfSectors(cmdp);
}
ctmp = tolower(param_getchar(Cmd, 4));
transferToEml |= (ctmp == 't');
createDumpFile |= (ctmp == 'd');
ctmp = tolower(param_getchar(Cmd, 6));
transferToEml |= (ctmp == 't');
createDumpFile |= (ctmp == 'd');
uint8_t j = 4;
while ( ctmp != 0x00 ) {
ctmp = tolower(param_getchar(Cmd, j));
transferToEml |= (ctmp == 't');
createDumpFile |= (ctmp == 'd');
j++;
}
// check if we can authenticate to sector
res = mfCheckKeys(blockNo, keyType, true, 1, key, &key64);
if (res) {
PrintAndLogEx(WARNING, "key is wrong. Can't authenticate to block:%3d key type:%c", blockNo, keyType ? 'B' : 'A');
PrintAndLogEx(WARNING, "Wrong key. Can't authenticate to block:%3d key type:%c", blockNo, keyType ? 'B' : 'A');
return 3;
}
@ -1113,9 +1121,9 @@ int CmdHF14AMfNested(const char *Cmd) {
if (transferToEml) {
uint8_t sectortrailer;
if (trgBlockNo < 32*4) { // 4 block sector
sectortrailer = (trgBlockNo & ~0x03) + 3;
sectortrailer = trgBlockNo | 0x03;
} else { // 16 block sector
sectortrailer = (trgBlockNo & ~0x0f) + 15;
sectortrailer = trgBlockNo | 0x0f;
}
mfEmlGetMem(keyBlock, sectortrailer, 1);
@ -1237,14 +1245,16 @@ int CmdHF14AMfNested(const char *Cmd) {
num_to_bytes(e_sector[i].Key[1], 6, &keyBlock[10]);
mfEmlSetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1);
}
PrintAndLogEx(SUCCESS, "key transferred to emulator memory.");
PrintAndLogEx(SUCCESS, "keys transferred to emulator memory.");
}
// Create dump file
if (createDumpFile) {
fptr = GenerateFilename("hf-mf-", "-key.bin");
if (fptr == NULL)
if (fptr == NULL) {
free(e_sector);
return 1;
}
if ((fkeys = fopen(fptr, "wb")) == NULL) {
PrintAndLogEx(WARNING, "could not create file " _YELLOW_(%s), fptr);
@ -1274,6 +1284,8 @@ int CmdHF14AMfNested(const char *Cmd) {
}
free(e_sector);
}
free(e_sector);
return 0;
}
@ -1721,7 +1733,7 @@ int CmdHF14AMfChk(const char *Cmd) {
if (strlen(Cmd) < 3 || ctmp == 'h') return usage_hf14_chk();
FILE * f;
char filename[FILE_PATH_SIZE]={0};
char filename[FILE_PATH_SIZE] = {0};
char buf[13];
uint8_t *keyBlock = NULL, *p;
sector_t *e_sector = NULL;
@ -1806,7 +1818,7 @@ int CmdHF14AMfChk(const char *Cmd) {
f = fopen( filename , "r");
if ( !f ) {
PrintAndLogEx(FAILED, "File: " _YELLOW_(%s)": not found or locked.", filename);
PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename);
continue;
}
@ -1968,8 +1980,11 @@ out:
if (createDumpFile) {
fptr = GenerateFilename("hf-mf-", "-key.bin");
if (fptr == NULL)
if (fptr == NULL) {
free(keyBlock);
free(e_sector);
return 1;
}
FILE *fkeys = fopen(fptr, "wb");
if (fkeys == NULL) {
@ -2230,11 +2245,7 @@ int CmdHF14AMfSniff(const char *Cmd){
bufsize = traceLen;
memset(buf, 0x00, traceLen);
}
if (bufPtr == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
free(buf);
return 2;
}
// what happens if LEN is bigger then TRACELEN --iceman
memcpy(bufPtr, resp.d.asBytes, len);
bufPtr += len;
@ -2487,19 +2498,21 @@ int CmdHF14AMfELoad(const char *Cmd) {
if ( blockWidth == 4 ) {
if ((blockNum != numBlocks)) {
PrintAndLogEx(FAILED, "Warning, Ultralight/Ntag file content, Loaded %d blocks into emulator memory", blockNum);
free(data);
return 0;
}
} else {
if ((blockNum != numBlocks)) {
PrintAndLogEx(FAILED, "Error, file content, Only loaded %d blocks, must be %d blocks into emulator memory", blockNum, numBlocks);
free(data);
return 4;
}
}
PrintAndLogEx(SUCCESS, "Loaded %d blocks from file: " _YELLOW_(%s), blockNum, filename);
free(data);
return 0;
}
#define MFBLOCK_SIZE 16
int CmdHF14AMfESave(const char *Cmd) {
char filename[FILE_PATH_SIZE];
@ -2541,6 +2554,7 @@ int CmdHF14AMfESave(const char *Cmd) {
saveFile(filename, "bin", dump, bytes);
saveFileEML(filename, "eml", dump, bytes, MFBLOCK_SIZE);
saveFileJSON(filename, "json", jsfCardMemory, dump, bytes);
free(dump);
return 0;
}
@ -2740,8 +2754,10 @@ int CmdHF14AMfCLoad(const char *Cmd) {
res = loadFileEML( Cmd, "eml", data, &datalen);
}
}
if ( res ) {
free(data);
if ( data )
free(data);
return 1;
}
@ -2915,7 +2931,6 @@ int CmdHF14AMfCSave(const char *Cmd) {
errors = true;
break;
}
if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5;
useuid = false;
hasname = true;
@ -3163,7 +3178,7 @@ out:
return 0;
}
int CmdHF14AMfAuth4(const char *cmd) {
int CmdHF14AMfAuth4(const char *Cmd) {
uint8_t keyn[20] = {0};
int keynlen = 0;
uint8_t key[16] = {0};
@ -3180,7 +3195,7 @@ int CmdHF14AMfAuth4(const char *cmd) {
arg_str1(NULL, NULL, "<Key Value (HEX 16 bytes)>", NULL),
arg_param_end
};
CLIExecWithReturn(cmd, argtable, true);
CLIExecWithReturn(Cmd, argtable, true);
CLIGetHexWithReturn(1, keyn, &keynlen);
CLIGetHexWithReturn(2, key, &keylen);
@ -3242,9 +3257,15 @@ int CmdHF14AMfMAD(const char *cmd) {
return 0;
}
int CmdHF14AMfList(const char *Cmd) {
CmdTraceList("mf");
return 0;
}
static command_t CommandTable[] = {
{"help", CmdHelp, 1, "This help"},
{"darkside", CmdHF14ADarkside, 0, "Darkside attack. read parity error messages."},
{"list", CmdHF14AMfList, 0, "[Deprecated] List ISO 14443-a / Mifare history"},
{"darkside", CmdHF14AMfDarkside, 0, "Darkside attack. read parity error messages."},
{"nested", CmdHF14AMfNested, 0, "Nested attack. Test nested authentication"},
{"hardnested", CmdHF14AMfNestedHard, 0, "Nested attack for hardened Mifare cards"},
{"keybrute", CmdHF14AMfKeyBrute, 0, "J_Run's 2nd phase of multiple sector nested authentication key recovery"},

View file

@ -35,6 +35,7 @@
extern int CmdHFMF(const char *Cmd);
extern int CmdHF14AMfList(const char *Cmd);
extern int CmdHF14AMfDbg(const char* cmd);
extern int CmdHF14AMfRdBl(const char* cmd);
extern int CmdHF14AMfURdBl(const char* cmd);
@ -45,7 +46,7 @@ extern int CmdHF14AMfRestore(const char* cmd);
extern int CmdHF14AMfWrBl(const char* cmd);
extern int CmdHF14AMfUWrBl(const char* cmd);
extern int CmdHF14AMfChk(const char* cmd);
extern int CmdHF14ADarkside(const char* cmd);
extern int CmdHF14AMfDarkside(const char* cmd);
extern int CmdHF14AMfNested(const char* cmd);
extern int CmdHF14AMfNestedHard(const char *Cmd);
//extern int CmdHF14AMfSniff(const char* cmd);

View file

@ -266,14 +266,20 @@ static void init_bitflip_bitarrays(void)
continue;
} else {
fseek(statesfile, 0, SEEK_END);
uint32_t filesize = (uint32_t)ftell(statesfile);
int fsize = ftell(statesfile);
if ( fsize == -1 ){
PrintAndLogEx(WARNING, "File read error with %s. Aborting...\n", state_file_name);
fclose(statesfile);
exit(5);
}
uint32_t filesize = (uint32_t)fsize;
rewind(statesfile);
uint8_t input_buffer[filesize];
size_t bytesread = fread(input_buffer, 1, filesize, statesfile);
if (bytesread != filesize) {
PrintAndLogEx(WARNING, "File read error with %s. Aborting...\n", state_file_name);
fclose(statesfile);
inflateEnd(&compressed_stream);
//inflateEnd(&compressed_stream);
exit(5);
}
fclose(statesfile);
@ -1042,7 +1048,7 @@ static bool shrink_key_space(float *brute_forces)
//iceman 2018
return ((hardnested_stage & CHECK_2ND_BYTES) &&
reduction_rate >= 0.0 &&
( reduction_rate < brute_force_per_second * (float)sample_period / 1000.0 || *brute_forces < 0x1F000000000));
( reduction_rate < brute_force_per_second * (float)sample_period / 1000.0 || *brute_forces < 0x1F00000000));
}
@ -1666,9 +1672,9 @@ static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_e
}
#endif
return false;
} else {
return true;
}
return true;
}
@ -1708,11 +1714,13 @@ static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even
#ifdef DEBUG_KEY_ELIMINATION
if (known_target_key != -1 && state == test_state[odd_even]) {
PrintAndLogEx(NORMAL, "all_bitflips_match() 1st Byte: %s test state (0x%06x): Eliminated. Bytes = %02x, %02x, Common Bits = %d\n",
odd_even==ODD_STATE?"odd":"even",
odd_even == ODD_STATE ? "odd" : "even",
test_state[odd_even],
byte, byte2, num_common);
byte,
byte2,
num_common);
if (failstr[0] == '\0') {
sprintf(failstr, "Other 1st Byte %s, all_bitflips_match(), no match", odd_even?"odd":"even");
sprintf(failstr, "Other 1st Byte %s, all_bitflips_match(), no match", odd_even ? "odd" : "even");
}
}
#endif
@ -1764,12 +1772,10 @@ static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, ui
uint32_t *bitarray_a8 = part_sum_a8_bitarrays[odd_even][part_sum_a8/2];
uint32_t *bitarray_bitflips = nonces[best_first_bytes[0]].states_bitarray[odd_even];
// for (uint32_t i = 0; i < (1<<19); i++) {
// candidates_bitarray[i] = bitarray_a0[i] & bitarray_a8[i] & bitarray_bitflips[i];
// }
bitarray_AND4(candidates_bitarray, bitarray_a0, bitarray_a8, bitarray_bitflips);
bitarray_to_list(best_first_bytes[0], candidates_bitarray, candidates->states[odd_even], &(candidates->len[odd_even]), odd_even);
if (candidates->len[odd_even] == 0) {
free(candidates->states[odd_even]);
candidates->states[odd_even] = NULL;
@ -1778,17 +1784,14 @@ static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, ui
}
free_bitarray(candidates_bitarray);
pthread_mutex_lock(&statelist_cache_mutex);
sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].sl = candidates->states[odd_even];
sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].len = candidates->len[odd_even];
sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].cache_status = COMPLETED;
pthread_mutex_unlock(&statelist_cache_mutex);
return;
}
static statelist_t *add_more_candidates(void)
{
statelist_t *new_candidates = candidates;
@ -1882,7 +1885,6 @@ static bool TestIfKeyExists(uint64_t key)
static work_status_t book_of_work[NUM_PART_SUMS][NUM_PART_SUMS][NUM_PART_SUMS][NUM_PART_SUMS];
static void init_book_of_work(void)
{
for (uint8_t p = 0; p < NUM_PART_SUMS; p++) {
@ -2046,19 +2048,6 @@ __attribute__((force_align_arg_pointer))
static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx)
{
// PrintAndLogEx(NORMAL, "Generating crypto1 state candidates... \n");
// estimate maximum candidate states
// maximum_states = 0;
// for (uint16_t sum_odd = 0; sum_odd <= 16; sum_odd += 2) {
// for (uint16_t sum_even = 0; sum_even <= 16; sum_even += 2) {
// if (sum_odd*(16-sum_even) + (16-sum_odd)*sum_even == sum_a0) {
// maximum_states += (uint64_t)count_states(part_sum_a0_bitarrays[EVEN_STATE][sum_even/2])
// * count_states(part_sum_a0_bitarrays[ODD_STATE][sum_odd/2]);
// }
// }
// }
// PrintAndLogEx(NORMAL, "Number of possible keys with Sum(a0) = %d: %" PRIu64 " (2^%1.1f)\n", sum_a0, maximum_states, log(maximum_states)/log(2.0));
init_statelist_cache();
init_book_of_work();
@ -2105,12 +2094,11 @@ static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx)
static void free_candidates_memory(statelist_t *sl)
{
if (sl == NULL) {
if (sl == NULL)
return;
} else {
free_candidates_memory(sl->next);
free(sl);
}
free_candidates_memory(sl->next);
free(sl);
}
@ -2131,7 +2119,6 @@ static void pre_XOR_nonces(void)
}
}
}
static bool brute_force(uint64_t *found_key)
{
@ -2141,7 +2128,6 @@ static bool brute_force(uint64_t *found_key)
return brute_force_bs(NULL, candidates, cuid, num_acquired_nonces, maximum_states, nonces, best_first_bytes, found_key);
}
static uint16_t SumProperty(struct Crypto1State *s)
{
uint16_t sum_odd = PartialSumProperty(s->odd, ODD_STATE);
@ -2217,11 +2203,11 @@ static void set_test_state(uint8_t byte)
int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests, uint64_t *foundkey, char *filename)
{
char progress_text[80];
char progress_text[80];
char instr_set[12] = {0};
get_SIMD_instruction_set(instr_set);
PrintAndLog("Using %s SIMD core.", instr_set);
PrintAndLogEx(SUCCESS,"Using %s SIMD core.", instr_set);
srand((unsigned) time(NULL));
brute_force_per_second = brute_force_benchmark();
@ -2235,6 +2221,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
PrintAndLogEx(WARNING, "Could not create/open file hardnested_stats.txt");
return 3;
}
for (uint32_t i = 0; i < tests; i++) {
start_time = msclock();
print_progress_header();
@ -2276,6 +2263,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
float expected_brute_force1 = (float)num_odd * num_even / 2.0;
float expected_brute_force2 = nonces[best_first_bytes[0]].expected_num_brute_force;
fprintf(fstats, "%1.1f;%1.1f;", log(expected_brute_force1)/log(2.0), log(expected_brute_force2)/log(2.0));
if (expected_brute_force1 < expected_brute_force2) {
hardnested_print_progress(num_acquired_nonces, "(Ignoring Sum(a8) properties)", expected_brute_force1, 0);
set_test_state(best_first_byte_smallest_bitarray);
@ -2285,12 +2273,11 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) {
maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE];
}
//PrintAndLogEx(NORMAL, "Number of remaining possible keys: %" PRIu64 " (2^%1.1f)\n", maximum_states, log(maximum_states)/log(2.0));
// fPrintAndLogEx(NORMAL, "fstats, "%" PRIu64 ";", maximum_states);
best_first_bytes[0] = best_first_byte_smallest_bitarray;
pre_XOR_nonces();
prepare_bf_test_nonces(nonces, best_first_bytes[0]);
//hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force1, 0);
key_found = brute_force(foundkey);
free(candidates->states[ODD_STATE]);
free(candidates->states[EVEN_STATE]);
@ -2307,10 +2294,8 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
sprintf(progress_text, "(Estimated Sum(a8) is WRONG! Correct Sum(a8) = %" PRIu16 ")", real_sum_a8);
hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
}
// PrintAndLogEx(NORMAL, "Estimated remaining states: %" PRIu64 " (2^%1.1f)\n", nonces[best_first_bytes[0]].sum_a8_guess[j].num_states, log(nonces[best_first_bytes[0]].sum_a8_guess[j].num_states)/log(2.0));
generate_candidates(first_byte_Sum, nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx);
// PrintAndLogEx(NORMAL, "Time for generating key candidates list: %1.0f sec (%1.1f sec CPU)\n", difftime(time(NULL), start_time), (float)(msclock() - start_clock)/1000.0);
//hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force, 0);
key_found = brute_force(foundkey);
free_statelist_cache();
free_candidates_memory(candidates);
@ -2393,40 +2378,43 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc
uint32_t num_even = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[EVEN_STATE];
float expected_brute_force1 = (float)num_odd * num_even / 2.0;
float expected_brute_force2 = nonces[best_first_bytes[0]].expected_num_brute_force;
if (expected_brute_force1 < expected_brute_force2) {
hardnested_print_progress(num_acquired_nonces, "(Ignoring Sum(a8) properties)", expected_brute_force1, 0);
set_test_state(best_first_byte_smallest_bitarray);
add_bitflip_candidates(best_first_byte_smallest_bitarray);
Tests2();
maximum_states = 0;
for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) {
maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE];
}
// PrintAndLogEx(NORMAL, "Number of remaining possible keys: %" PRIu64 " (2^%1.1f)\n", maximum_states, log(maximum_states)/log(2.0));
best_first_bytes[0] = best_first_byte_smallest_bitarray;
pre_XOR_nonces();
prepare_bf_test_nonces(nonces, best_first_bytes[0]);
//hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force1, 0);
key_found = brute_force(foundkey);
free(candidates->states[ODD_STATE]);
free(candidates->states[EVEN_STATE]);
free_candidates_memory(candidates);
candidates = NULL;
} else {
pre_XOR_nonces();
prepare_bf_test_nonces(nonces, best_first_bytes[0]);
for (uint8_t j = 0; j < NUM_SUMS && !key_found; j++) {
float expected_brute_force = nonces[best_first_bytes[0]].expected_num_brute_force;
sprintf(progress_text, "(%d. guess: Sum(a8) = %" PRIu16 ")", j+1, sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx]);
hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
if (trgkey != NULL && sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx] != real_sum_a8) {
sprintf(progress_text, "(Estimated Sum(a8) is WRONG! Correct Sum(a8) = %" PRIu16 ")", real_sum_a8);
hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
}
// PrintAndLogEx(NORMAL, "Estimated remaining states: %" PRIu64 " (2^%1.1f)\n", nonces[best_first_bytes[0]].sum_a8_guess[j].num_states, log(nonces[best_first_bytes[0]].sum_a8_guess[j].num_states)/log(2.0));
generate_candidates(first_byte_Sum, nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx);
// PrintAndLogEx(NORMAL, "Time for generating key candidates list: %1.0f sec (%1.1f sec CPU)\n", difftime(time(NULL), start_time), (float)(msclock() - start_clock)/1000.0);
//hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force, 0);
key_found = brute_force(foundkey);
free_statelist_cache();
free_candidates_memory(candidates);

View file

@ -1982,6 +1982,7 @@ int CmdHF14AMfURestore(const char *Cmd){
uint8_t *dump = calloc(fsize, sizeof(uint8_t));
if ( !dump ) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
fclose(f);
return 1;
}
@ -1990,6 +1991,7 @@ int CmdHF14AMfURestore(const char *Cmd){
fclose(f);
if ( bytes_read < 48 ) {
PrintAndLogEx(WARNING, "Error, dump file is too small");
free(dump);
return 1;
}
@ -2379,7 +2381,7 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_hf_mfu_gendiverse();
if ( cmdp == 'r' ) {
// read uid from tag
// read uid from tag
UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_RATS, 0, 0}};
clearCommandBuffer();
SendCommand(&c);
@ -2388,8 +2390,13 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){
iso14a_card_select_t card;
memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t));
uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision
if(select_status == 0) {
uint64_t select_status = resp.arg[0];
// 0: couldn't read,
// 1: OK, with ATS
// 2: OK, no ATS
// 3: proprietary Anticollision
if ( select_status == 0 ) {
PrintAndLogEx(WARNING, "iso14443a card select failed");
return 1;
}
@ -2444,12 +2451,12 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){
PrintAndLogEx(NORMAL, "Diversified key: %s", sprint_hex(divkey+1, 6));
for (int i=0; i < sizeof(mifarekeyA); ++i){
dkeyA[i] = (mifarekeyA[i] << 1) & 0xff;
dkeyA[6] |= ((mifarekeyA[i] >> 7) & 1) << (i+1);
dkeyA[i] = (mifarekeyA[i] << 1) & 0xff;
dkeyA[6] |= ((mifarekeyA[i] >> 7) & 1) << (i+1);
}
for (int i=0; i < sizeof(mifarekeyB); ++i){
dkeyB[1] |= ((mifarekeyB[i] >> 7) & 1) << (i+1);
dkeyB[1] |= ((mifarekeyB[i] >> 7) & 1) << (i+1);
dkeyB[2+i] = (mifarekeyB[i] << 1) & 0xff;
}
@ -2486,6 +2493,7 @@ int CmdHF14AMfuPwdGen(const char *Cmd){
uint8_t uid[7] = {0x00};
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_hf_mfu_pwdgen();
if (cmdp == 't') return ul_ev1_pwdgen_selftest();
if ( cmdp == 'r') {
@ -2498,8 +2506,12 @@ int CmdHF14AMfuPwdGen(const char *Cmd){
iso14a_card_select_t card;
memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t));
uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision
if(select_status == 0) {
uint64_t select_status = resp.arg[0];
// 0: couldn't read
// 1: OK with ATS
// 2: OK, no ATS
// 3: proprietary Anticollision
if ( select_status == 0 ) {
PrintAndLogEx(WARNING, "iso14443a card select failed");
return 1;
}
@ -2512,6 +2524,7 @@ int CmdHF14AMfuPwdGen(const char *Cmd){
else {
if (param_gethex(Cmd, 0, uid, 14)) return usage_hf_mfu_pwdgen();
}
PrintAndLogEx(NORMAL, "---------------------------------");
PrintAndLogEx(NORMAL, " Using UID : %s", sprint_hex(uid, 7));
PrintAndLogEx(NORMAL, "---------------------------------");
@ -2529,8 +2542,7 @@ int CmdHF14AMfuPwdGen(const char *Cmd){
//------------------------------------
// Menu Stuff
//------------------------------------
static command_t CommandTable[] =
{
static command_t CommandTable[] = {
{"help", CmdHelp, 1, "This help"},
{"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"},
{"info", CmdHF14AMfUInfo, 0, "Tag information"},
@ -2550,7 +2562,6 @@ static command_t CommandTable[] =
int CmdHFMFUltra(const char *Cmd){
clearCommandBuffer();
//WaitForResponseTimeout(CMD_ACK,NULL,100);
CmdsParse(CommandTable, Cmd);
return 0;
}

View file

@ -186,15 +186,21 @@ int CmdLFCommandRead(const char *Cmd) {
}
int CmdFlexdemod(const char *Cmd) {
#define LONG_WAIT 100
if ( GraphTraceLen < 0 )
return 0;
#ifndef LONG_WAIT
#define LONG_WAIT 100
#endif
int i, j, start, bit, sum, phase = 0;
uint8_t data[MAX_GRAPH_TRACE_LEN] = {0};
size_t size = getFromGraphBuf(data);
if (size == 0)
return 0;
int data[GraphTraceLen];
memcpy(data, GraphBuffer, GraphTraceLen);
for (i = 0; i < size; ++i)
size_t size = GraphTraceLen;
for (i = 0; i < GraphTraceLen; ++i)
data[i] = (data[i] < 0) ? -1 : 1;
for (start = 0; start < size - LONG_WAIT; start++) {
@ -819,14 +825,16 @@ int CheckChipType(bool getDeviceData) {
//check for em4x05/em4x69 chips first
uint32_t word = 0;
if (EM4x05IsBlock0(&word)) {
PrintAndLogEx(NORMAL, "\nValid EM4x05/EM4x69 Chip Found\nTry lf em 4x05... commands\n");
PrintAndLogEx(SUCCESS, "\nValid EM4x05/EM4x69 Chip Found");
PrintAndLogEx(SUCCESS, "Try " _YELLOW_(`lf em 4x05`) " commands");
save_restoreGB(GRAPH_RESTORE);
return 1;
}
//check for t55xx chip...
if (tryDetectP1(true)) {
PrintAndLogEx(NORMAL, "\nValid T55xx Chip Found\nTry `lf t55xx` commands\n");
PrintAndLogEx(SUCCESS, "\nValid T55xx Chip Found");
PrintAndLogEx(SUCCESS, "Try " _YELLOW_(`lf t55xx`)" commands");
save_restoreGB(GRAPH_RESTORE);
return 1;
}
@ -856,9 +864,10 @@ int CmdLFfind(const char *Cmd) {
return 0;
}
PrintAndLogEx(NORMAL, "NOTE: some demods output possible binary\n if it finds something that looks like a tag");
PrintAndLogEx(NORMAL, "False Positives ARE possible\n");
PrintAndLogEx(NORMAL, "\nChecking for known tags:\n");
PrintAndLogEx(INFO, "NOTE: some demods output possible binary");
PrintAndLogEx(INFO, "if it finds something that looks like a tag");
PrintAndLogEx(INFO, "False Positives " _YELLOW_(ARE) "possible\n");
PrintAndLogEx(INFO, "\nChecking for known tags:\n");
// only run these tests if device is online
if (isOnline) {
@ -891,6 +900,7 @@ int CmdLFfind(const char *Cmd) {
if (CmdLFNedapDemod("")) { PrintAndLogEx(SUCCESS, "\nValid NEDAP ID Found!"); goto out;}
if (CmdNexWatchDemod("")) { PrintAndLogEx(SUCCESS, "\nValid NexWatch ID Found!"); goto out;}
if (CmdNoralsyDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Noralsy ID Found!"); goto out;}
if (CmdKeriDemod("")) { PrintAndLogEx(SUCCESS, "\nValid KERI ID Found!"); goto out;}
if (CmdPacDemod("")) { PrintAndLogEx(SUCCESS, "\nValid PAC/Stanley ID Found!"); goto out;}
if (CmdParadoxDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Paradox ID Found!"); goto out;}
if (CmdPrescoDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Presco ID Found!"); goto out;}
@ -957,6 +967,7 @@ static command_t CommandTable[] = {
{"indala", CmdLFINDALA, 1, "{ Indala RFIDs... }"},
{"io", CmdLFIO, 1, "{ ioProx RFIDs... }"},
{"jablotron", CmdLFJablotron, 1, "{ Jablotron RFIDs... }"},
{"keri", CmdLFKeri, 1, "{ KERI RFIDs... }"},
{"nedap", CmdLFNedap, 1, "{ Nedap RFIDs... }"},
{"nexwatch", CmdLFNEXWATCH, 1, "{ NexWatch RFIDs... }"},
{"noralsy", CmdLFNoralsy, 1, "{ Noralsy RFIDs... }"},

View file

@ -42,13 +42,14 @@
#include "cmdlfnoralsy.h" // for NORALSY meny
#include "cmdlffdx.h" // for FDX-B meny
#include "cmdlfcotag.h" // for COTAG meny
#include "cmdlfindala.h" // for indala menu
#include "cmdlfguard.h"// for gproxii menu
#include "cmdlffdx.h" // for fdx-b menu
#include "cmdlfparadox.h"// for paradox menu
#include "cmdlfindala.h" // for indala menu
#include "cmdlfguard.h" // for gproxii menu
#include "cmdlffdx.h" // for fdx-b menu
#include "cmdlfparadox.h" // for paradox menu
#include "cmdlfnexwatch.h" //for nexwatch menu
#include "cmdlfsecurakey.h" //for securakey menu
#include "cmdlfpac.h" // for pac menu
#include "cmdlfkeri.h" // for keri menu
#define T55XX_WRITE_TIMEOUT 1500

View file

@ -101,7 +101,7 @@ static bool sendPing(void){
static bool sendTry(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint32_t delay, uint8_t *bits, size_t bs_len, bool verbose){
if ( verbose )
PrintAndLogEx(NORMAL, "Trying FC: %u; CN: %u", fc, cn);
PrintAndLogEx(INFO, "Trying FC: %u; CN: %u", fc, cn);
if ( !getAWIDBits(fmtlen, fc, cn, bits)) {
PrintAndLogEx(WARNING, "Error with tag bitstream generation.");
@ -171,7 +171,7 @@ int getAWIDBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *bits) {
if (bitLen != 88) return 0;
PrintAndLogEx(NORMAL, "awid raw bits:\n %s \n", sprint_bin(bits, bitLen));
PrintAndLogEx(SUCCESS, "awid raw bits:\n %s \n", sprint_bin(bits, bitLen));
return 1;
}
@ -181,27 +181,27 @@ static void verify_values(uint8_t *fmtlen, uint32_t *fc, uint32_t *cn){
case 50:
if ((*fc & 0xFFFF) != *fc) {
*fc &= 0xFFFF;
PrintAndLogEx(NORMAL, "Facility-Code Truncated to 16-bits (AWID50): %u", *fc);
PrintAndLogEx(INFO, "Facility-Code Truncated to 16-bits (AWID50): %u", *fc);
}
break;
case 37:
if ((*fc & 0x1FFF) != *fc) {
*fc &= 0x1FFF;
PrintAndLogEx(NORMAL, "Facility-Code Truncated to 13-bits (AWID37): %u", *fc);
PrintAndLogEx(INFO, "Facility-Code Truncated to 13-bits (AWID37): %u", *fc);
}
if ((*cn & 0x3FFFF) != *cn) {
*cn &= 0x3FFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 18-bits (AWID37): %u", *cn);
PrintAndLogEx(INFO, "Card Number Truncated to 18-bits (AWID37): %u", *cn);
}
break;
case 34:
if ((*fc & 0xFF) != *fc) {
*fc &= 0xFF;
PrintAndLogEx(NORMAL, "Facility-Code Truncated to 8-bits (AWID34): %u", *fc);
PrintAndLogEx(INFO, "Facility-Code Truncated to 8-bits (AWID34): %u", *fc);
}
if ((*cn & 0xFFFFFF) != *cn) {
*cn &= 0xFFFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 24-bits (AWID34): %u", *cn);
PrintAndLogEx(INFO, "Card Number Truncated to 24-bits (AWID34): %u", *cn);
}
break;
case 26:
@ -209,11 +209,11 @@ static void verify_values(uint8_t *fmtlen, uint32_t *fc, uint32_t *cn){
*fmtlen = 26;
if ((*fc & 0xFF) != *fc) {
*fc &= 0xFF;
PrintAndLogEx(NORMAL, "Facility-Code Truncated to 8-bits (AWID26): %u", *fc);
PrintAndLogEx(INFO, "Facility-Code Truncated to 8-bits (AWID26): %u", *fc);
}
if ((*cn & 0xFFFF) != *cn) {
*cn &= 0xFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 16-bits (AWID26): %u", *cn);
PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (AWID26): %u", *cn);
}
break;
}
@ -290,7 +290,7 @@ int CmdAWIDDemod(const char *Cmd) {
uint32_t rawHi2 = bytebits_to_byte(bits + idx, 32);
size = removeParity(bits, idx+8, 4, 1, 88);
if (size != 66){
if (size != 66) {
PrintAndLogEx(DEBUG, "DEBUG: Error - AWID at parity check-tag size does not match AWID format");
return 0;
}
@ -323,21 +323,21 @@ int CmdAWIDDemod(const char *Cmd) {
fc = bytebits_to_byte(bits + 9, 8);
cardnum = bytebits_to_byte(bits + 17, 16);
code1 = bytebits_to_byte(bits + 8,fmtLen);
PrintAndLogEx(NORMAL, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo);
PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo);
break;
case 34:
fc = bytebits_to_byte(bits + 9, 8);
cardnum = bytebits_to_byte(bits + 17, 24);
code1 = bytebits_to_byte(bits + 8, (fmtLen-32) );
code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32);
PrintAndLogEx(NORMAL, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo);
PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo);
break;
case 37:
fc = bytebits_to_byte(bits + 9, 13);
cardnum = bytebits_to_byte(bits + 22, 18);
code1 = bytebits_to_byte(bits + 8, (fmtLen-32) );
code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32);
PrintAndLogEx(NORMAL, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo);
PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo);
break;
// case 40:
// break;
@ -346,18 +346,18 @@ int CmdAWIDDemod(const char *Cmd) {
cardnum = bytebits_to_byte(bits + 25, 32);
code1 = bytebits_to_byte(bits + 8, (fmtLen-32) );
code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32);
PrintAndLogEx(NORMAL, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo);
PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo);
break;
default:
if (fmtLen > 32 ) {
cardnum = bytebits_to_byte(bits + 8 + (fmtLen-17), 16);
code1 = bytebits_to_byte(bits + 8, fmtLen-32);
code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32);
PrintAndLogEx(NORMAL, "AWID Found - BitLength: %d -unknown BitLength- (%u) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo);
PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d -unknown BitLength- (%u) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo);
} else {
cardnum = bytebits_to_byte(bits + 8 + (fmtLen-17), 16);
code1 = bytebits_to_byte(bits + 8, fmtLen);
PrintAndLogEx(NORMAL, "AWID Found - BitLength: %d -unknown BitLength- (%u) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo);
PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d -unknown BitLength- (%u) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo);
}
break;
}
@ -386,8 +386,8 @@ int CmdAWIDSim(const char *Cmd) {
verify_values(&fmtlen, &fc, &cn);
PrintAndLogEx(NORMAL, "Emulating AWID %u -- FC: %u; CN: %u\n", fmtlen, fc, cn);
PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation or run another command");
PrintAndLogEx(SUCCESS, "Simulating AWID %u -- FC: %u; CN: %u\n", fmtlen, fc, cn);
PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or run another command");
if (!getAWIDBits(fmtlen, fc, cn, bits)) {
PrintAndLogEx(WARNING, "Error with tag bitstream generation.");
@ -417,8 +417,8 @@ int CmdAWIDClone(const char *Cmd) {
uint8_t *bs=bits;
memset(bs,0,sizeof(bits));
char cmdp = param_getchar(Cmd, 0);
if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_awid_clone();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_awid_clone();
fmtlen = param_get8(Cmd, 0);
fc = param_get32ex(Cmd, 1, 0, 10);
@ -426,7 +426,7 @@ int CmdAWIDClone(const char *Cmd) {
if ( !fc || !cn) return usage_lf_awid_clone();
if (param_getchar(Cmd, 3) == 'Q' || param_getchar(Cmd, 3) == 'q')
if (tolower(param_getchar(Cmd, 3)) == 'q')
//t5555 (Q5) BITRATE = (RF-2)/2 (iceman)
blocks[0] = T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | T5555_SET_BITRATE(50) | 3<<T5555_MAXBLOCK_SHIFT;
@ -441,7 +441,7 @@ int CmdAWIDClone(const char *Cmd) {
blocks[2] = bytebits_to_byte(bs + 32, 32);
blocks[3] = bytebits_to_byte(bs + 64, 32);
PrintAndLogEx(NORMAL, "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);
UsbCommand resp;
@ -470,38 +470,32 @@ int CmdAWIDBrute(const char *Cmd) {
memset(bits, 0x00, size);
uint8_t cmdp = 0;
while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch(param_getchar(Cmd, cmdp)) {
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch ( tolower(param_getchar(Cmd, cmdp))) {
case 'h':
case 'H':
return usage_lf_awid_brute();
case 'f':
case 'F':
fc = param_get32ex(Cmd ,cmdp+1, 0, 10);
if ( !fc )
errors = true;
cmdp += 2;
break;
case 'd':
case 'D':
// delay between attemps, defaults to 1000ms.
delay = param_get32ex(Cmd, cmdp+1, 1000, 10);
cmdp += 2;
break;
case 'c':
case 'C':
cn = param_get32ex(Cmd, cmdp+1, 0, 10);
// truncate cardnumber.
cn &= 0xFFFF;
cmdp += 2;
break;
case 'a':
case 'A':
fmtlen = param_get8(Cmd, cmdp+1);
cmdp += 2;
break;
case 'v':
case 'V':
verbose = true;
cmdp++;
break;
@ -511,7 +505,7 @@ int CmdAWIDBrute(const char *Cmd) {
break;
}
}
if ( fc == 0 )errors = true;
if ( fc == 0 ) errors = true;
if ( errors ) return usage_lf_awid_brute();
// limit fc according to selected format
@ -519,19 +513,19 @@ int CmdAWIDBrute(const char *Cmd) {
case 50:
if ((fc & 0xFFFF) != fc) {
fc &= 0xFFFF;
PrintAndLogEx(NORMAL, "Facility-code truncated to 16-bits (AWID50): %u", fc);
PrintAndLogEx(INFO, "Facility-code truncated to 16-bits (AWID50): %u", fc);
}
break;
default:
if ((fc & 0xFF) != fc) {
fc &= 0xFF;
PrintAndLogEx(NORMAL, "Facility-code truncated to 8-bits (AWID26): %u", fc);
PrintAndLogEx(INFO, "Facility-code truncated to 8-bits (AWID26): %u", fc);
}
break;
}
PrintAndLogEx(NORMAL, "Bruteforceing AWID %d Reader", fmtlen);
PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation or press key");
PrintAndLogEx(SUCCESS, "Bruteforceing AWID %d Reader", fmtlen);
PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or press key");
uint16_t up = cn;
uint16_t down = cn;

View file

@ -58,7 +58,7 @@ int CmdCOTAGDemod(const char *Cmd) {
0 1001 1100 1100 0001 1000 0101 0000 0000 100001010000000001111011100000011010000010000000000000000000000000000000000000000000000000000000100111001100000110000101000
1001 1100 1100 0001 10000101
*/
PrintAndLogEx(NORMAL, "COTAG Found: FC %u, CN: %u Raw: %08X%08X%08X%08X", fc, cn, raw1 ,raw2, raw3, raw4);
PrintAndLogEx(SUCCESS, "COTAG Found: FC %u, CN: %u Raw: %08X%08X%08X%08X", fc, cn, raw1 ,raw2, raw3, raw4);
return 1;
}

View file

@ -364,9 +364,7 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) {
int ans = Em410xDecode(bits, &size, &idx, hi, lo);
if ( ans < 0){
if (ans == -1)
PrintAndLogEx(DEBUG, "DEBUG: Error - Em410x not only 0|1 in decoded bitstream");
else if (ans == -2)
if (ans == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - Em410x not enough samples after demod");
else if (ans == -4)
PrintAndLogEx(DEBUG, "DEBUG: Error - Em410x preamble not found");
@ -404,8 +402,7 @@ int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose) {
// this read is the "normal" read, which download lf signal and tries to demod here.
int CmdEM410xRead(const char *Cmd) {
lf_read(true, 8192);
CmdEM410xDemod(Cmd);
return 0;
return CmdEM410xDemod(Cmd);
}
// this read loops on device side.
@ -446,14 +443,14 @@ int CmdEM410xSim(const char *Cmd) {
uint8_t clock = 64;
if (param_gethex(Cmd, 0, uid, 10)) {
PrintAndLogEx(NORMAL, "UID must include 10 HEX symbols");
PrintAndLogEx(FAILED, "UID must include 10 HEX symbols");
return 0;
}
param_getdec(Cmd, 1, &clock);
PrintAndLogEx(NORMAL, "Starting simulating UID %02X%02X%02X%02X%02X clock: %d", uid[0],uid[1],uid[2],uid[3],uid[4],clock);
PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation");
PrintAndLogEx(SUCCESS, "Starting simulating UID %02X%02X%02X%02X%02X clock: %d", uid[0],uid[1],uid[2],uid[3],uid[4],clock);
PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation");
ConstructEM410xEmulGraph(Cmd, clock);
@ -474,14 +471,14 @@ int CmdEM410xBrute(const char *Cmd) {
/* default pause time: 1 second */
uint32_t delay = 1000;
char cmdp = param_getchar(Cmd, 0);
if (cmdp == 'h' || cmdp == 'H') return usage_lf_em410x_brute();
char cmdp = tolower(param_getchar(Cmd, 0));
if (cmdp == 'h') return usage_lf_em410x_brute();
cmdp = param_getchar(Cmd, 1);
if (cmdp == 'd' || cmdp == 'D') {
cmdp = tolower(param_getchar(Cmd, 1));
if (cmdp == 'd') {
delay = param_get32ex(Cmd, 2, 1000, 10);
param_getdec(Cmd, 4, &clock);
} else if (cmdp == 'c' || cmdp == 'C') {
} else if (cmdp == 'c') {
param_getdec(Cmd, 2, &clock);
delay = param_get32ex(Cmd, 4, 1000, 10);
}
@ -498,7 +495,10 @@ int CmdEM410xBrute(const char *Cmd) {
}
uidBlock = calloc(stUidBlock, 5);
if (uidBlock == NULL) return 1;
if (uidBlock == NULL) {
fclose(f);
return 1;
}
while( fgets(buf, sizeof(buf), f) ) {
if (strlen(buf) < 10 || buf[9] == '\n') continue;
@ -508,7 +508,7 @@ int CmdEM410xBrute(const char *Cmd) {
if( buf[0]=='#' ) continue;
if (param_gethex(buf, 0, uid, 10)) {
PrintAndLogEx(NORMAL, "UIDs must include 10 HEX symbols");
PrintAndLogEx(FAILED, "UIDs must include 10 HEX symbols");
free(uidBlock);
fclose(f);
return 1;
@ -535,11 +535,12 @@ int CmdEM410xBrute(const char *Cmd) {
fclose(f);
if (uidcnt == 0) {
PrintAndLogEx(NORMAL, "No UIDs found in file");
PrintAndLogEx(FAILED, "No UIDs found in file");
free(uidBlock);
return 1;
}
PrintAndLogEx(NORMAL, "Loaded %d UIDs from %s, pause delay: %d ms", uidcnt, filename, delay);
PrintAndLogEx(SUCCESS, "Loaded %d UIDs from %s, pause delay: %d ms", uidcnt, filename, delay);
// loop
for(uint32_t c = 0; c < uidcnt; ++c ) {
@ -599,7 +600,7 @@ int CmdEM410xWatchnSpoof(const char *Cmd) {
// loops if the captured ID was in XL-format.
CmdEM410xWatch(Cmd);
PrintAndLogEx(NORMAL, "# Replaying captured ID: %010" PRIx64 , g_em410xid);
PrintAndLogEx(SUCCESS, "# Replaying captured ID: %010" PRIx64 , g_em410xid);
CmdLFaskSim("");
return 0;
}
@ -645,17 +646,17 @@ int CmdEM410xWrite(const char *Cmd) {
}
if (card == 1) {
PrintAndLogEx(NORMAL, "Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock);
PrintAndLogEx(SUCCESS, "Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock);
// NOTE: We really should pass the clock in as a separate argument, but to
// provide for backwards-compatibility for older firmware, and to avoid
// having to add another argument to CMD_EM410X_WRITE_TAG, we just store
// the clock rate in bits 8-15 of the card value
card = (card & 0xFF) | ((clock << 8) & 0xFF00);
} else if (card == 0) {
PrintAndLogEx(NORMAL, "Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock);
PrintAndLogEx(SUCCESS, "Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock);
card = (card & 0xFF) | ((clock << 8) & 0xFF00);
} else {
PrintAndLogEx(WARNING, "Error! Bad card type selected.\n");
PrintAndLogEx(FAILED, "Error! Bad card type selected.\n");
return 0;
}

View file

@ -82,11 +82,11 @@ int detectFDXB(uint8_t *dest, size_t *size) {
static void verify_values(uint32_t countryid, uint64_t animalid){
if ((animalid & 0x3FFFFFFFFF) != animalid) {
animalid &= 0x3FFFFFFFFF;
PrintAndLogEx(NORMAL, "Animal ID Truncated to 38bits: %"PRIx64, animalid);
PrintAndLogEx(INFO, "Animal ID Truncated to 38bits: %"PRIx64, animalid);
}
if ( (countryid & 0x3ff) != countryid ) {
countryid &= 0x3ff;
PrintAndLogEx(NORMAL, "Country ID Truncated to 10bits: %03d", countryid);
PrintAndLogEx(INFO, "Country ID Truncated to 10bits: %03d", countryid);
}
}
@ -159,26 +159,24 @@ int getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t
*/
int CmdFDXBdemodBI(const char *Cmd){
int invert = 1;
int clk = 32;
int errCnt = 0;
int offset = 0, maxErr = 0;
uint8_t BitStream[MAX_DEMOD_BUF_LEN];
size_t size = getFromGraphBuf(BitStream);
int clk = 32;
int invert = 1, errCnt = 0, offset = 0, maxErr = 0;
uint8_t bs[MAX_DEMOD_BUF_LEN];
size_t size = getFromGraphBuf(bs);
errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0);
errCnt = askdemod(bs, &size, &clk, &invert, maxErr, 0, 0);
if ( errCnt < 0 || errCnt > maxErr ) {
PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB no data or error found %d, clock: %d", errCnt, clk);
return 0;
}
errCnt = BiphaseRawDecode(BitStream, &size, &offset, 1);
errCnt = BiphaseRawDecode(bs, &size, &offset, 1);
if (errCnt < 0 || errCnt > maxErr ) {
PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB BiphaseRawDecode: %d", errCnt);
return 0;
}
int preambleIndex = detectFDXB(BitStream, &size);
int preambleIndex = detectFDXB(bs, &size);
if (preambleIndex < 0){
PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB preamble not found :: %d",preambleIndex);
return 0;
@ -188,44 +186,44 @@ int CmdFDXBdemodBI(const char *Cmd){
return 0;
}
setDemodBuf(BitStream, 128, preambleIndex);
setDemodBuf(bs, 128, preambleIndex);
// remove marker bits (1's every 9th digit after preamble) (pType = 2)
size = removeParity(BitStream, preambleIndex + 11, 9, 2, 117);
size = removeParity(bs, preambleIndex + 11, 9, 2, 117);
if ( size != 104 ) {
PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB error removeParity:: %d", size);
return 0;
}
PrintAndLogEx(NORMAL, "\nFDX-B / ISO 11784/5 Animal Tag ID Found:");
PrintAndLogEx(SUCCESS, "\nFDX-B / ISO 11784/5 Animal Tag ID Found:");
//got a good demod
uint64_t NationalCode = ((uint64_t)(bytebits_to_byteLSBF(BitStream+32,6)) << 32) | bytebits_to_byteLSBF(BitStream,32);
uint32_t countryCode = bytebits_to_byteLSBF(BitStream+38,10);
uint8_t dataBlockBit = BitStream[48];
uint32_t reservedCode = bytebits_to_byteLSBF(BitStream+49,14);
uint8_t animalBit = BitStream[63];
uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16);
uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24);
uint64_t NationalCode = ((uint64_t)(bytebits_to_byteLSBF(bs+32, 6)) << 32) | bytebits_to_byteLSBF(bs, 32);
uint32_t countryCode = bytebits_to_byteLSBF(bs+38, 10);
uint8_t dataBlockBit = bs[48];
uint32_t reservedCode = bytebits_to_byteLSBF(bs+49, 14);
uint8_t animalBit = bs[63];
uint32_t crc16 = bytebits_to_byteLSBF(bs+64, 16);
uint32_t extended = bytebits_to_byteLSBF(bs+80, 24);
uint64_t rawid = ((uint64_t)bytebits_to_byte(BitStream,32)<<32) | bytebits_to_byte(BitStream+32,32);
uint64_t rawid = ((uint64_t)bytebits_to_byte(bs, 32) << 32) | bytebits_to_byte(bs+32, 32);
uint8_t raw[8];
num_to_bytes(rawid, 8, raw);
PrintAndLogEx(NORMAL, "Raw ID Hex: %s", sprint_hex(raw,8));
PrintAndLogEx(SUCCESS, "Raw ID Hex: %s", sprint_hex(raw,8));
uint16_t calcCrc = crc16_kermit(raw, 8);
PrintAndLogEx(NORMAL, "Animal ID: %04u-%012" PRIu64, countryCode, NationalCode);
PrintAndLogEx(NORMAL, "National Code: %012" PRIu64, NationalCode);
PrintAndLogEx(NORMAL, "CountryCode: %04u", countryCode);
PrintAndLogEx(SUCCESS, "Animal ID: %04u-%012" PRIu64, countryCode, NationalCode);
PrintAndLogEx(SUCCESS, "National Code: %012" PRIu64, NationalCode);
PrintAndLogEx(SUCCESS, "CountryCode: %04u", countryCode);
PrintAndLogEx(NORMAL, "Reserved/RFU: %u", reservedCode);
PrintAndLogEx(NORMAL, "Animal Tag: %s", animalBit ? "True" : "False");
PrintAndLogEx(NORMAL, "Has extended data: %s [0x%X]", dataBlockBit ? "True" : "False", extended);
PrintAndLogEx(NORMAL, "CRC: 0x%04X - [%04X] - %s", crc16, calcCrc, (calcCrc == crc16) ? "Passed" : "Failed");
PrintAndLogEx(SUCCESS, "Reserved/RFU: %u", reservedCode);
PrintAndLogEx(SUCCESS, "Animal Tag: %s", animalBit ? _YELLOW_(True) : "False");
PrintAndLogEx(SUCCESS, "Has extended data: %s [0x%X]", dataBlockBit ? _YELLOW_(True) : "False", extended);
PrintAndLogEx(SUCCESS, "CRC: 0x%04X - [%04X] - %s", crc16, calcCrc, (calcCrc == crc16) ? _GREEN_(Passed) : "Failed");
if (g_debugMode) {
PrintAndLogEx(DEBUG, "Start marker %d; Size %d", preambleIndex, size);
char *bin = sprint_bin_break(BitStream,size,16);
char *bin = sprint_bin_break(bs, size, 16);
PrintAndLogEx(DEBUG, "DEBUG BinStream:\n%s",bin);
}
return 1;
@ -282,14 +280,14 @@ int CmdFdxDemod(const char *Cmd) {
uint16_t calcCrc = crc16_kermit(raw, 8);
PrintAndLogEx(NORMAL, "\nFDX-B / ISO 11784/5 Animal Tag ID Found: Raw : %s", sprint_hex(raw, 8));
PrintAndLogEx(NORMAL, "Animal ID %04u-%012" PRIu64, countryCode, NationalCode);
PrintAndLogEx(NORMAL, "National Code %012" PRIu64 " (0x%" PRIx64 ")", NationalCode, NationalCode);
PrintAndLogEx(NORMAL, "Country Code %04u", countryCode);
PrintAndLogEx(NORMAL, "Reserved/RFU %u (0x04%X)", reservedCode, reservedCode);
PrintAndLogEx(NORMAL, "Animal Tag %s", animalBit ? "True" : "False");
PrintAndLogEx(NORMAL, "Has extended data %s [0x%X]", dataBlockBit ? "True" : "False", extended);
PrintAndLogEx(NORMAL, "CRC-16 0x%04X - 0x%04X [%s]", crc16, calcCrc, (calcCrc == crc16) ? "Ok" : "Failed");
PrintAndLogEx(SUCCESS, "\nFDX-B / ISO 11784/5 Animal Tag ID Found: Raw : %s", sprint_hex(raw, 8));
PrintAndLogEx(SUCCESS, "Animal ID %04u-%012" PRIu64, countryCode, NationalCode);
PrintAndLogEx(SUCCESS, "National Code %012" PRIu64 " (0x%" PRIx64 ")", NationalCode, NationalCode);
PrintAndLogEx(SUCCESS, "Country Code %04u", countryCode);
PrintAndLogEx(SUCCESS, "Reserved/RFU %u (0x04%X)", reservedCode, reservedCode);
PrintAndLogEx(SUCCESS, "Animal Tag %s", animalBit ? _YELLOW_(True) : "False");
PrintAndLogEx(SUCCESS, "Has extended data %s [0x%X]", dataBlockBit ? _YELLOW_(True) : "False", extended);
PrintAndLogEx(SUCCESS, "CRC-16 0x%04X - 0x%04X [%s]", crc16, calcCrc, (calcCrc == crc16) ? _GREEN_(Ok) : "Failed");
if (g_debugMode) {
PrintAndLogEx(DEBUG, "Start marker %d; Size %d", preambleIndex, size);
@ -341,7 +339,7 @@ int CmdFdxClone(const char *Cmd) {
blocks[3] = bytebits_to_byte(bs + 64, 32);
blocks[4] = bytebits_to_byte(bs + 96, 32);
PrintAndLogEx(NORMAL, "Preparing to clone FDX-B to T55x7 with animal ID: %04u-%"PRIu64, countryid, animalid);
PrintAndLogEx(INFO, "Preparing to clone FDX-B to T55x7 with animal ID: %04u-%"PRIu64, countryid, animalid);
print_blocks(blocks, 5);
UsbCommand resp;
@ -379,7 +377,7 @@ int CmdFdxSim(const char *Cmd) {
arg1 = clk << 8 | encoding;
arg2 = invert << 8 | separator;
PrintAndLogEx(NORMAL, "Simulating FDX-B animal ID: %04u-%"PRIu64, countryid, animalid);
PrintAndLogEx(SUCCESS, "Simulating FDX-B animal ID: %04u-%"PRIu64, countryid, animalid);
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};

View file

@ -107,21 +107,21 @@ int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) {
for (i = 0; i < 4; ++i)
rawbytes[i+4] = bytebits_to_byte( pre + (i*8), 8);
if (g_debugMode) PrintAndLogEx(NORMAL, " WIE | %s\n", sprint_hex(rawbytes, sizeof(rawbytes)));
PrintAndLogEx(DEBUG, " WIE | %s\n", sprint_hex(rawbytes, sizeof(rawbytes)));
// XOR (only works on wiegand stuff)
for (i = 1; i < 12; ++i)
rawbytes[i] ^= xorKey ;
if (g_debugMode) PrintAndLogEx(NORMAL, " XOR | %s \n", sprint_hex(rawbytes, sizeof(rawbytes)));
PrintAndLogEx(DEBUG, " XOR | %s \n", sprint_hex(rawbytes, sizeof(rawbytes)));
// convert rawbytes to bits in pre
for (i = 0; i < 12; ++i)
num_to_bytebitsLSBF( rawbytes[i], 8, pre + (i*8));
if (g_debugMode) PrintAndLogEx(NORMAL, "\n Raw | %s \n", sprint_hex(rawbytes, sizeof(rawbytes)));
if (g_debugMode) PrintAndLogEx(NORMAL, " Raw | %s\n", sprint_bin(pre, 64) );
PrintAndLogEx(DEBUG, "\n Raw | %s \n", sprint_hex(rawbytes, sizeof(rawbytes)));
PrintAndLogEx(DEBUG, " Raw | %s\n", sprint_bin(pre, 64) );
// add spacer bit 0 every 4 bits, starting with index 0,
// 12 bytes, 24 nibbles. 24+1 extra bites. 3bytes. ie 9bytes | 1byte xorkey, 8bytes rawdata (64bits, should be enough for a 40bit wiegand)
@ -135,7 +135,7 @@ int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) {
guardBits[4] = 1;
guardBits[5] = 0;
if (g_debugMode) PrintAndLogEx(NORMAL, " FIN | %s\n", sprint_bin(guardBits, 96) );
PrintAndLogEx(DEBUG, " FIN | %s\n", sprint_bin(guardBits, 96) );
return 1;
}
@ -192,7 +192,7 @@ int CmdGuardDemod(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII preamble not found");
else if (preambleIndex == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII size not correct: %d", size);
else if (preambleIndex == -3)
else if (preambleIndex == -5)
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII wrong spacerbits");
else
PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII ans: %d", preambleIndex);
@ -246,9 +246,9 @@ int CmdGuardDemod(const char *Cmd) {
break;
}
if ( !unknown)
PrintAndLogEx(NORMAL, "G-Prox-II Found: Format Len: %ubit - FC: %u - Card: %u, Raw: %08x%08x%08x", fmtLen, FC, Card, raw1, raw2, raw3);
PrintAndLogEx(SUCCESS, "G-Prox-II Found: Format Len: %ubit - FC: %u - Card: %u, Raw: %08x%08x%08x", fmtLen, FC, Card, raw1, raw2, raw3);
else
PrintAndLogEx(NORMAL, "Unknown G-Prox-II Fmt Found: Format Len: %u, Raw: %08x%08x%08x", fmtLen, raw1, raw2, raw3);
PrintAndLogEx(SUCCESS, "Unknown G-Prox-II Fmt Found: Format Len: %u, Raw: %08x%08x%08x", fmtLen, raw1, raw2, raw3);
return 1;
}
@ -290,7 +290,7 @@ int CmdGuardClone(const char *Cmd) {
blocks[2] = bytebits_to_byte(bs + 32, 32);
blocks[3] = bytebits_to_byte(bs + 64, 32);
PrintAndLogEx(NORMAL, "Preparing to clone Guardall to T55x7 with Facility Code: %u, Card Number: %u", facilitycode, cardnumber);
PrintAndLogEx(INFO, "Preparing to clone Guardall to T55x7 with Facility Code: %u, Card Number: %u", facilitycode, cardnumber);
print_blocks(blocks, 4);
UsbCommand resp;
@ -333,7 +333,7 @@ int CmdGuardSim(const char *Cmd) {
return 1;
}
PrintAndLogEx(NORMAL, "Simulating Guardall - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber );
PrintAndLogEx(SUCCESS, "Simulating Guardall - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber );
uint64_t arg1, arg2;
arg1 = (clock << 8) | encoding;

View file

@ -106,7 +106,7 @@ static bool sendTry(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint32_t delay, ui
// this should be optional.
if ( verbose )
PrintAndLogEx(NORMAL, "Trying FC: %u; CN: %u", fc, cn);
PrintAndLogEx(INFO, "Trying FC: %u; CN: %u", fc, cn);
calcWiegand( fmtlen, fc, cn, bits);
@ -164,7 +164,7 @@ int CmdHIDDemod(const char *Cmd) {
}
if (hi2 != 0){ //extra large HID tags
PrintAndLogEx(NORMAL, "HID Prox TAG ID: %x%08x%08x (%u)", hi2, hi, lo, (lo>>1) & 0xFFFF);
PrintAndLogEx(SUCCESS, "HID Prox TAG ID: %x%08x%08x (%u)", hi2, hi, lo, (lo>>1) & 0xFFFF);
} else { //standard HID tags <38 bits
uint8_t fmtLen = 0;
uint32_t cc = 0;
@ -209,9 +209,9 @@ int CmdHIDDemod(const char *Cmd) {
}
}
if(fmtLen==32 && (lo & 0x40000000)){//if 32 bit and Kastle bit set
PrintAndLogEx(NORMAL, "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: %08x (%u) - Format Len: 32bit - CC: %u - FC: %u - Card: %u", lo, (lo >> 1) & 0xFFFF, cc, fc, cardnum);
}else{
PrintAndLogEx(NORMAL, "HID Prox TAG ID: %x%08x (%u) - Format Len: %ubit - FC: %u - Card: %u", hi, lo, (lo >> 1) & 0xFFFF, fmtLen, fc, cardnum);
PrintAndLogEx(SUCCESS, "HID Prox TAG ID: %x%08x (%u) - Format Len: %ubit - FC: %u - Card: %u", hi, lo, (lo >> 1) & 0xFFFF, fmtLen, fc, cardnum);
}
}
@ -244,16 +244,16 @@ int CmdHIDSim(const char *Cmd) {
uint32_t hi = 0, lo = 0;
uint32_t n = 0, i = 0;
uint8_t ctmp = param_getchar(Cmd, 0);
if ( strlen(Cmd) == 0 || ctmp == 'H' || ctmp == 'h' ) return usage_lf_hid_sim();
uint8_t ctmp = tolower(param_getchar(Cmd, 0));
if ( strlen(Cmd) == 0 || ctmp == 'h' ) return usage_lf_hid_sim();
while (sscanf(&Cmd[i++], "%1x", &n ) == 1) {
hi = (hi << 4) | (lo >> 28);
lo = (lo << 4) | (n & 0xf);
}
PrintAndLogEx(NORMAL, "Emulating tag with ID %x%08x", hi, lo);
PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation");
PrintAndLogEx(SUCCESS, "Simulating HID tag with ID %x%08x", hi, lo);
PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation");
UsbCommand c = {CMD_HID_SIM_TAG, {hi, lo, 0}};
clearCommandBuffer();
@ -277,7 +277,7 @@ int CmdHIDClone(const char *Cmd) {
lo = (lo << 4) | (n & 0xf);
}
PrintAndLogEx(NORMAL, "Cloning tag with long ID %x%08x%08x", hi2, hi, lo);
PrintAndLogEx(INFO, "Preparing to clone HID tag with long ID %x%08x%08x", hi2, hi, lo);
c.d.asBytes[0] = 1;
} else {
@ -285,7 +285,7 @@ int CmdHIDClone(const char *Cmd) {
hi = (hi << 4) | (lo >> 28);
lo = (lo << 4) | (n & 0xf);
}
PrintAndLogEx(NORMAL, "Cloning tag with ID %x%08x", hi, lo);
PrintAndLogEx(INFO, "Preparing to clone HID tag with ID %x%08x", hi, lo);
hi2 = 0;
c.d.asBytes[0] = 0;
}
@ -492,33 +492,28 @@ int CmdHIDBrute(const char *Cmd){
memset(bits, 0, sizeof(bits));
uint8_t cmdp = 0;
while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch(param_getchar(Cmd, cmdp)) {
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
case 'H':
return usage_lf_hid_brute();
case 'f':
case 'F':
fc = param_get32ex(Cmd ,cmdp+1, 0, 10);
if ( !fc )
errors = true;
cmdp += 2;
break;
case 'd':
case 'D':
// delay between attemps, defaults to 1000ms.
delay = param_get32ex(Cmd, cmdp+1, 1000, 10);
cmdp += 2;
break;
case 'c':
case 'C':
cn = param_get32ex(Cmd, cmdp+1, 0, 10);
// truncate cardnumber.
cn &= 0xFFFF;
cmdp += 2;
break;
case 'a':
case 'A':
fmtlen = param_get8(Cmd, cmdp+1);
cmdp += 2;
bool is_ftm_ok = false;
@ -532,7 +527,6 @@ int CmdHIDBrute(const char *Cmd){
errors = !is_ftm_ok;
break;
case 'v':
case 'V':
verbose = true;
cmdp++;
break;
@ -545,8 +539,8 @@ int CmdHIDBrute(const char *Cmd){
if ( fc == 0 ) errors = true;
if ( errors ) return usage_lf_hid_brute();
PrintAndLogEx(NORMAL, "Brute-forcing HID reader");
PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation or run another command");
PrintAndLogEx(INFO, "Brute-forcing HID reader");
PrintAndLogEx(INFO, "Press pm3-button to abort simulation or run another command");
uint16_t up = cn;
uint16_t down = cn;

View file

@ -136,7 +136,7 @@ int CmdIndalaDemod(const char *Cmd) {
idx = indala224decode(DemodBuffer, &size, &invert);
if (idx < 0 || size != 224) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Indala wrong size, expected [64|224] got: %d (startindex %i)", size, idx);
return -1;
return 0;
}
}
@ -231,8 +231,8 @@ int CmdIndalaDemodAlt(const char *Cmd) {
}
if (rawbit > 0){
PrintAndLogEx(NORMAL, "Recovered %d raw bits, expected: %d", rawbit, GraphTraceLen/32);
PrintAndLogEx(NORMAL, "worst metric (0=best..7=worst): %d at pos %d", worst, worstPos);
PrintAndLogEx(INFO, "Recovered %d raw bits, expected: %d", rawbit, GraphTraceLen/32);
PrintAndLogEx(INFO, "worst metric (0=best..7=worst): %d at pos %d", worst, worstPos);
} else {
return 0;
}
@ -262,7 +262,7 @@ int CmdIndalaDemodAlt(const char *Cmd) {
}
if (start == rawbit - uidlen + 1) {
PrintAndLogEx(NORMAL, "nothing to wait for");
PrintAndLogEx(FAILED, "nothing to wait for");
return 0;
}
@ -288,7 +288,7 @@ int CmdIndalaDemodAlt(const char *Cmd) {
showbits[bit] = '.' + bits[bit];
}
showbits[bit+1]='\0';
PrintAndLogEx(NORMAL, "Partial UID=%s", showbits);
PrintAndLogEx(SUCCESS, "Partial UID | %s", showbits);
return 0;
} else {
for (bit = 0; bit < uidlen; bit++) {
@ -313,7 +313,7 @@ int CmdIndalaDemodAlt(const char *Cmd) {
uid2 = (uid2<<1) | 1;
}
}
PrintAndLogEx(NORMAL, "UID=%s (%x%08x)", showbits, uid1, uid2);
PrintAndLogEx(SUCCESS, "UID | %s (%x%08x)", showbits, uid1, uid2);
}
else {
uid3 = uid4 = uid5 = uid6 = uid7 = 0;
@ -331,7 +331,7 @@ int CmdIndalaDemodAlt(const char *Cmd) {
else
uid7 = (uid7<<1) | 1;
}
PrintAndLogEx(NORMAL, "UID=%s (%x%08x%08x%08x%08x%08x%08x)", showbits, uid1, uid2, uid3, uid4, uid5, uid6, uid7);
PrintAndLogEx(SUCCESS, "UID | %s (%x%08x%08x%08x%08x%08x%08x)", showbits, uid1, uid2, uid3, uid4, uid5, uid6, uid7);
}
// Checking UID against next occurrences
@ -350,7 +350,7 @@ int CmdIndalaDemodAlt(const char *Cmd) {
times += 1;
}
PrintAndLogEx(NORMAL, "Occurrences: %d (expected %d)", times, (rawbit - start) / uidlen);
PrintAndLogEx(DEBUG, "Occurrences: %d (expected %d)", times, (rawbit - start) / uidlen);
// Remodulating for tag cloning
// HACK: 2015-01-04 this will have an impact on our new way of seening lf commands (demod)
@ -377,8 +377,8 @@ int CmdIndalaDemodAlt(const char *Cmd) {
int CmdIndalaSim(const char *Cmd) {
char cmdp = param_getchar(Cmd, 0);
if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_indala_sim();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_indala_sim();
uint8_t bits[224];
size_t size = sizeof(bits);
@ -392,9 +392,9 @@ int CmdIndalaSim(const char *Cmd) {
return usage_lf_indala_sim();
// convert to binarray
uint8_t counter = 224;
for (uint8_t i=0; i< len; i++) {
for(uint8_t j=0; j<8; j++) {
uint8_t counter = 223;
for (uint8_t i = 0; i < len; i++) {
for(uint8_t j = 0; j < 8; j++) {
bits[counter--] = hexuid[i] & 1;
hexuid[i] >>= 1;
}
@ -409,8 +409,8 @@ int CmdIndalaSim(const char *Cmd) {
// It has to send either 64bits (8bytes) or 224bits (28bytes). Zero padding needed if not.
// lf simpsk 1 c 32 r 2 d 0102030405060708
// PrintAndLogEx(NORMAL, "Emulating Indala UID: %u \n", cn);
// PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation or run another command");
PrintAndLogEx(SUCCESS, "Simulating Indala UID: %s", sprint_hex(hexuid, len));
PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or run another command");
UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}};
memcpy(c.d.asBytes, bits, size);
@ -427,6 +427,7 @@ int CmdIndalaClone(const char *Cmd) {
uint32_t n = 0, i = 0;
if (strchr(Cmd,'l') != 0) {
while (sscanf(&Cmd[i++], "%1x", &n ) == 1) {
uid1 = (uid1 << 4) | (uid2 >> 28);
uid2 = (uid2 << 4) | (uid3 >> 28);
@ -436,7 +437,8 @@ int CmdIndalaClone(const char *Cmd) {
uid6 = (uid6 << 4) | (uid7 >> 28);
uid7 = (uid7 << 4) | (n & 0xf);
}
PrintAndLogEx(NORMAL, "Cloning 224bit tag with UID %x%08x%08x%08x%08x%08x%08x", uid1, uid2, uid3, uid4, uid5, uid6, uid7);
PrintAndLogEx(INFO, "Preparing to clone Indala 224bit tag with UID %x%08x%08x%08x%08x%08x%08x", uid1, uid2, uid3, uid4, uid5, uid6, uid7);
c.cmd = CMD_INDALA_CLONE_TAG_L;
c.d.asDwords[0] = uid1;
c.d.asDwords[1] = uid2;
@ -450,7 +452,7 @@ int CmdIndalaClone(const char *Cmd) {
uid1 = (uid1 << 4) | (uid2 >> 28);
uid2 = (uid2 << 4) | (n & 0xf);
}
PrintAndLogEx(NORMAL, "Cloning 64bit tag with UID %x%08x", uid1, uid2);
PrintAndLogEx(INFO, "Preparing to clone Indala 64bit tag with UID %x%08x", uid1, uid2);
c.cmd = CMD_INDALA_CLONE_TAG;
c.arg[0] = uid1;
c.arg[1] = uid2;

View file

@ -86,15 +86,15 @@ int CmdIOProxDemod(const char *Cmd) {
uint8_t bits[MAX_GRAPH_TRACE_LEN] = {0};
size_t size = getFromGraphBuf(bits);
if (size < 65) {
if (g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples in GraphBuffer");
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples in GraphBuffer");
return 0;
}
//get binary from fsk wave
int waveIdx = 0;
idx = detectIOProx(bits, &size, &waveIdx);
if (idx < 0){
if (g_debugMode){
if (idx == -1){
if (idx < 0) {
if (g_debugMode) {
if (idx == -1) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples");
} else if (idx == -2) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox just noise detected");
@ -115,10 +115,10 @@ int CmdIOProxDemod(const char *Cmd) {
setDemodBuf(bits, size, idx);
setClockGrid(64, waveIdx + (idx*64));
if (idx==0){
if (g_debugMode){
if (idx == 0) {
if (g_debugMode) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox data not found - FSK Bits: %d", size);
if (size > 92) PrintAndLogEx(NORMAL, "%s", sprint_bin_break(bits, 92, 16));
if (size > 92) PrintAndLogEx(DEBUG, "%s", sprint_bin_break(bits, 92, 16));
}
return retval;
}
@ -132,15 +132,13 @@ int CmdIOProxDemod(const char *Cmd) {
//
//XSF(version)facility:codeone+codetwo (raw)
if (g_debugMode) {
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d", bits[idx], bits[idx+1], bits[idx+2], bits[idx+3], bits[idx+4], bits[idx+5], bits[idx+6], bits[idx+7], bits[idx+8]);
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d", bits[idx+9], bits[idx+10], bits[idx+11],bits[idx+12],bits[idx+13],bits[idx+14],bits[idx+15],bits[idx+16],bits[idx+17]);
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d facility", bits[idx+18], bits[idx+19], bits[idx+20],bits[idx+21],bits[idx+22],bits[idx+23],bits[idx+24],bits[idx+25],bits[idx+26]);
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d version", bits[idx+27], bits[idx+28], bits[idx+29],bits[idx+30],bits[idx+31],bits[idx+32],bits[idx+33],bits[idx+34],bits[idx+35]);
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d code1", bits[idx+36], bits[idx+37], bits[idx+38],bits[idx+39],bits[idx+40],bits[idx+41],bits[idx+42],bits[idx+43],bits[idx+44]);
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d code2", bits[idx+45], bits[idx+46], bits[idx+47],bits[idx+48],bits[idx+49],bits[idx+50],bits[idx+51],bits[idx+52],bits[idx+53]);
PrintAndLogEx(NORMAL, "%d%d%d%d%d%d%d%d %d%d checksum", bits[idx+54],bits[idx+55],bits[idx+56],bits[idx+57],bits[idx+58],bits[idx+59],bits[idx+60],bits[idx+61],bits[idx+62],bits[idx+63]);
}
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d", bits[idx], bits[idx+1], bits[idx+2], bits[idx+3], bits[idx+4], bits[idx+5], bits[idx+6], bits[idx+7], bits[idx+8]);
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d", bits[idx+9], bits[idx+10], bits[idx+11],bits[idx+12],bits[idx+13],bits[idx+14],bits[idx+15],bits[idx+16],bits[idx+17]);
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d facility", bits[idx+18], bits[idx+19], bits[idx+20],bits[idx+21],bits[idx+22],bits[idx+23],bits[idx+24],bits[idx+25],bits[idx+26]);
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d version", bits[idx+27], bits[idx+28], bits[idx+29],bits[idx+30],bits[idx+31],bits[idx+32],bits[idx+33],bits[idx+34],bits[idx+35]);
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d code1", bits[idx+36], bits[idx+37], bits[idx+38],bits[idx+39],bits[idx+40],bits[idx+41],bits[idx+42],bits[idx+43],bits[idx+44]);
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d code2", bits[idx+45], bits[idx+46], bits[idx+47],bits[idx+48],bits[idx+49],bits[idx+50],bits[idx+51],bits[idx+52],bits[idx+53]);
PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d%d checksum", bits[idx+54],bits[idx+55],bits[idx+56],bits[idx+57],bits[idx+58],bits[idx+59],bits[idx+60],bits[idx+61],bits[idx+62],bits[idx+63]);
uint32_t code = bytebits_to_byte(bits+idx,32);
uint32_t code2 = bytebits_to_byte(bits+idx+32,32);
@ -163,13 +161,13 @@ int CmdIOProxDemod(const char *Cmd) {
snprintf(crcStr, 3, "ok");
retval = 1;
} else {
if (g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox crc failed");
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox crc failed");
snprintf(crcStr, sizeof(crcStr), "failed 0x%02X != 0x%02X", crc, calccrc);
retval = 0;
}
PrintAndLogEx(NORMAL, "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){
PrintAndLogEx(DEBUG, "DEBUG: IO prox idx: %d, Len: %d, Printing demod buffer:", idx, size);
@ -241,7 +239,7 @@ int getIOProxBits(uint8_t version, uint8_t fc, uint16_t cn, uint8_t *bits) {
memcpy(bits, pre, sizeof(pre));
PrintAndLogEx(NORMAL, "IO raw bits:\n %s \n", sprint_bin(bits, 64));
PrintAndLogEx(SUCCESS, "IO raw bits:\n %s \n", sprint_bin(bits, 64));
return 1;
}
@ -252,8 +250,8 @@ int CmdIOProxSim(const char *Cmd) {
size_t size = sizeof(bits);
memset(bits, 0x00, size);
char cmdp = param_getchar(Cmd, 0);
if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_io_sim();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_io_sim();
version = param_get8(Cmd, 0);
fc = param_get8(Cmd, 1);
@ -263,7 +261,7 @@ int CmdIOProxSim(const char *Cmd) {
if ((cn & 0xFFFF) != cn) {
cn &= 0xFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 16-bits (IOProx): %u", cn);
PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (IOProx): %u", cn);
}
// clock 64, FSK2a fcHIGH 10 | fcLOW 8
@ -272,8 +270,8 @@ int CmdIOProxSim(const char *Cmd) {
arg1 = high << 8 | low;
arg2 = invert << 8 | clk;
PrintAndLogEx(NORMAL, "Emulating IOProx Version: %u FC: %u; CN: %u\n", version, fc, cn);
PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation or run another command");
PrintAndLogEx(SUCCESS, "Simulating IOProx version: %u FC: %u; CN: %u\n", version, fc, cn);
PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or run another command");
if ( !getIOProxBits(version, fc, cn, bits)) {
PrintAndLogEx(WARNING, "Error with tag bitstream generation.");
@ -309,7 +307,7 @@ int CmdIOProxClone(const char *Cmd) {
if ((cn & 0xFFFF) != cn) {
cn &= 0xFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 16-bits (IOProx): %u", cn);
PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (IOProx): %u", cn);
}
if ( !getIOProxBits(version, fc, cn, bits)) {
@ -323,7 +321,7 @@ int CmdIOProxClone(const char *Cmd) {
blocks[1] = bytebits_to_byte(bits, 32);
blocks[2] = bytebits_to_byte(bits + 32, 32);
PrintAndLogEx(NORMAL, "Preparing to clone IOProx to T55x7 with Version: %u FC: %u, CN: %u", version, fc, cn);
PrintAndLogEx(INFO, "Preparing to clone IOProx to T55x7 with Version: %u FC: %u, CN: %u", version, fc, cn);
print_blocks(blocks, 3);
//UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}};

View file

@ -130,14 +130,14 @@ int CmdJablotronDemod(const char *Cmd) {
PrintAndLogEx(SUCCESS, "Jablotron Tag Found: Card ID: %"PRIx64" :: Raw: %08X%08X", id, raw1, raw2);
uint8_t chksum = raw2 & 0xFF;
PrintAndLogEx(NORMAL, "Checksum: %02X [%s]",
PrintAndLogEx(INFO, "Checksum: %02X [%s]",
chksum,
(chksum == jablontron_chksum(DemodBuffer)) ? "OK":"FAIL"
(chksum == jablontron_chksum(DemodBuffer)) ? _GREEN_(OK) : _RED_(FAIL)
);
id = DEC2BCD(id);
// Printed format: 1410-nn-nnnn-nnnn
PrintAndLogEx(NORMAL, "Printed: 1410-%02X-%04X-%04X",
PrintAndLogEx(SUCCESS, "Printed: 1410-%02X-%04X-%04X",
(uint8_t)(id >> 32) & 0xFF,
(uint16_t)(id >> 16) & 0xFFFF,
(uint16_t)id & 0xFFFF
@ -158,8 +158,8 @@ int CmdJablotronClone(const char *Cmd) {
uint8_t bits[64];
memset(bits, 0, sizeof(bits));
char cmdp = param_getchar(Cmd, 0);
if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_jablotron_clone();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_jablotron_clone();
fullcode = param_get64ex(Cmd, 0, 0, 16);
@ -170,7 +170,7 @@ int CmdJablotronClone(const char *Cmd) {
// clearing the topbit needed for the preambl detection.
if ((fullcode & 0x7FFFFFFFFF) != fullcode) {
fullcode &= 0x7FFFFFFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 39bits: %"PRIx64, fullcode);
PrintAndLogEx(INFO, "Card Number Truncated to 39bits: %"PRIx64, fullcode);
}
if ( !getJablotronBits(fullcode, bits)) {
@ -181,13 +181,13 @@ int CmdJablotronClone(const char *Cmd) {
blocks[1] = bytebits_to_byte(bits, 32);
blocks[2] = bytebits_to_byte(bits + 32, 32);
PrintAndLogEx(NORMAL, "Preparing to clone Jablotron to T55x7 with FullCode: %"PRIx64, fullcode);
PrintAndLogEx(INFO, "Preparing to clone Jablotron to T55x7 with FullCode: %"PRIx64, fullcode);
print_blocks(blocks, 3);
UsbCommand resp;
UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}};
for (uint8_t i=0; i<4; i++) {
for (uint8_t i=0; i<3; i++) {
c.arg[0] = blocks[i];
c.arg[1] = i;
clearCommandBuffer();
@ -203,15 +203,15 @@ int CmdJablotronClone(const char *Cmd) {
int CmdJablotronSim(const char *Cmd) {
uint64_t fullcode = 0;
char cmdp = param_getchar(Cmd, 0);
if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_jablotron_sim();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_jablotron_sim();
fullcode = param_get64ex(Cmd, 0, 0, 16);
// clearing the topbit needed for the preambl detection.
if ((fullcode & 0x7FFFFFFFFF) != fullcode) {
fullcode &= 0x7FFFFFFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 39bits: %"PRIx64, fullcode);
PrintAndLogEx(INFO, "Card Number Truncated to 39bits: %"PRIx64, fullcode);
}
uint8_t clk = 64, encoding = 2, separator = 0, invert = 1;
@ -220,7 +220,7 @@ int CmdJablotronSim(const char *Cmd) {
arg1 = clk << 8 | encoding;
arg2 = invert << 8 | separator;
PrintAndLogEx(NORMAL, "Simulating Jablotron - FullCode: %"PRIx64, fullcode);
PrintAndLogEx(SUCCESS, "Simulating Jablotron - FullCode: %"PRIx64, fullcode);
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
getJablotronBits(fullcode, c.d.asBytes);

243
client/cmdlfkeri.c Normal file
View file

@ -0,0 +1,243 @@
//-----------------------------------------------------------------------------
//
// 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 KERI tag commands
// PSK1, RF/128, RF/2, 64 bits long
//-----------------------------------------------------------------------------
#include "cmdlfkeri.h"
static int CmdHelp(const char *Cmd);
int usage_lf_keri_clone(void){
PrintAndLogEx(NORMAL, "clone a KERI tag to a T55x7 tag.");
PrintAndLogEx(NORMAL, "Usage: lf keri clone [h] <id> <Q5>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h : This help");
PrintAndLogEx(NORMAL, " <id> : Keri Internal ID");
PrintAndLogEx(NORMAL, " <Q5> : specify write to Q5 (t5555 instead of t55x7)");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf keri clone 112233");
return 0;
}
int usage_lf_keri_sim(void) {
PrintAndLogEx(NORMAL, "Enables simulation of KERI card with specified card number.");
PrintAndLogEx(NORMAL, "Simulation runs until the button is pressed or another USB command is issued.");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: lf keri sim [h] <id>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h : This help");
PrintAndLogEx(NORMAL, " <id> : Keri Internal ID");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf keri sim 112233");
return 0;
}
// find KERI preamble in already demoded data
int detectKeri(uint8_t *dest, size_t *size, bool *invert) {
uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
uint8_t preamble_i[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0};
// sanity check.
if ( *size < sizeof(preamble) + 100) return -1;
size_t startIdx = 0;
if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) {
// if didn't find preamble try again inverting
if (!preambleSearch(DemodBuffer, preamble_i, sizeof(preamble_i), size, &startIdx))
return -2;
*invert ^= 1;
}
if (*size != 64) return -3; //wrong demoded size
return (int)startIdx;
}
int CmdKeriDemod(const char *Cmd) {
if (!PSKDemod("", false)) {
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: PSK1 Demod failed");
return 0;
}
bool invert = false;
size_t size = DemodBufferLen;
int idx = detectKeri(DemodBuffer, &size, &invert);
if (idx < 0) {
if (idx == -1)
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: too few bits found");
else if (idx == -2)
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: preamble not found");
else if (idx == -3)
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: Size not correct: 64 != %d", size);
else
PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: ans: %d", idx);
return 0;
}
setDemodBuf(DemodBuffer, size, idx);
setClockGrid(g_DemodClock, g_DemodStartIdx + (idx * g_DemodClock));
//got a good demod
uint32_t raw1 = bytebits_to_byte(DemodBuffer , 32);
uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32);
//get internal id
uint32_t ID = bytebits_to_byte(DemodBuffer+29, 32);
ID &= 0x7FFFFFFF;
/*
000000000000000000000000000001XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX111
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1###############################^^^
Preamble block 29 bits of ZEROS
32 bit Internal ID (First bit always 1)
3 bit of 1s in the end
How this is decoded to Facility ID, Card number is unknown
Facility ID = 0-31 (indicates 5 bits)
Card number = up to 10 digits
Might be a hash of FC & CN to generate Internal ID
*/
PrintAndLogEx(SUCCESS, "KERI Tag Found -- Internal ID: %u", ID);
PrintAndLogEx(SUCCESS, "Raw: %08X%08X", raw1 ,raw2);
if (invert){
PrintAndLogEx(INFO, "Had to Invert - probably KERI");
for (size_t i = 0; i < size; i++)
DemodBuffer[i] ^= 1;
CmdPrintDemodBuff("x");
}
return 1;
}
int CmdKeriRead(const char *Cmd) {
lf_read(true, 10000);
return CmdKeriDemod(Cmd);
}
int CmdKeriClone(const char *Cmd) {
uint32_t internalid = 0;
uint32_t blocks[3] = {
T55x7_TESTMODE_DISABLED |
T55x7_X_MODE |
T55x7_MODULATION_PSK1 |
T55x7_PSKCF_RF_2 |
2 << T55x7_MAXBLOCK_SHIFT,
0,
0};
// dynamic bitrate used
blocks[0] |= 0xF << 18;
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_keri_clone();
internalid = param_get32ex(Cmd, 0, 0, 10);
//Q5
if (tolower(param_getchar(Cmd, 1)) == 'q') {
blocks[0] =
T5555_MODULATION_PSK1 |
T5555_SET_BITRATE(128) |
T5555_PSK_RF_2 |
2 << T5555_MAXBLOCK_SHIFT;
}
// MSB is ONE
internalid |= 0x80000000;
// 3 LSB is ONE
uint64_t data = ((uint64_t)internalid << 3 ) + 7;
//
blocks[1] = data >> 32;
blocks[2] = data & 0xFFFFFFFF;
PrintAndLogEx(INFO, "Preparing to clone KERI to T55x7 with Internal Id: %u", internalid);
print_blocks(blocks, 3);
UsbCommand resp;
UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}};
for (uint8_t i = 0; i < 3; i++) {
c.arg[0] = blocks[i];
c.arg[1] = i;
clearCommandBuffer();
SendCommand(&c);
if (!WaitForResponseTimeout(CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){
PrintAndLogEx(WARNING, "Error occurred, device did not respond during write operation.");
return -1;
}
}
return 0;
}
int CmdKeriSim(const char *Cmd) {
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_keri_sim();
uint64_t internalid = param_get32ex(Cmd, 0, 0, 10);
internalid |= 0x80000000;
internalid <<= 3;
internalid += 7;
uint8_t bits[64] = {0x00};
// loop to bits
uint8_t j = 0;
for ( int8_t i = 63; i >= 0; --i) {
bits[j++] = ((internalid >> i) & 1 );
}
uint8_t clk = 32, carrier = 2, invert = 0;
uint16_t arg1, arg2;
size_t size = 64;
arg1 = clk << 8 | carrier;
arg2 = invert;
PrintAndLogEx(SUCCESS, "Simulating KERI - Internal Id: %u", internalid);
UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}};
memcpy(c.d.asBytes, bits, size);
clearCommandBuffer();
SendCommand(&c);
return 0;
}
static command_t CommandTable[] = {
{"help", CmdHelp, 1, "This help"},
{"demod", CmdKeriDemod, 1, "Demodulate an KERI tag from the GraphBuffer"},
{"read", CmdKeriRead, 0, "Attempt to read and extract tag data from the antenna"},
{"clone", CmdKeriClone, 0, "clone KERI to T55x7"},
{"sim", CmdKeriSim, 0, "simulate KERI tag"},
{NULL, NULL, 0, NULL}
};
int CmdLFKeri(const char *Cmd) {
clearCommandBuffer();
CmdsParse(CommandTable, Cmd);
return 0;
}
int CmdHelp(const char *Cmd) {
CmdsHelp(CommandTable);
return 0;
}

36
client/cmdlfkeri.h Normal file
View file

@ -0,0 +1,36 @@
//-----------------------------------------------------------------------------
//
// 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 Stanley/PAC tag commands
//-----------------------------------------------------------------------------
#ifndef CMDLFKERI_H__
#define CMDLFKERI_H__
#include <string.h>
#include <inttypes.h>
#include "proxmark3.h"
#include "ui.h"
#include "util.h"
#include "graph.h"
#include "cmdparser.h"
#include "cmddata.h"
#include "cmdmain.h"
#include "cmdlf.h"
#include "protocols.h" // for T55xx config register definitions
#include "lfdemod.h" // preamble test
extern int CmdLFKeri(const char *Cmd);
extern int CmdKeriRead(const char *Cmd);
extern int CmdKeriDemod(const char *Cmd);
extern int CmdKeriClone(const char *Cmd);
extern int CmdKeriSim(const char *Cmd);
extern int detectKeri(uint8_t *dest, size_t *size, bool *invert);
extern int usage_lf_keri_clone(void);
extern int usage_lf_keri_sim(void);
#endif

View file

@ -194,15 +194,15 @@ int CmdLFNedapDemod(const char *Cmd) {
chksum2 = bytebits_to_byte(DemodBuffer+110, 8);
chksum2 |= bytebits_to_byte(DemodBuffer+119, 8) << 8;
PrintAndLogEx(NORMAL, "NEDAP ID Found - Raw: %08x%08x%08x%08x", raw[3], raw[2], raw[1], raw[0]);
PrintAndLogEx(NORMAL, " - UID: %06X", uid);
PrintAndLogEx(NORMAL, " - i: %04X", two);
PrintAndLogEx(NORMAL, " - Checksum2 %04X", chksum2);
PrintAndLogEx(SUCCESS, "NEDAP ID Found - Raw: %08x%08x%08x%08x", raw[3], raw[2], raw[1], raw[0]);
PrintAndLogEx(SUCCESS, " - UID: %06X", uid);
PrintAndLogEx(SUCCESS, " - i: %04X", two);
PrintAndLogEx(SUCCESS, " - Checksum2 %04X", chksum2);
if (g_debugMode){
PrintAndLogEx(DEBUG, "DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, 128);
printDemodBuff();
PrintAndLogEx(NORMAL, "BIN:\n%s", sprint_bin_break( DemodBuffer, 128, 64) );
PrintAndLogEx(DEBUG, "BIN:\n%s", sprint_bin_break( DemodBuffer, 128, 64) );
}
return 1;
@ -268,7 +268,7 @@ int CmdLFNedapClone(const char *Cmd) {
blocks[3] = bytebits_to_byte(bits + 64, 32);
blocks[4] = bytebits_to_byte(bits + 96, 32);
PrintAndLogEx(NORMAL, "Preparing to clone NEDAP to T55x7 with card number: %u", cardnumber);
PrintAndLogEx(INFO, "Preparing to clone NEDAP to T55x7 with card number: %u", cardnumber);
print_blocks(blocks, 5);
UsbCommand resp;
@ -314,8 +314,8 @@ int CmdLFNedapSim(const char *Cmd) {
return 1;
}
PrintAndLogEx(NORMAL, "bin %s", sprint_bin_break(bs, 128, 32));
PrintAndLogEx(NORMAL, "Simulating Nedap - CardNumber: %u", cardnumber );
PrintAndLogEx(SUCCESS, "bin %s", sprint_bin_break(bs, 128, 32));
PrintAndLogEx(SUCCESS, "Simulating Nedap - CardNumber: %u", cardnumber );
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
memcpy(c.d.asBytes, bs, size);
@ -332,7 +332,7 @@ int CmdLFNedapChk(const char *Cmd){
len = ( len == 0 ) ? 5 : len>>1;
PrintAndLogEx(NORMAL, "Input: [%d] %s", len, sprint_hex(data, len));
PrintAndLogEx(SUCCESS, "Input: [%d] %s", len, sprint_hex(data, len));
//uint8_t last = GetParity(data, EVEN, 62);
//PrintAndLogEx(NORMAL, "TEST PARITY:: %d | %d ", DemodBuffer[62], last);
@ -367,7 +367,7 @@ int CmdLFNedapChk(const char *Cmd){
}
}
PrintAndLogEx(NORMAL, "Nedap checksum: 0x%X", ((ch << 8) | cl) );
PrintAndLogEx(SUCCESS, "Nedap checksum: 0x%X", ((ch << 8) | cl) );
return 0;
}

View file

@ -34,14 +34,13 @@ int detectNexWatch(uint8_t *dest, size_t *size, bool *invert) {
int CmdNexWatchDemod(const char *Cmd) {
if (!PSKDemod("", false)) {
if (g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: Error - NexWatch can't demod signal");
PrintAndLogEx(DEBUG, "DEBUG: Error - NexWatch can't demod signal");
return 0;
}
bool invert = false;
size_t size = DemodBufferLen;
int idx = detectNexWatch(DemodBuffer, &size, &invert);
if (idx <= 0){
if (g_debugMode){
if (idx <= 0) {
if (idx == -1)
PrintAndLogEx(DEBUG, "DEBUG: Error - NexWatch not enough samples");
// else if (idx == -2)
@ -54,7 +53,7 @@ int CmdNexWatchDemod(const char *Cmd) {
// PrintAndLogEx(DEBUG, "DEBUG: Error - NexWatch size not correct: %d", size);
else
PrintAndLogEx(DEBUG, "DEBUG: Error - NexWatch error %d",idx);
}
return 0;
}
@ -101,6 +100,7 @@ static command_t CommandTable[] = {
};
int CmdLFNEXWATCH(const char *Cmd) {
clearCommandBuffer();
CmdsParse(CommandTable, Cmd);
return 0;
}

View file

@ -161,10 +161,10 @@ int CmdNoralsyDemod(const char *Cmd) {
return 0;
}
PrintAndLogEx(NORMAL, "Noralsy Tag Found: Card ID %u, Year: %u Raw: %08X%08X%08X", cardid, year, raw1 ,raw2, raw3);
PrintAndLogEx(SUCCESS, "Noralsy Tag Found: Card ID %u, Year: %u Raw: %08X%08X%08X", cardid, year, raw1 ,raw2, raw3);
if (raw1 != 0xBB0214FF) {
PrintAndLogEx(NORMAL, "Unknown bits set in first block! Expected 0xBB0214FF, Found: 0x%08X", raw1);
PrintAndLogEx(NORMAL, "Please post this output in forum to further research on this format");
PrintAndLogEx(WARNING, "Unknown bits set in first block! Expected 0xBB0214FF, Found: 0x%08X", raw1);
PrintAndLogEx(WARNING, "Please post this output in forum to further research on this format");
}
return 1;
}
@ -202,7 +202,7 @@ int CmdNoralsyClone(const char *Cmd) {
blocks[2] = bytebits_to_byte(bits + 32, 32);
blocks[3] = bytebits_to_byte(bits + 64, 32);
PrintAndLogEx(NORMAL, "Preparing to clone Noralsy to T55x7 with CardId: %u", id);
PrintAndLogEx(INFO, "Preparing to clone Noralsy to T55x7 with CardId: %u", id);
print_blocks(blocks, 4);
UsbCommand resp;
@ -247,7 +247,7 @@ int CmdNoralsySim(const char *Cmd) {
return 1;
}
PrintAndLogEx(NORMAL, "Simulating Noralsy - CardId: %u", id);
PrintAndLogEx(SUCCESS, "Simulating Noralsy - CardId: %u", id);
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
memcpy(c.d.asBytes, bs, size);

View file

@ -12,11 +12,11 @@ static int CmdHelp(const char *Cmd);
int usage_lf_presco_clone(void){
PrintAndLogEx(NORMAL, "clone a Presco tag to a T55x7 tag.");
PrintAndLogEx(NORMAL, "Usage: lf presco clone [h] d <Card-ID> H <hex-ID> <Q5>");
PrintAndLogEx(NORMAL, "Usage: lf presco clone [h] d <Card-ID> c <hex-ID> <Q5>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " d <Card-ID> : 9 digit presco card ID");
PrintAndLogEx(NORMAL, " H <hex-ID> : 8 digit hex card number");
PrintAndLogEx(NORMAL, " c <hex-ID> : 8 digit hex card number");
PrintAndLogEx(NORMAL, " <Q5> : specify write to Q5 (t5555 instead of t55x7)");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
@ -29,11 +29,11 @@ int usage_lf_presco_sim(void) {
PrintAndLogEx(NORMAL, "Simulation runs until the button is pressed or another USB command is issued.");
PrintAndLogEx(NORMAL, "Per presco format, the card number is 9 digit number and can contain *# chars. Larger values are truncated.");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Usage: lf presco sim [h] d <Card-ID> or H <hex-ID>");
PrintAndLogEx(NORMAL, "Usage: lf presco sim [h] d <Card-ID> or c <hex-ID>");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h : this help");
PrintAndLogEx(NORMAL, " d <Card-ID> : 9 digit presco card number");
PrintAndLogEx(NORMAL, " H <hex-ID> : 8 digit hex card number");
PrintAndLogEx(NORMAL, " c <hex-ID> : 8 digit hex card number");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " lf presco sim d 123456789");
@ -62,24 +62,22 @@ int GetWiegandFromPresco(const char *Cmd, uint32_t *sitecode, uint32_t *usercode
int stringlen = 0;
memset(id, 0x00, sizeof(id));
while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch(param_getchar(Cmd, cmdp)) {
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
return -1;
case 'H':
case 'c':
hex = true;
//get hex
*fullcode = param_get32ex(Cmd, cmdp+1, 0, 16);
cmdp+=2;
break;
case 'D':
case 'd':
//param get string int param_getstr(const char *line, int paramnum, char * str)
stringlen = param_getstr(Cmd, cmdp+1, id, sizeof(id));
if (stringlen < 2) return -1;
cmdp += 2;
break;
case 'Q':
case 'q':
*Q5 = true;
cmdp++;
@ -136,7 +134,6 @@ int CmdPrescoDemod(const char *Cmd) {
size_t size = DemodBufferLen;
int ans = detectPresco(DemodBuffer, &size);
if (ans < 0) {
if (ans == -1)
PrintAndLogEx(DEBUG, "DEBUG: Error - Presco: too few bits found");
else if (ans == -2)
@ -163,7 +160,7 @@ int CmdPrescoDemod(const char *Cmd) {
char cmd[12] = {0};
sprintf(cmd, "H %08X", cardid);
GetWiegandFromPresco(cmd, &sitecode, &usercode, &fullcode, &Q5);
PrintAndLogEx(NORMAL, "SiteCode %u, UserCode %u, FullCode, %08X", sitecode, usercode, fullcode);
PrintAndLogEx(SUCCESS, "SiteCode %u, UserCode %u, FullCode, %08X", sitecode, usercode, fullcode);
return 1;
}
@ -190,12 +187,12 @@ int CmdPrescoClone(const char *Cmd) {
if ((sitecode & 0xFF) != sitecode) {
sitecode &= 0xFF;
PrintAndLogEx(NORMAL, "Facility-Code Truncated to 8-bits (Presco): %u", sitecode);
PrintAndLogEx(INFO, "Facility-Code Truncated to 8-bits (Presco): %u", sitecode);
}
if ((usercode & 0xFFFF) != usercode) {
usercode &= 0xFFFF;
PrintAndLogEx(NORMAL, "Card Number Truncated to 16-bits (Presco): %u", usercode);
PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (Presco): %u", usercode);
}
blocks[1] = 0x10D00000; //preamble
@ -203,7 +200,7 @@ int CmdPrescoClone(const char *Cmd) {
blocks[3] = 0x00000000;
blocks[4] = fullcode;
PrintAndLogEx(NORMAL, "Preparing to clone Presco to T55x7 with SiteCode: %u, UserCode: %u, FullCode: %08x", sitecode, usercode, fullcode);
PrintAndLogEx(INFO, "Preparing to clone Presco to T55x7 with SiteCode: %u, UserCode: %u, FullCode: %08x", sitecode, usercode, fullcode);
print_blocks(blocks, 5);
UsbCommand resp;
@ -236,7 +233,7 @@ int CmdPrescoSim(const char *Cmd) {
arg1 = clk << 8 | encoding;
arg2 = invert << 8 | separator;
PrintAndLogEx(NORMAL, "Simulating Presco - SiteCode: %u, UserCode: %u, FullCode: %08X",sitecode, usercode, fullcode);
PrintAndLogEx(SUCCESS, "Simulating Presco - SiteCode: %u, UserCode: %u, FullCode: %08X",sitecode, usercode, fullcode);
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
GetPrescoBits(fullcode, c.d.asBytes);

View file

@ -285,7 +285,7 @@ int CmdPyramidClone(const char *Cmd) {
blocks[3] = bytebits_to_byte(bs + 64, 32);
blocks[4] = bytebits_to_byte(bs + 96, 32);
PrintAndLogEx(NORMAL, "Preparing to clone Farpointe/Pyramid to T55x7 with Facility Code: %u, Card Number: %u", facilitycode, cardnumber);
PrintAndLogEx(INFO, "Preparing to clone Farpointe/Pyramid to T55x7 with Facility Code: %u, Card Number: %u", facilitycode, cardnumber);
print_blocks(blocks, 5);
UsbCommand resp;
@ -331,7 +331,7 @@ int CmdPyramidSim(const char *Cmd) {
return 1;
}
PrintAndLogEx(NORMAL, "Simulating Farpointe/Pyramid - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber );
PrintAndLogEx(SUCCESS, "Simulating Farpointe/Pyramid - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber );
UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}};
memcpy(c.d.asBytes, bs, size);

View file

@ -97,12 +97,12 @@ int CmdSecurakeyDemod(const char *Cmd) {
// test parities - evenparity32 looks to add an even parity returns 0 if already even...
bool parity = !evenparity32(lWiegand) && !oddparity32(rWiegand);
PrintAndLogEx(NORMAL, "Securakey Tag Found--BitLen: %u, Card ID: %u, FC: 0x%X, Raw: %08X%08X%08X", bitLen, cardid, fc, raw1 ,raw2, raw3);
PrintAndLogEx(SUCCESS, "Securakey Tag Found--BitLen: %u, Card ID: %u, FC: 0x%X, Raw: %08X%08X%08X", bitLen, cardid, fc, raw1 ,raw2, raw3);
if (bitLen <= 32)
PrintAndLogEx(NORMAL, "Wiegand: %08X, Parity: %s", (lWiegand<<(bitLen/2)) | rWiegand, parity ? "Passed" : "Failed");
PrintAndLogEx(NORMAL, "\nHow the FC translates to printed FC is unknown");
PrintAndLogEx(NORMAL, "How the checksum is calculated is unknown");
PrintAndLogEx(NORMAL, "Help the community identify this format further\n by sharing your tag on the pm3 forum or with forum members");
PrintAndLogEx(SUCCESS, "Wiegand: %08X, Parity: %s", (lWiegand<<(bitLen/2)) | rWiegand, parity ? "Passed" : "Failed");
PrintAndLogEx(INFO, "\nHow the FC translates to printed FC is unknown");
PrintAndLogEx(INFO, "How the checksum is calculated is unknown");
PrintAndLogEx(INFO, "Help the community identify this format further\n by sharing your tag on the pm3 forum or with forum members");
return 1;
}

View file

@ -691,7 +691,7 @@ bool tryDetectModulation(){
bool retval = false;
if ( hits > 1) {
PrintAndLogEx(NORMAL, "Found [%d] possible matches for modulation.",hits);
PrintAndLogEx(SUCCESS, "Found [%d] possible matches for modulation.", hits);
for(int i=0; i<hits; ++i){
retval = testKnownConfigBlock(tests[i].block0);
if ( retval ) {
@ -942,9 +942,9 @@ int printConfiguration( t55xx_conf_block_t b){
PrintAndLogEx(NORMAL, "Chip Type : %s", (b.Q5) ? "T5555(Q5)" : "T55x7");
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, "Inverted : %s", (b.inverted) ? "Yes" : "No" );
PrintAndLogEx(NORMAL, "Inverted : %s", (b.inverted) ? _GREEN_(Yes) : "No" );
PrintAndLogEx(NORMAL, "Offset : %d", b.offset);
PrintAndLogEx(NORMAL, "Seq. Term. : %s", (b.ST) ? "Yes" : "No" );
PrintAndLogEx(NORMAL, "Seq. Term. : %s", (b.ST) ? _GREEN_(Yes) : "No" );
PrintAndLogEx(NORMAL, "Block0 : 0x%08X", b.block0);
PrintAndLogEx(NORMAL, "");
return 0;
@ -954,13 +954,11 @@ int CmdT55xxWakeUp(const char *Cmd) {
uint32_t password = 0;
uint8_t cmdp = 0;
bool errors = false;
while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch(param_getchar(Cmd, cmdp)) {
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
case 'H':
return usage_t55xx_wakup();
case 'p':
case 'P':
password = param_get32ex(Cmd, cmdp+1, 0, 16);
cmdp += 2;
errors = false;
@ -976,7 +974,7 @@ int CmdT55xxWakeUp(const char *Cmd) {
UsbCommand c = {CMD_T55XX_WAKEUP, {password, 0, 0}};
clearCommandBuffer();
SendCommand(&c);
PrintAndLogEx(NORMAL, "Wake up command sent. Try read now");
PrintAndLogEx(SUCCESS, "Wake up command sent. Try read now");
return 0;
}
@ -990,30 +988,25 @@ int CmdT55xxWriteBlock(const char *Cmd) {
bool testMode = false;
bool errors = false;
uint8_t cmdp = 0;
while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch(param_getchar(Cmd, cmdp)) {
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
case 'H':
return usage_t55xx_write();
case 'b':
case 'B':
errors |= param_getdec(Cmd, cmdp+1, &block);
cmdp += 2;
break;
case 'd':
case 'D':
data = param_get32ex(Cmd, cmdp+1, 0, 16);
gotdata = true;
cmdp += 2;
break;
case 'p':
case 'P':
password = param_get32ex(Cmd, cmdp+1, 0, 16);
usepwd = true;
cmdp += 2;
break;
case 't':
case 'T':
testMode = true;
cmdp++;
break;
@ -1030,7 +1023,7 @@ int CmdT55xxWriteBlock(const char *Cmd) {
if (errors || !gotdata) return usage_t55xx_write();
if (block > 7) {
PrintAndLogEx(NORMAL, "Block number must be between 0 and 7");
PrintAndLogEx(WARNING, "Block number must be between 0 and 7");
return 0;
}
@ -1042,7 +1035,7 @@ int CmdT55xxWriteBlock(const char *Cmd) {
char pwdStr[16] = {0};
snprintf(pwdStr, sizeof(pwdStr), "pwd: 0x%08X", password);
PrintAndLogEx(NORMAL, "Writing page %d block: %02d data: 0x%08X %s", page1, block, data, (usepwd) ? pwdStr : "" );
PrintAndLogEx(INFO, "Writing page %d block: %02d data: 0x%08X %s", page1, block, data, (usepwd) ? pwdStr : "" );
//Password mode
if (usepwd) {
@ -1059,12 +1052,13 @@ int CmdT55xxWriteBlock(const char *Cmd) {
}
int CmdT55xxReadTrace(const char *Cmd) {
char cmdp = param_getchar(Cmd, 0);
bool pwdmode = false;
uint32_t password = 0;
if (strlen(Cmd) > 1 || cmdp == 'h' || cmdp == 'H') return usage_t55xx_trace();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) > 1 || cmdp == 'h') return usage_t55xx_trace();
if (strlen(Cmd)==0) {
bool pwdmode = false;
uint32_t password = 0;
if (strlen(Cmd) == 0) {
// sanity check.
if (!SanityOfflineCheck(false)) return 1;
@ -1091,7 +1085,7 @@ int CmdT55xxReadTrace(const char *Cmd) {
uint32_t hdr = PackBits(si, 9, DemodBuffer); si += 9;
if (hdr != 0x1FF) {
PrintAndLogEx(NORMAL, "Invalid Q5 Trace data header (expected 0x1FF, found %X)", hdr);
PrintAndLogEx(FAILED, "Invalid Q5 Trace data header (expected 0x1FF, found %X)", hdr);
return 1;
}
@ -1130,7 +1124,7 @@ int CmdT55xxReadTrace(const char *Cmd) {
data.acl = PackBits(si, 8, DemodBuffer); si += 8;
if ( data.acl != 0xE0 ) {
PrintAndLogEx(NORMAL, "The modulation is most likely wrong since the ACL is not 0xE0. ");
PrintAndLogEx(FAILED, "The modulation is most likely wrong since the ACL is not 0xE0. ");
return 1;
}
@ -1227,11 +1221,11 @@ int CmdT55xxInfo(const char *Cmd){
*/
bool pwdmode = false;
uint32_t password = 0;
char cmdp = param_getchar(Cmd, 0);
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) > 1 || cmdp == 'h' || cmdp == 'H') return usage_t55xx_info();
if (strlen(Cmd) > 1 || cmdp == 'h') return usage_t55xx_info();
if (strlen(Cmd)==0){
if (strlen(Cmd) == 0) {
// sanity check.
if (!SanityOfflineCheck(false)) return 1;
@ -1264,24 +1258,26 @@ int CmdT55xxInfo(const char *Cmd){
uint32_t inv = PackBits(si, 1, DemodBuffer); si += 1;
uint32_t por = PackBits(si, 1, DemodBuffer); si += 1;
if (config.Q5) PrintAndLogEx(NORMAL, "*** Warning *** Config Info read off a Q5 will not display as expected");
if (config.Q5)
PrintAndLogEx(NORMAL, _RED_(*** Warning ***) " Config Info read off a Q5 will not display as expected");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, "-- T55x7 Configuration & Tag Information --------------------");
PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
PrintAndLogEx(NORMAL, " Safer key : %s", GetSaferStr(safer));
PrintAndLogEx(NORMAL, " reserved : %d", resv);
PrintAndLogEx(NORMAL, " Data bit rate : %s", GetBitRateStr(dbr, extend));
PrintAndLogEx(NORMAL, " eXtended mode : %s", (extend) ? "Yes - Warning":"No");
PrintAndLogEx(NORMAL, " eXtended mode : %s", (extend) ? _YELLOW_(Yes - Warning) : "No");
PrintAndLogEx(NORMAL, " Modulation : %s", GetModulationStr(datamod));
PrintAndLogEx(NORMAL, " PSK clock frequency : %d", pskcf);
PrintAndLogEx(NORMAL, " AOR - Answer on Request : %s", (aor) ? "Yes":"No");
PrintAndLogEx(NORMAL, " OTP - One Time Pad : %s", (otp) ? "Yes - Warning":"No" );
PrintAndLogEx(NORMAL, " AOR - Answer on Request : %s", (aor) ? _GREEN_(Yes) : "No");
PrintAndLogEx(NORMAL, " OTP - One Time Pad : %s", (otp) ? _YELLOW_(Yes - Warning) : "No" );
PrintAndLogEx(NORMAL, " Max block : %d", maxblk);
PrintAndLogEx(NORMAL, " Password mode : %s", (pwd) ? "Yes":"No");
PrintAndLogEx(NORMAL, " Sequence Start Terminator : %s", (sst) ? "Yes":"No");
PrintAndLogEx(NORMAL, " Fast Write : %s", (fw) ? "Yes":"No");
PrintAndLogEx(NORMAL, " Inverse data : %s", (inv) ? "Yes":"No");
PrintAndLogEx(NORMAL, " POR-Delay : %s", (por) ? "Yes":"No");
PrintAndLogEx(NORMAL, " Password mode : %s", (pwd) ? _GREEN_(Yes) : "No");
PrintAndLogEx(NORMAL, " Sequence Start Terminator : %s", (sst) ? _GREEN_(Yes) : "No");
PrintAndLogEx(NORMAL, " Fast Write : %s", (fw) ? _GREEN_(Yes) : "No");
PrintAndLogEx(NORMAL, " Inverse data : %s", (inv) ? _GREEN_(Yes) : "No");
PrintAndLogEx(NORMAL, " POR-Delay : %s", (por) ? _GREEN_(Yes) : "No");
PrintAndLogEx(NORMAL, "-------------------------------------------------------------");
PrintAndLogEx(NORMAL, " Raw Data - Page 0");
PrintAndLogEx(NORMAL, " Block 0 : 0x%08X %s", block0, sprint_bin(DemodBuffer + config.offset, 32) );
@ -1293,8 +1289,8 @@ int CmdT55xxDump(const char *Cmd){
uint32_t password = 0;
bool override = false;
char cmdp = param_getchar(Cmd, 0);
if ( cmdp == 'h' || cmdp == 'H') return usage_t55xx_dump();
char cmdp = tolower(param_getchar(Cmd, 0));
if ( cmdp == 'h') return usage_t55xx_dump();
bool usepwd = ( strlen(Cmd) > 0);
if ( usepwd ){
@ -1479,7 +1475,7 @@ int CmdT55xxWipe(const char *Cmd) {
// Try with the default password to reset block 0
// With a pwd should work even if pwd bit not set
PrintAndLogEx(NORMAL, "\nBeginning Wipe of a T55xx tag (assuming the tag is not password protected)\n");
PrintAndLogEx(INFO, "\nBeginning Wipe of a T55xx tag (assuming the tag is not password protected)\n");
if ( Q5 )
snprintf(ptrData,sizeof(writeData),"b 0 d 6001F004 p 0");
@ -1494,7 +1490,7 @@ int CmdT55xxWipe(const char *Cmd) {
if (!CmdT55xxWriteBlock(ptrData)) PrintAndLogEx(WARNING, "Error writing blk %d", blk);
memset(writeData,0x00, sizeof(writeData));
memset(writeData, 0x00, sizeof(writeData));
}
return 0;
}
@ -1521,7 +1517,7 @@ int CmdT55xxChkPwds(const char *Cmd) {
memset(line, 0, sizeof(line));
char cmdp = tolower(param_getchar(Cmd, 0));
if (cmdp == 'h') return usage_t55xx_chk();
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_t55xx_chk();
/*
if ( T55xxReadBlock(7, 0, 0, 0, 0) ) {
@ -1581,7 +1577,7 @@ int CmdT55xxChkPwds(const char *Cmd) {
FILE * f = fopen( filename , "r");
if ( !f ) {
PrintAndLogEx(WARNING, "File: %s: not found or locked.", filename);
PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename);
free(keyBlock);
return 1;
}
@ -1622,7 +1618,8 @@ int CmdT55xxChkPwds(const char *Cmd) {
// PrintAndLogEx(NORMAL, "chk custom pwd[%2d] %08X", keycnt, bytes_to_num(keyBlock + 4 * keycnt, 4) );
keycnt++;
memset(line, 0, sizeof(line));
}
}
if (f)
fclose(f);
@ -1704,7 +1701,7 @@ int CmdT55xxBruteForce(const char *Cmd) {
PrintAndLogEx(INFO, "Search password range [%08X -> %08X]", start_password, end_password);
while ((!found) || (curr <= end_password)){
while ( !found || (curr <= end_password)){
printf("."); fflush(stdout);
@ -1716,9 +1713,9 @@ int CmdT55xxBruteForce(const char *Cmd) {
PrintAndLogEx(WARNING, "Aquireing data from device failed. Quitting");
return 0;
}
found = tryDetectModulation();
if (found) break;
++curr;
}
@ -1735,7 +1732,7 @@ int CmdT55xxBruteForce(const char *Cmd) {
}
int tryOnePassword(uint32_t password) {
PrintAndLogEx(NORMAL, "Trying password %08x", password);
PrintAndLogEx(INFO, "Trying password %08x", password);
if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, password)) {
PrintAndLogEx(NORMAL, "Acquire data from device failed. Quitting");
return -1;
@ -1754,8 +1751,8 @@ int CmdT55xxRecoverPW(const char *Cmd) {
uint32_t prev_password = 0xffffffff;
uint32_t mask = 0x0;
int found = 0;
char cmdp = param_getchar(Cmd, 0);
if (cmdp == 'h' || cmdp == 'H') return usage_t55xx_recoverpw();
char cmdp = tolower(param_getchar(Cmd, 0));
if (cmdp == 'h' ) return usage_t55xx_recoverpw();
orig_password = param_get32ex(Cmd, 0, 0x51243648, 16); //password used by handheld cloners
@ -1938,13 +1935,11 @@ int CmdT55xxDetectPage1(const char *Cmd){
uint32_t password = 0;
uint8_t cmdp = 0;
while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch(param_getchar(Cmd, cmdp)) {
while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
switch (tolower(param_getchar(Cmd, cmdp))) {
case 'h':
case 'H':
return usage_t55xx_detectP1();
case 'p':
case 'P':
password = param_get32ex(Cmd, cmdp+1, 0, 16);
usepwd = true;
cmdp += 2;
@ -1967,7 +1962,7 @@ int CmdT55xxDetectPage1(const char *Cmd){
return false;
}
bool success = tryDetectP1(false);
if (success) PrintAndLogEx(NORMAL, "T55xx chip found!");
if (success) PrintAndLogEx(SUCCESS, "T55xx chip found!");
return success;
}

View file

@ -118,7 +118,7 @@ int CmdVikingClone(const char *Cmd) {
rawID = getVikingBits(id);
PrintAndLogEx(NORMAL, "Cloning - ID: %08X, Raw: %08X%08X",id,(uint32_t)(rawID >> 32),(uint32_t) (rawID & 0xFFFFFFFF));
PrintAndLogEx(INFO, "Preparing to clone Viking tag - ID: %08X, Raw: %08X%08X",id,(uint32_t)(rawID >> 32),(uint32_t) (rawID & 0xFFFFFFFF));
UsbCommand c = {CMD_VIKING_CLONE_TAG, {rawID >> 32, rawID & 0xFFFFFFFF, Q5}};
clearCommandBuffer();
@ -149,7 +149,7 @@ int CmdVikingSim(const char *Cmd) {
arg1 = clk << 8 | encoding;
arg2 = invert << 8 | separator;
PrintAndLogEx(NORMAL, "Simulating Viking - ID: %08X, Raw: %08X%08X",id,(uint32_t)(rawID >> 32),(uint32_t) (rawID & 0xFFFFFFFF));
PrintAndLogEx(SUCCESS, "Simulating Viking - ID: %08X, Raw: %08X%08X",id,(uint32_t)(rawID >> 32),(uint32_t) (rawID & 0xFFFFFFFF));
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
num_to_bytebits(rawID, size, c.d.asBytes);

View file

@ -165,8 +165,8 @@ int CmdVisa2kClone(const char *Cmd) {
uint64_t id = 0;
uint32_t blocks[4] = {T55x7_MODULATION_MANCHESTER | T55x7_BITRATE_RF_64 | T55x7_ST_TERMINATOR | 3 << T55x7_MAXBLOCK_SHIFT, BL0CK1, 0};
char cmdp = param_getchar(Cmd, 0);
if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_visa2k_clone();
char cmdp = tolower(param_getchar(Cmd, 0));
if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_visa2k_clone();
id = param_get32ex(Cmd, 0, 0, 10);
@ -210,7 +210,7 @@ int CmdVisa2kSim(const char *Cmd) {
arg1 = clk << 8 | encoding;
arg2 = invert << 8 | separator;
PrintAndLogEx(NORMAL, "Simulating Visa2000 - CardId: %u", id);
PrintAndLogEx(SUCCESS, "Simulating Visa2000 - CardId: %u", id);
UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};

View file

@ -595,7 +595,7 @@ int CmdSmartUpgrade(const char *Cmd) {
// load file
f = fopen(filename, "rb");
if ( !f ){
PrintAndLogEx(FAILED, "File: %s: not found or locked.", filename);
PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename);
return 1;
}
@ -946,8 +946,8 @@ static int smart_brute_sfi(bool decodeTLV){
return 0;
}
static void smart_brute_options(bool decodeTLV){
static void smart_brute_options(bool decodeTLV) {
uint8_t* buf = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t));
if ( !buf )
return;
@ -1022,8 +1022,10 @@ int CmdSmartBruteforceSFI(const char *Cmd) {
return 1;
PrintAndLogEx(INFO, "Selecting card");
if ( !smart_select(false, NULL) )
if ( !smart_select(false, NULL) ) {
free(buf);
return 1;
}
char* caid = NULL;
@ -1055,7 +1057,7 @@ int CmdSmartBruteforceSFI(const char *Cmd) {
continue;
size_t aidlen = strlen(aid);
char* caid = calloc( 8+2+aidlen+1, sizeof(uint8_t));
caid = calloc( 8+2+aidlen+1, sizeof(uint8_t));
snprintf(caid, 8+2+aidlen+1, SELECT, aidlen >> 1, aid);
int hexlen = 0;

View file

@ -14,7 +14,6 @@ static int CmdHelp(const char *Cmd);
// trace pointer
static uint8_t *trace;
long traceLen = 0;
bool preRDV40 = true;
int usage_trace_list(){
PrintAndLogEx(NORMAL, "List protocol data in trace buffer.");
@ -166,7 +165,8 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
crcStatus = iso14443B_CRC_check(frame, data_len);
break;
case PROTO_MIFARE:
crcStatus = mifare_CRC_check(isResponse, frame, data_len);
crcStatus = mifare_CRC_check(isResponse, frame, data_len);
break;
case ISO_14443A:
case MFDES:
crcStatus = iso14443A_CRC_check(isResponse, frame, data_len);
@ -289,6 +289,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
void printFelica(uint16_t traceLen, uint8_t *trace) {
PrintAndLogEx(NORMAL, "ISO18092 / FeliCa - Timings are not as accurate");
PrintAndLogEx(NORMAL, " Gap | Src | Data | CRC | Annotation |");
PrintAndLogEx(NORMAL, "--------|-----|---------------------------------|----------|-------------------|");
uint16_t tracepos = 0;
@ -297,8 +298,9 @@ void printFelica(uint16_t traceLen, uint8_t *trace) {
if (tracepos + 3 >= traceLen) break;
uint16_t gap = (uint16_t)trace[tracepos+1] + ((uint16_t)trace[tracepos] >> 8);
uint16_t crc_ok = trace[tracepos+2];
uint16_t gap = *((uint16_t *)(trace + tracepos));
uint8_t crc_ok = trace[tracepos+2];
tracepos += 3;
if (tracepos + 3 >= traceLen) break;
@ -511,8 +513,8 @@ int CmdTraceList(const char *Cmd) {
}
}
PrintAndLogEx(NORMAL, "Recorded Activity (TraceLen = %d bytes)", traceLen);
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %d bytes)", traceLen);
PrintAndLogEx(INFO, "");
if (protocol == FELICA) {
printFelica(traceLen, trace);
} else {
@ -526,8 +528,6 @@ int CmdTraceList(const char *Cmd) {
" Tag Mode: Timings are in sub carrier periods (1/212 kHz == 4.7us)");
if ( protocol == ISO_15693 )
PrintAndLogEx(NORMAL, "ISO15693 - Timings are not as accurate");
if ( protocol == FELICA )
PrintAndLogEx(NORMAL, "ISO18092 / FeliCa - Timings are not as accurate");
if ( protocol == ISO_7816_4 )
PrintAndLogEx(NORMAL, "ISO7816-4 / Smartcard - Timings N/A yet");

View file

@ -237,10 +237,13 @@ static char *asn1_oid_description(const char *oid, bool with_group_desc) {
static char res[300];
memset(res, 0x00, sizeof(res));
strcpy(fname, get_my_executable_directory());
size_t len = strlen(get_my_executable_directory());
if ( len > 300 ) len = 299;
strncpy(fname, get_my_executable_directory(), len);
strcat(fname, "crypto/oids.json");
if (access(fname, F_OK) < 0) {
strcpy(fname, get_my_executable_directory());
strncpy(fname, get_my_executable_directory(), len);
strcat(fname, "oids.json");
if (access(fname, F_OK) < 0) {
goto error; // file not found

View file

@ -8,3 +8,4 @@ AEA684A6DAB23278 -- AA1
5b7c62c491c11b39 -- from loclass demo file.
F0E1D2C3B4A59687 -- Kd from PicoPass 2k documentation
5CBCF1DA45D5FB4F -- PicoPass Default Exchange Key
31ad7ebd2f282168 -- From HID multiclassSE reader

View file

@ -98,6 +98,7 @@ fc00018778f7,--VästtrafikenKeyA, RKFÖstgötaTrafikenKeyA
314B49474956,--VIGIK1KeyA
564c505f4d41,--VIGIK1KeyB
ba5b895da162,--VIGIK1KeyB
4143414F5250,
#
# Data from: http://irq5.io/2013/04/13/decoding-bcard-conference-badges/
f4a9ef2afc6d,--BCARD KeyB

View file

@ -253,6 +253,7 @@ int CmdEMVGPO(const char *cmd) {
// calc PDOL
struct tlv *pdol_data_tlv = NULL;
struct tlvdb *tmp_ext = NULL;
struct tlv data_tlv = {
.tag = 0x83,
.len = datalen,
@ -266,9 +267,11 @@ int CmdEMVGPO(const char *cmd) {
ParamLoadFromJson(tlvRoot);
};
pdol_data_tlv = dol_process((const struct tlv *)tlvdb_external(0x9f38, datalen, data), tlvRoot, 0x83);
tmp_ext = tlvdb_external(0x9f38, datalen, data);
pdol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x83);
if (!pdol_data_tlv){
PrintAndLogEx(ERR, "Can't create PDOL TLV.");
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
return 4;
}
@ -283,6 +286,7 @@ int CmdEMVGPO(const char *cmd) {
unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len);
if (!pdol_data_tlv_data) {
PrintAndLogEx(ERR, "Can't create PDOL data.");
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
return 4;
}
@ -296,6 +300,8 @@ int CmdEMVGPO(const char *cmd) {
if (pdol_data_tlv != &data_tlv)
free(pdol_data_tlv);
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
if (sw)
@ -430,6 +436,7 @@ int CmdEMVAC(const char *cmd) {
// calc CDOL
struct tlv *cdol_data_tlv = NULL;
struct tlvdb *tmp_ext = NULL;
struct tlv data_tlv = {
.tag = 0x01,
.len = datalen,
@ -444,9 +451,11 @@ int CmdEMVAC(const char *cmd) {
ParamLoadFromJson(tlvRoot);
};
cdol_data_tlv = dol_process((const struct tlv *)tlvdb_external(0x8c, datalen, data), tlvRoot, 0x01); // 0x01 - dummy tag
tmp_ext = tlvdb_external(0x8c, datalen, data);
cdol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x01); // 0x01 - dummy tag
if (!cdol_data_tlv){
PrintAndLogEx(ERR, "Can't create CDOL TLV.");
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
return 4;
}
@ -467,6 +476,8 @@ int CmdEMVAC(const char *cmd) {
if (cdol_data_tlv != &data_tlv)
free(cdol_data_tlv);
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
if (sw)
@ -572,6 +583,7 @@ int CmdEMVInternalAuthenticate(const char *cmd) {
// calc DDOL
struct tlv *ddol_data_tlv = NULL;
struct tlvdb *tmp_ext = NULL;
struct tlv data_tlv = {
.tag = 0x01,
.len = datalen,
@ -586,9 +598,11 @@ int CmdEMVInternalAuthenticate(const char *cmd) {
ParamLoadFromJson(tlvRoot);
};
ddol_data_tlv = dol_process((const struct tlv *)tlvdb_external(0x9f49, datalen, data), tlvRoot, 0x01); // 0x01 - dummy tag
tmp_ext = tlvdb_external(0x9f49, datalen, data);
ddol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x01); // 0x01 - dummy tag
if (!ddol_data_tlv){
PrintAndLogEx(ERR, "Can't create DDOL TLV.");
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
return 4;
}
@ -609,6 +623,8 @@ int CmdEMVInternalAuthenticate(const char *cmd) {
if (ddol_data_tlv != &data_tlv)
free(ddol_data_tlv);
tlvdb_free(tmp_ext);
tlvdb_free(tlvRoot);
if (sw)
@ -1204,6 +1220,7 @@ int CmdEMVExec(const char *cmd) {
if (res) {
PrintAndLogEx(NORMAL, "AC1 error(%d): %4x. Exit...", res, sw);
free(cdol1_data_tlv);
dreturn(7);
}
@ -1804,6 +1821,7 @@ int CmdEMVRoca(const char *cmd) {
PrintAndLogEx(ERR, "Can't create PDOL data.");
tlvdb_free(tlvRoot);
DropFieldEx( channel );
free(pdol_data_tlv);
return 6;
}
PrintAndLogEx(INFO, "PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));

View file

@ -429,9 +429,6 @@ char *emv_pk_get_ca_pk_file(const char *dirname, const unsigned char *rid, unsig
if (!dirname)
dirname = ".";//openemv_config_get_str("capk.dir", NULL);
if (!dirname)
return NULL;
char *filename;
int ret = asprintf(&filename, "%s/%02hhx%02hhx%02hhx%02hhx%02hhx_%02hhx.0",
dirname,
@ -453,9 +450,6 @@ char *emv_pk_get_ca_pk_rid_file(const char *dirname, const unsigned char *rid)
if (!dirname)
dirname = "."; //openemv_config_get_str("capk.dir", NULL);
if (!dirname)
return NULL;
char *filename;
int ret = asprintf(&filename, "%s/%02hhx%02hhx%02hhx%02hhx%02hhx.pks",
dirname,

View file

@ -242,24 +242,25 @@ int JsonSaveTLVTree(json_t *root, json_t *elm, char *path, struct tlvdb *tlvdbel
bool HexToBuffer(const char *errormsg, const char *hexvalue, uint8_t * buffer, size_t maxbufferlen, size_t *bufferlen) {
int buflen = 0;
switch(param_gethex_to_eol(hexvalue, 0, buffer, maxbufferlen, &buflen)) {
case 1:
PrintAndLog("%s Invalid HEX value.", errormsg);
return false;
case 2:
PrintAndLog("%s Hex value too large.", errormsg);
return false;
case 3:
PrintAndLog("%s Hex value must have even number of digits.", errormsg);
return false;
switch (param_gethex_to_eol(hexvalue, 0, buffer, maxbufferlen, &buflen)) {
case 1:
PrintAndLog("%s Invalid HEX value.", errormsg);
return false;
case 2:
PrintAndLog("%s Hex value too large.", errormsg);
return false;
case 3:
PrintAndLog("%s Hex value must have even number of digits.", errormsg);
return false;
}
if (buflen > maxbufferlen) {
PrintAndLog("%s HEX length (%d) more than %d", errormsg, *bufferlen, maxbufferlen);
PrintAndLog("%s HEX length (%d) more than %d", errormsg, (bufferlen) ? *bufferlen : -1, maxbufferlen);
return false;
}
*bufferlen = buflen;
if ( bufferlen )
*bufferlen = buflen;
return true;
}

View file

@ -347,8 +347,10 @@ bool CheckrpIdHash(json_t *json, uint8_t *hash) {
uint8_t hash2[32] = {0};
JsonLoadStr(json, "$.RelyingPartyEntity.id", hashval);
sha256hash((uint8_t *)hashval, strlen(hashval), hash2);
int res = sha256hash((uint8_t *)hashval, strlen(hashval), hash2);
if (res)
return false;
return !memcmp(hash, hash2, 32);
}

View file

@ -115,10 +115,13 @@ int GetAskClock(const char *str, bool printAns) {
if (st == false) {
idx = DetectASKClock(bits, size, &clock, 20);
}
setClockGrid(clock, idx);
if ( clock > 0 ) {
setClockGrid(clock, idx);
}
// Only print this message if we're not looping something
if (printAns || g_debugMode)
PrintAndLogEx(NORMAL, "Auto-detected clock rate: %d, Best Starting Position: %d", clock, idx);
PrintAndLogEx(SUCCESS, "Auto-detected clock rate: %d, Best Starting Position: %d", clock, idx);
return clock;
}
@ -137,7 +140,7 @@ uint8_t GetPskCarrier(const char *str, bool printAns) {
if (( fc >> 8) == 10 && carrier == 8) return 0;
// Only print this message if we're not looping something
if (printAns)
PrintAndLogEx(NORMAL, "Auto-detected PSK carrier rate: %d", carrier);
PrintAndLogEx(SUCCESS, "Auto-detected PSK carrier rate: %d", carrier);
return carrier;
}
@ -159,7 +162,7 @@ int GetPskClock(const char* str, bool printAns) {
setClockGrid(clock, firstPhaseShiftLoc);
// Only print this message if we're not looping something
if (printAns)
PrintAndLogEx(NORMAL, "Auto-detected clock rate: %d", clock);
PrintAndLogEx(SUCCESS, "Auto-detected clock rate: %d", clock);
return clock;
}
@ -181,7 +184,7 @@ int GetNrzClock(const char* str, bool printAns) {
setClockGrid(clock, clkStartIdx);
// Only print this message if we're not looping something
if (printAns)
PrintAndLogEx(NORMAL, "Auto-detected clock rate: %d", clock);
PrintAndLogEx(SUCCESS, "Auto-detected clock rate: %d", clock);
return clock;
}
//by marshmellow
@ -200,7 +203,7 @@ int GetFskClock(const char* str, bool printAns) {
if ((fc1==10 && fc2==8) || (fc1==8 && fc2==5)){
if (printAns)
PrintAndLogEx(NORMAL, "Detected Field Clocks: FC/%d, FC/%d - Bit Clock: RF/%d", fc1, fc2, rf1);
PrintAndLogEx(SUCCESS, "Detected Field Clocks: FC/%d, FC/%d - Bit Clock: RF/%d", fc1, fc2, rf1);
setClockGrid(rf1, firstClockEdge);
return rf1;
}

View file

@ -59,6 +59,7 @@ THE SOFTWARE.
#include <string.h>
#include "crapto1/crapto1.h"
#include "parity.h"
#include "util.h"
// bitslice type
// while AVX supports 256 bit vector floating point operations, we need integer operations for boolean logic
@ -99,9 +100,6 @@ typedef union {
// size of nonce to be decrypted
#define KEYSTREAM_SIZE 24
// endianness conversion
#define rev32(word) ((((word) & 0xff) << 24) | ((((word) >> 8) & 0xff) << 16) | ((((word) >> 16) & 0xff) << 8) | ((((word) >> 24) & 0xff)))
// this needs to be compiled several times for each instruction set.
// For each instruction set, define a dedicated function name:
#if defined (__AVX512F__)
@ -184,7 +182,7 @@ void BITSLICE_TEST_NONCES(uint32_t nonces_to_bruteforce, uint32_t *bf_test_nonce
// bitslice nonces' 2nd to 4th byte
for (uint32_t i = 0; i < nonces_to_bruteforce; i++) {
for(uint32_t bit_idx = 0; bit_idx < KEYSTREAM_SIZE; bit_idx++){
bool bit = get_bit(KEYSTREAM_SIZE-1-bit_idx, rev32(bf_test_nonce[i] << 8));
bool bit = get_bit(KEYSTREAM_SIZE-1-bit_idx, BSWAP_32(bf_test_nonce[i] << 8));
if(bit){
bitsliced_encrypted_nonces[i][bit_idx].value = bs_ones.value;
} else {

View file

@ -170,7 +170,9 @@ crack_states_thread(void* x){
__atomic_fetch_add(&found_bs_key, key, __ATOMIC_SEQ_CST);
char progress_text[80];
sprintf(progress_text, "Brute force phase completed. Key found: %012" PRIx64, key);
char keystr[18];
sprintf(keystr, "%012" PRIx64 " ", key);
sprintf(progress_text, "Brute force phase completed. Key found: " _YELLOW_(%s), keystr);
hardnested_print_progress(thread_arg->num_acquired_nonces, progress_text, 0.0, 0);
break;
} else if(keys_found){
@ -311,6 +313,11 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint
uint64_t start_time = msclock();
#if defined(__linux__) || defined(__APPLE__)
if ( NUM_BRUTE_FORCE_THREADS < 0 )
return false;
#endif
pthread_t threads[NUM_BRUTE_FORCE_THREADS];
struct args {
bool silent;
@ -322,7 +329,7 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint
uint8_t *best_first_bytes;
} thread_args[NUM_BRUTE_FORCE_THREADS];
for(uint32_t i = 0; i < NUM_BRUTE_FORCE_THREADS; i++){
for (uint32_t i = 0; i < NUM_BRUTE_FORCE_THREADS; i++){
thread_args[i].thread_ID = i;
thread_args[i].silent = silent;
thread_args[i].cuid = cuid;
@ -332,7 +339,7 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint
thread_args[i].best_first_bytes = best_first_bytes;
pthread_create(&threads[i], NULL, crack_states_thread, (void*)&thread_args[i]);
}
for(uint32_t i = 0; i < NUM_BRUTE_FORCE_THREADS; i++){
for (uint32_t i = 0; i < NUM_BRUTE_FORCE_THREADS; i++){
pthread_join(threads[i], 0);
}

View file

@ -3,8 +3,7 @@
void jsonp_error_init(json_error_t *error, const char *source)
{
if(error)
{
if (error) {
error->text[0] = '\0';
error->line = -1;
error->column = -1;
@ -20,13 +19,13 @@ void jsonp_error_set_source(json_error_t *error, const char *source)
{
size_t length;
if(!error || !source)
if (!error || !source)
return;
length = strlen(source);
if(length < JSON_ERROR_SOURCE_LENGTH)
strncpy(error->source, source, JSON_ERROR_SOURCE_LENGTH);
else {
if (length < JSON_ERROR_SOURCE_LENGTH) {
strncpy(error->source, source, length);
} else {
size_t extra = length - JSON_ERROR_SOURCE_LENGTH + 4;
memcpy(error->source, "...", 3);
strncpy(error->source + 3, source + extra, length - extra + 1);
@ -38,7 +37,6 @@ void jsonp_error_set(json_error_t *error, int line, int column,
const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
jsonp_error_vset(error, line, column, position, code, msg, ap);
va_end(ap);
@ -48,10 +46,10 @@ void jsonp_error_vset(json_error_t *error, int line, int column,
size_t position, enum json_error_code code,
const char *msg, va_list ap)
{
if(!error)
if (!error)
return;
if(error->text[0] != '\0') {
if (error->text[0] != '\0') {
/* error already set */
return;
}

View file

@ -538,18 +538,19 @@ int bruteforceFile(const char *filename, uint16_t keytable[]) {
if (fsize < 0) {
PrintAndLogDevice(WARNING, "Error, when getting filesize");
if (f) fclose(f);
fclose(f);
return 1;
}
uint8_t *dump = calloc(fsize, sizeof(uint8_t));
if ( !dump ) {
PrintAndLogDevice(WARNING, "Failed to allocate memory");
fclose(f);
return 2;
}
size_t bytes_read = fread(dump, 1, fsize, f);
if (f) fclose(f);
fclose(f);
if (bytes_read < fsize) {
PrintAndLogDevice(WARNING, "Error, could only read %d bytes (should be %d)", bytes_read, fsize );

View file

@ -266,8 +266,8 @@ int loadFile(const char *preferredName, const char *suffix, void* data, size_t*
FILE *f = fopen(fileName, "rb");
if ( !f ) {
PrintAndLogDevice(WARNING, "file not found or locked. '" _YELLOW_(%s)"'", fileName);
retval = 1;
goto out;
free(fileName);
return 1;
}
// get filesize in order to malloc memory
@ -310,7 +310,12 @@ int loadFile(const char *preferredName, const char *suffix, void* data, size_t*
out:
fclose(f);
if (data)
free(data);
free(fileName);
return retval;
}
@ -318,6 +323,7 @@ int loadFileEML(const char *preferredName, const char *suffix, void* data, size_
if ( preferredName == NULL ) return 1;
if ( suffix == NULL ) return 1;
if ( data == NULL ) return 1;
size_t counter = 0;
int retval = 0, hexlen = 0;
@ -359,7 +365,9 @@ int loadFileEML(const char *preferredName, const char *suffix, void* data, size_
}
fclose(f);
PrintAndLogDevice(SUCCESS, "loaded %d bytes from text file " _YELLOW_(%s), counter, fileName);
*datalen = counter;
if ( datalen )
*datalen = counter;
out:
free(fileName);
@ -367,12 +375,14 @@ out:
}
int loadFileJSON(const char *preferredName, const char *suffix, void* data, size_t maxdatalen, size_t* datalen) {
*datalen = 0;
json_t *root;
json_error_t error;
if ( preferredName == NULL ) return 1;
if ( suffix == NULL ) return 1;
if ( data == NULL ) return 1;
*datalen = 0;
json_t *root;
json_error_t error;
int retval = 0;
int size = sizeof(char) * (strlen(preferredName) + strlen(suffix) + 10);
@ -456,6 +466,7 @@ int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data
if ( preferredName == NULL ) return 1;
if ( suffix == NULL ) return 1;
if ( data == NULL ) return 1;
// t5577 == 4bytes
// mifare == 6 bytes
@ -511,8 +522,10 @@ int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data
counter += (keylen >> 1);
}
fclose(f);
PrintAndLogDevice(SUCCESS, "loaded " _GREEN_(%2d) "keys from dictionary file " _YELLOW_(%s), *keycnt, fileName);
*datalen = counter;
PrintAndLogDevice(SUCCESS, "loaded " _GREEN_(%2d) "keys from dictionary file " _YELLOW_(%s), *keycnt, fileName);
if ( datalen )
*datalen = counter;
out:
free(fileName);
return retval;

View file

@ -428,8 +428,8 @@ void testPermute()
printarr("permuted", res, 8);
}
//These testcases are
//{ UID , TEMP_KEY, DIV_KEY} using the specific key
// These testcases are
// { UID , TEMP_KEY, DIV_KEY} using the specific key
typedef struct
{
uint8_t uid[8];
@ -475,7 +475,7 @@ int testDES(Testcase testcase, mbedtls_des_context ctx_enc, mbedtls_des_context
return retval;
}
bool des_getParityBitFromKey(uint8_t key)
{//The top 7 bits is used
{ // The top 7 bits is used
bool parity = ((key & 0x80) >> 7)
^ ((key & 0x40) >> 6) ^ ((key & 0x20) >> 5)
^ ((key & 0x10) >> 4) ^ ((key & 0x08) >> 3)
@ -676,7 +676,8 @@ static bool readKeyFile(uint8_t key[8]) {
bool retval = false;
//Test a few variants
char filename[30];
char filename[30] = {0};
if (fileExists("iclass_key.bin")){
sprintf(filename, "%s.bin", "iclass_key");
} else if (fileExists("loclass/iclass_key.bin")){
@ -685,6 +686,9 @@ static bool readKeyFile(uint8_t key[8]) {
sprintf(filename, "%s.bin", "client/loclass/iclass_key");
}
if ( strlen(filename) == 0 )
return retval;
FILE *f = fopen(filename, "rb");
if (!f)
return retval;

View file

@ -1,4 +1,4 @@
// Merlok, 2011, 2012
// Merlok, 2011, 2012, 2019
// people from mifare@nethemba.com, 2010
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
@ -982,11 +982,11 @@ int detect_classic_nackbug(bool verbose){
if (verbose) {
PrintAndLogEx(FAILED, "card random number generator seems to be based on the well-known generating polynomial");
PrintAndLogEx(NORMAL, "[- ]with 16 effective bits only, but shows unexpected behavior, try again.");
return 0;
}
return 2;
}
case 2 : PrintAndLogEx(SUCCESS, "always leak NACK detected"); return 3;
case 1 : PrintAndLogEx(SUCCESS, "NACK bug detected"); return 1;
case 2 : PrintAndLogEx(SUCCESS, _GREEN_(always leak NACK detected)); return 3;
case 1 : PrintAndLogEx(SUCCESS, _GREEN_(NACK bug detected)); return 1;
case 0 : PrintAndLogEx(SUCCESS, "No NACK bug detected"); return 2;
default : PrintAndLogEx(WARNING, "errorcode from device [%i]", ok); return 0;
}
@ -1007,9 +1007,9 @@ void detect_classic_magic(void) {
isGeneration = resp.arg[0] & 0xff;
switch( isGeneration ){
case 1: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1a): YES"); break;
case 2: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1b): YES"); break;
//case 4: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 2): YES"); break;
default: PrintAndLogEx(INFO, "Answers to magic commands: NO"); break;
case 1: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1a): " _GREEN_(YES)); break;
case 2: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1b): " _GREEN_(YES)); break;
//case 4: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 2): " _GREEN_(YES)); break;
default: PrintAndLogEx(INFO, "Answers to magic commands: " _YELLOW_(NO)); break;
}
}

View file

@ -1,4 +1,4 @@
// Merlok, 2011
// Merlok, 2011, 2019
// people from mifare@nethemba.com, 2010
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,

View file

@ -608,7 +608,7 @@ static int l_hardnested(lua_State *L){
char filename[FILE_PATH_SIZE]="nonces.bin";
const char *p_filename = luaL_checklstring(L, 11, &size);
if(size != 0)
strcpy(filename, p_filename);
memcpy(filename, p_filename, FILE_PATH_SIZE-1);
uint32_t blockNo = 0, keyType = 0;
uint32_t trgBlockNo = 0, trgKeyType = 0;

View file

@ -130,7 +130,7 @@ uint64_t msclock(void) {
#else
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (t.tv_sec * 1000 + t.tv_nsec / 1000000);
return ( 1000 * (uint64_t)t.tv_sec + t.tv_nsec / 1000000);
#endif
}

View file

@ -33,21 +33,6 @@ static void __attribute__((constructor)) fill_lut()
#define filter(x) (filterlut[(x) & 0xfffff])
#endif
/** binsearch
* Binary search for the first occurence of *stop's MSB in sorted [start,stop]
*/
/* static inline uint32_t* binsearch(uint32_t *start, uint32_t *stop)
{
uint32_t mid, val = *stop & 0xff000000;
while(start != stop)
if(start[mid = (stop - start) >> 1] > val)
stop = &start[mid];
else
start += mid + 1;
return start;
}
*/
/** update_contribution
* helper, calculates the partial linear feedback contributions and puts in MSB
*/
@ -174,7 +159,7 @@ struct Crypto1State* lfsr_recovery32(uint32_t ks2, uint32_t in)
// allocate memory for out of place bucket_sort
bucket_array_t bucket;
for (uint32_t i = 0; i < 2; i++) {
for (uint32_t j = 0; j <= 0xff; j++) {
bucket[i][j].head = malloc(sizeof(uint32_t) << 14);
@ -311,7 +296,7 @@ uint8_t lfsr_rollback_bit(struct Crypto1State *s, uint32_t in, int fb)
int out;
uint8_t ret;
uint32_t t;
s->odd &= 0xffffff;
t = s->odd, s->odd = s->even, s->even = t;
@ -329,12 +314,6 @@ uint8_t lfsr_rollback_bit(struct Crypto1State *s, uint32_t in, int fb)
*/
uint8_t lfsr_rollback_byte(struct Crypto1State *s, uint32_t in, int fb)
{
/*
int i, ret=0;
for (i = 7; i >= 0; --i)
ret |= lfsr_rollback_bit(s, BIT(in, i), fb) << i;
*/
// unfold loop 20160112
uint8_t ret = 0;
ret |= lfsr_rollback_bit(s, BIT(in, 7), fb) << 7;
ret |= lfsr_rollback_bit(s, BIT(in, 6), fb) << 6;
@ -351,13 +330,7 @@ uint8_t lfsr_rollback_byte(struct Crypto1State *s, uint32_t in, int fb)
*/
uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb)
{
/*
int i;
uint32_t ret = 0;
for (i = 31; i >= 0; --i)
ret |= lfsr_rollback_bit(s, BEBIT(in, i), fb) << (i ^ 24);
*/
// unfold loop 20160112
uint32_t ret = 0;
ret |= lfsr_rollback_bit(s, BEBIT(in, 31), fb) << (31 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 30), fb) << (30 ^ 24);
@ -376,7 +349,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb)
ret |= lfsr_rollback_bit(s, BEBIT(in, 18), fb) << (18 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 17), fb) << (17 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 16), fb) << (16 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 15), fb) << (15 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 14), fb) << (14 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 13), fb) << (13 ^ 24);
@ -385,7 +358,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb)
ret |= lfsr_rollback_bit(s, BEBIT(in, 10), fb) << (10 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 9), fb) << (9 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 8), fb) << (8 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 7), fb) << (7 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 6), fb) << (6 ^ 24);
ret |= lfsr_rollback_bit(s, BEBIT(in, 5), fb) << (5 ^ 24);
@ -445,7 +418,7 @@ uint32_t *lfsr_prefix_ks(uint8_t ks[8], int isodd)
{
uint32_t *candidates = calloc(4 << 10, sizeof(uint8_t));
if (!candidates) return 0;
uint32_t c, entry;
int size = 0, i, good;
@ -458,7 +431,7 @@ uint32_t *lfsr_prefix_ks(uint8_t ks[8], int isodd)
if (good)
candidates[size++] = i;
}
candidates[size] = -1;
return candidates;

View file

@ -48,9 +48,8 @@ struct Crypto1State * crypto1_create(uint64_t key)
if ( !s ) return NULL;
s->odd = s->even = 0;
int i;
//for(i = 47;s && i > 0; i -= 2) {
for(i = 47; i > 0; i -= 2) {
s->odd = s->odd << 1 | BIT(key, (i - 1) ^ 7);
s->even = s->even << 1 | BIT(key, i ^ 7);
@ -89,13 +88,6 @@ uint8_t crypto1_bit(struct Crypto1State *s, uint8_t in, int is_encrypted)
}
uint8_t crypto1_byte(struct Crypto1State *s, uint8_t in, int is_encrypted)
{
/*
uint8_t i, ret = 0;
for (i = 0; i < 8; ++i)
ret |= crypto1_bit(s, BIT(in, i), is_encrypted) << i;
*/
// unfold loop 20161012
uint8_t ret = 0;
ret |= crypto1_bit(s, BIT(in, 0), is_encrypted) << 0;
ret |= crypto1_bit(s, BIT(in, 1), is_encrypted) << 1;
@ -109,13 +101,6 @@ uint8_t crypto1_byte(struct Crypto1State *s, uint8_t in, int is_encrypted)
}
uint32_t crypto1_word(struct Crypto1State *s, uint32_t in, int is_encrypted)
{
/*
uint32_t i, ret = 0;
for (i = 0; i < 32; ++i)
ret |= crypto1_bit(s, BEBIT(in, i), is_encrypted) << (i ^ 24);
*/
//unfold loop 2016012
uint32_t ret = 0;
ret |= crypto1_bit(s, BEBIT(in, 0), is_encrypted) << (0 ^ 24);
ret |= crypto1_bit(s, BEBIT(in, 1), is_encrypted) << (1 ^ 24);
@ -125,7 +110,7 @@ uint32_t crypto1_word(struct Crypto1State *s, uint32_t in, int is_encrypted)
ret |= crypto1_bit(s, BEBIT(in, 5), is_encrypted) << (5 ^ 24);
ret |= crypto1_bit(s, BEBIT(in, 6), is_encrypted) << (6 ^ 24);
ret |= crypto1_bit(s, BEBIT(in, 7), is_encrypted) << (7 ^ 24);
ret |= crypto1_bit(s, BEBIT(in, 8), is_encrypted) << (8 ^ 24);
ret |= crypto1_bit(s, BEBIT(in, 9), is_encrypted) << (9 ^ 24);
ret |= crypto1_bit(s, BEBIT(in, 10), is_encrypted) << (10 ^ 24);

View file

@ -77,7 +77,7 @@ static void resetSignal(void) {
signalprop.isnoise = true;
}
static void printSignal(void) {
prnt("LF Signal properties:");
prnt("LF signal properties:");
prnt(" high..........%d", signalprop.high);
prnt(" low...........%d", signalprop.low);
prnt(" mean..........%d", signalprop.mean);
@ -1922,7 +1922,7 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s
dest[numBits++] = curPhase;
} else if (waveLenCnt < fc - 1) { //wave is smaller than field clock (shouldn't happen often)
errCnt2++;
if(errCnt2 > 101) return errCnt2;
if (errCnt2 > 101) return errCnt2;
avgWaveVal += dest[i+1];
continue;
}

View file

@ -389,6 +389,7 @@ void getMemConfig(uint8_t mem_cfg, uint8_t chip_cfg, uint8_t *max_blk, uint8_t *
#define T55x7_BITRATE_RF_64 0x00140000
#define T55x7_BITRATE_RF_100 0x00180000
#define T55x7_BITRATE_RF_128 0x001C0000
#define T55x7_TESTMODE_DISABLED 0x60000000
/* T5555 (Q5) configuration register definitions */
#define T5555_ST_TERMINATOR 0x00000001

View file

@ -62,350 +62,363 @@
typedef struct termios term_info;
typedef struct {
int fd; // Serial port file descriptor
term_info tiOld; // Terminal info before using the port
term_info tiNew; // Terminal info during the transaction
int fd; // Serial port file descriptor
term_info tiOld; // Terminal info before using the port
term_info tiNew; // Terminal info during the transaction
} serial_port_unix;
// Set time-out on 30 miliseconds
struct timeval timeout = {
.tv_sec = 0, // 0 second
.tv_usec = 30000 // 30000 micro seconds
.tv_sec = 0, // 0 second
.tv_usec = 30000 // 30 000 micro seconds
};
serial_port uart_open(const char* pcPortName)
{
serial_port_unix* sp = calloc(sizeof(serial_port_unix), sizeof(uint8_t));
if (sp == 0) return INVALID_SERIAL_PORT;
serial_port uart_open(const char* pcPortName) {
serial_port_unix* sp = calloc(sizeof(serial_port_unix), sizeof(uint8_t));
if (sp == 0) return INVALID_SERIAL_PORT;
if (memcmp(pcPortName, "tcp:", 4) == 0) {
struct addrinfo *addr, *rp;
char *addrstr = strdup(pcPortName + 4);
if (memcmp(pcPortName, "tcp:", 4) == 0) {
struct addrinfo *addr, *rp;
char *addrstr = strdup(pcPortName + 4);
if (addrstr == NULL) {
printf("Error: strdup\n");
return INVALID_SERIAL_PORT;
}
if (addrstr == NULL) {
printf("Error: strdup\n");
free(sp);
return INVALID_SERIAL_PORT;
}
char *colon = strrchr(addrstr, ':');
char *portstr;
timeout.tv_usec = 300000; // 300 000 micro seconds
char *colon = strrchr(addrstr, ':');
char *portstr;
if (colon) {
portstr = colon + 1;
*colon = '\0';
} else {
portstr = "7901";
}
// Set time-out to 300 miliseconds only for TCP port
timeout.tv_usec = 300000;
int s = getaddrinfo(addrstr, portstr, NULL, &addr);
if (s != 0) {
printf("Error: getaddrinfo: %s\n", gai_strerror(s));
freeaddrinfo(addr);
free(addrstr);
free(sp);
return INVALID_SERIAL_PORT;
}
if (colon) {
portstr = colon + 1;
*colon = '\0';
} else {
portstr = "7901";
int sfd;
for (rp = addr; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break;
close(sfd);
}
if (rp == NULL) { /* No address succeeded */
printf("Error: Could not connect\n");
freeaddrinfo(addr);
free(addrstr);
free(sp);
return INVALID_SERIAL_PORT;
}
freeaddrinfo(addr);
free(addrstr);
sp->fd = sfd;
int one = 1;
int res = setsockopt(sp->fd, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
if ( res != 0) {
free(sp);
return INVALID_SERIAL_PORT;
}
return sp;
}
int s = getaddrinfo(addrstr, portstr, NULL, &addr);
if (s != 0) {
printf("Error: getaddrinfo: %s\n", gai_strerror(s));
return INVALID_SERIAL_PORT;
}
int sfd;
for (rp = addr; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break;
close(sfd);
}
if (rp == NULL) { /* No address succeeded */
printf("Error: Could not connect\n");
return INVALID_SERIAL_PORT;
}
freeaddrinfo(addr);
free(addrstr);
sp->fd = sfd;
int one = 1;
setsockopt(sp->fd, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
return sp;
}
sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if(sp->fd == -1) {
uart_close(sp);
return INVALID_SERIAL_PORT;
}
sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (sp->fd == -1) {
uart_close(sp);
return INVALID_SERIAL_PORT;
}
// Finally figured out a way to claim a serial port interface under unix
// We just try to set a (advisory) lock on the file descriptor
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
// Does the system allows us to place a lock on this file descriptor
if (fcntl(sp->fd, F_SETLK, &fl) == -1) {
// A conflicting lock is held by another process
free(sp);
return CLAIMED_SERIAL_PORT;
}
// Finally figured out a way to claim a serial port interface under unix
// We just try to set a (advisory) lock on the file descriptor
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
// Does the system allows us to place a lock on this file descriptor
if (fcntl(sp->fd, F_SETLK, &fl) == -1) {
// A conflicting lock is held by another process
free(sp);
return CLAIMED_SERIAL_PORT;
}
// Try to retrieve the old (current) terminal info struct
if (tcgetattr(sp->fd,&sp->tiOld) == -1) {
uart_close(sp);
return INVALID_SERIAL_PORT;
}
// Duplicate the (old) terminal info struct
sp->tiNew = sp->tiOld;
// Configure the serial port
sp->tiNew.c_cflag = CS8 | CLOCAL | CREAD;
sp->tiNew.c_iflag = IGNPAR;
sp->tiNew.c_oflag = 0;
sp->tiNew.c_lflag = 0;
// Block until n bytes are received
sp->tiNew.c_cc[VMIN] = 0;
// Block until a timer expires (n * 100 mSec.)
sp->tiNew.c_cc[VTIME] = 0;
// Try to set the new terminal info struct
if (tcsetattr(sp->fd, TCSANOW, &sp->tiNew) == -1) {
uart_close(sp);
return INVALID_SERIAL_PORT;
}
// Try to retrieve the old (current) terminal info struct
if(tcgetattr(sp->fd,&sp->tiOld) == -1) {
uart_close(sp);
return INVALID_SERIAL_PORT;
}
// Duplicate the (old) terminal info struct
sp->tiNew = sp->tiOld;
// Configure the serial port
sp->tiNew.c_cflag = CS8 | CLOCAL | CREAD;
sp->tiNew.c_iflag = IGNPAR;
sp->tiNew.c_oflag = 0;
sp->tiNew.c_lflag = 0;
// Block until n bytes are received
sp->tiNew.c_cc[VMIN] = 0;
// Block until a timer expires (n * 100 mSec.)
sp->tiNew.c_cc[VTIME] = 0;
// Try to set the new terminal info struct
if(tcsetattr(sp->fd, TCSANOW, &sp->tiNew) == -1) {
uart_close(sp);
return INVALID_SERIAL_PORT;
}
// Flush all lingering data that may exist
tcflush(sp->fd, TCIOFLUSH);
#ifdef WITH_FPC
if ( uart_set_speed(sp, 115200) ) {
printf("[=] UART Setting serial baudrate 115200 [FPC enabled]\n");
printf("[=] UART Setting serial baudrate 115200 [FPC enabled]\n");
} else {
uart_set_speed(sp, 9600);
printf("[=] UART Setting serial baudrate 9600 [FPC enabled]\n");
}
#else
// set speed, works for UBUNTU 14.04
bool success = uart_set_speed(sp, 460800);
if (success) {
printf("[=] UART Setting serial baudrate 460800\n");
} else {
uart_set_speed(sp, 115200);
printf("[=] UART Setting serial baudrate 115200\n");
}
// set speed, works for UBUNTU 14.04
bool success = uart_set_speed(sp, 460800);
if (success) {
printf("[=] UART Setting serial baudrate 460800\n");
} else {
uart_set_speed(sp, 115200);
printf("[=] UART Setting serial baudrate 115200\n");
}
#endif
return sp;
return sp;
}
void uart_close(const serial_port sp) {
serial_port_unix* spu = (serial_port_unix*)sp;
tcflush(spu->fd, TCIOFLUSH);
tcsetattr(spu->fd, TCSANOW, &(spu->tiOld));
struct flock fl;
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
serial_port_unix* spu = (serial_port_unix*)sp;
tcflush(spu->fd, TCIOFLUSH);
tcsetattr(spu->fd, TCSANOW, &(spu->tiOld));
struct flock fl;
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
// Does the system allows us to place a lock on this file descriptor
int err = fcntl(spu->fd, F_SETLK, &fl);
if ( err == -1) {
//perror("fcntl");
}
close(spu->fd);
free(sp);
// Does the system allows us to place a lock on this file descriptor
int err = fcntl(spu->fd, F_SETLK, &fl);
if ( err == -1) {
//perror("fcntl");
}
close(spu->fd);
free(sp);
}
bool uart_receive(const serial_port sp, uint8_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen) {
int res;
int byteCount;
fd_set rfds;
struct timeval tv;
int res;
int byteCount;
fd_set rfds;
struct timeval tv;
// Reset the output count
*pszRxLen = 0;
// Reset the output count
*pszRxLen = 0;
do {
// Reset file descriptor
FD_ZERO(&rfds);
FD_SET(((serial_port_unix*)sp)->fd, &rfds);
tv = timeout;
res = select(((serial_port_unix*)sp)->fd + 1, &rfds, NULL, NULL, &tv);
// Read error
if (res < 0) {
return false;
}
// Read time-out
if (res == 0) {
if (*pszRxLen == 0) {
// Error, we received no data
return false;
} else {
// We received some data, but nothing more is available
return true;
}
}
// Retrieve the count of the incoming bytes
res = ioctl(((serial_port_unix*)sp)->fd, FIONREAD, &byteCount);
if (res < 0) return false;
// Cap the number of bytes, so we don't overrun the buffer
if (pszMaxRxLen - (*pszRxLen) < byteCount) {
byteCount = pszMaxRxLen - (*pszRxLen);
}
do {
// Reset file descriptor
FD_ZERO(&rfds);
FD_SET(((serial_port_unix*)sp)->fd, &rfds);
tv = timeout;
res = select(((serial_port_unix*)sp)->fd + 1, &rfds, NULL, NULL, &tv);
// There is something available, read the data
res = read(((serial_port_unix*)sp)->fd, pbtRx + (*pszRxLen), byteCount);
// Read error
if (res < 0) {
return false;
}
// Stop if the OS has some troubles reading the data
if (res <= 0) return false;
*pszRxLen += res;
// Read time-out
if (res == 0) {
if (*pszRxLen == 0) {
// Error, we received no data
return false;
} else {
// We received some data, but nothing more is available
return true;
}
}
if (*pszRxLen == pszMaxRxLen) {
// We have all the data we wanted.
return true;
}
} while (byteCount);
// Retrieve the count of the incoming bytes
res = ioctl(((serial_port_unix*)sp)->fd, FIONREAD, &byteCount);
if (res < 0) return false;
return true;
// Cap the number of bytes, so we don't overrun the buffer
if (pszMaxRxLen - (*pszRxLen) < byteCount) {
byteCount = pszMaxRxLen - (*pszRxLen);
}
// There is something available, read the data
res = read(((serial_port_unix*)sp)->fd, pbtRx + (*pszRxLen), byteCount);
// Stop if the OS has some troubles reading the data
if (res <= 0) return false;
*pszRxLen += res;
if (*pszRxLen == pszMaxRxLen) {
// We have all the data we wanted.
return true;
}
} while (byteCount);
return true;
}
bool uart_send(const serial_port sp, const uint8_t* pbtTx, const size_t len) {
int32_t res;
size_t pos = 0;
fd_set rfds;
struct timeval tv;
int32_t res;
size_t pos = 0;
fd_set rfds;
struct timeval tv;
while (pos < len) {
// Reset file descriptor
FD_ZERO(&rfds);
FD_SET(((serial_port_unix*)sp)->fd, &rfds);
tv = timeout;
res = select(((serial_port_unix*)sp)->fd+1, NULL, &rfds, NULL, &tv);
// Write error
if (res < 0) {
printf("UART:: write error (%d)\n", res);
return false;
}
// Write time-out
if (res == 0) {
printf("UART:: write time-out\n");
return false;
}
// Send away the bytes
res = write(((serial_port_unix*)sp)->fd, pbtTx + pos, len - pos);
// Stop if the OS has some troubles sending the data
if (res <= 0) return false;
pos += res;
}
return true;
while (pos < len) {
// Reset file descriptor
FD_ZERO(&rfds);
FD_SET(((serial_port_unix*)sp)->fd, &rfds);
tv = timeout;
res = select(((serial_port_unix*)sp)->fd+1, NULL, &rfds, NULL, &tv);
// Write error
if (res < 0) {
printf("UART:: write error (%d)\n", res);
return false;
}
// Write time-out
if (res == 0) {
printf("UART:: write time-out\n");
return false;
}
// Send away the bytes
res = write(((serial_port_unix*)sp)->fd, pbtTx + pos, len - pos);
// Stop if the OS has some troubles sending the data
if (res <= 0) return false;
pos += res;
}
return true;
}
bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) {
const serial_port_unix* spu = (serial_port_unix*)sp;
speed_t stPortSpeed;
switch (uiPortSpeed) {
case 0: stPortSpeed = B0; break;
case 50: stPortSpeed = B50; break;
case 75: stPortSpeed = B75; break;
case 110: stPortSpeed = B110; break;
case 134: stPortSpeed = B134; break;
case 150: stPortSpeed = B150; break;
case 300: stPortSpeed = B300; break;
case 600: stPortSpeed = B600; break;
case 1200: stPortSpeed = B1200; break;
case 1800: stPortSpeed = B1800; break;
case 2400: stPortSpeed = B2400; break;
case 4800: stPortSpeed = B4800; break;
case 9600: stPortSpeed = B9600; break;
case 19200: stPortSpeed = B19200; break;
case 38400: stPortSpeed = B38400; break;
const serial_port_unix* spu = (serial_port_unix*)sp;
speed_t stPortSpeed;
switch (uiPortSpeed) {
case 0: stPortSpeed = B0; break;
case 50: stPortSpeed = B50; break;
case 75: stPortSpeed = B75; break;
case 110: stPortSpeed = B110; break;
case 134: stPortSpeed = B134; break;
case 150: stPortSpeed = B150; break;
case 300: stPortSpeed = B300; break;
case 600: stPortSpeed = B600; break;
case 1200: stPortSpeed = B1200; break;
case 1800: stPortSpeed = B1800; break;
case 2400: stPortSpeed = B2400; break;
case 4800: stPortSpeed = B4800; break;
case 9600: stPortSpeed = B9600; break;
case 19200: stPortSpeed = B19200; break;
case 38400: stPortSpeed = B38400; break;
# ifdef B57600
case 57600: stPortSpeed = B57600; break;
case 57600: stPortSpeed = B57600; break;
# endif
# ifdef B115200
case 115200: stPortSpeed = B115200; break;
case 115200: stPortSpeed = B115200; break;
# endif
# ifdef B230400
case 230400: stPortSpeed = B230400; break;
case 230400: stPortSpeed = B230400; break;
# endif
# ifdef B460800
case 460800: stPortSpeed = B460800; break;
case 460800: stPortSpeed = B460800; break;
# endif
# ifdef B921600
case 921600: stPortSpeed = B921600; break;
case 921600: stPortSpeed = B921600; break;
# endif
default: return false;
};
struct termios ti;
if (tcgetattr(spu->fd,&ti) == -1) return false;
// Set port speed (Input and Output)
cfsetispeed(&ti, stPortSpeed);
cfsetospeed(&ti, stPortSpeed);
return (tcsetattr(spu->fd, TCSANOW, &ti) != -1);
default: return false;
};
struct termios ti;
if (tcgetattr(spu->fd,&ti) == -1)
return false;
// Set port speed (Input and Output)
cfsetispeed(&ti, stPortSpeed);
cfsetospeed(&ti, stPortSpeed);
return (tcsetattr(spu->fd, TCSANOW, &ti) != -1);
}
uint32_t uart_get_speed(const serial_port sp) {
struct termios ti;
uint32_t uiPortSpeed;
const serial_port_unix* spu = (serial_port_unix*)sp;
if (tcgetattr(spu->fd, &ti) == -1) return 0;
// Set port speed (Input)
speed_t stPortSpeed = cfgetispeed(&ti);
switch (stPortSpeed) {
case B0: uiPortSpeed = 0; break;
case B50: uiPortSpeed = 50; break;
case B75: uiPortSpeed = 75; break;
case B110: uiPortSpeed = 110; break;
case B134: uiPortSpeed = 134; break;
case B150: uiPortSpeed = 150; break;
case B300: uiPortSpeed = 300; break;
case B600: uiPortSpeed = 600; break;
case B1200: uiPortSpeed = 1200; break;
case B1800: uiPortSpeed = 1800; break;
case B2400: uiPortSpeed = 2400; break;
case B4800: uiPortSpeed = 4800; break;
case B9600: uiPortSpeed = 9600; break;
case B19200: uiPortSpeed = 19200; break;
case B38400: uiPortSpeed = 38400; break;
struct termios ti;
uint32_t uiPortSpeed;
const serial_port_unix* spu = (serial_port_unix*)sp;
if (tcgetattr(spu->fd, &ti) == -1)
return 0;
// Set port speed (Input)
speed_t stPortSpeed = cfgetispeed(&ti);
switch (stPortSpeed) {
case B0: uiPortSpeed = 0; break;
case B50: uiPortSpeed = 50; break;
case B75: uiPortSpeed = 75; break;
case B110: uiPortSpeed = 110; break;
case B134: uiPortSpeed = 134; break;
case B150: uiPortSpeed = 150; break;
case B300: uiPortSpeed = 300; break;
case B600: uiPortSpeed = 600; break;
case B1200: uiPortSpeed = 1200; break;
case B1800: uiPortSpeed = 1800; break;
case B2400: uiPortSpeed = 2400; break;
case B4800: uiPortSpeed = 4800; break;
case B9600: uiPortSpeed = 9600; break;
case B19200: uiPortSpeed = 19200; break;
case B38400: uiPortSpeed = 38400; break;
# ifdef B57600
case B57600: uiPortSpeed = 57600; break;
case B57600: uiPortSpeed = 57600; break;
# endif
# ifdef B115200
case B115200: uiPortSpeed = 115200; break;
case B115200: uiPortSpeed = 115200; break;
# endif
# ifdef B230400
case B230400: uiPortSpeed = 230400; break;
case B230400: uiPortSpeed = 230400; break;
# endif
# ifdef B460800
case B460800: uiPortSpeed = 460800; break;
case B460800: uiPortSpeed = 460800; break;
# endif
# ifdef B921600
case B921600: uiPortSpeed = 921600; break;
case B921600: uiPortSpeed = 921600; break;
# endif
default: return 0;
};
return uiPortSpeed;
default: return 0;
};
return uiPortSpeed;
}
#endif