From 87d0ba5dbc67d70e6465c05f44ceb403d3f8afe2 Mon Sep 17 00:00:00 2001 From: Michael Farrell Date: Tue, 17 Oct 2017 22:30:23 +1100 Subject: [PATCH 1/4] Refactor the comms code only from PR#346, without comms_globals.h --- client/Makefile | 10 +- client/cmdlf.c | 8 +- client/cmdmain.c | 139 +------------------ client/cmdmain.h | 7 +- client/cmdparser.c | 3 +- client/comms.c | 304 +++++++++++++++++++++++++++++++++++++++++ client/comms.h | 45 ++++++ client/flash.c | 77 +++++++---- client/flash.h | 5 +- client/flasher.c | 85 ++++-------- client/proxgui.cpp | 12 +- client/proxgui.h | 4 +- client/proxguiqt.h | 4 +- client/proxmark3.c | 104 ++++---------- client/proxmark3.h | 3 +- client/ui.c | 12 +- client/ui.h | 8 +- common/iso15693tools.c | 3 +- include/usb_cmd.h | 2 +- 19 files changed, 512 insertions(+), 323 deletions(-) create mode 100644 client/comms.c create mode 100644 client/comms.h diff --git a/client/Makefile b/client/Makefile index 3a96e9e9..e14939e3 100644 --- a/client/Makefile +++ b/client/Makefile @@ -21,7 +21,7 @@ LDLIBS = -L/opt/local/lib -L/usr/local/lib -lreadline -lpthread -lm LUALIB = ../liblua/liblua.a LDFLAGS = $(ENV_LDFLAGS) CFLAGS = $(ENV_CFLAGS) -std=c99 -D_ISOC99_SOURCE -I. -I../include -I../common -I../zlib -I../uart -I/opt/local/include -I../liblua -Wall -g -O3 -CXXFLAGS = -I../include -Wall -O3 +CXXFLAGS = -I../include -I../uart -Wall -O3 LUAPLATFORM = generic platform = $(shell uname) @@ -82,7 +82,10 @@ POSTCOMPILE = $(MV) -f $(OBJDIR)/$*.Td $(OBJDIR)/$*.d CORESRCS = uart_posix.c \ uart_win32.c \ util.c \ - util_posix.c + util_posix.c \ + comms.c \ + data.c \ + ui.c CMDSRCS = crapto1/crapto1.c\ crapto1/crypto1.c\ @@ -102,9 +105,7 @@ CMDSRCS = crapto1/crapto1.c\ crc64.c \ iso14443crc.c \ iso15693tools.c \ - data.c \ graph.c \ - ui.c \ cmddata.c \ lfdemod.c \ cmdhf.c \ @@ -175,6 +176,7 @@ ZLIBFLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED #-DDEBUG -Dverbose=1 QTGUISRCS = proxgui.cpp proxguiqt.cpp proxguiqt.moc.cpp guidummy.cpp +NOGUISRCS = guidummy.cpp COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) CMDOBJS = $(CMDSRCS:%.c=$(OBJDIR)/%.o) diff --git a/client/cmdlf.c b/client/cmdlf.c index eb664a11..501bfaed 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -335,7 +335,7 @@ int CmdLFSetConfig(const char *Cmd) } bool lf_read(bool silent, uint32_t samples) { - if (offline) return false; + if (IsOffline()) return false; UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_125K, {silent,samples,0}}; clearCommandBuffer(); //And ship it to device @@ -878,7 +878,7 @@ int CmdVchDemod(const char *Cmd) int CheckChipType(char cmdp) { uint32_t wordData = 0; - if (offline || cmdp == '1') return 0; + if (IsOffline() || cmdp == '1') return 0; save_restoreGB(GRAPH_SAVE); save_restoreDB(GRAPH_SAVE); @@ -923,7 +923,7 @@ int CmdLFfind(const char *Cmd) return 0; } - if (!offline && (cmdp != '1')) { + if (!IsOffline() && (cmdp != '1')) { lf_read(true, 30000); } else if (GraphTraceLen < minLength) { PrintAndLog("Data in Graphbuffer was too small."); @@ -939,7 +939,7 @@ int CmdLFfind(const char *Cmd) // only run if graphbuffer is just noise as it should be for hitag/cotag if (graphJustNoise(GraphBuffer, testLen)) { // only run these tests if we are in online mode - if (!offline && (cmdp != '1')) { + if (!IsOffline() && (cmdp != '1')) { // test for em4x05 in reader talk first mode. if (EM4x05Block0Test(&wordData)) { PrintAndLog("\nValid EM4x05/EM4x69 Chip Found\nUse lf em 4x05readword/dump commands to read\n"); diff --git a/client/cmdmain.c b/client/cmdmain.c index db88b3ac..94174f99 100644 --- a/client/cmdmain.c +++ b/client/cmdmain.c @@ -34,14 +34,6 @@ static int CmdHelp(const char *Cmd); static int CmdQuit(const char *Cmd); static int CmdRev(const char *Cmd); -//For storing command that are received from the device -#define CMD_BUFFER_SIZE 50 -static UsbCommand cmdBuffer[CMD_BUFFER_SIZE]; -//Points to the next empty position to write to -static int cmd_head;//Starts as 0 -//Points to the position of the last unread command -static int cmd_tail;//Starts as 0 - static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help. Use ' help' for details of a particular command."}, @@ -60,6 +52,7 @@ command_t* getTopLevelCommandTable() { return CommandTable; } + int CmdHelp(const char *Cmd) { CmdsHelp(CommandTable); @@ -77,101 +70,6 @@ int CmdRev(const char *Cmd) return 0; } -/** - * @brief This method should be called when sending a new command to the pm3. In case any old - * responses from previous commands are stored in the buffer, a call to this method should clear them. - * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which - * operation. Right now we'll just have to live with this. - */ -void clearCommandBuffer() -{ - //This is a very simple operation - cmd_tail = cmd_head; -} - -/** - * @brief storeCommand stores a USB command in a circular buffer - * @param UC - */ -void storeCommand(UsbCommand *command) -{ - if( ( cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail) - { - //If these two are equal, we're about to overwrite in the - // circular buffer. - PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!"); - } - //Store the command at the 'head' location - UsbCommand* destination = &cmdBuffer[cmd_head]; - memcpy(destination, command, sizeof(UsbCommand)); - - cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap -} - - -/** - * @brief getCommand gets a command from an internal circular buffer. - * @param response location to write command - * @return 1 if response was returned, 0 if nothing has been received - */ -int getCommand(UsbCommand* response) -{ - //If head == tail, there's nothing to read, or if we just got initialized - if(cmd_head == cmd_tail){ - return 0; - } - //Pick out the next unread command - UsbCommand* last_unread = &cmdBuffer[cmd_tail]; - memcpy(response, last_unread, sizeof(UsbCommand)); - //Increment tail - this is a circular buffer, so modulo buffer size - cmd_tail = (cmd_tail +1 ) % CMD_BUFFER_SIZE; - - return 1; -} - - -/** - * Waits for a certain response type. This method waits for a maximum of - * ms_timeout milliseconds for a specified response command. - *@brief WaitForResponseTimeout - * @param cmd command to wait for - * @param response struct to copy received command into. - * @param ms_timeout - * @return true if command was returned, otherwise false - */ -bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) { - - UsbCommand resp; - - if (response == NULL) { - response = &resp; - } - - // Wait until the command is received - for(size_t dm_seconds=0; dm_seconds < ms_timeout/10; dm_seconds++) { - while(getCommand(response)) { - if(response->cmd == cmd){ - return true; - } - } - msleep(10); // XXX ugh - if (dm_seconds == 200 && show_warning) { // Two seconds elapsed - PrintAndLog("Waiting for a response from the proxmark..."); - PrintAndLog("Don't forget to cancel its operation first by pressing on the button"); - } - } - return false; -} - -bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) { - return WaitForResponseTimeoutW(cmd, response, ms_timeout, true); -} - -bool WaitForResponse(uint32_t cmd, UsbCommand* response) { - return WaitForResponseTimeoutW(cmd, response, -1, true); -} - - //----------------------------------------------------------------------------- // Entry point into our code: called whenever the user types a command and // then presses Enter, which the full command line that they typed. @@ -180,38 +78,3 @@ int CommandReceived(char *Cmd) { return CmdsParse(CommandTable, Cmd); } - -//----------------------------------------------------------------------------- -// Entry point into our code: called whenever we received a packet over USB -// that we weren't necessarily expecting, for example a debug print. -//----------------------------------------------------------------------------- -void UsbCommandReceived(UsbCommand *UC) -{ - switch(UC->cmd) { - // First check if we are handling a debug message - case CMD_DEBUG_PRINT_STRING: { - char s[USB_CMD_DATA_SIZE+1]; - memset(s, 0x00, sizeof(s)); - size_t len = MIN(UC->arg[0],USB_CMD_DATA_SIZE); - memcpy(s,UC->d.asBytes,len); - PrintAndLog("#db# %s", s); - return; - } break; - - case CMD_DEBUG_PRINT_INTEGERS: { - PrintAndLog("#db# %08x, %08x, %08x \r\n", UC->arg[0], UC->arg[1], UC->arg[2]); - return; - } break; - - case CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K: { - memcpy(sample_buf+(UC->arg[0]),UC->d.asBytes,UC->arg[1]); - return; - } break; - - default: - storeCommand(UC); - break; - } - -} - diff --git a/client/cmdmain.h b/client/cmdmain.h index d39bc114..a833b41e 100644 --- a/client/cmdmain.h +++ b/client/cmdmain.h @@ -15,13 +15,10 @@ #include #include "usb_cmd.h" #include "cmdparser.h" +#include "comms.h" + -extern void UsbCommandReceived(UsbCommand *UC); extern int CommandReceived(char *Cmd); -extern bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning); -extern bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout); -extern bool WaitForResponse(uint32_t cmd, UsbCommand* response); -extern void clearCommandBuffer(); extern command_t* getTopLevelCommandTable(); #endif diff --git a/client/cmdparser.c b/client/cmdparser.c index 32508997..28ca2196 100644 --- a/client/cmdparser.c +++ b/client/cmdparser.c @@ -14,6 +14,7 @@ #include "ui.h" #include "cmdparser.h" #include "proxmark3.h" +#include "comms.h" void CmdsHelp(const command_t Commands[]) @@ -23,7 +24,7 @@ void CmdsHelp(const command_t Commands[]) int i = 0; while (Commands[i].Name) { - if (!offline || Commands[i].Offline) + if (!IsOffline() || Commands[i].Offline) PrintAndLog("%-16s %s", Commands[i].Name, Commands[i].Help); ++i; } diff --git a/client/comms.c b/client/comms.c new file mode 100644 index 00000000..a1f85799 --- /dev/null +++ b/client/comms.c @@ -0,0 +1,304 @@ +//----------------------------------------------------------------------------- +// Copyright (C) 2009 Michael Gernoth +// Copyright (C) 2010 iZsh +// +// 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. +//----------------------------------------------------------------------------- +// Code for communicating with the proxmark3 hardware. +//----------------------------------------------------------------------------- + +#include + +#include "comms.h" +#include "uart.h" +#include "ui.h" +#include "common.h" +#include "data.h" +#include "util_posix.h" + +// Declare globals. + +// Serial port that we are communicating with the PM3 on. +static serial_port* port; + +// If TRUE, then there is no active connection to the PM3, and we will drop commands sent. +static bool offline; + +// Transmit buffer. +// TODO: Use locks and execute this on the main thread, rather than the receiver +// thread. Running on the main thread means we need to be careful in the +// flasher, as it means SendCommand is no longer async, and can't be used as a +// buffer for a pending command when the connection is re-established. +static UsbCommand txcmd; +static bool txcmd_pending; + +// Used by UsbReceiveCommand as a ring buffer for messages that are yet to be +// processed by a command handler (WaitForResponse{,Timeout}) +static UsbCommand cmdBuffer[CMD_BUFFER_SIZE]; + +// Points to the next empty position to write to +static int cmd_head = 0; + +// Points to the position of the last unread command +static int cmd_tail = 0; + +// These wrappers are required because it is not possible to access a static +// global variable outside of the context of a single file. + +void SetSerialPort(serial_port* new_port) { + port = new_port; +} + +serial_port* GetSerialPort() { + return port; +} + +void SetOffline(bool new_offline) { + offline = new_offline; +} + +bool IsOffline() { + return offline; +} + +void SendCommand(UsbCommand *c) { + #ifdef COMMS_DEBUG + printf("Sending %04x cmd\n", c->cmd); + #endif + + if (offline) { + PrintAndLog("Sending bytes to proxmark failed - offline"); + return; + } + /** + The while-loop below causes hangups at times, when the pm3 unit is unresponsive + or disconnected. The main console thread is alive, but comm thread just spins here. + Not good.../holiman + **/ + while(txcmd_pending); + txcmd = *c; + txcmd_pending = true; +} + +/** + * @brief This method should be called when sending a new command to the pm3. In case any old + * responses from previous commands are stored in the buffer, a call to this method should clear them. + * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which + * operation. Right now we'll just have to live with this. + */ +void clearCommandBuffer() +{ + //This is a very simple operation + cmd_tail = cmd_head; +} + +/** + * @brief storeCommand stores a USB command in a circular buffer + * @param UC + */ +void storeCommand(UsbCommand *command) +{ + if( (cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail) + { + //If these two are equal, we're about to overwrite in the + // circular buffer. + PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!"); + } + //Store the command at the 'head' location + UsbCommand* destination = &cmdBuffer[cmd_head]; + memcpy(destination, command, sizeof(UsbCommand)); + + cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap +} + + +/** + * @brief getCommand gets a command from an internal circular buffer. + * @param response location to write command + * @return 1 if response was returned, 0 if nothing has been received + */ +int getCommand(UsbCommand* response) +{ + //If head == tail, there's nothing to read, or if we just got initialized + if (cmd_head == cmd_tail){ + return 0; + } + //Pick out the next unread command + UsbCommand* last_unread = &cmdBuffer[cmd_tail]; + memcpy(response, last_unread, sizeof(UsbCommand)); + //Increment tail - this is a circular buffer, so modulo buffer size + cmd_tail = (cmd_tail + 1) % CMD_BUFFER_SIZE; + + return 1; +} + +//----------------------------------------------------------------------------- +// Entry point into our code: called whenever we received a packet over USB +// that we weren't necessarily expecting, for example a debug print. +//----------------------------------------------------------------------------- +void UsbCommandReceived(UsbCommand *UC) +{ + switch(UC->cmd) { + + // First check if we are handling a debug message + case CMD_DEBUG_PRINT_STRING: { + char s[USB_CMD_DATA_SIZE+1]; + memset(s, 0x00, sizeof(s)); + size_t len = MIN(UC->arg[0],USB_CMD_DATA_SIZE); + memcpy(s,UC->d.asBytes,len); + PrintAndLog("#db# %s", s); + return; + } + + case CMD_DEBUG_PRINT_INTEGERS: { + PrintAndLog("#db# %08x, %08x, %08x \r\n", UC->arg[0], UC->arg[1], UC->arg[2]); + return; + } + + case CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K: { + // FIXME: This does unsanitised copies into memory when we don't know + // the size of the buffer. + if (sample_buf) { + memcpy(sample_buf+(UC->arg[0]),UC->d.asBytes,UC->arg[1]); + } + return; + } + + default: { + storeCommand(UC); + return; + } + } +} + +// Gets a single command from a proxmark3 device. This should never be used +// with the full client. +// +// @param conn A receiver_arg structure. +// @param command A buffer to store the received command. +bool ReceiveCommand(receiver_arg* conn, UsbCommand* command) { + // Local recieve buffer + size_t rxlen; + byte_t rx[sizeof(UsbCommand)]; + byte_t* prx = rx; + + while (conn->run) { + rxlen = 0; + if (uart_receive(port, prx, sizeof(UsbCommand) - (prx-rx), &rxlen)) { + prx += rxlen; + if (prx-rx < sizeof(UsbCommand)) { + // Keep reading until we have a completed response. + continue; + } + + // We have a completed response. + memcpy(command, rx, sizeof(UsbCommand)); + return true; + } + + if (prx == rx) { + // We got no complete command while waiting, give up control + return false; + } + } + + // did not get a complete command before being cancelled. + return false; +} + +// Worker thread for processing incoming events from the PM3 +void *uart_receiver(void *targ) { + receiver_arg *conn = (receiver_arg*)targ; + UsbCommand rx; + + while (conn->run) { + #ifdef COMMS_DEBUG + printf("uart_receiver: get lock\n"); + #endif + // Lock up receives, in case they try to take it away from us. + pthread_mutex_lock(&conn->recv_lock); + #ifdef COMMS_DEBUG + printf("uart_receiver: lock acquired\n"); + #endif + + if (port == NULL) { + #ifdef COMMS_DEBUG + printf("uart_receiver: port disappeared\n"); + #endif + // Our port disappeared, stall. This code path matters for the flasher, + // where it is fiddling with the serial port under us. + pthread_mutex_unlock(&conn->recv_lock); + msleep(10); + continue; + } + + bool got_command = ReceiveCommand(conn, &rx); + #ifdef COMMS_DEBUG + printf("uart_receiver: got command\n"); + #endif + pthread_mutex_unlock(&conn->recv_lock); + + if (got_command) { + UsbCommandReceived(&rx); + } + + // We aren't normally trying to transmit in the flasher when the port would + // be reset, so we can just keep going at this point. + if (txcmd_pending) { + if (!uart_send(port, (byte_t*) &txcmd, sizeof(UsbCommand))) { + PrintAndLog("Sending bytes to proxmark failed"); + } + txcmd_pending = false; + } + } + + pthread_exit(NULL); + return NULL; +} + +/** + * Waits for a certain response type. This method waits for a maximum of + * ms_timeout milliseconds for a specified response command. + *@brief WaitForResponseTimeout + * @param cmd command to wait for, or CMD_ANY to take any command. + * @param response struct to copy received command into. + * @param ms_timeout + * @param show_warning + * @return true if command was returned, otherwise false + */ +bool WaitForResponseTimeoutW(uint64_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) { + UsbCommand resp; + + #ifdef COMMS_DEBUG + printf("Waiting for %04x cmd\n", cmd); + #endif + + if (response == NULL) { + response = &resp; + } + + // Wait until the command is received + for(size_t dm_seconds=0; dm_seconds < ms_timeout/10; dm_seconds++) { + while(getCommand(response)) { + if (cmd == CMD_ANY || response->cmd == cmd) { + return true; + } + } + msleep(10); // XXX ugh + if (dm_seconds == 200 && show_warning) { // Two seconds elapsed + PrintAndLog("Waiting for a response from the proxmark..."); + PrintAndLog("Don't forget to cancel its operation first by pressing on the button"); + } + } + return false; +} + +bool WaitForResponseTimeout(uint64_t cmd, UsbCommand* response, size_t ms_timeout) { + return WaitForResponseTimeoutW(cmd, response, ms_timeout, true); +} + +bool WaitForResponse(uint64_t cmd, UsbCommand* response) { + return WaitForResponseTimeout(cmd, response, -1); +} diff --git a/client/comms.h b/client/comms.h new file mode 100644 index 00000000..75adeea1 --- /dev/null +++ b/client/comms.h @@ -0,0 +1,45 @@ +#ifndef COMMS_H_ +#define COMMS_H_ + +#include +#include + +#include "usb_cmd.h" +#include "uart.h" + +#ifndef CMD_BUFFER_SIZE +#define CMD_BUFFER_SIZE 50 +#endif + +#ifndef MAX_DEMOD_BUF_LEN +#define MAX_DEMOD_BUF_LEN (1024*128) +#endif + +#ifndef BIGBUF_SIZE +#define BIGBUF_SIZE 40000 +#endif + +typedef struct { + // If TRUE, continue running the uart_receiver thread. + bool run; + + // Lock around serial port receives + pthread_mutex_t recv_lock; +} receiver_arg; + + +// Wrappers required as static variables can only be used in one file. +void SetSerialPort(serial_port* new_port); +serial_port* GetSerialPort(); +void SetOffline(bool new_offline); +bool IsOffline(); + +void SendCommand(UsbCommand *c); +void *uart_receiver(void *targ); +void UsbCommandReceived(UsbCommand *UC); +void clearCommandBuffer(); +bool WaitForResponseTimeoutW(uint64_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning); +bool WaitForResponseTimeout(uint64_t cmd, UsbCommand* response, size_t ms_timeout); +bool WaitForResponse(uint64_t cmd, UsbCommand* response); + +#endif // COMMS_H_ diff --git a/client/flash.c b/client/flash.c index 7622e8a5..bf01b911 100644 --- a/client/flash.c +++ b/client/flash.c @@ -13,6 +13,7 @@ #include #include #include + #include "proxmark3.h" #include "util.h" #include "util_posix.h" @@ -20,11 +21,7 @@ #include "elf.h" #include "proxendian.h" #include "usb_cmd.h" - -void SendCommand(UsbCommand* txcmd); -void ReceiveCommand(UsbCommand* rxcmd); -void CloseProxmark(); -int OpenProxmark(size_t i); +#include "comms.h" // FIXME: what the fuckity fuck unsigned int current_command = CMD_UNKNOWN; @@ -44,6 +41,32 @@ static const uint8_t elf_ident[] = { EV_CURRENT }; +void CloseProxmark(receiver_arg* conn, char* serial_port_name) { + pthread_mutex_lock(&conn->recv_lock); + + // Block the port from being used by anything + serial_port* my_port = GetSerialPort(); + SetSerialPort(NULL); + + // Then close the port. + uart_close(my_port); + pthread_mutex_unlock(&conn->recv_lock); + + // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/* + unlink(serial_port_name); +} + +bool OpenProxmark(char* serial_port_name) { + serial_port *new_port = uart_open(serial_port_name); + if (new_port == INVALID_SERIAL_PORT || new_port == CLAIMED_SERIAL_PORT) { + //poll once a second + return false; + } + + SetSerialPort(new_port); + return true; +} + // Turn PHDRs into flasher segments, checking for PHDR sanity and merging adjacent // unaligned segments if needed static int build_segs_from_phdrs(flash_file_t *ctx, FILE *fd, Elf32_Phdr *phdrs, int num_phdrs) @@ -278,9 +301,12 @@ static int get_proxmark_state(uint32_t *state) { UsbCommand c; c.cmd = CMD_DEVICE_INFO; - SendCommand(&c); + SendCommand(&c); UsbCommand resp; - ReceiveCommand(&resp); + while (!WaitForResponse(CMD_ANY, &resp)) { + // Keep waiting for a response + msleep(100); + } // Three outcomes: // 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK @@ -307,7 +333,7 @@ static int get_proxmark_state(uint32_t *state) } // Enter the bootloader to be able to start flashing -static int enter_bootloader(char *serial_port_name) +static int enter_bootloader(receiver_arg* conn, char *serial_port_name) { uint32_t state; @@ -338,16 +364,17 @@ static int enter_bootloader(char *serial_port_name) SendCommand(&c); fprintf(stderr,"Press and hold down button NOW if your bootloader requires it.\n"); } - msleep(100); - CloseProxmark(); + + msleep(100); + CloseProxmark(conn, serial_port_name); fprintf(stderr,"Waiting for Proxmark to reappear on %s",serial_port_name); - do { + do { sleep(1); fprintf(stderr, "."); - } while (!OpenProxmark(0)); + } while (!OpenProxmark(serial_port_name)); + fprintf(stderr," Found.\n"); - return 0; } @@ -355,23 +382,25 @@ static int enter_bootloader(char *serial_port_name) return -1; } -static int wait_for_ack(void) +static int wait_for_ack() { - UsbCommand ack; - ReceiveCommand(&ack); - if (ack.cmd != CMD_ACK) { - printf("Error: Unexpected reply 0x%04" PRIx64 " (expected ACK)\n", ack.cmd); + UsbCommand resp; + while (!WaitForResponse(CMD_ANY, &resp)) { + msleep(100); + } + if (resp.cmd != CMD_ACK) { + printf("Error: Unexpected reply 0x%04" PRIx64 " (expected ACK)\n", resp.cmd); return -1; } return 0; } // Go into flashing mode -int flash_start_flashing(int enable_bl_writes,char *serial_port_name) +int flash_start_flashing(receiver_arg* conn, int enable_bl_writes,char *serial_port_name) { uint32_t state; - if (enter_bootloader(serial_port_name) < 0) + if (enter_bootloader(conn, serial_port_name) < 0) return -1; if (get_proxmark_state(&state) < 0) @@ -470,9 +499,9 @@ void flash_free(flash_file_t *ctx) } // just reset the unit -int flash_stop_flashing(void) { +int flash_stop_flashing() { UsbCommand c = {CMD_HARDWARE_RESET}; - SendCommand(&c); - msleep(100); - return 0; + SendCommand(&c); + msleep(100); + return 0; } diff --git a/client/flash.h b/client/flash.h index 3e9f77a7..279062af 100644 --- a/client/flash.h +++ b/client/flash.h @@ -11,6 +11,7 @@ #include #include "elf.h" +#include "comms.h" typedef struct { void *data; @@ -26,10 +27,12 @@ typedef struct { } flash_file_t; int flash_load(flash_file_t *ctx, const char *name, int can_write_bl); -int flash_start_flashing(int enable_bl_writes,char *serial_port_name); +int flash_start_flashing(receiver_arg* conn, int enable_bl_writes, char *serial_port_name); int flash_write(flash_file_t *ctx); void flash_free(flash_file_t *ctx); int flash_stop_flashing(void); +void CloseProxmark(receiver_arg* conn, char* serial_port_name); +bool OpenProxmark(char* serial_port_name); #endif diff --git a/client/flasher.c b/client/flasher.c index f257d994..40e40524 100644 --- a/client/flasher.c +++ b/client/flasher.c @@ -10,12 +10,15 @@ #include #include #include +#include + #include "proxmark3.h" #include "util.h" #include "util_posix.h" #include "flash.h" #include "uart.h" #include "usb_cmd.h" +#include "comms.h" #ifdef _WIN32 # define unlink(x) @@ -23,9 +26,6 @@ # include #endif -static serial_port sp; -static char* serial_port_name; - void cmd_debug(UsbCommand* UC) { // Debug printf("UsbCommand length[len=%zd]\n",sizeof(UsbCommand)); @@ -40,45 +40,6 @@ void cmd_debug(UsbCommand* UC) { printf("...\n"); } -void SendCommand(UsbCommand* txcmd) { -// printf("send: "); -// cmd_debug(txcmd); - if (!uart_send(sp,(byte_t*)txcmd,sizeof(UsbCommand))) { - printf("Sending bytes to proxmark failed\n"); - exit(1); - } -} - -void ReceiveCommand(UsbCommand* rxcmd) { - byte_t* prxcmd = (byte_t*)rxcmd; - byte_t* prx = prxcmd; - size_t rxlen; - while (true) { - if (uart_receive(sp, prx, sizeof(UsbCommand) - (prx-prxcmd), &rxlen)) { - prx += rxlen; - if ((prx-prxcmd) >= sizeof(UsbCommand)) { - return; - } - } - } -} - -void CloseProxmark() { - // Clean up the port - uart_close(sp); - // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/* - unlink(serial_port_name); -} - -int OpenProxmark(size_t i) { - sp = uart_open(serial_port_name); - if (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT) { - //poll once a second - return 0; - } - return 1; -} - static void usage(char *argv0) { fprintf(stderr, "Usage: %s [-b] image.elf [image.elf...]\n\n", argv0); @@ -86,9 +47,10 @@ static void usage(char *argv0) //Is the example below really true? /Martin fprintf(stderr, "Example:\n\n\t %s path/to/osimage.elf path/to/fpgaimage.elf\n", argv0); fprintf(stderr, "\nExample (Linux):\n\n\t %s /dev/ttyACM0 armsrc/obj/fullimage.elf\n", argv0); - fprintf(stderr, "\nNote (Linux): if the flasher gets stuck in 'Waiting for Proxmark to reappear on ',\n"); - fprintf(stderr, " you need to blacklist proxmark for modem-manager - see wiki for more details:\n"); - fprintf(stderr, " http://code.google.com/p/proxmark3/wiki/Linux\n\n"); + fprintf(stderr, "\nNote (Linux): if the flasher gets stuck at 'Waiting for Proxmark to reappear',\n"); + fprintf(stderr, " you may need to blacklist proxmark for modem-manager. v1.4.14 and later\n"); + fprintf(stderr, " include this configuration patch already. The change can be found at:\n"); + fprintf(stderr, " https://cgit.freedesktop.org/ModemManager/ModemManager/commit/?id=6e7ff47\n\n"); } #define MAX_FILES 4 @@ -99,7 +61,10 @@ int main(int argc, char **argv) int num_files = 0; int res; flash_file_t files[MAX_FILES]; + receiver_arg conn; + pthread_t reader_thread; + memset(&conn, 0, sizeof(receiver_arg)); memset(files, 0, sizeof(files)); if (argc < 3) { @@ -126,16 +91,22 @@ int main(int argc, char **argv) } } - serial_port_name = argv[1]; - - fprintf(stderr,"Waiting for Proxmark to appear on %s",serial_port_name); - do { - msleep(1000); - fprintf(stderr, "."); - } while (!OpenProxmark(0)); - fprintf(stderr," Found.\n"); + pthread_mutex_init(&conn.recv_lock, NULL); - res = flash_start_flashing(can_write_bl,serial_port_name); + char* serial_port_name = argv[1]; + + fprintf(stderr,"Waiting for Proxmark to appear on %s", serial_port_name); + do { + sleep(1); + fprintf(stderr, "."); + } while (!OpenProxmark(serial_port_name)); + fprintf(stderr," Found.\n"); + + // Lets start up the communications thread + conn.run = true; + pthread_create(&reader_thread, NULL, &uart_receiver, &conn); + + res = flash_start_flashing(&conn, can_write_bl, serial_port_name); if (res < 0) return -1; @@ -155,7 +126,11 @@ int main(int argc, char **argv) if (res < 0) return -1; - CloseProxmark(); + // Stop the command thread. + conn.run = false; + pthread_join(reader_thread, NULL); + CloseProxmark(&conn, serial_port_name); + pthread_mutex_destroy(&conn.recv_lock); fprintf(stderr, "All done.\n\n"); fprintf(stderr, "Have a nice day!\n"); diff --git a/client/proxgui.cpp b/client/proxgui.cpp index e7fdae6c..808c7de5 100644 --- a/client/proxgui.cpp +++ b/client/proxgui.cpp @@ -11,11 +11,15 @@ #include "proxgui.h" #include "proxguiqt.h" #include "proxmark3.h" +#include "uart.h" static ProxGuiQT *gui = NULL; static WorkerThread *main_loop_thread = NULL; -WorkerThread::WorkerThread(char *script_cmds_file, bool usb_present) : script_cmds_file(script_cmds_file), usb_present(usb_present) +WorkerThread::WorkerThread(char *script_cmds_file, bool usb_present, serial_port* sp) + : script_cmds_file(script_cmds_file), usb_present(usb_present), + sp(sp) + { } @@ -24,7 +28,7 @@ WorkerThread::~WorkerThread() } void WorkerThread::run() { - main_loop(script_cmds_file, usb_present); + main_loop(script_cmds_file, usb_present, sp); } extern "C" void ShowGraphWindow(void) @@ -60,7 +64,7 @@ extern "C" void MainGraphics(void) gui->MainLoop(); } -extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present) +extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* sp) { #ifdef Q_WS_X11 bool useGUI = getenv("DISPLAY") != 0; @@ -71,7 +75,7 @@ extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool return; gui = new ProxGuiQT(argc, argv); - main_loop_thread = new WorkerThread(script_cmds_file, usb_present); + main_loop_thread = new WorkerThread(script_cmds_file, usb_present, sp); QObject::connect(main_loop_thread, SIGNAL(finished()), main_loop_thread, SLOT(deleteLater())); QObject::connect(main_loop_thread, SIGNAL(finished()), gui, SLOT(_Exit())); } diff --git a/client/proxgui.h b/client/proxgui.h index 6e261cb9..8cc05128 100644 --- a/client/proxgui.h +++ b/client/proxgui.h @@ -14,12 +14,13 @@ extern "C" { #include #include +#include "uart.h" void ShowGraphWindow(void); void HideGraphWindow(void); void RepaintGraphWindow(void); void MainGraphics(void); -void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present); +void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* sp); void ExitGraphics(void); #define MAX_GRAPH_TRACE_LEN (40000*8) @@ -30,7 +31,6 @@ extern int s_Buff[MAX_GRAPH_TRACE_LEN]; extern double CursorScaleFactor; extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, CursorCPos, CursorDPos, GridOffset; extern int CommandFinished; -extern int offline; extern bool GridLocked; //Operations defined in data_operations diff --git a/client/proxguiqt.h b/client/proxguiqt.h index 8a3b8cfc..8eb518af 100644 --- a/client/proxguiqt.h +++ b/client/proxguiqt.h @@ -21,6 +21,7 @@ #include #include +#include "uart.h" #include "ui/ui_overlays.h" /** * @brief The actual plot, black area were we paint the graph @@ -123,12 +124,13 @@ class ProxGuiQT : public QObject class WorkerThread : public QThread { Q_OBJECT; public: - WorkerThread(char*, bool); + WorkerThread(char*, bool, serial_port*); ~WorkerThread(); void run(); private: char *script_cmds_file = NULL; bool usb_present; + serial_port *sp = NULL; }; #endif // PROXGUI_QT diff --git a/client/proxmark3.c b/client/proxmark3.c index 956eb6a8..09c60ee0 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -25,80 +25,30 @@ #include "cmdparser.h" #include "cmdhw.h" #include "whereami.h" +#include "comms.h" - -// a global mutex to prevent interlaced printing from different threads -pthread_mutex_t print_lock; - -static serial_port sp; -static UsbCommand txcmd; -volatile static bool txcmd_pending = false; - -void SendCommand(UsbCommand *c) { - #if 0 - printf("Sending %d bytes\n", sizeof(UsbCommand)); - #endif - - if (offline) { - PrintAndLog("Sending bytes to proxmark failed - offline"); - return; - } - /** - The while-loop below causes hangups at times, when the pm3 unit is unresponsive - or disconnected. The main console thread is alive, but comm thread just spins here. - Not good.../holiman - **/ - while(txcmd_pending); - txcmd = *c; - txcmd_pending = true; -} - -struct receiver_arg { - int run; -}; - -byte_t rx[sizeof(UsbCommand)]; -byte_t* prx = rx; - -static void *uart_receiver(void *targ) { - struct receiver_arg *arg = (struct receiver_arg*)targ; - size_t rxlen; - - while (arg->run) { - rxlen = 0; - if (uart_receive(sp, prx, sizeof(UsbCommand) - (prx-rx), &rxlen)) { - prx += rxlen; - if (prx-rx < sizeof(UsbCommand)) { - continue; - } - - UsbCommandReceived((UsbCommand*)rx); - } - prx = rx; - - if(txcmd_pending) { - if (!uart_send(sp, (byte_t*) &txcmd, sizeof(UsbCommand))) { - PrintAndLog("Sending bytes to proxmark failed"); - } - txcmd_pending = false; - } - } - - pthread_exit(NULL); - return NULL; -} - - -void main_loop(char *script_cmds_file, bool usb_present) { - struct receiver_arg rarg; +void main_loop(char *script_cmds_file, bool usb_present, serial_port* sp) { + receiver_arg conn; char *cmd = NULL; pthread_t reader_thread; + memset(&conn, 0, sizeof(receiver_arg)); + pthread_mutex_init(&conn.recv_lock, NULL); + + // TODO: Move this into comms.c + PlotGridXdefault = 64; + PlotGridYdefault = 64; + showDemod = true; + CursorScaleFactor = 1; if (usb_present) { - rarg.run = 1; - pthread_create(&reader_thread, NULL, &uart_receiver, &rarg); + conn.run = true; + SetSerialPort(sp); + SetOffline(false); + pthread_create(&reader_thread, NULL, &uart_receiver, &conn); // cache Version information now: CmdVersion(NULL); + } else { + SetOffline(true); } FILE *script_file = NULL; @@ -113,7 +63,7 @@ void main_loop(char *script_cmds_file, bool usb_present) { read_history(".history"); - while(1) { + while (1) { // If there is a script file if (script_file) @@ -163,7 +113,7 @@ void main_loop(char *script_cmds_file, bool usb_present) { write_history(".history"); if (usb_present) { - rarg.run = 0; + conn.run = false; pthread_join(reader_thread, NULL); } @@ -172,6 +122,7 @@ void main_loop(char *script_cmds_file, bool usb_present) { script_file = NULL; } + pthread_mutex_destroy(&conn.recv_lock); } static void dumpAllHelp(int markdown) @@ -240,19 +191,18 @@ int main(int argc, char* argv[]) { bool usb_present = false; char *script_cmds_file = NULL; + + g_debugMode = 0; - sp = uart_open(argv[1]); + serial_port *sp = uart_open(argv[1]); if (sp == INVALID_SERIAL_PORT) { printf("ERROR: invalid serial port\n"); usb_present = false; - offline = 1; } else if (sp == CLAIMED_SERIAL_PORT) { printf("ERROR: serial port is claimed by another process\n"); usb_present = false; - offline = 1; } else { usb_present = true; - offline = 0; } // If the user passed the filename of the 'script' to execute, get it @@ -275,23 +225,23 @@ int main(int argc, char* argv[]) { #ifdef HAVE_GUI #ifdef _WIN32 - InitGraphics(argc, argv, script_cmds_file, usb_present); + InitGraphics(argc, argv, script_cmds_file, usb_present, sp); MainGraphics(); #else char* display = getenv("DISPLAY"); if (display && strlen(display) > 1) { - InitGraphics(argc, argv, script_cmds_file, usb_present); + InitGraphics(argc, argv, script_cmds_file, usb_present, sp); MainGraphics(); } else { - main_loop(script_cmds_file, usb_present); + main_loop(script_cmds_file, usb_present, sp); } #endif #else - main_loop(script_cmds_file, usb_present); + main_loop(script_cmds_file, usb_present, sp); #endif // Clean up the port diff --git a/client/proxmark3.h b/client/proxmark3.h index 7ff7f676..e2cb0c02 100644 --- a/client/proxmark3.h +++ b/client/proxmark3.h @@ -13,6 +13,7 @@ #define PROXMARK3_H__ #include "usb_cmd.h" +#include "uart.h" #define PROXPROMPT "proxmark3> " @@ -23,7 +24,7 @@ extern "C" { void SendCommand(UsbCommand *c); const char *get_my_executable_path(void); const char *get_my_executable_directory(void); -void main_loop(char *script_cmds_file, bool usb_present); +void main_loop(char *script_cmds_file, bool usb_present, serial_port* sp); #ifdef __cplusplus } diff --git a/client/ui.c b/client/ui.c index df2c3ce3..48869fd1 100644 --- a/client/ui.c +++ b/client/ui.c @@ -21,7 +21,7 @@ double CursorScaleFactor = 1; int PlotGridX=0, PlotGridY=0, PlotGridXdefault= 64, PlotGridYdefault= 64, CursorCPos= 0, CursorDPos= 0; int offline; -int flushAfterWrite = 0; //buzzy +bool flushAfterWrite = false; //buzzy int GridOffset = 0; bool GridLocked = false; bool showDemod = true; @@ -62,7 +62,6 @@ void PrintAndLog(char *fmt, ...) } #else // We are using libedit (OSX), which doesn't support this flag. - int need_hack = 0; #endif va_start(argptr, fmt); @@ -72,6 +71,9 @@ void PrintAndLog(char *fmt, ...) va_end(argptr); printf("\n"); + // This needs to be wrapped in ifdefs, as this if optimisation is disabled, + // this block won't be removed, and it'll fail at the linker. +#ifdef RL_STATE_READCMD if (need_hack) { rl_restore_prompt(); rl_replace_line(saved_line, 0); @@ -79,6 +81,7 @@ void PrintAndLog(char *fmt, ...) rl_redisplay(); free(saved_line); } +#endif if (logging && logfile) { vfprintf(logfile, fmt, argptr2); @@ -100,3 +103,8 @@ void SetLogFilename(char *fn) { logfilename = fn; } + +void SetFlushAfterWrite(bool flush_after_write) { + flushAfterWrite = flush_after_write; +} + diff --git a/client/ui.h b/client/ui.h index 4049033d..2986efaf 100644 --- a/client/ui.h +++ b/client/ui.h @@ -13,6 +13,11 @@ #include #include +#include + +// a global mutex to prevent interlaced printing from different threads +pthread_mutex_t print_lock; +extern uint8_t g_debugMode; void ShowGui(void); void HideGraphWindow(void); @@ -23,8 +28,7 @@ void SetLogFilename(char *fn); extern double CursorScaleFactor; extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, CursorCPos, CursorDPos, GridOffset; -extern int offline; -extern int flushAfterWrite; //buzzy +extern bool flushAfterWrite; //buzzy extern bool GridLocked; extern bool showDemod; diff --git a/common/iso15693tools.c b/common/iso15693tools.c index 26e636ca..cf7d5341 100644 --- a/common/iso15693tools.c +++ b/common/iso15693tools.c @@ -50,8 +50,9 @@ int Iso15693AddCrc(uint8_t *req, int n) { return n+2; } - +#ifdef ON_DEVICE int sprintf(char *str, const char *format, ...); +#endif // returns a string representation of the UID // UID is transmitted and stored LSB first, displayed MSB first diff --git a/include/usb_cmd.h b/include/usb_cmd.h index 194a9d53..df2923a0 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -212,7 +212,7 @@ typedef struct{ #define CMD_HF_SNIFFER 0x0800 #define CMD_UNKNOWN 0xFFFF - +#define CMD_ANY 0xFFFFFFFFFFFFFFFF //Mifare simulation flags #define FLAG_INTERACTIVE 0x01 From b217320a26cf84c67af31fb6829cb276120bfdbb Mon Sep 17 00:00:00 2001 From: Michael Farrell Date: Sat, 8 Jul 2017 22:08:20 +1000 Subject: [PATCH 2/4] Refactoring out the global state in the client --- client/cmdcrc.c | 10 +- client/cmdcrc.h | 10 +- client/cmddata.c | 543 ++++++++++++++++++++-------------------- client/cmddata.h | 102 ++++---- client/cmdhf.c | 39 +-- client/cmdhf.h | 6 +- client/cmdhf14a.c | 76 +++--- client/cmdhf14a.h | 12 +- client/cmdhf14b.c | 160 ++++++------ client/cmdhf14b.h | 18 +- client/cmdhf15.c | 120 ++++----- client/cmdhf15.h | 20 +- client/cmdhfepa.c | 28 +-- client/cmdhfepa.h | 5 +- client/cmdhficlass.c | 176 ++++++------- client/cmdhficlass.h | 42 ++-- client/cmdhflegic.c | 48 ++-- client/cmdhflegic.h | 18 +- client/cmdhfmf.c | 213 ++++++++-------- client/cmdhfmf.h | 91 ++++--- client/cmdhfmfhard.c | 17 +- client/cmdhfmfhard.h | 3 +- client/cmdhfmfu.c | 288 ++++++++++----------- client/cmdhfmfu.h | 16 +- client/cmdhftopaz.c | 92 +++---- client/cmdhftopaz.h | 2 +- client/cmdhw.c | 75 +++--- client/cmdhw.h | 24 +- client/cmdlf.c | 357 +++++++++++++------------- client/cmdlf.h | 31 +-- client/cmdlfawid.c | 41 +-- client/cmdlfawid.h | 11 +- client/cmdlfcotag.c | 41 +-- client/cmdlfcotag.h | 6 +- client/cmdlfem4x.c | 290 ++++++++++----------- client/cmdlfem4x.h | 39 +-- client/cmdlffdx.c | 48 ++-- client/cmdlffdx.h | 11 +- client/cmdlfgproxii.c | 40 +-- client/cmdlfgproxii.h | 8 +- client/cmdlfhid.c | 32 +-- client/cmdlfhid.h | 11 +- client/cmdlfhitag.c | 48 ++-- client/cmdlfhitag.h | 11 +- client/cmdlfindala.c | 92 +++---- client/cmdlfindala.h | 9 +- client/cmdlfio.c | 34 +-- client/cmdlfio.h | 8 +- client/cmdlfjablotron.c | 50 ++-- client/cmdlfjablotron.h | 12 +- client/cmdlfnexwatch.c | 40 +-- client/cmdlfnexwatch.h | 9 +- client/cmdlfnoralsy.c | 60 ++--- client/cmdlfnoralsy.h | 12 +- client/cmdlfpac.c | 38 +-- client/cmdlfpac.h | 8 +- client/cmdlfparadox.c | 26 +- client/cmdlfparadox.h | 9 +- client/cmdlfpcf7931.c | 26 +- client/cmdlfpcf7931.h | 10 +- client/cmdlfpresco.c | 52 ++-- client/cmdlfpresco.h | 7 +- client/cmdlfpyramid.c | 42 ++-- client/cmdlfpyramid.h | 12 +- client/cmdlfsecurakey.c | 40 +-- client/cmdlfsecurakey.h | 12 +- client/cmdlft55xx.c | 483 +++++++++++++++++------------------ client/cmdlft55xx.h | 40 +-- client/cmdlfti.c | 60 ++--- client/cmdlfti.h | 10 +- client/cmdlfviking.c | 50 ++-- client/cmdlfviking.h | 13 +- client/cmdlfvisa2000.c | 54 ++-- client/cmdlfvisa2000.h | 13 +- client/cmdmain.c | 26 +- client/cmdmain.h | 3 +- client/cmdparser.c | 14 +- client/cmdparser.h | 8 +- client/cmdscript.c | 18 +- client/cmdscript.h | 3 +- client/comms.c | 144 ++++------- client/comms.h | 79 ++++-- client/data.c | 12 +- client/data.h | 4 +- client/flash.c | 67 ++--- client/flash.h | 10 +- client/flasher.c | 14 +- client/graph.c | 117 +++++---- client/graph.h | 30 +-- client/guidummy.cpp | 7 +- client/mifarehost.c | 82 +++--- client/mifarehost.h | 21 +- client/proxgui.cpp | 11 +- client/proxgui.h | 28 +-- client/proxguiqt.h | 5 +- client/proxmark3.c | 42 ++-- client/proxmark3.h | 4 +- client/scripting.c | 29 ++- client/scripting.h | 3 +- client/ui.c | 15 +- client/ui.h | 14 +- common/iso15693tools.c | 6 +- common/lfdemod.c | 16 +- include/usb_cmd.h | 2 + liblua/lstate.h | 3 + uart/uart.h | 14 +- uart/uart_posix.c | 19 +- uart/uart_win32.c | 12 +- 108 files changed, 2768 insertions(+), 2724 deletions(-) diff --git a/client/cmdcrc.c b/client/cmdcrc.c index 01f65f55..142ba2fa 100644 --- a/client/cmdcrc.c +++ b/client/cmdcrc.c @@ -62,7 +62,7 @@ int split(char *str, char *arr[MAX_ARGS]){ return wordCnt; } -int CmdCrc(const char *Cmd) +int CmdCrc(pm3_connection* conn, const char *Cmd) { char name[] = {"reveng "}; char Cmd2[50 + 7]; @@ -72,7 +72,7 @@ int CmdCrc(const char *Cmd) int argc = split(Cmd2, argv); if (argc == 3 && memcmp(argv[1],"-g",2)==0) { - CmdrevengSearch(argv[2]); + CmdrevengSearch(conn, argv[2]); } else { reveng_main(argc, argv); } @@ -269,7 +269,7 @@ int GetModels(char *Models[], int *count, uint8_t *width){ } //test call to GetModels -int CmdrevengTest(const char *Cmd){ +int CmdrevengTest(pm3_connection* conn, const char *Cmd){ char *Models[80]; int count = 0; uint8_t widtharr[80] = {0}; @@ -427,7 +427,7 @@ int RunModel(char *inModel, char *inHexStr, bool reverse, char endian, char *res } //test call to RunModel -int CmdrevengTestC(const char *Cmd){ +int CmdrevengTestC(pm3_connection* conn, const char *Cmd){ int cmdp = 0; char inModel[30] = {0x00}; char inHexStr[30] = {0x00}; @@ -462,7 +462,7 @@ char *SwapEndianStr(const char *inStr, const size_t len, const uint8_t blockSize } // takes hex string in and searches for a matching result (hex string must include checksum) -int CmdrevengSearch(const char *Cmd){ +int CmdrevengSearch(pm3_connection* conn, const char *Cmd){ char inHexStr[50] = {0x00}; int dataLen = param_getstr(Cmd, 0, inHexStr); if (dataLen < 4) return 0; diff --git a/client/cmdcrc.h b/client/cmdcrc.h index 5041554d..e5374c84 100644 --- a/client/cmdcrc.h +++ b/client/cmdcrc.h @@ -11,10 +11,12 @@ #ifndef CMDCRC_H__ #define CMDCRC_H__ -int CmdCrc(const char *Cmd); -int CmdrevengTest(const char *Cmd); -int CmdrevengTestC(const char *Cmd); -int CmdrevengSearch(const char *Cmd); +#include "comms.h" + +int CmdCrc(pm3_connection* conn, const char *Cmd); +int CmdrevengTest(pm3_connection* conn, const char *Cmd); +int CmdrevengTestC(pm3_connection* conn, const char *Cmd); +int CmdrevengSearch(pm3_connection* conn, const char *Cmd); int GetModels(char *Models[], int *count, uint8_t *width); int RunModel(char *inModel, char *inHexStr, bool reverse, char endian, char *result); #endif diff --git a/client/cmddata.c b/client/cmddata.c index 1f548284..94cb093f 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -25,17 +25,11 @@ #include "loclass/cipherutils.h" // for decimating samples in getsamples #include "cmdlfem4x.h"// for em410x demod -uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; -uint8_t g_debugMode=0; -size_t DemodBufferLen=0; -int g_DemodStartIdx=0; -int g_DemodClock=0; - -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); //set the demod buffer with given array of binary (one bit per byte) //by marshmellow -void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx) +void setDemodBuf(pm3_connection* conn, uint8_t *buff, size_t size, size_t startIdx) { if (buff == NULL) return; @@ -43,28 +37,31 @@ void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx) if ( size > MAX_DEMOD_BUF_LEN - startIdx) size = MAX_DEMOD_BUF_LEN - startIdx; + // FIXME: memcpy size_t i = 0; for (; i < size; i++){ - DemodBuffer[i]=buff[startIdx++]; + conn->DemodBuffer[i]=buff[startIdx++]; } - DemodBufferLen=size; + conn->DemodBufferLen=size; return; } -bool getDemodBuf(uint8_t *buff, size_t *size) { +bool getDemodBuf(pm3_connection* conn, uint8_t *buff, size_t *size) { if (buff == NULL) return false; if (size == NULL) return false; if (*size == 0) return false; - *size = (*size > DemodBufferLen) ? DemodBufferLen : *size; + *size = (*size > conn->DemodBufferLen) ? conn->DemodBufferLen : *size; - memcpy(buff, DemodBuffer, *size); + memcpy(buff, conn->DemodBuffer, *size); return true; } -// option '1' to save DemodBuffer any other to restore -void save_restoreDB(uint8_t saveOpt) +// option '1' to save conn->DemodBuffer any other to restore +void save_restoreDB(pm3_connection* conn, uint8_t saveOpt) { + // FIXME: This function only allows a buffer of 1 graph to be stored. + // FIXME: This function is not thread-safe. static uint8_t SavedDB[MAX_DEMOD_BUF_LEN]; static size_t SavedDBlen; static bool DB_Saved = false; @@ -73,21 +70,21 @@ void save_restoreDB(uint8_t saveOpt) if (saveOpt == GRAPH_SAVE) { //save - memcpy(SavedDB, DemodBuffer, sizeof(DemodBuffer)); - SavedDBlen = DemodBufferLen; + memcpy(SavedDB, conn->DemodBuffer, sizeof(conn->DemodBuffer)); + SavedDBlen = conn->DemodBufferLen; DB_Saved=true; - savedDemodStartIdx = g_DemodStartIdx; - savedDemodClock = g_DemodClock; + savedDemodStartIdx = conn->g_DemodStartIdx; + savedDemodClock = conn->g_DemodClock; } else if (DB_Saved) { //restore - memcpy(DemodBuffer, SavedDB, sizeof(DemodBuffer)); - DemodBufferLen = SavedDBlen; - g_DemodClock = savedDemodClock; - g_DemodStartIdx = savedDemodStartIdx; + memcpy(conn->DemodBuffer, SavedDB, sizeof(conn->DemodBuffer)); + conn->DemodBufferLen = SavedDBlen; + conn->g_DemodClock = savedDemodClock; + conn->g_DemodStartIdx = savedDemodStartIdx; } return; } -int CmdSetDebugMode(const char *Cmd) +int CmdSetDebugMode(pm3_connection* conn, const char *Cmd) { int demod=0; sscanf(Cmd, "%i", &demod); @@ -106,22 +103,22 @@ int usage_data_printdemodbuf(){ } //by marshmellow -void printDemodBuff(void) +void printDemodBuff(pm3_connection* conn) { - int bitLen = DemodBufferLen; + int bitLen = conn->DemodBufferLen; if (bitLen<1) { PrintAndLog("no bits found in demod buffer"); return; } if (bitLen>512) bitLen=512; //max output to 512 bits if we have more - should be plenty - char *bin = sprint_bin_break(DemodBuffer,bitLen,16); + char *bin = sprint_bin_break(conn->DemodBuffer,bitLen,16); PrintAndLog("%s",bin); return; } -int CmdPrintDemodBuff(const char *Cmd) +int CmdPrintDemodBuff(pm3_connection* conn, const char *Cmd) { char hex[512]={0x00}; bool hexMode = false; @@ -162,35 +159,35 @@ int CmdPrintDemodBuff(const char *Cmd) } //Validations if(errors) return usage_data_printdemodbuf(); - length = (length > (DemodBufferLen-offset)) ? DemodBufferLen-offset : length; + length = (length > (conn->DemodBufferLen-offset)) ? conn->DemodBufferLen-offset : length; int numBits = (length) & 0x00FFC; //make sure we don't exceed our string if (hexMode){ - char *buf = (char *) (DemodBuffer + offset); + char *buf = (char *) (conn->DemodBuffer + offset); numBits = (numBits > sizeof(hex)) ? sizeof(hex) : numBits; numBits = binarraytohex(hex, buf, numBits); if (numBits==0) return 0; - PrintAndLog("DemodBuffer: %s",hex); + PrintAndLog("conn->DemodBuffer: %s",hex); } else { - PrintAndLog("DemodBuffer:\n%s", sprint_bin_break(DemodBuffer+offset,numBits,16)); + PrintAndLog("conn->DemodBuffer:\n%s", sprint_bin_break(conn->DemodBuffer+offset,numBits,16)); } return 1; } //by marshmellow //this function strictly converts >1 to 1 and <1 to 0 for each sample in the graphbuffer -int CmdGetBitStream(const char *Cmd) +int CmdGetBitStream(pm3_connection* conn, const char *Cmd) { int i; - CmdHpf(Cmd); - for (i = 0; i < GraphTraceLen; i++) { - if (GraphBuffer[i] >= 1) { - GraphBuffer[i] = 1; + CmdHpf(conn, Cmd); + for (i = 0; i < conn->GraphTraceLen; i++) { + if (conn->GraphBuffer[i] >= 1) { + conn->GraphBuffer[i] = 1; } else { - GraphBuffer[i] = 0; + conn->GraphBuffer[i] = 0; } } - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } @@ -200,7 +197,7 @@ int CmdGetBitStream(const char *Cmd) //verbose will print results and demoding messages //emSearch will auto search for EM410x format in bitstream //askType switches decode: ask/raw = 0, ask/manchester = 1 -int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck) { +int ASKDemod_ext(pm3_connection* conn, const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck) { int invert=0; int clk=0; int maxErr=100; @@ -218,7 +215,7 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, invert=1; clk=0; } - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (g_debugMode) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen); if (BitLen < 255) return 0; if (maxLen < BitLen && maxLen != 0) BitLen = maxLen; @@ -233,14 +230,14 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, *stCheck = st; if (st) { clk = (clk == 0) ? foundclk : clk; - CursorCPos = ststart; - CursorDPos = stend; + conn->CursorCPos = ststart; + conn->CursorDPos = stend; if (verbose || g_debugMode) PrintAndLog("\nFound Sequence Terminator - First one is shown by orange and blue graph markers"); //Graph ST trim (for testing) //for (int i = 0; i < BitLen; i++) { - // GraphBuffer[i] = BitStream[i]-128; + // conn->GraphBuffer[i] = BitStream[i]-128; //} - //RepaintGraphWindow(); + //RepaintGraphWindow(conn); } int startIdx = 0; int errCnt = askdemod_ext(BitStream, &BitLen, &clk, &invert, maxErr, askamp, askType, &startIdx); @@ -254,34 +251,34 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, } if (verbose || g_debugMode) PrintAndLog("\nUsing Clock:%d, Invert:%d, Bits Found:%d",clk,invert,BitLen); //output - setDemodBuf(BitStream,BitLen,0); - setClockGrid(clk, startIdx); + setDemodBuf(conn, BitStream, BitLen, 0); + setClockGrid(conn, clk, startIdx); if (verbose || g_debugMode){ if (errCnt>0) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); if (askType) PrintAndLog("ASK/Manchester - Clock: %d - Decoded bitstream:",clk); else PrintAndLog("ASK/Raw - Clock: %d - Decoded bitstream:",clk); // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); + printDemodBuff(conn); } uint64_t lo = 0; uint32_t hi = 0; if (emSearch){ - AskEm410xDecode(true, &hi, &lo); + AskEm410xDecode(conn, true, &hi, &lo); } return 1; } -int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) { +int ASKDemod(pm3_connection* conn, const char *Cmd, bool verbose, bool emSearch, uint8_t askType) { bool st = false; - return ASKDemod_ext(Cmd, verbose, emSearch, askType, &st); + return ASKDemod_ext(conn, Cmd, verbose, emSearch, askType, &st); } //by marshmellow //takes 5 arguments - clock, invert, maxErr, maxLen as integers and amplify as char == 'a' //attempts to demodulate ask while decoding manchester //prints binary found and saves in graphbuffer for further commands -int Cmdaskmandemod(const char *Cmd) +int Cmdaskmandemod(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 45 || cmdp == 'h' || cmdp == 'H') { @@ -302,17 +299,17 @@ int Cmdaskmandemod(const char *Cmd) } bool st = true; if (Cmd[0]=='s') - return ASKDemod_ext(Cmd++, true, false, 1, &st); + return ASKDemod_ext(conn, Cmd++, true, false, 1, &st); else if (Cmd[1] == 's') - return ASKDemod_ext(Cmd+=2, true, false, 1, &st); + return ASKDemod_ext(conn, Cmd+=2, true, false, 1, &st); else - return ASKDemod(Cmd, true, false, 1); + return ASKDemod(conn, Cmd, true, false, 1); } //by marshmellow //manchester decode //stricktly take 10 and 01 and convert to 0 and 1 -int Cmdmandecoderaw(const char *Cmd) +int Cmdmandecoderaw(pm3_connection* conn, const char *Cmd) { int i =0; int errCnt=0; @@ -330,13 +327,13 @@ int Cmdmandecoderaw(const char *Cmd) PrintAndLog(" sample: data manrawdecode = decode manchester bitstream from the demodbuffer"); return 0; } - if (DemodBufferLen==0) return 0; + if (conn->DemodBufferLen==0) return 0; uint8_t BitStream[MAX_DEMOD_BUF_LEN]={0}; int high=0,low=0; - for (;ihigh) high=DemodBuffer[i]; - else if(DemodBuffer[i]DemodBufferLen;++i){ + if (conn->DemodBuffer[i]>high) high=conn->DemodBuffer[i]; + else if(conn->DemodBuffer[i]DemodBuffer[i]; + BitStream[i]=conn->DemodBuffer[i]; } if (high>7 || low <0 ){ PrintAndLog("Error: please raw demod the wave first then manchester raw decode"); @@ -373,7 +370,7 @@ int Cmdmandecoderaw(const char *Cmd) //takes 2 arguments "offset" default = 0 if 1 it will shift the decode by one bit // and "invert" default = 0 if 1 it will invert output // the argument offset allows us to manually shift if the output is incorrect - [EDIT: now auto detects] -int CmdBiphaseDecodeRaw(const char *Cmd) +int CmdBiphaseDecodeRaw(pm3_connection* conn, const char *Cmd) { size_t size=0; int offset=0, invert=0, maxErr=20, errCnt=0; @@ -393,13 +390,13 @@ int CmdBiphaseDecodeRaw(const char *Cmd) return 0; } sscanf(Cmd, "%i %i %i", &offset, &invert, &maxErr); - if (DemodBufferLen==0) { - PrintAndLog("DemodBuffer Empty - run 'data rawdemod ar' first"); + if (conn->DemodBufferLen==0) { + PrintAndLog("conn->DemodBuffer Empty - run 'data rawdemod ar' first"); return 0; } uint8_t BitStream[MAX_DEMOD_BUF_LEN]={0}; size = sizeof(BitStream); - if ( !getDemodBuf(BitStream, &size) ) return 0; + if ( !getDemodBuf(conn, BitStream, &size) ) return 0; errCnt=BiphaseRawDecode(BitStream, &size, &offset, invert); if (errCnt<0){ PrintAndLog("Error during decode:%d", errCnt); @@ -417,21 +414,21 @@ int CmdBiphaseDecodeRaw(const char *Cmd) PrintAndLog("Biphase Decoded using offset: %d - # invert:%d - data:",offset,invert); PrintAndLog("%s", sprint_bin_break(BitStream, size, 16)); - if (offset) setDemodBuf(DemodBuffer,DemodBufferLen-offset, offset); //remove first bit from raw demod - setClockGrid(g_DemodClock, g_DemodStartIdx + g_DemodClock*offset/2); + if (offset) setDemodBuf(conn, conn->DemodBuffer,conn->DemodBufferLen-offset, offset); //remove first bit from raw demod + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + conn->g_DemodClock*offset/2); return 1; } //by marshmellow // - ASK Demod then Biphase decode GraphBuffer samples -int ASKbiphaseDemod(const char *Cmd, bool verbose) +int ASKbiphaseDemod(pm3_connection* conn, const char *Cmd, bool verbose) { //ask raw demod GraphBuffer first int offset=0, clk=0, invert=0, maxErr=0; sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); uint8_t BitStream[MAX_GRAPH_TRACE_LEN]; - size_t size = getFromGraphBuf(BitStream); + size_t size = getFromGraphBuf(conn, BitStream); int startIdx = 0; //invert here inverts the ask raw demoded bits which has no effect on the demod, but we need the pointer int errCnt = askdemod_ext(BitStream, &size, &clk, &invert, maxErr, 0, 0, &startIdx); @@ -450,17 +447,17 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode too many errors: %d", errCnt); return 0; } - //success set DemodBuffer and return - setDemodBuf(BitStream, size, 0); - setClockGrid(clk, startIdx + clk*offset/2); + //success set conn->DemodBuffer and return + setDemodBuf(conn, BitStream, size, 0); + setClockGrid(conn, clk, startIdx + clk*offset/2); if (g_debugMode || verbose){ PrintAndLog("Biphase Decoded using offset: %d - clock: %d - # errors:%d - data:",offset,clk,errCnt); - printDemodBuff(); + printDemodBuff(conn); } return 1; } //by marshmellow - see ASKbiphaseDemod -int Cmdaskbiphdemod(const char *Cmd) +int Cmdaskbiphdemod(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') { @@ -486,11 +483,11 @@ int Cmdaskbiphdemod(const char *Cmd) PrintAndLog(" : data rawdemod ab 0 64 1 0 0 a = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp"); return 0; } - return ASKbiphaseDemod(Cmd, true); + return ASKbiphaseDemod(conn, Cmd, true); } //by marshmellow - see ASKDemod -int Cmdaskrawdemod(const char *Cmd) +int Cmdaskrawdemod(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 35 || cmdp == 'h' || cmdp == 'H') { @@ -510,16 +507,16 @@ int Cmdaskrawdemod(const char *Cmd) PrintAndLog(" : data rawdemod ar 64 1 0 0 a = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp"); return 0; } - return ASKDemod(Cmd, true, false, 0); + return ASKDemod(conn, Cmd, true, false, 0); } -int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose) +int AutoCorrelate(pm3_connection* conn, const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose) { static int CorrelBuffer[MAX_GRAPH_TRACE_LEN]; size_t Correlation = 0; int maxSum = 0; int lastMax = 0; - if (verbose) PrintAndLog("performing %d correlations", GraphTraceLen - window); + if (verbose) PrintAndLog("performing %d correlations", conn->GraphTraceLen - window); for (int i = 0; i < len - window; ++i) { int sum = 0; for (int j = 0; j < window; ++j) { @@ -551,7 +548,7 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph if (SaveGrph) { //GraphTraceLen = GraphTraceLen - window; memcpy(out, CorrelBuffer, len * sizeof(int)); - RepaintGraphWindow(); + RepaintGraphWindow(conn); } return Correlation; } @@ -567,7 +564,7 @@ int usage_data_autocorr(void) return 0; } -int CmdAutoCorr(const char *Cmd) +int CmdAutoCorr(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (cmdp == 'h' || cmdp == 'H') @@ -577,52 +574,52 @@ int CmdAutoCorr(const char *Cmd) bool updateGrph = false; sscanf(Cmd, "%i %c", &window, &grph); - if (window >= GraphTraceLen) { + if (window >= conn->GraphTraceLen) { PrintAndLog("window must be smaller than trace (%d samples)", - GraphTraceLen); + conn->GraphTraceLen); return 0; } if (grph == 'g') updateGrph=true; - return AutoCorrelate(GraphBuffer, GraphBuffer, GraphTraceLen, window, updateGrph, true); + return AutoCorrelate(conn, conn->GraphBuffer, conn->GraphBuffer, conn->GraphTraceLen, window, updateGrph, true); } -int CmdBitsamples(const char *Cmd) +int CmdBitsamples(pm3_connection* conn, const char *Cmd) { int cnt = 0; uint8_t got[12288]; - GetFromBigBuf(got,sizeof(got),0); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, got, sizeof(got), 0); + WaitForResponse(conn, CMD_ACK,NULL); for (int j = 0; j < sizeof(got); j++) { for (int k = 0; k < 8; k++) { if(got[j] & (1 << (7 - k))) { - GraphBuffer[cnt++] = 1; + conn->GraphBuffer[cnt++] = 1; } else { - GraphBuffer[cnt++] = 0; + conn->GraphBuffer[cnt++] = 0; } } } - GraphTraceLen = cnt; - RepaintGraphWindow(); + conn->GraphTraceLen = cnt; + RepaintGraphWindow(conn); return 0; } -int CmdBuffClear(const char *Cmd) +int CmdBuffClear(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_BUFF_CLEAR}; - SendCommand(&c); - ClearGraph(true); + SendCommand(conn, &c); + ClearGraph(conn, true); return 0; } -int CmdDec(const char *Cmd) +int CmdDec(pm3_connection* conn, const char *Cmd) { - for (int i = 0; i < (GraphTraceLen / 2); ++i) - GraphBuffer[i] = GraphBuffer[i * 2]; - GraphTraceLen /= 2; + for (int i = 0; i < (conn->GraphTraceLen / 2); ++i) + conn->GraphBuffer[i] = conn->GraphBuffer[i * 2]; + conn->GraphTraceLen /= 2; PrintAndLog("decimated by 2"); - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } /** @@ -632,7 +629,7 @@ int CmdDec(const char *Cmd) * @param Cmd * @return */ -int CmdUndec(const char *Cmd) +int CmdUndec(pm3_connection* conn, const char *Cmd) { if(param_getchar(Cmd, 0) == 'h') { @@ -649,40 +646,40 @@ int CmdUndec(const char *Cmd) //We have memory, don't we? int swap[MAX_GRAPH_TRACE_LEN] = { 0 }; uint32_t g_index = 0, s_index = 0; - while(g_index < GraphTraceLen && s_index + factor < MAX_GRAPH_TRACE_LEN) + while(g_index < conn->GraphTraceLen && s_index + factor < MAX_GRAPH_TRACE_LEN) { int count = 0; for(count = 0; count < factor && s_index + count < MAX_GRAPH_TRACE_LEN; count++) - swap[s_index+count] = GraphBuffer[g_index]; + swap[s_index+count] = conn->GraphBuffer[g_index]; s_index += count; g_index++; } - memcpy(GraphBuffer, swap, s_index * sizeof(int)); - GraphTraceLen = s_index; - RepaintGraphWindow(); + memcpy(conn->GraphBuffer, swap, s_index * sizeof(int)); + conn->GraphTraceLen = s_index; + RepaintGraphWindow(conn); return 0; } //by marshmellow //shift graph zero up or down based on input + or - -int CmdGraphShiftZero(const char *Cmd) +int CmdGraphShiftZero(pm3_connection* conn, const char *Cmd) { int shift=0; //set options from parameters entered with the command sscanf(Cmd, "%i", &shift); int shiftedVal=0; - for(int i = 0; iGraphTraceLen; i++){ + shiftedVal=conn->GraphBuffer[i]+shift; if (shiftedVal>127) shiftedVal=127; else if (shiftedVal<-127) shiftedVal=-127; - GraphBuffer[i]= shiftedVal; + conn->GraphBuffer[i]= shiftedVal; } - CmdNorm(""); + CmdNorm(conn, ""); return 0; } @@ -702,21 +699,21 @@ int AskEdgeDetect(const int *in, int *out, int len, int threshold) { //use large jumps in read samples to identify edges of waves and then amplify that wave to max //similar to dirtheshold, threshold commands //takes a threshold length which is the measured length between two samples then determines an edge -int CmdAskEdgeDetect(const char *Cmd) +int CmdAskEdgeDetect(pm3_connection* conn, const char *Cmd) { int thresLen = 25; int ans = 0; sscanf(Cmd, "%i", &thresLen); - ans = AskEdgeDetect(GraphBuffer, GraphBuffer, GraphTraceLen, thresLen); - RepaintGraphWindow(); + ans = AskEdgeDetect(conn->GraphBuffer, conn->GraphBuffer, conn->GraphTraceLen, thresLen); + RepaintGraphWindow(conn); return ans; } /* Print our clock rate */ // uses data from graphbuffer // adjusted to take char parameter for type of modulation to find the clock - by marshmellow. -int CmdDetectClockRate(const char *Cmd) +int CmdDetectClockRate(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 6 || strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') { @@ -732,13 +729,13 @@ int CmdDetectClockRate(const char *Cmd) } int ans=0; if (cmdp == 'a'){ - ans = GetAskClock(Cmd+1, true, false); + ans = GetAskClock(conn, Cmd+1, true, false); } else if (cmdp == 'f'){ - ans = GetFskClock("", true, false); + ans = GetFskClock(conn, "", true, false); } else if (cmdp == 'n'){ - ans = GetNrzClock("", true, false); + ans = GetNrzClock(conn, "", true, false); } else if (cmdp == 'p'){ - ans = GetPskClock("", true, false); + ans = GetPskClock(conn, "", true, false); } else { PrintAndLog ("Please specify a valid modulation to detect the clock of - see option h for help"); } @@ -770,7 +767,7 @@ char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert) //fsk raw demod and print binary //takes 4 arguments - Clock, invert, fchigh, fclow //defaults: clock = 50, invert=1, fchigh=10, fclow=8 (RF/10 RF/8 (fsk2a)) -int FSKrawDemod(const char *Cmd, bool verbose) +int FSKrawDemod(pm3_connection* conn, const char *Cmd, bool verbose) { //raw fsk demod no manchester decoding no start bit finding just get binary from wave uint8_t rfLen, invert, fchigh, fclow; @@ -788,7 +785,7 @@ int FSKrawDemod(const char *Cmd, bool verbose) } } uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (BitLen==0) return 0; //get field clock lengths uint16_t fcs=0; @@ -811,14 +808,14 @@ int FSKrawDemod(const char *Cmd, bool verbose) int startIdx = 0; int size = fskdemod(BitStream, BitLen, rfLen, invert, fchigh, fclow, &startIdx); if (size > 0) { - setDemodBuf(BitStream,size,0); - setClockGrid(rfLen, startIdx); + setDemodBuf(conn, BitStream, size, 0); + setClockGrid(conn, rfLen, startIdx); // Now output the bitstream to the scrollback by line of 16 bits if (verbose || g_debugMode) { PrintAndLog("\nUsing Clock:%u, invert:%u, fchigh:%u, fclow:%u", (unsigned int)rfLen, (unsigned int)invert, (unsigned int)fchigh, (unsigned int)fclow); PrintAndLog("%s decoded bitstream:",GetFSKType(fchigh,fclow,invert)); - printDemodBuff(); + printDemodBuff(conn); } return 1; @@ -832,7 +829,7 @@ int FSKrawDemod(const char *Cmd, bool verbose) //fsk raw demod and print binary //takes 4 arguments - Clock, invert, fchigh, fclow //defaults: clock = 50, invert=1, fchigh=10, fclow=8 (RF/10 RF/8 (fsk2a)) -int CmdFSKrawdemod(const char *Cmd) +int CmdFSKrawdemod(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 20 || cmdp == 'h' || cmdp == 'H') { @@ -851,12 +848,12 @@ int CmdFSKrawdemod(const char *Cmd) PrintAndLog(" : data rawdemod fs 50 1 10 8 = demod an fsk2a RF/50 tag from GraphBuffer"); return 0; } - return FSKrawDemod(Cmd, true); + return FSKrawDemod(conn, Cmd, true); } //by marshmellow //attempt to psk1 demod graph buffer -int PSKDemod(const char *Cmd, bool verbose) +int PSKDemod(pm3_connection* conn, const char *Cmd, bool verbose) { int invert=0; int clk=0; @@ -871,7 +868,7 @@ int PSKDemod(const char *Cmd, bool verbose) return 0; } uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (BitLen==0) return 0; int errCnt=0; int startIdx = 0; @@ -891,8 +888,8 @@ int PSKDemod(const char *Cmd, bool verbose) } } //prime demod buffer for output - setDemodBuf(BitStream,BitLen,0); - setClockGrid(clk, startIdx); + setDemodBuf(conn, BitStream, BitLen, 0); + setClockGrid(conn, clk, startIdx); return 1; } @@ -901,7 +898,7 @@ int PSKDemod(const char *Cmd, bool verbose) // takes 3 arguments - clock, invert, maxErr as integers // attempts to demodulate nrz only // prints binary found and saves in demodbuffer for further commands -int NRZrawDemod(const char *Cmd, bool verbose) +int NRZrawDemod(pm3_connection* conn, const char *Cmd, bool verbose) { int invert=0; int clk=0; @@ -916,7 +913,7 @@ int NRZrawDemod(const char *Cmd, bool verbose) return 0; } uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (BitLen==0) return 0; int errCnt=0; int clkStartIdx = 0; @@ -931,20 +928,20 @@ int NRZrawDemod(const char *Cmd, bool verbose) } if (verbose || g_debugMode) PrintAndLog("Tried NRZ Demod using Clock: %d - invert: %d - Bits Found: %d",clk,invert,BitLen); //prime demod buffer for output - setDemodBuf(BitStream,BitLen,0); - setClockGrid(clk, clkStartIdx); + setDemodBuf(conn, BitStream, BitLen, 0); + setClockGrid(conn, clk, clkStartIdx); if (errCnt>0 && (verbose || g_debugMode)) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); if (verbose || g_debugMode) { PrintAndLog("NRZ demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); + printDemodBuff(conn); } return 1; } -int CmdNRZrawDemod(const char *Cmd) +int CmdNRZrawDemod(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 16 || cmdp == 'h' || cmdp == 'H') { @@ -960,14 +957,14 @@ int CmdNRZrawDemod(const char *Cmd) PrintAndLog(" : data rawdemod nr 64 1 0 = demod a nrz/direct tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); return 0; } - return NRZrawDemod(Cmd, true); + return NRZrawDemod(conn, Cmd, true); } // by marshmellow // takes 3 arguments - clock, invert, maxErr as integers // attempts to demodulate psk only // prints binary found and saves in demodbuffer for further commands -int CmdPSK1rawDemod(const char *Cmd) +int CmdPSK1rawDemod(pm3_connection* conn, const char *Cmd) { int ans; char cmdp = param_getchar(Cmd, 0); @@ -984,7 +981,7 @@ int CmdPSK1rawDemod(const char *Cmd) PrintAndLog(" : data rawdemod p1 64 1 0 = demod a psk1 tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); return 0; } - ans = PSKDemod(Cmd, true); + ans = PSKDemod(conn, Cmd, true); //output if (!ans){ if (g_debugMode) PrintAndLog("Error demoding: %d",ans); @@ -993,13 +990,13 @@ int CmdPSK1rawDemod(const char *Cmd) PrintAndLog("PSK1 demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); + printDemodBuff(conn); return 1; } // by marshmellow // takes same args as cmdpsk1rawdemod -int CmdPSK2rawDemod(const char *Cmd) +int CmdPSK2rawDemod(pm3_connection* conn, const char *Cmd) { int ans=0; char cmdp = param_getchar(Cmd, 0); @@ -1016,20 +1013,20 @@ int CmdPSK2rawDemod(const char *Cmd) PrintAndLog(" : data rawdemod p2 64 1 0 = demod a psk2 tag from GraphBuffer using a clock of RF/64, inverting output and allowing 0 demod errors"); return 0; } - ans=PSKDemod(Cmd, true); + ans=PSKDemod(conn, Cmd, true); if (!ans){ if (g_debugMode) PrintAndLog("Error demoding: %d",ans); return 0; } - psk1TOpsk2(DemodBuffer, DemodBufferLen); + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); PrintAndLog("PSK2 demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); + printDemodBuff(conn); return 1; } // by marshmellow - combines all raw demod functions into one menu command -int CmdRawDemod(const char *Cmd) +int CmdRawDemod(pm3_connection* conn, const char *Cmd) { char cmdp = Cmd[0]; //param_getchar(Cmd, 0); @@ -1053,65 +1050,65 @@ int CmdRawDemod(const char *Cmd) char cmdp2 = Cmd[1]; int ans = 0; if (cmdp == 'f' && cmdp2 == 's'){ - ans = CmdFSKrawdemod(Cmd+2); + ans = CmdFSKrawdemod(conn, Cmd+2); } else if(cmdp == 'a' && cmdp2 == 'b'){ - ans = Cmdaskbiphdemod(Cmd+2); + ans = Cmdaskbiphdemod(conn, Cmd+2); } else if(cmdp == 'a' && cmdp2 == 'm'){ - ans = Cmdaskmandemod(Cmd+2); + ans = Cmdaskmandemod(conn, Cmd+2); } else if(cmdp == 'a' && cmdp2 == 'r'){ - ans = Cmdaskrawdemod(Cmd+2); + ans = Cmdaskrawdemod(conn, Cmd+2); } else if(cmdp == 'n' && cmdp2 == 'r'){ - ans = CmdNRZrawDemod(Cmd+2); + ans = CmdNRZrawDemod(conn, Cmd+2); } else if(cmdp == 'p' && cmdp2 == '1'){ - ans = CmdPSK1rawDemod(Cmd+2); + ans = CmdPSK1rawDemod(conn, Cmd+2); } else if(cmdp == 'p' && cmdp2 == '2'){ - ans = CmdPSK2rawDemod(Cmd+2); + ans = CmdPSK2rawDemod(conn, Cmd+2); } else { PrintAndLog("unknown modulation entered - see help ('h') for parameter structure"); } return ans; } -void setClockGrid(int clk, int offset) { - g_DemodStartIdx = offset; - g_DemodClock = clk; +void setClockGrid(pm3_connection* conn, int clk, int offset) { + conn->g_DemodStartIdx = offset; + conn->g_DemodClock = clk; if (g_debugMode) PrintAndLog("demodoffset %d, clk %d",offset,clk); if (offset > clk) offset %= clk; if (offset < 0) offset += clk; - if (offset > GraphTraceLen || offset < 0) return; - if (clk < 8 || clk > GraphTraceLen) { - GridLocked = false; - GridOffset = 0; - PlotGridX = 0; - PlotGridXdefault = 0; - RepaintGraphWindow(); + if (offset > conn->GraphTraceLen || offset < 0) return; + if (clk < 8 || clk > conn->GraphTraceLen) { + conn->GridLocked = false; + conn->GridOffset = 0; + conn->PlotGridX = 0; + conn->PlotGridXdefault = 0; + RepaintGraphWindow(conn); } else { - GridLocked = true; - GridOffset = offset; - PlotGridX = clk; - PlotGridXdefault = clk; - RepaintGraphWindow(); + conn->GridLocked = true; + conn->GridOffset = offset; + conn->PlotGridX = clk; + conn->PlotGridXdefault = clk; + RepaintGraphWindow(conn); } } -int CmdGrid(const char *Cmd) +int CmdGrid(pm3_connection* conn, const char *Cmd) { - sscanf(Cmd, "%i %i", &PlotGridX, &PlotGridY); - PlotGridXdefault= PlotGridX; - PlotGridYdefault= PlotGridY; - RepaintGraphWindow(); + sscanf(Cmd, "%i %i", &conn->PlotGridX, &conn->PlotGridY); + conn->PlotGridXdefault= conn->PlotGridX; + conn->PlotGridYdefault= conn->PlotGridY; + RepaintGraphWindow(conn); return 0; } -int CmdSetGraphMarkers(const char *Cmd) { - sscanf(Cmd, "%i %i", &CursorCPos, &CursorDPos); - RepaintGraphWindow(); +int CmdSetGraphMarkers(pm3_connection* conn, const char *Cmd) { + sscanf(Cmd, "%i %i", &conn->CursorCPos, &conn->CursorDPos); + RepaintGraphWindow(conn); return 0; } -int CmdHexsamples(const char *Cmd) +int CmdHexsamples(pm3_connection* conn, const char *Cmd) { int i, j; int requested = 0; @@ -1131,8 +1128,8 @@ int CmdHexsamples(const char *Cmd) return 0; } - GetFromBigBuf(got,requested,offset); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, got, requested, offset); + WaitForResponse(conn, CMD_ACK, NULL); i = 0; for (j = 0; j < requested; j++) { @@ -1154,25 +1151,25 @@ int CmdHexsamples(const char *Cmd) return 0; } -int CmdHide(const char *Cmd) +int CmdHide(pm3_connection* conn, const char *Cmd) { - HideGraphWindow(); + HideGraphWindow(conn); return 0; } //zero mean GraphBuffer -int CmdHpf(const char *Cmd) +int CmdHpf(pm3_connection* conn, const char *Cmd) { int i; int accum = 0; - for (i = 10; i < GraphTraceLen; ++i) - accum += GraphBuffer[i]; - accum /= (GraphTraceLen - 10); - for (i = 0; i < GraphTraceLen; ++i) - GraphBuffer[i] -= accum; + for (i = 10; i < conn->GraphTraceLen; ++i) + accum += conn->GraphBuffer[i]; + accum /= (conn->GraphTraceLen - 10); + for (i = 0; i < conn->GraphTraceLen; ++i) + conn->GraphBuffer[i] -= accum; - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } @@ -1187,7 +1184,7 @@ uint8_t getByte(uint8_t bits_per_sample, BitstreamIn* b) return val; } -int getSamples(int n, bool silent) +int getSamples(pm3_connection* conn, int n, bool silent) { //If we get all but the last byte in bigbuf, // we don't have to worry about remaining trash @@ -1200,10 +1197,10 @@ int getSamples(int n, bool silent) n = sizeof(got); if (!silent) PrintAndLog("Reading %d bytes from device memory\n", n); - GetFromBigBuf(got,n,0); + GetFromBigBuf(conn, got, n, 0); if (!silent) PrintAndLog("Data fetched"); UsbCommand response; - WaitForResponse(CMD_ACK, &response); + WaitForResponse(conn, CMD_ACK, &response); uint8_t bits_per_sample = 8; //Old devices without this feature would send 0 at arg[0] @@ -1221,31 +1218,31 @@ int getSamples(int n, bool silent) int j =0; for (j = 0; j * bits_per_sample < n * 8 && j < n; j++) { uint8_t sample = getByte(bits_per_sample, &bout); - GraphBuffer[j] = ((int) sample )- 128; + conn->GraphBuffer[j] = ((int) sample )- 128; } - GraphTraceLen = j; + conn->GraphTraceLen = j; PrintAndLog("Unpacked %d samples" , j ); }else { for (int j = 0; j < n; j++) { - GraphBuffer[j] = ((int)got[j]) - 128; + conn->GraphBuffer[j] = ((int)got[j]) - 128; } - GraphTraceLen = n; + conn->GraphTraceLen = n; } - setClockGrid(0,0); - DemodBufferLen = 0; - RepaintGraphWindow(); + setClockGrid(conn, 0, 0); + conn->DemodBufferLen = 0; + RepaintGraphWindow(conn); return 0; } -int CmdSamples(const char *Cmd) +int CmdSamples(pm3_connection* conn, const char *Cmd) { int n = strtol(Cmd, NULL, 0); - return getSamples(n, false); + return getSamples(conn, n, false); } -int CmdTuneSamples(const char *Cmd) +int CmdTuneSamples(pm3_connection* conn, const char *Cmd) { int timeout = 0, arg = FLAG_TUNE_ALL; @@ -1261,10 +1258,10 @@ int CmdTuneSamples(const char *Cmd) printf("\nMeasuring antenna characteristics, please wait..."); UsbCommand c = {CMD_MEASURE_ANTENNA_TUNING, {arg, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - while(!WaitForResponseTimeout(CMD_MEASURED_ANTENNA_TUNING,&resp,1000)) { + while(!WaitForResponseTimeout(conn, CMD_MEASURED_ANTENNA_TUNING,&resp,1000)) { timeout++; printf("."); if (timeout > 7) { @@ -1302,20 +1299,20 @@ int CmdTuneSamples(const char *Cmd) if (peakv >= LF_UNUSABLE_V) { for (int i = 0; i < 256; i++) { - GraphBuffer[i] = resp.d.asBytes[i] - 128; + conn->GraphBuffer[i] = resp.d.asBytes[i] - 128; } PrintAndLog("Displaying LF tuning graph. Divisor 89 is 134khz, 95 is 125khz.\n"); PrintAndLog("\n"); - GraphTraceLen = 256; - ShowGraphWindow(); - RepaintGraphWindow(); + conn->GraphTraceLen = 256; + ShowGraphWindow(conn); + RepaintGraphWindow(conn); } return 0; } -int CmdLoad(const char *Cmd) +int CmdLoad(pm3_connection* conn, const char *Cmd) { char filename[FILE_PATH_SIZE] = {0x00}; int len = 0; @@ -1330,88 +1327,88 @@ int CmdLoad(const char *Cmd) return 0; } - GraphTraceLen = 0; + conn->GraphTraceLen = 0; char line[80]; while (fgets(line, sizeof (line), f)) { - GraphBuffer[GraphTraceLen] = atoi(line); - GraphTraceLen++; + conn->GraphBuffer[conn->GraphTraceLen++] = atoi(line); } fclose(f); - PrintAndLog("loaded %d samples", GraphTraceLen); - setClockGrid(0,0); - DemodBufferLen = 0; - RepaintGraphWindow(); + + PrintAndLog("loaded %d samples", conn->GraphTraceLen); + setClockGrid(conn, 0, 0); + conn->DemodBufferLen = 0; + RepaintGraphWindow(conn); return 0; } -int CmdLtrim(const char *Cmd) +int CmdLtrim(pm3_connection* conn, const char *Cmd) { int ds = atoi(Cmd); - if (GraphTraceLen<=0) return 0; - for (int i = ds; i < GraphTraceLen; ++i) - GraphBuffer[i-ds] = GraphBuffer[i]; - GraphTraceLen -= ds; + if (conn->GraphTraceLen<=0) return 0; + for (int i = ds; i < conn->GraphTraceLen; ++i) + conn->GraphBuffer[i-ds] = conn->GraphBuffer[i]; + conn->GraphTraceLen -= ds; - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } // trim graph to input argument length -int CmdRtrim(const char *Cmd) +int CmdRtrim(pm3_connection* conn, const char *Cmd) { int ds = atoi(Cmd); - GraphTraceLen = ds; + conn->GraphTraceLen = ds; - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } // trim graph (middle) piece -int CmdMtrim(const char *Cmd) { +int CmdMtrim(pm3_connection* conn, const char *Cmd) { int start = 0, stop = 0; sscanf(Cmd, "%i %i", &start, &stop); - if (start > GraphTraceLen || stop > GraphTraceLen || start > stop) return 0; + if (start > conn->GraphTraceLen || stop > conn->GraphTraceLen || start > stop) return 0; start++; //leave start position sample - GraphTraceLen = stop - start; - for (int i = 0; i < GraphTraceLen; i++) { - GraphBuffer[i] = GraphBuffer[start+i]; + conn->GraphTraceLen = stop - start; + for (int i = 0; i < conn->GraphTraceLen; i++) { + conn->GraphBuffer[i] = conn->GraphBuffer[start+i]; } return 0; } -int CmdNorm(const char *Cmd) +int CmdNorm(pm3_connection* conn, const char *Cmd) { int i; int max = INT_MIN, min = INT_MAX; - for (i = 10; i < GraphTraceLen; ++i) { - if (GraphBuffer[i] > max) - max = GraphBuffer[i]; - if (GraphBuffer[i] < min) - min = GraphBuffer[i]; + for (i = 10; i < conn->GraphTraceLen; ++i) { + if (conn->GraphBuffer[i] > max) + max = conn->GraphBuffer[i]; + if (conn->GraphBuffer[i] < min) + min = conn->GraphBuffer[i]; } if (max != min) { - for (i = 0; i < GraphTraceLen; ++i) { - GraphBuffer[i] = ((long)(GraphBuffer[i] - ((max + min) / 2)) * 256) / (max - min); + for (i = 0; i < conn->GraphTraceLen; ++i) { + conn->GraphBuffer[i] = ((long)(conn->GraphBuffer[i] - ((max + min) / 2)) * 256) / (max - min); //marshmelow: adjusted *1000 to *256 to make +/- 128 so demod commands still work } } - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } -int CmdPlot(const char *Cmd) +int CmdPlot(pm3_connection* conn, const char *Cmd) { - ShowGraphWindow(); + ShowGraphWindow(conn); return 0; } -int CmdSave(const char *Cmd) +int CmdSave(pm3_connection* conn, const char *Cmd) { char filename[FILE_PATH_SIZE] = {0x00}; int len = 0; @@ -1427,22 +1424,22 @@ int CmdSave(const char *Cmd) return 0; } int i; - for (i = 0; i < GraphTraceLen; i++) { - fprintf(f, "%d\n", GraphBuffer[i]); + for (i = 0; i < conn->GraphTraceLen; i++) { + fprintf(f, "%d\n", conn->GraphBuffer[i]); } fclose(f); PrintAndLog("saved to '%s'", Cmd); return 0; } -int CmdScale(const char *Cmd) +int CmdScale(pm3_connection* conn, const char *Cmd) { - CursorScaleFactor = atoi(Cmd); - if (CursorScaleFactor == 0) { + conn->CursorScaleFactor = atoi(Cmd); + if (conn->CursorScaleFactor == 0) { PrintAndLog("bad, can't have zero scale"); - CursorScaleFactor = 1; + conn->CursorScaleFactor = 1; } - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } @@ -1474,36 +1471,36 @@ int directionalThreshold(const int* in, int *out, size_t len, int8_t up, int8_t return 0; } -int CmdDirectionalThreshold(const char *Cmd) +int CmdDirectionalThreshold(pm3_connection* conn, const char *Cmd) { int8_t upThres = param_get8(Cmd, 0); int8_t downThres = param_get8(Cmd, 1); printf("Applying Up Threshold: %d, Down Threshold: %d\n", upThres, downThres); - directionalThreshold(GraphBuffer, GraphBuffer,GraphTraceLen, upThres, downThres); - RepaintGraphWindow(); + directionalThreshold(conn->GraphBuffer, conn->GraphBuffer, conn->GraphTraceLen, upThres, downThres); + RepaintGraphWindow(conn); return 0; } -int CmdZerocrossings(const char *Cmd) +int CmdZerocrossings(pm3_connection* conn, const char *Cmd) { // Zero-crossings aren't meaningful unless the signal is zero-mean. - CmdHpf(""); + CmdHpf(conn, ""); int sign = 1; int zc = 0; int lastZc = 0; - for (int i = 0; i < GraphTraceLen; ++i) { - if (GraphBuffer[i] * sign >= 0) { + for (int i = 0; i < conn->GraphTraceLen; ++i) { + if (conn->GraphBuffer[i] * sign >= 0) { // No change in sign, reproduce the previous sample count. zc++; - GraphBuffer[i] = lastZc; + conn->GraphBuffer[i] = lastZc; } else { // Change in sign, reset the sample count. sign = -sign; - GraphBuffer[i] = lastZc; + conn->GraphBuffer[i] = lastZc; if (sign > 0) { lastZc = zc; zc = 0; @@ -1511,7 +1508,7 @@ int CmdZerocrossings(const char *Cmd) } } - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } @@ -1526,7 +1523,7 @@ int usage_data_bin2hex(){ * @param Cmd * @return */ -int Cmdbin2hex(const char *Cmd) +int Cmdbin2hex(pm3_connection* conn, const char *Cmd) { int bg =0, en =0; if(param_getptr(Cmd, &bg, &en, 0)) @@ -1572,7 +1569,7 @@ int usage_data_hex2bin() { } -int Cmdhex2bin(const char *Cmd) +int Cmdhex2bin(pm3_connection* conn, const char *Cmd) { int bg =0, en =0; if(param_getptr(Cmd, &bg, &en, 0)) @@ -1687,11 +1684,11 @@ void GetHiLoTone(int *LowTone, int *HighTone, int clk, int LowToneFC, int HighTo //old CmdFSKdemod adapted by marshmellow //converts FSK to clear NRZ style wave. (or demodulates) -int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { +int FSKToNRZ(pm3_connection* conn, int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { uint8_t ans=0; if (clk == 0 || LowToneFC == 0 || HighToneFC == 0) { int firstClockEdge=0; - ans = fskClocks((uint8_t *) &LowToneFC, (uint8_t *) &HighToneFC, (uint8_t *) &clk, false, &firstClockEdge); + ans = fskClocks(conn, (uint8_t *) &LowToneFC, (uint8_t *) &HighToneFC, (uint8_t *) &clk, false, &firstClockEdge); if (g_debugMode > 1) { PrintAndLog ("DEBUG FSKtoNRZ: detected clocks: fc_low %i, fc_high %i, clk %i, firstClockEdge %i, ans %u", LowToneFC, HighToneFC, clk, firstClockEdge, ans); } @@ -1758,7 +1755,7 @@ int usage_data_fsktonrz() { return 0; } -int CmdFSKToNRZ(const char *Cmd) { +int CmdFSKToNRZ(pm3_connection* conn, const char *Cmd) { // take clk, fc_low, fc_high // blank = auto; bool errors = false; @@ -1797,11 +1794,11 @@ int CmdFSKToNRZ(const char *Cmd) { //Validations if(errors) return usage_data_fsktonrz(); - setClockGrid(0,0); - DemodBufferLen = 0; - int ans = FSKToNRZ(GraphBuffer, &GraphTraceLen, clk, fc_low, fc_high); - CmdNorm(""); - RepaintGraphWindow(); + setClockGrid(conn, 0, 0); + conn->DemodBufferLen = 0; + int ans = FSKToNRZ(conn, conn->GraphBuffer, &conn->GraphTraceLen, clk, fc_low, fc_high); + CmdNorm(conn, ""); + RepaintGraphWindow(conn); return ans; } @@ -1811,7 +1808,7 @@ static command_t CommandTable[] = {"help", CmdHelp, 1, "This help"}, {"askedgedetect", CmdAskEdgeDetect, 1, "[threshold] Adjust Graph for manual ask demod using the length of sample differences to detect the edge of a wave (use 20-45, def:25)"}, {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"}, - {"biphaserawdecode",CmdBiphaseDecodeRaw,1, "[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, + {"biphaserawdecode",CmdBiphaseDecodeRaw,1, "[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in conn->DemodBuffer (offset = 0|1 bits to shift the decode start)"}, {"bin2hex", Cmdbin2hex, 1, "bin2hex -- Converts binary to hexadecimal"}, {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"}, {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"}, @@ -1828,10 +1825,10 @@ static command_t CommandTable[] = {"ltrim", CmdLtrim, 1, " -- Trim samples from left of trace"}, {"rtrim", CmdRtrim, 1, " -- Trim samples from right of trace"}, {"mtrim", CmdMtrim, 1, " -- Trim out samples from the specified start to the specified stop"}, - {"manrawdecode", Cmdmandecoderaw, 1, "[invert] [maxErr] -- Manchester decode binary stream in DemodBuffer"}, + {"manrawdecode", Cmdmandecoderaw, 1, "[invert] [maxErr] -- Manchester decode binary stream in conn->DemodBuffer"}, {"norm", CmdNorm, 1, "Normalize max/min to +/-128"}, {"plot", CmdPlot, 1, "Show graph window (hit 'h' in window for keystroke help)"}, - {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] [o] [l] -- print the data in the DemodBuffer - 'x' for hex output"}, + {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] [o] [l] -- print the data in the conn->DemodBuffer - 'x' for hex output"}, {"rawdemod", CmdRawDemod, 1, "[modulation] ... -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"}, {"samples", CmdSamples, 0, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"}, {"save", CmdSave, 1, " -- Save trace (from graph window)"}, @@ -1846,14 +1843,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdData(const char *Cmd) +int CmdData(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmddata.h b/client/cmddata.h index 0484acdb..900d1ab4 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -19,62 +19,56 @@ command_t * CmdDataCommands(); -int CmdData(const char *Cmd); -void printDemodBuff(void); -void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx); -bool getDemodBuf(uint8_t *buff, size_t *size); -void save_restoreDB(uint8_t saveOpt);// option '1' to save DemodBuffer any other to restore -int CmdPrintDemodBuff(const char *Cmd); -int Cmdaskrawdemod(const char *Cmd); -int Cmdaskmandemod(const char *Cmd); -int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose); -int CmdAutoCorr(const char *Cmd); -int CmdBiphaseDecodeRaw(const char *Cmd); -int CmdBitsamples(const char *Cmd); -int CmdBuffClear(const char *Cmd); -int CmdDec(const char *Cmd); -int CmdDetectClockRate(const char *Cmd); -int CmdFSKrawdemod(const char *Cmd); -int CmdPSK1rawDemod(const char *Cmd); -int CmdPSK2rawDemod(const char *Cmd); -int CmdGrid(const char *Cmd); -int CmdGetBitStream(const char *Cmd); -int CmdHexsamples(const char *Cmd); -int CmdHide(const char *Cmd); -int CmdHpf(const char *Cmd); -int CmdLoad(const char *Cmd); -int CmdLtrim(const char *Cmd); -int CmdRtrim(const char *Cmd); -int Cmdmandecoderaw(const char *Cmd); -int CmdNorm(const char *Cmd); -int CmdNRZrawDemod(const char *Cmd); -int CmdPlot(const char *Cmd); -int CmdPrintDemodBuff(const char *Cmd); -int CmdRawDemod(const char *Cmd); -int CmdSamples(const char *Cmd); -int CmdTuneSamples(const char *Cmd); -int CmdSave(const char *Cmd); -int CmdScale(const char *Cmd); -int CmdDirectionalThreshold(const char *Cmd); -int CmdZerocrossings(const char *Cmd); -int ASKbiphaseDemod(const char *Cmd, bool verbose); -int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType); -int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck); -int FSKrawDemod(const char *Cmd, bool verbose); -int PSKDemod(const char *Cmd, bool verbose); -int NRZrawDemod(const char *Cmd, bool verbose); -int getSamples(int n, bool silent); -void setClockGrid(int clk, int offset); +int CmdData(pm3_connection* conn, const char *Cmd); +void printDemodBuff(pm3_connection* conn); +void setDemodBuf(pm3_connection* conn, uint8_t *buff, size_t size, size_t startIdx); +bool getDemodBuf(pm3_connection* conn, uint8_t *buff, size_t *size); +// option '1' to save DemodBuffer any other to restore +void save_restoreDB(pm3_connection* conn, uint8_t saveOpt); + +int CmdPrintDemodBuff(pm3_connection* conn, const char *Cmd); +int Cmdaskrawdemod(pm3_connection* conn, const char *Cmd); +int Cmdaskmandemod(pm3_connection* conn, const char *Cmd); +int AutoCorrelate(pm3_connection* conn, const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose); +int CmdAutoCorr(pm3_connection* conn, const char *Cmd); +int CmdBiphaseDecodeRaw(pm3_connection* conn, const char *Cmd); +int CmdBitsamples(pm3_connection* conn, const char *Cmd); +int CmdBuffClear(pm3_connection* conn, const char *Cmd); +int CmdDec(pm3_connection* conn, const char *Cmd); +int CmdDetectClockRate(pm3_connection* conn, const char *Cmd); +int CmdFSKrawdemod(pm3_connection* conn, const char *Cmd); +int CmdPSK1rawDemod(pm3_connection* conn, const char *Cmd); +int CmdPSK2rawDemod(pm3_connection* conn, const char *Cmd); +int CmdGrid(pm3_connection* conn, const char *Cmd); +int CmdGetBitStream(pm3_connection* conn, const char *Cmd); +int CmdHexsamples(pm3_connection* conn, const char *Cmd); +int CmdHide(pm3_connection* conn, const char *Cmd); +int CmdHpf(pm3_connection* conn, const char *Cmd); +int CmdLoad(pm3_connection* conn, const char *Cmd); +int CmdLtrim(pm3_connection* conn, const char *Cmd); +int CmdRtrim(pm3_connection* conn, const char *Cmd); +int Cmdmandecoderaw(pm3_connection* conn, const char *Cmd); +int CmdNorm(pm3_connection* conn, const char *Cmd); +int CmdNRZrawDemod(pm3_connection* conn, const char *Cmd); +int CmdPlot(pm3_connection* conn, const char *Cmd); +int CmdPrintDemodBuff(pm3_connection* conn, const char *Cmd); +int CmdRawDemod(pm3_connection* conn, const char *Cmd); +int CmdSamples(pm3_connection* conn, const char *Cmd); +int CmdTuneSamples(pm3_connection* conn, const char *Cmd); +int CmdSave(pm3_connection* conn, const char *Cmd); +int CmdScale(pm3_connection* conn, const char *Cmd); +int CmdDirectionalThreshold(pm3_connection* conn, const char *Cmd); +int CmdZerocrossings(pm3_connection* conn, const char *Cmd); +int ASKbiphaseDemod(pm3_connection* conn, const char *Cmd, bool verbose); +int ASKDemod(pm3_connection* conn, const char *Cmd, bool verbose, bool emSearch, uint8_t askType); +int ASKDemod_ext(pm3_connection* conn, const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck); +int FSKrawDemod(pm3_connection* conn, const char *Cmd, bool verbose); +int PSKDemod(pm3_connection* conn, const char *Cmd, bool verbose); +int NRZrawDemod(pm3_connection* conn, const char *Cmd, bool verbose); +int getSamples(pm3_connection* conn, int n, bool silent); +void setClockGrid(pm3_connection* conn, int clk, int offset); int directionalThreshold(const int* in, int *out, size_t len, int8_t up, int8_t down); extern int AskEdgeDetect(const int *in, int *out, int len, int threshold); //int autoCorr(const int* in, int *out, size_t len, int window); -#define MAX_DEMOD_BUF_LEN (1024*128) -extern uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; -extern size_t DemodBufferLen; -extern int g_DemodStartIdx; -extern int g_DemodClock; -extern uint8_t g_debugMode; -#define BIGBUF_SIZE 40000 - #endif diff --git a/client/cmdhf.c b/client/cmdhf.c index 6aa5ae4e..c1026f8e 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -31,12 +31,12 @@ #include "cmdhftopaz.h" #include "protocols.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); -int CmdHFTune(const char *Cmd) +int CmdHFTune(pm3_connection* conn, const char *Cmd) { UsbCommand c={CMD_MEASURE_ANTENNA_TUNING_HF}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -557,7 +557,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui } -int CmdHFList(const char *Cmd) +int CmdHFList(pm3_connection* conn, const char *Cmd) { bool showWaitCycles = false; bool markCRCBytes = false; @@ -627,8 +627,8 @@ int CmdHFList(const char *Cmd) // Query for the size of the trace UsbCommand response; - GetFromBigBuf(trace, USB_CMD_DATA_SIZE, 0); - WaitForResponse(CMD_ACK, &response); + GetFromBigBuf(conn, trace, USB_CMD_DATA_SIZE, 0); + WaitForResponse(conn, CMD_ACK, &response); uint16_t traceLen = response.arg[2]; if (traceLen > USB_CMD_DATA_SIZE) { uint8_t *p = realloc(trace, traceLen); @@ -638,8 +638,8 @@ int CmdHFList(const char *Cmd) return 2; } trace = p; - GetFromBigBuf(trace, traceLen, 0); - WaitForResponse(CMD_ACK, NULL); + GetFromBigBuf(conn, trace, traceLen, 0); + WaitForResponse(conn, CMD_ACK, NULL); } PrintAndLog("Recorded Activity (TraceLen = %d bytes)", traceLen); @@ -660,26 +660,27 @@ int CmdHFList(const char *Cmd) return 0; } -int CmdHFSearch(const char *Cmd){ +int CmdHFSearch(pm3_connection* conn, const char *Cmd){ int ans = 0; PrintAndLog(""); - ans = CmdHF14AReader("s"); + ans = CmdHF14AReader(conn, "s"); if (ans > 0) { PrintAndLog("\nValid ISO14443A Tag Found - Quiting Search\n"); return ans; } - ans = HFiClassReader("", false, false); + ans = HFiClassReader(conn, "", false, false); if (ans) { PrintAndLog("\nValid iClass Tag (or PicoPass Tag) Found - Quiting Search\n"); return ans; } - ans = HF15Reader("", false); + ans = HF15Reader(conn, "", false); if (ans) { PrintAndLog("\nValid ISO15693 Tag Found - Quiting Search\n"); return ans; } + //14b is longest test currently (and rarest chip type) ... put last - ans = HF14BInfo(false); + ans = HF14BInfo(conn, false); if (ans) { PrintAndLog("\nValid ISO14443B Tag Found - Quiting Search\n"); return ans; @@ -688,11 +689,11 @@ int CmdHFSearch(const char *Cmd){ return 0; } -int CmdHFSnoop(const char *Cmd) +int CmdHFSnoop(pm3_connection* conn, const char *Cmd) { char * pEnd; UsbCommand c = {CMD_HF_SNIFFER, {strtol(Cmd, &pEnd,0),strtol(pEnd, &pEnd,0),0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -715,14 +716,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHF(const char *Cmd) +int CmdHF(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhf.h b/client/cmdhf.h index 026357b5..0109ad67 100644 --- a/client/cmdhf.h +++ b/client/cmdhf.h @@ -11,7 +11,7 @@ #ifndef CMDHF_H__ #define CMDHF_H__ -int CmdHF(const char *Cmd); -int CmdHFTune(const char *Cmd); -int CmdHFList(const char *Cmd); +int CmdHF(pm3_connection* conn, const char *Cmd); +int CmdHFTune(pm3_connection* conn, const char *Cmd); +int CmdHFList(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index db9ce46e..fef78b04 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -28,8 +28,8 @@ #include "cmdhfmfu.h" #include "mifarehost.h" -static int CmdHelp(const char *Cmd); -static void waitCmd(uint8_t iLen); +static int CmdHelp(pm3_connection* conn, const char *Cmd); +static void waitCmd(pm3_connection* conn, uint8_t iLen); // structure and database for uid -> tagtype lookups typedef struct { @@ -127,19 +127,19 @@ char* getTagInfo(uint8_t uid) { return manufactureMapping[len-1].desc; } -int CmdHF14AList(const char *Cmd) +int CmdHF14AList(pm3_connection* conn, const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list 14a' instead"); return 0; } -int CmdHF14AReader(const char *Cmd) +int CmdHF14AReader(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); @@ -152,7 +152,7 @@ int CmdHF14AReader(const char *Cmd) c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -163,7 +163,7 @@ int CmdHF14AReader(const char *Cmd) c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -179,9 +179,9 @@ int CmdHF14AReader(const char *Cmd) c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); - uint32_t tagT = GetHF14AMfU_Type(); + uint32_t tagT = GetHF14AMfU_Type(conn); ul_print_type(tagT, 0); //reconnect for further tests @@ -189,10 +189,10 @@ int CmdHF14AReader(const char *Cmd) c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); @@ -204,7 +204,7 @@ int CmdHF14AReader(const char *Cmd) c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -214,8 +214,8 @@ int CmdHF14AReader(const char *Cmd) c.arg[1] = 1; c.arg[2] = 0; c.d.asBytes[0] = 0x60; - SendCommand(&c); - WaitForResponse(CMD_ACK,&resp); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK,&resp); uint8_t version[10] = {0}; memcpy(version, resp.d.asBytes, resp.arg[0] < sizeof(version) ? resp.arg[0] : sizeof(version)); @@ -258,8 +258,8 @@ int CmdHF14AReader(const char *Cmd) c.arg[1] = 2; c.arg[2] = 0; memcpy(c.d.asBytes, rats, 2); - SendCommand(&c); - WaitForResponse(CMD_ACK,&resp); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK,&resp); memcpy(card.ats, resp.d.asBytes, resp.arg[0]); card.ats_len = resp.arg[0]; // note: ats_len includes CRC Bytes @@ -409,8 +409,8 @@ int CmdHF14AReader(const char *Cmd) c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); - WaitForResponse(CMD_ACK,&resp); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK, &resp); uint8_t isGeneration = resp.arg[0] & 0xff; switch( isGeneration ){ @@ -424,13 +424,13 @@ int CmdHF14AReader(const char *Cmd) c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); return select_status; } // Collect ISO14443 Type A UIDs -int CmdHF14ACUIDs(const char *Cmd) +int CmdHF14ACUIDs(pm3_connection* conn, const char *Cmd) { // requested number of UIDs int n = atoi(Cmd); @@ -443,10 +443,10 @@ int CmdHF14ACUIDs(const char *Cmd) for (int i = 0; i < n; i++) { // execute anticollision procedure UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_RATS, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); iso14a_card_select_t *card = (iso14a_card_select_t *) resp.d.asBytes; @@ -468,7 +468,7 @@ int CmdHF14ACUIDs(const char *Cmd) // ## simulate iso14443a tag // ## greg - added ability to specify tag UID -int CmdHF14ASim(const char *Cmd) +int CmdHF14ASim(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_SIMULATE_TAG_ISO_14443a,{0,0,0}}; @@ -544,11 +544,11 @@ int CmdHF14ASim(const char *Cmd) */ // UsbCommand c = {CMD_SIMULATE_TAG_ISO_14443a,param_get32ex(Cmd,0,0,10),param_get32ex(Cmd,1,0,16),param_get32ex(Cmd,2,0,16)}; // PrintAndLog("Emulating ISO/IEC 14443 type A tag with UID %01d %08x %08x",c.arg[0],c.arg[1],c.arg[2]); - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF14ASnoop(const char *Cmd) { +int CmdHF14ASnoop(pm3_connection* conn, const char *Cmd) { int param = 0; uint8_t ctmp = param_getchar(Cmd, 0) ; @@ -569,12 +569,12 @@ int CmdHF14ASnoop(const char *Cmd) { } UsbCommand c = {CMD_SNOOP_ISO_14443a, {param, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF14ACmdRaw(const char *cmd) { +int CmdHF14ACmdRaw(pm3_connection* conn, const char *cmd) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; bool reply=1; bool crc = false; @@ -731,25 +731,25 @@ int CmdHF14ACmdRaw(const char *cmd) { c.arg[1] = (datalen & 0xFFFF) | ((uint32_t)numbits << 16); memcpy(c.d.asBytes,data,datalen); - SendCommand(&c); + SendCommand(conn, &c); if (reply) { if(active_select) - waitCmd(1); + waitCmd(conn, 1); if(datalen>0) - waitCmd(0); + waitCmd(conn, 0); } // if reply return 0; } -static void waitCmd(uint8_t iSelect) +static void waitCmd(pm3_connection* conn, uint8_t iSelect) { uint8_t *recv; UsbCommand resp; char *hexout; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { recv = resp.d.asBytes; uint8_t iLen = iSelect ? resp.arg[1] : resp.arg[0]; PrintAndLog("received %i octets", iLen); @@ -782,17 +782,17 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHF14A(const char *Cmd) { +int CmdHF14A(pm3_connection* conn, const char *Cmd) { // flush - WaitForResponseTimeout(CMD_ACK,NULL,100); + WaitForResponseTimeout(conn, CMD_ACK,NULL,100); // parse - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhf14a.h b/client/cmdhf14a.h index dfdf1f4a..c028868e 100644 --- a/client/cmdhf14a.h +++ b/client/cmdhf14a.h @@ -14,12 +14,12 @@ #include -int CmdHF14A(const char *Cmd); -int CmdHF14AList(const char *Cmd); -int CmdHF14AMifare(const char *Cmd); -int CmdHF14AReader(const char *Cmd); -int CmdHF14ASim(const char *Cmd); -int CmdHF14ASnoop(const char *Cmd); +int CmdHF14A(pm3_connection* conn, const char *Cmd); +int CmdHF14AList(pm3_connection* conn, const char *Cmd); +int CmdHF14AMifare(pm3_connection* conn, const char *Cmd); +int CmdHF14AReader(pm3_connection* conn, const char *Cmd); +int CmdHF14ASim(pm3_connection* conn, const char *Cmd); +int CmdHF14ASnoop(pm3_connection* conn, const char *Cmd); char* getTagInfo(uint8_t uid); #endif diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 36932cbd..1f44be65 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -24,28 +24,28 @@ #include "cmdmain.h" #include "cmdhf14a.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); -int CmdHF14BList(const char *Cmd) +int CmdHF14BList(pm3_connection* conn, const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list 14b' instead"); return 0; } -int CmdHF14BSim(const char *Cmd) +int CmdHF14BSim(pm3_connection* conn, const char *Cmd) { UsbCommand c={CMD_SIMULATE_TAG_ISO_14443B}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } -int CmdHF14BSnoop(const char *Cmd) +int CmdHF14BSnoop(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_SNOOP_ISO_14443B}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -53,11 +53,11 @@ int CmdHF14BSnoop(const char *Cmd) * SRI512 tags are ISO14443-B modulated memory tags, * this command just dumps the contents of the memory */ -int CmdSri512Read(const char *Cmd) +int CmdSri512Read(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_READ_SRI512_TAG, {strtol(Cmd, NULL, 0), 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -65,26 +65,26 @@ int CmdSri512Read(const char *Cmd) * SRIX4K tags are ISO14443-B modulated memory tags, * this command just dumps the contents of the memory/ */ -int CmdSrix4kRead(const char *Cmd) +int CmdSrix4kRead(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_READ_SRIX4K_TAG, {strtol(Cmd, NULL, 0), 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } -int rawClose(void){ +int rawClose(pm3_connection* conn){ UsbCommand resp; UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)) { return 0; } return 0; } -int HF14BCmdRaw(bool reply, bool *crc, bool power, uint8_t *data, uint8_t *datalen, bool verbose){ +int HF14BCmdRaw(pm3_connection* conn, bool reply, bool *crc, bool power, uint8_t *data, uint8_t *datalen, bool verbose){ UsbCommand resp; UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; // len,recv,power if(*crc) @@ -100,12 +100,12 @@ int HF14BCmdRaw(bool reply, bool *crc, bool power, uint8_t *data, uint8_t *datal c.arg[1] = reply; c.arg[2] = power; memcpy(c.d.asBytes,data,*datalen); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); if (!reply) return 1; - if (!WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)) { if (verbose) PrintAndLog("timeout while waiting for reply."); return 0; } @@ -128,7 +128,7 @@ int HF14BCmdRaw(bool reply, bool *crc, bool power, uint8_t *data, uint8_t *datal return 1; } -int CmdHF14BCmdRaw (const char *Cmd) { +int CmdHF14BCmdRaw (pm3_connection* conn, const char *Cmd) { bool reply = true; bool crc = false; bool power = false; @@ -224,10 +224,10 @@ int CmdHF14BCmdRaw (const char *Cmd) { cmd2[2] = 0x08; } - if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(conn); - if ( SRx && (cmdLen != 3 || !crc2) ) return rawClose(); - else if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); + if ( SRx && (cmdLen != 3 || !crc2) ) return rawClose(conn); + else if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(conn); uint8_t chipID = 0; if (SRx) { @@ -247,12 +247,12 @@ int CmdHF14BCmdRaw (const char *Cmd) { cmdLen = 9; } - if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(conn); - if (cmdLen != 3 || !crc2) return rawClose(); - if (SRx && cmd2[0] != chipID) return rawClose(); + if (cmdLen != 3 || !crc2) return rawClose(conn); + if (SRx && cmd2[0] != chipID) return rawClose(conn); } - return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); + return HF14BCmdRaw(conn, reply, &crc, power, data, &datalen, true); } // print full atqb info @@ -324,7 +324,7 @@ char *get_ST_Chip_Model(uint8_t data){ return retStr; } -int print_ST_Lock_info(uint8_t model){ +int print_ST_Lock_info(pm3_connection* conn, uint8_t model){ //assume connection open and tag selected... uint8_t data[16] = {0x00}; uint8_t datalen = 2; @@ -342,9 +342,9 @@ int print_ST_Lock_info(uint8_t model){ } //std read cmd - if (HF14BCmdRaw(true, &crc, true, data, &datalen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc, true, data, &datalen, false)==0) return rawClose(conn); - if (datalen != resplen || !crc) return rawClose(); + if (datalen != resplen || !crc) return rawClose(conn); PrintAndLog("Chip Write Protection Bits:"); // now interpret the data @@ -384,7 +384,7 @@ int print_ST_Lock_info(uint8_t model){ } break; default: - return rawClose(); + return rawClose(conn); } return 1; } @@ -399,7 +399,7 @@ static void print_st_general_info(uint8_t *data){ } // 14b get and print UID only (general info) -int HF14BStdReader(uint8_t *data, uint8_t *datalen){ +int HF14BStdReader(pm3_connection* conn, uint8_t *data, uint8_t *datalen){ //05 00 00 = find one tag in field //1d xx xx xx xx 00 08 01 00 = attrib xx=UID (resp 10 [f9 e0]) //a3 = ? (resp 03 [e2 c2]) @@ -424,9 +424,9 @@ int HF14BStdReader(uint8_t *data, uint8_t *datalen){ data[1] = 0x00; data[2] = 0x08; - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)==0) return rawClose(conn); - if (data[0] != 0x50 || *datalen != 14 || !crc) return rawClose(); + if (data[0] != 0x50 || *datalen != 14 || !crc) return rawClose(conn); PrintAndLog ("\n14443-3b tag found:"); PrintAndLog (" UID: %s", sprint_hex(data+1,4)); @@ -448,18 +448,18 @@ int HF14BStdReader(uint8_t *data, uint8_t *datalen){ cmdLen = 9; // attrib - if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(conn); - if (cmdLen != 3 || !crc2) return rawClose(); + if (cmdLen != 3 || !crc2) return rawClose(conn); // add attrib responce to data data[14] = cmd2[0]; - rawClose(); + rawClose(conn); return 1; } // 14b get and print Full Info (as much as we know) -int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ - if (!HF14BStdReader(data,datalen)) return 0; +int HF14BStdInfo(pm3_connection* conn, uint8_t *data, uint8_t *datalen){ + if (!HF14BStdReader(conn, data, datalen)) return 0; //add more info here print_atqb_resp(data); @@ -469,7 +469,7 @@ int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ } // SRx get and print general info about SRx chip from UID -int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ +int HF14B_ST_Reader(pm3_connection* conn, uint8_t *data, uint8_t *datalen, bool closeCon){ bool crc = true; *datalen = 2; //wake cmd @@ -478,9 +478,9 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ //leave power on // verbose on for now for testing - turn off when functional - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)==0) return rawClose(conn); - if (*datalen != 3 || !crc) return rawClose(); + if (*datalen != 3 || !crc) return rawClose(conn); uint8_t chipID = data[0]; // select @@ -489,21 +489,21 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ *datalen = 2; //leave power on - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)==0) return rawClose(conn); - if (*datalen != 3 || !crc || data[0] != chipID) return rawClose(); + if (*datalen != 3 || !crc || data[0] != chipID) return rawClose(conn); // get uid data[0] = 0x0B; *datalen = 1; //leave power on - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)==0) return rawClose(conn); - if (*datalen != 10 || !crc) return rawClose(); + if (*datalen != 10 || !crc) return rawClose(conn); //power off ? - if (closeCon) rawClose(); + if (closeCon) rawClose(conn); PrintAndLog("\n14443-3b ST tag found:"); print_st_general_info(data); @@ -511,18 +511,18 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ } // SRx get and print full info (needs more info...) -int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ - if (!HF14B_ST_Reader(data, datalen, false)) return 0; +int HF14B_ST_Info(pm3_connection* conn, uint8_t *data, uint8_t *datalen){ + if (!HF14B_ST_Reader(conn, data, datalen, false)) return 0; //add locking bit information here. - if (print_ST_Lock_info(data[5]>>2)) - rawClose(); + if (print_ST_Lock_info(conn, data[5]>>2)) + rawClose(conn); return 1; } // test for other 14b type tags (mimic another reader - don't have tags to identify) -int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ +int HF14B_Other_Reader(pm3_connection* conn, uint8_t *data, uint8_t *datalen){ bool crc = true; *datalen = 4; //std read cmd @@ -531,12 +531,12 @@ int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ data[2] = 0x3f; data[3] = 0x80; - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)!=0) { if (*datalen > 2 || !crc) { PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x000b3f80 command ans:"); PrintAndLog ("%s",sprint_hex(data,*datalen)); - rawClose(); + rawClose(conn); return 1; } } @@ -545,12 +545,12 @@ int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ *datalen = 1; data[0] = 0x0a; - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)!=0) { if (*datalen > 0) { PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x0A command ans:"); PrintAndLog ("%s",sprint_hex(data,*datalen)); - rawClose(); + rawClose(conn); return 1; } } @@ -559,68 +559,68 @@ int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ *datalen = 1; data[0] = 0x0c; - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { + if (HF14BCmdRaw(conn, true, &crc, true, data, datalen, false)!=0) { if (*datalen > 0) { PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x0C command ans:"); PrintAndLog ("%s",sprint_hex(data,*datalen)); - rawClose(); + rawClose(conn); return 1; } } - rawClose(); + rawClose(conn); return 0; } // get and print all info known about any known 14b tag -int HF14BInfo(bool verbose){ +int HF14BInfo(pm3_connection* conn, bool verbose){ uint8_t data[100]; uint8_t datalen = 5; // try std 14b (atqb) - if (HF14BStdInfo(data, &datalen)) return 1; + if (HF14BStdInfo(conn, data, &datalen)) return 1; // try st 14b - if (HF14B_ST_Info(data, &datalen)) return 1; + if (HF14B_ST_Info(conn, data, &datalen)) return 1; // try unknown 14b read commands (to be identified later) // could be read of calypso, CEPAS, moneo, or pico pass. - if (HF14B_Other_Reader(data, &datalen)) return 1; + if (HF14B_Other_Reader(conn, data, &datalen)) return 1; if (verbose) PrintAndLog("no 14443B tag found"); return 0; } // menu command to get and print all info known about any known 14b tag -int CmdHF14Binfo(const char *Cmd){ - return HF14BInfo(true); +int CmdHF14Binfo(pm3_connection* conn, const char *Cmd){ + return HF14BInfo(conn, true); } // get and print general info about all known 14b chips -int HF14BReader(bool verbose){ +int HF14BReader(pm3_connection* conn, bool verbose){ uint8_t data[100]; uint8_t datalen = 5; // try std 14b (atqb) - if (HF14BStdReader(data, &datalen)) return 1; + if (HF14BStdReader(conn, data, &datalen)) return 1; // try st 14b - if (HF14B_ST_Reader(data, &datalen, true)) return 1; + if (HF14B_ST_Reader(conn, data, &datalen, true)) return 1; // try unknown 14b read commands (to be identified later) // could be read of calypso, CEPAS, moneo, or pico pass. - if (HF14B_Other_Reader(data, &datalen)) return 1; + if (HF14B_Other_Reader(conn, data, &datalen)) return 1; if (verbose) PrintAndLog("no 14443B tag found"); return 0; } // menu command to get and print general info about all known 14b chips -int CmdHF14BReader(const char *Cmd){ - return HF14BReader(true); +int CmdHF14BReader(pm3_connection* conn, const char *Cmd){ + return HF14BReader(conn, true); } -int CmdSriWrite( const char *Cmd){ +int CmdSriWrite(pm3_connection* conn, const char *Cmd){ /* * For SRIX4K blocks 00 - 7F * hf 14b raw -c -p 09 $srix4kwblock $srix4kwdata @@ -683,7 +683,7 @@ int CmdSriWrite( const char *Cmd){ sprintf(str, "-c 09 %02x %02x%02x%02x%02x", blockno, data[0], data[1], data[2], data[3]); - CmdHF14BCmdRaw(str); + CmdHF14BCmdRaw(conn, str); return 0; } @@ -702,14 +702,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHF14B(const char *Cmd) +int CmdHF14B(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhf14b.h b/client/cmdhf14b.h index a45b7434..24fa940d 100644 --- a/client/cmdhf14b.h +++ b/client/cmdhf14b.h @@ -11,14 +11,14 @@ #ifndef CMDHF14B_H__ #define CMDHF14B_H__ -int CmdHF14B(const char *Cmd); -int CmdHF14BList(const char *Cmd); -int CmdHF14BInfo(const char *Cmd); -int CmdHF14BSim(const char *Cmd); -int CmdHF14BSnoop(const char *Cmd); -int CmdSri512Read(const char *Cmd); -int CmdSrix4kRead(const char *Cmd); -int CmdHF14BWrite( const char *cmd); -int HF14BInfo(bool verbose); +int CmdHF14B(pm3_connection* conn, const char *Cmd); +int CmdHF14BList(pm3_connection* conn, const char *Cmd); +int CmdHF14BInfo(pm3_connection* conn, const char *Cmd); +int CmdHF14BSim(pm3_connection* conn, const char *Cmd); +int CmdHF14BSnoop(pm3_connection* conn, const char *Cmd); +int CmdSri512Read(pm3_connection* conn, const char *Cmd); +int CmdSrix4kRead(pm3_connection* conn, const char *Cmd); +int CmdHF14BWrite(pm3_connection* conn, const char *cmd); +int HF14BInfo(pm3_connection* conn, bool verbose); #endif diff --git a/client/cmdhf15.c b/client/cmdhf15.c index 8ddbea89..64ec68df 100644 --- a/client/cmdhf15.c +++ b/client/cmdhf15.c @@ -202,7 +202,7 @@ const productName uidmapping[] = { // fast method to just read the UID of a tag (collission detection not supported) // *buf should be large enough to fit the 64bit uid // returns 1 if suceeded -int getUID(uint8_t *buf) +int getUID(pm3_connection* conn, uint8_t *buf) { UsbCommand resp; uint8_t *recv; @@ -219,9 +219,9 @@ int getUID(uint8_t *buf) reqlen=AddCrc(req,3); c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)) { recv = resp.d.asBytes; if (resp.arg[0]>=12 && ISO15_CRC_CHECK==Crc(recv,12)) { memcpy(buf,&recv[2],8); @@ -279,7 +279,7 @@ static char* TagErrorStr(uint8_t error) { // Mode 3 -int CmdHF15Demod(const char *Cmd) +int CmdHF15Demod(pm3_connection* conn, const char *Cmd) { // The sampling rate is 106.353 ksps/s, for T = 18.8 us @@ -288,13 +288,13 @@ int CmdHF15Demod(const char *Cmd) int skip = 4; - if (GraphTraceLen < 1000) return 0; + if (conn->GraphTraceLen < 1000) return 0; // First, correlate for SOF for (i = 0; i < 100; i++) { int corr = 0; for (j = 0; j < arraylen(FrameSOF); j += skip) { - corr += FrameSOF[j] * GraphBuffer[i + (j / skip)]; + corr += FrameSOF[j] * conn->GraphBuffer[i + (j / skip)]; } if (corr > max) { max = corr; @@ -312,13 +312,13 @@ int CmdHF15Demod(const char *Cmd) for (;;) { int corr0 = 0, corr1 = 0, corrEOF = 0; for (j = 0; j < arraylen(Logic0); j += skip) { - corr0 += Logic0[j] * GraphBuffer[i + (j / skip)]; + corr0 += Logic0[j] * conn->GraphBuffer[i + (j / skip)]; } for (j = 0; j < arraylen(Logic1); j += skip) { - corr1 += Logic1[j] * GraphBuffer[i + (j / skip)]; + corr1 += Logic1[j] * conn->GraphBuffer[i + (j / skip)]; } for (j = 0; j < arraylen(FrameEOF); j += skip) { - corrEOF += FrameEOF[j] * GraphBuffer[i + (j / skip)]; + corrEOF += FrameEOF[j] * conn->GraphBuffer[i + (j / skip)]; } // Even things out by the length of the target waveform. corr0 *= 4; @@ -338,7 +338,7 @@ int CmdHF15Demod(const char *Cmd) k++; mask = 0x01; } - if ((i + (int)arraylen(FrameEOF)) >= GraphTraceLen) { + if ((i + (int)arraylen(FrameEOF)) >= conn->GraphTraceLen) { PrintAndLog("ran off end!"); break; } @@ -359,26 +359,26 @@ int CmdHF15Demod(const char *Cmd) // * Acquire Samples as Reader (enables carrier, sends inquiry) -int CmdHF15Read(const char *Cmd) +int CmdHF15Read(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } // Record Activity without enabeling carrier -int CmdHF15Record(const char *Cmd) +int CmdHF15Record(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_RECORD_RAW_ADC_SAMPLES_ISO_15693}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int HF15Reader(const char *Cmd, bool verbose) +int HF15Reader(pm3_connection* conn, const char *Cmd, bool verbose) { uint8_t uid[8]; - if (!getUID(uid)) { + if (!getUID(conn, uid)) { if (verbose) PrintAndLog("No Tag found."); return 0; } @@ -388,15 +388,15 @@ int HF15Reader(const char *Cmd, bool verbose) return 1; } -int CmdHF15Reader(const char *Cmd) +int CmdHF15Reader(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_READER_ISO_15693, {strtol(Cmd, NULL, 0), 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } // Simulation is still not working very good -int CmdHF15Sim(const char *Cmd) +int CmdHF15Sim(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); uint8_t uid[8] = {0x00}; @@ -420,21 +420,21 @@ int CmdHF15Sim(const char *Cmd) UsbCommand c = {CMD_SIMTAG_ISO_15693, {0, 0, 0}}; memcpy(c.d.asBytes,uid,8); - SendCommand(&c); + SendCommand(conn, &c); return 0; } // finds the AFI (Application Family Idendifier) of a card, by trying all values // (There is no standard way of reading the AFI, allthough some tags support this) -int CmdHF15Afi(const char *Cmd) +int CmdHF15Afi(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_ISO_15693_FIND_AFI, {strtol(Cmd, NULL, 0), 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } // Reads all memory pages -int CmdHF15DumpMem(const char*Cmd) { +int CmdHF15DumpMem(pm3_connection* conn, const char*Cmd) { UsbCommand resp; uint8_t uid[8]; uint8_t *recv=NULL; @@ -444,7 +444,7 @@ int CmdHF15DumpMem(const char*Cmd) { int blocknum=0; char output[80]; - if (!getUID(uid)) { + if (!getUID(conn, uid)) { PrintAndLog("No Tag found."); return 0; } @@ -462,9 +462,9 @@ int CmdHF15DumpMem(const char*Cmd) { reqlen=AddCrc(req,11); c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1000)) { recv = resp.d.asBytes; if (ISO15_CRC_CHECK==Crc(recv,resp.arg[0])) { if (!(recv[0] & ISO15_RES_ERROR)) { @@ -515,15 +515,15 @@ static command_t CommandTable15[] = {NULL, NULL, 0, NULL} }; -int CmdHF15(const char *Cmd) +int CmdHF15(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable15, Cmd); + CmdsParse(conn, CommandTable15, Cmd); return 0; } -int CmdHF15Help(const char *Cmd) +int CmdHF15Help(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable15); + CmdsHelp(conn, CommandTable15); return 0; } @@ -531,7 +531,7 @@ int CmdHF15Help(const char *Cmd) // "HF 15 Cmd" Interface // Allows direct communication with the tag on command level -int CmdHF15CmdInquiry(const char *Cmd) +int CmdHF15CmdInquiry(pm3_connection* conn, const char *Cmd) { UsbCommand resp; uint8_t *recv; @@ -546,9 +546,9 @@ int CmdHF15CmdInquiry(const char *Cmd) reqlen=AddCrc(req,3); c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1000)) { if (resp.arg[0]>=12) { recv = resp.d.asBytes; PrintAndLog("UID=%s",sprintUID(NULL,&recv[2])); @@ -564,7 +564,7 @@ int CmdHF15CmdInquiry(const char *Cmd) // Turns debugging on(1)/off(0) -int CmdHF15CmdDebug( const char *cmd) { +int CmdHF15CmdDebug(pm3_connection* conn, const char *cmd) { int debug=atoi(cmd); if (strlen(cmd)<1) { PrintAndLog("Usage: hf 15 cmd debug <0|1>"); @@ -574,12 +574,12 @@ int CmdHF15CmdDebug( const char *cmd) { } UsbCommand c = {CMD_ISO_15693_DEBUG, {debug, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF15CmdRaw (const char *cmd) { +int CmdHF15CmdRaw (pm3_connection* conn, const char *cmd) { UsbCommand resp; uint8_t *recv; UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv? @@ -652,10 +652,10 @@ int CmdHF15CmdRaw (const char *cmd) { c.arg[2]=reply; memcpy(c.d.asBytes,data,datalen); - SendCommand(&c); + SendCommand(conn, &c); if (reply) { - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1000)) { recv = resp.d.asBytes; PrintAndLog("received %i octets",resp.arg[0]); hexout = (char *)malloc(resp.arg[0] * 3 + 1); @@ -680,7 +680,7 @@ int CmdHF15CmdRaw (const char *cmd) { * Parameters: * **cmd command line */ -int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd[], int iso15cmdlen) { +int prepareHF15Cmd(pm3_connection* conn, char **cmd, UsbCommand *c, uint8_t iso15cmd[], int iso15cmdlen) { int temp; uint8_t *req=c->d.asBytes; uint8_t uid[8] = {0x00}; @@ -732,7 +732,7 @@ int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd[], int iso15cmdle ISO15_REQ_NONINVENTORY | ISO15_REQ_ADDRESS; memcpy(&req[reqlen],&iso15cmd[0],iso15cmdlen); reqlen+=iso15cmdlen; - if (!getUID(uid)) { + if (!getUID(conn, uid)) { PrintAndLog("No Tag found"); return 0; } @@ -773,7 +773,7 @@ int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd[], int iso15cmdle * Commandline handling: HF15 CMD SYSINFO * get system information from tag/VICC */ -int CmdHF15CmdSysinfo(const char *Cmd) { +int CmdHF15CmdSysinfo(pm3_connection* conn, const char *Cmd) { UsbCommand resp; uint8_t *recv; UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv? @@ -801,15 +801,15 @@ int CmdHF15CmdSysinfo(const char *Cmd) { return 0; } - prepareHF15Cmd(&cmd, &c,(uint8_t[]){ISO15_CMD_SYSINFO},1); + prepareHF15Cmd(conn, &cmd, &c,(uint8_t[]){ISO15_CMD_SYSINFO},1); reqlen=c.arg[0]; reqlen=AddCrc(req,reqlen); c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && resp.arg[0]>2) { + if (WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000) && resp.arg[0]>2) { recv = resp.d.asBytes; if (ISO15_CRC_CHECK==Crc(recv,resp.arg[0])) { if (!(recv[0] & ISO15_RES_ERROR)) { @@ -861,7 +861,7 @@ int CmdHF15CmdSysinfo(const char *Cmd) { * Commandline handling: HF15 CMD READMULTI * Read multiple blocks at once (not all tags support this) */ -int CmdHF15CmdReadmulti(const char *Cmd) { +int CmdHF15CmdReadmulti(pm3_connection* conn, const char *Cmd) { UsbCommand resp; uint8_t *recv; UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv? @@ -888,7 +888,7 @@ int CmdHF15CmdReadmulti(const char *Cmd) { return 0; } - prepareHF15Cmd(&cmd, &c,(uint8_t[]){ISO15_CMD_READMULTI},1); + prepareHF15Cmd(conn, &cmd, &c,(uint8_t[]){ISO15_CMD_READMULTI},1); reqlen=c.arg[0]; pagenum=strtol(cmd,NULL,0); @@ -908,9 +908,9 @@ int CmdHF15CmdReadmulti(const char *Cmd) { c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && resp.arg[0]>2) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1000) && resp.arg[0]>2) { recv = resp.d.asBytes; if (ISO15_CRC_CHECK==Crc(recv,resp.arg[0])) { if (!(recv[0] & ISO15_RES_ERROR)) { @@ -940,7 +940,7 @@ int CmdHF15CmdReadmulti(const char *Cmd) { * Commandline handling: HF15 CMD READ * Reads a single Block */ -int CmdHF15CmdRead(const char *Cmd) { +int CmdHF15CmdRead(pm3_connection* conn, const char *Cmd) { UsbCommand resp; uint8_t *recv; UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv? @@ -966,7 +966,7 @@ int CmdHF15CmdRead(const char *Cmd) { return 0; } - prepareHF15Cmd(&cmd, &c,(uint8_t[]){ISO15_CMD_READ},1); + prepareHF15Cmd(conn, &cmd, &c,(uint8_t[]){ISO15_CMD_READ},1); reqlen=c.arg[0]; pagenum=strtol(cmd,NULL,0); @@ -981,9 +981,9 @@ int CmdHF15CmdRead(const char *Cmd) { c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && resp.arg[0]>2) { + if (WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000) && resp.arg[0]>2) { recv = resp.d.asBytes; if (ISO15_CRC_CHECK==Crc(recv,resp.arg[0])) { if (!(recv[0] & ISO15_RES_ERROR)) { @@ -1015,7 +1015,7 @@ int CmdHF15CmdRead(const char *Cmd) { * Commandline handling: HF15 CMD WRITE * Writes a single Block - might run into timeout, even when successful */ -int CmdHF15CmdWrite(const char *Cmd) { +int CmdHF15CmdWrite(pm3_connection* conn, const char *Cmd) { UsbCommand resp; uint8_t *recv; UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv? @@ -1043,7 +1043,7 @@ int CmdHF15CmdWrite(const char *Cmd) { return 0; } - prepareHF15Cmd(&cmd, &c,(uint8_t[]){ISO15_CMD_WRITE},1); + prepareHF15Cmd(conn, &cmd, &c,(uint8_t[]){ISO15_CMD_WRITE},1); reqlen=c.arg[0]; // *cmd -> page num ; *cmd2 -> data @@ -1074,9 +1074,9 @@ int CmdHF15CmdWrite(const char *Cmd) { c.arg[0]=reqlen; - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,2000) && resp.arg[0]>2) { + if (WaitForResponseTimeout(conn, CMD_ACK, &resp, 2000) && resp.arg[0]>2) { recv = resp.d.asBytes; if (ISO15_CRC_CHECK==Crc(recv,resp.arg[0])) { if (!(recv[0] & ISO15_RES_ERROR)) { @@ -1112,15 +1112,15 @@ static command_t CommandTable15Cmd[] = {NULL, NULL, 0, NULL} }; -int CmdHF15Cmd(const char *Cmd) +int CmdHF15Cmd(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable15Cmd, Cmd); + CmdsParse(conn, CommandTable15Cmd, Cmd); return 0; } -int CmdHF15CmdHelp(const char *Cmd) +int CmdHF15CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable15Cmd); + CmdsHelp(conn, CommandTable15Cmd); return 0; } diff --git a/client/cmdhf15.h b/client/cmdhf15.h index c6264604..58a7df6b 100644 --- a/client/cmdhf15.h +++ b/client/cmdhf15.h @@ -11,16 +11,16 @@ #ifndef CMDHF15_H__ #define CMDHF15_H__ -int CmdHF15(const char *Cmd); +int CmdHF15(pm3_connection* conn, const char *Cmd); -int CmdHF15Demod(const char *Cmd); -int CmdHF15Read(const char *Cmd); -int HF15Reader(const char *Cmd, bool verbose); -int CmdHF15Reader(const char *Cmd); -int CmdHF15Sim(const char *Cmd); -int CmdHF15Record(const char *Cmd); -int CmdHF15Cmd(const char*Cmd); -int CmdHF15CmdHelp(const char*Cmd); -int CmdHF15Help(const char*Cmd); +int CmdHF15Demod(pm3_connection* conn, const char *Cmd); +int CmdHF15Read(pm3_connection* conn, const char *Cmd); +int HF15Reader(pm3_connection* conn, const char *Cmd, bool verbose); +int CmdHF15Reader(pm3_connection* conn, const char *Cmd); +int CmdHF15Sim(pm3_connection* conn, const char *Cmd); +int CmdHF15Record(pm3_connection* conn, const char *Cmd); +int CmdHF15Cmd(pm3_connection* conn, const char*Cmd); +int CmdHF15CmdHelp(pm3_connection* conn, const char*Cmd); +int CmdHF15Help(pm3_connection* conn, const char*Cmd); #endif diff --git a/client/cmdhfepa.c b/client/cmdhfepa.c index f3456afb..fb985e74 100644 --- a/client/cmdhfepa.c +++ b/client/cmdhfepa.c @@ -23,10 +23,10 @@ #include "common.h" #include "cmdmain.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); // Perform (part of) the PACE protocol -int CmdHFEPACollectPACENonces(const char *Cmd) +int CmdHFEPACollectPACENonces(pm3_connection* conn, const char *Cmd) { // requested nonce size unsigned int m = 0; @@ -47,10 +47,10 @@ int CmdHFEPACollectPACENonces(const char *Cmd) for (unsigned int i = 0; i < n; i++) { // execute PACE UsbCommand c = {CMD_EPA_PACE_COLLECT_NONCE, {(int)m, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); // check if command failed if (resp.arg[0] != 0) { @@ -78,7 +78,7 @@ int CmdHFEPACollectPACENonces(const char *Cmd) ////////////////////////////////The commands lie below here///////////////////////////////////////////////////////////////////////////////////////// // perform the PACE protocol by replaying APDUs -int CmdHFEPAPACEReplay(const char *Cmd) +int CmdHFEPAPACEReplay(pm3_connection* conn, const char *Cmd) { // the 4 APDUs which are replayed + their lengths uint8_t msesa_apdu[41], gn_apdu[8], map_apdu[75]; @@ -145,8 +145,8 @@ int CmdHFEPAPACEReplay(const char *Cmd) memcpy(usb_cmd.d.asBytes, // + (j * sizeof(usb_cmd.d.asBytes)), apdus[i] + (j * sizeof(usb_cmd.d.asBytes)), packet_length); - SendCommand(&usb_cmd); - WaitForResponse(CMD_ACK, &resp); + SendCommand(conn, &usb_cmd); + WaitForResponse(conn, CMD_ACK, &resp); if (resp.arg[0] != 0) { PrintAndLog("Transfer of APDU #%d Part %d failed!", i, j); return 0; @@ -156,8 +156,8 @@ int CmdHFEPAPACEReplay(const char *Cmd) // now perform the replay usb_cmd.arg[0] = 0; - SendCommand(&usb_cmd); - WaitForResponse(CMD_ACK, &resp); + SendCommand(conn, &usb_cmd); + WaitForResponse(conn, CMD_ACK, &resp); if (resp.arg[0] != 0) { PrintAndLog("\nPACE replay failed in step %u!", (uint32_t)resp.arg[0]); PrintAndLog("Measured times:"); @@ -194,18 +194,18 @@ static const command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } -int CmdHFEPA(const char *Cmd) +int CmdHFEPA(pm3_connection* conn, const char *Cmd) { // flush - WaitForResponseTimeout(CMD_ACK,NULL,100); + WaitForResponseTimeout(conn, CMD_ACK,NULL,100); // parse - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } diff --git a/client/cmdhfepa.h b/client/cmdhfepa.h index 94ad7d23..e90ebc79 100644 --- a/client/cmdhfepa.h +++ b/client/cmdhfepa.h @@ -10,9 +10,10 @@ #ifndef CMDHFEPA_H__ #define CMDHFEPA_H__ +#include "comms.h" -int CmdHFEPA(const char *Cmd); +int CmdHFEPA(pm3_connection* conn, const char *Cmd); -int CmdHFEPACollectPACENonces(const char *Cmd); +int CmdHFEPACollectPACENonces(pm3_connection* conn, const char *Cmd); #endif // CMDHFEPA_H__ diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index d02eff8d..15e3eaeb 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -33,7 +33,7 @@ #include "usb_cmd.h" #include "cmdhfmfu.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); #define ICLASS_KEYS_MAX 8 static uint8_t iClass_Key_Table[ICLASS_KEYS_MAX][8] = { @@ -59,14 +59,14 @@ int xorbits_8(uint8_t val) { return res & 1; } -int CmdHFiClassList(const char *Cmd) { +int CmdHFiClassList(pm3_connection* conn, const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list iclass' instead"); return 0; } -int CmdHFiClassSnoop(const char *Cmd) { +int CmdHFiClassSnoop(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_SNOOP_ICLASS}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -85,7 +85,7 @@ int usage_hf_iclass_sim(void) { } #define NUM_CSNS 15 -int CmdHFiClassSim(const char *Cmd) { +int CmdHFiClassSim(pm3_connection* conn, const char *Cmd) { uint8_t simType = 0; uint8_t CSN[8] = {0, 0, 0, 0, 0, 0, 0, 0}; @@ -134,8 +134,8 @@ int CmdHFiClassSim(const char *Cmd) { memcpy(c.d.asBytes, csns, 8*NUM_CSNS); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, -1)) { + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, -1)) { PrintAndLog("Command timed out"); return 0; } @@ -172,13 +172,13 @@ int CmdHFiClassSim(const char *Cmd) { { UsbCommand c = {CMD_SIMULATE_TAG_ICLASS, {simType,numberOfCSNs}}; memcpy(c.d.asBytes, CSN, 8); - SendCommand(&c); + SendCommand(conn, &c); } return 0; } -int HFiClassReader(const char *Cmd, bool loop, bool verbose) { +int HFiClassReader(pm3_connection* conn, const char *Cmd, bool loop, bool verbose) { bool tagFound = false; UsbCommand c = {CMD_READER_ICLASS, {FLAG_ICLASS_READER_CSN | FLAG_ICLASS_READER_CC | FLAG_ICLASS_READER_CONF | FLAG_ICLASS_READER_AA | @@ -186,8 +186,8 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { // loop in client not device - else on windows have a communication error UsbCommand resp; while(!ukbhit()){ - SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp, 4500)) { + SendCommand(conn, &c); + if (WaitForResponseTimeout(conn, CMD_ACK,&resp, 4500)) { uint8_t readStatus = resp.arg[0] & 0xff; uint8_t *data = resp.d.asBytes; @@ -228,11 +228,11 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { return 0; } -int CmdHFiClassReader(const char *Cmd) { - return HFiClassReader(Cmd, true, true); +int CmdHFiClassReader(pm3_connection* conn, const char *Cmd) { + return HFiClassReader(conn, Cmd, true, true); } -int CmdHFiClassReader_Replay(const char *Cmd) { +int CmdHFiClassReader_Replay(pm3_connection* conn, const char *Cmd) { uint8_t readerType = 0; uint8_t MAC[4]={0x00, 0x00, 0x00, 0x00}; @@ -249,15 +249,15 @@ int CmdHFiClassReader_Replay(const char *Cmd) { UsbCommand c = {CMD_READER_ICLASS_REPLAY, {readerType}}; memcpy(c.d.asBytes, MAC, 4); - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int iclassEmlSetMem(uint8_t *data, int blockNum, int blocksCount) { +int iclassEmlSetMem(pm3_connection* conn, uint8_t *data, int blockNum, int blocksCount) { UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}}; memcpy(c.d.asBytes, data, blocksCount * 16); - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -269,7 +269,7 @@ int hf_iclass_eload_usage(void) { return 0; } -int CmdHFiClassELoad(const char *Cmd) { +int CmdHFiClassELoad(pm3_connection* conn, const char *Cmd) { char opt = param_getchar(Cmd, 0); if (strlen(Cmd)<1 || opt == 'h') @@ -322,7 +322,7 @@ int CmdHFiClassELoad(const char *Cmd) { uint32_t bytes_in_packet = MIN(USB_CMD_DATA_SIZE, bytes_remaining); UsbCommand c = {CMD_ICLASS_EML_MEMSET, {bytes_sent,bytes_in_packet,0}}; memcpy(c.d.asBytes, dump, bytes_in_packet); - SendCommand(&c); + SendCommand(conn, &c); bytes_remaining -= bytes_in_packet; bytes_sent += bytes_in_packet; } @@ -369,7 +369,7 @@ int usage_hf_iclass_decrypt(void) { return 1; } -int CmdHFiClassDecrypt(const char *Cmd) { +int CmdHFiClassDecrypt(pm3_connection* conn, const char *Cmd) { uint8_t key[16] = { 0 }; if(readKeyfile("iclass_decryptionkey.bin", 16, key)) { @@ -461,7 +461,7 @@ static int iClassEncryptBlkData(uint8_t *blkData) { return 1; } -int CmdHFiClassEncryptBlk(const char *Cmd) { +int CmdHFiClassEncryptBlk(pm3_connection* conn, const char *Cmd) { uint8_t blkData[8] = {0}; char opt = param_getchar(Cmd, 0); if (strlen(Cmd)<1 || opt == 'h') @@ -487,7 +487,7 @@ void Calc_wb_mac(uint8_t blockno, uint8_t *data, uint8_t *div_key, uint8_t MAC[4 //printf("Cal wb mac block [%02x][%02x%02x%02x%02x%02x%02x%02x%02x] : MAC [%02x%02x%02x%02x]",WB[0],WB[1],WB[2],WB[3],WB[4],WB[5],WB[6],WB[7],WB[8],MAC[0],MAC[1],MAC[2],MAC[3]); } -static bool select_only(uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool verbose) { +static bool select_only(pm3_connection* conn, uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool verbose) { UsbCommand resp; UsbCommand c = {CMD_READER_ICLASS, {0}}; @@ -495,9 +495,9 @@ static bool select_only(uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool v if (use_credit_key) c.arg[0] |= FLAG_ICLASS_READER_CEDITKEY; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,4500)) { PrintAndLog("Command execute timeout"); return false; @@ -519,11 +519,11 @@ static bool select_only(uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool v return true; } -static bool select_and_auth(uint8_t *KEY, uint8_t *MAC, uint8_t *div_key, bool use_credit_key, bool elite, bool rawkey, bool verbose) { +static bool select_and_auth(pm3_connection* conn, uint8_t *KEY, uint8_t *MAC, uint8_t *div_key, bool use_credit_key, bool elite, bool rawkey, bool verbose) { uint8_t CSN[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t CCNR[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - if (!select_only(CSN, CCNR, use_credit_key, verbose)) + if (!select_only(conn, CSN, CCNR, use_credit_key, verbose)) return false; //get div_key @@ -537,9 +537,9 @@ static bool select_and_auth(uint8_t *KEY, uint8_t *MAC, uint8_t *div_key, bool u UsbCommand resp; UsbCommand d = {CMD_ICLASS_AUTHENTICATION, {0}}; memcpy(d.d.asBytes, MAC, 4); - clearCommandBuffer(); - SendCommand(&d); - if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + clearCommandBuffer(conn); + SendCommand(conn, &d); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,4500)) { PrintAndLog("Auth Command execute timeout"); return false; @@ -570,7 +570,7 @@ int usage_hf_iclass_dump(void) { return 0; } -int CmdHFiClassReader_Dump(const char *Cmd) { +int CmdHFiClassReader_Dump(pm3_connection* conn, const char *Cmd) { uint8_t MAC[4] = {0x00,0x00,0x00,0x00}; uint8_t div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; @@ -679,11 +679,11 @@ int CmdHFiClassReader_Dump(const char *Cmd) { UsbCommand resp; uint8_t tag_data[255*8]; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 4500)) { PrintAndLog("Command execute timeout"); - ul_switch_off_field(); + ul_switch_off_field(conn); return 0; } uint8_t readStatus = resp.arg[0] & 0xff; @@ -691,7 +691,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { if(readStatus == 0){ PrintAndLog("No tag found..."); - ul_switch_off_field(); + ul_switch_off_field(conn); return 0; } if( readStatus & (FLAG_ICLASS_READER_CSN|FLAG_ICLASS_READER_CONF|FLAG_ICLASS_READER_CC)){ @@ -702,30 +702,30 @@ int CmdHFiClassReader_Dump(const char *Cmd) { // large memory - not able to dump pages currently if (numblks > maxBlk) numblks = maxBlk; } - ul_switch_off_field(); + ul_switch_off_field(conn); // authenticate debit key and get div_key - later store in dump block 3 - if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, rawkey, false)){ + if (!select_and_auth(conn, KEY, MAC, div_key, use_credit_key, elite, rawkey, false)){ //try twice - for some reason it sometimes fails the first time... - if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, rawkey, false)){ - ul_switch_off_field(); + if (!select_and_auth(conn, KEY, MAC, div_key, use_credit_key, elite, rawkey, false)){ + ul_switch_off_field(conn); return 0; } } // begin dump UsbCommand w = {CMD_ICLASS_DUMP, {blockno, numblks-blockno+1}}; - clearCommandBuffer(); - SendCommand(&w); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { + clearCommandBuffer(conn); + SendCommand(conn, &w); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 4500)) { PrintAndLog("Command execute time-out 1"); - ul_switch_off_field(); + ul_switch_off_field(conn); return 1; } uint32_t blocksRead = resp.arg[1]; uint8_t isOK = resp.arg[0] & 0xff; if (!isOK && !blocksRead) { PrintAndLog("Read Block Failed"); - ul_switch_off_field(); + ul_switch_off_field(conn); return 0; } uint32_t startindex = resp.arg[2]; @@ -734,20 +734,20 @@ int CmdHFiClassReader_Dump(const char *Cmd) { blocksRead = (sizeof(tag_data)/8) - blockno; } // response ok - now get bigbuf content of the dump - GetFromBigBuf(tag_data+(blockno*8), blocksRead*8, startindex); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, tag_data+(blockno*8), blocksRead*8, startindex); + WaitForResponse(conn, CMD_ACK,NULL); size_t gotBytes = blocksRead*8 + blockno*8; // try AA2 if (have_credit_key) { //turn off hf field before authenticating with different key - ul_switch_off_field(); + ul_switch_off_field(conn); memset(MAC,0,4); // AA2 authenticate credit key and git c_div_key - later store in dump block 4 - if (!select_and_auth(CreditKEY, MAC, c_div_key, true, false, false, false)){ + if (!select_and_auth(conn, CreditKEY, MAC, c_div_key, true, false, false, false)){ //try twice - for some reason it sometimes fails the first time... - if (!select_and_auth(CreditKEY, MAC, c_div_key, true, false, false, false)){ - ul_switch_off_field(); + if (!select_and_auth(conn, CreditKEY, MAC, c_div_key, true, false, false, false)){ + ul_switch_off_field(conn); return 0; } } @@ -756,18 +756,18 @@ int CmdHFiClassReader_Dump(const char *Cmd) { // setup dump and start w.arg[0] = blockno + blocksRead; w.arg[1] = maxBlk - (blockno + blocksRead); - clearCommandBuffer(); - SendCommand(&w); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { + clearCommandBuffer(conn); + SendCommand(conn, &w); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 4500)) { PrintAndLog("Command execute timeout 2"); - ul_switch_off_field(); + ul_switch_off_field(conn); return 0; } uint8_t isOK = resp.arg[0] & 0xff; blocksRead = resp.arg[1]; if (!isOK && !blocksRead) { PrintAndLog("Read Block Failed 2"); - ul_switch_off_field(); + ul_switch_off_field(conn); return 0; } @@ -777,12 +777,12 @@ int CmdHFiClassReader_Dump(const char *Cmd) { blocksRead = (sizeof(tag_data) - gotBytes)/8; } // get dumped data from bigbuf - GetFromBigBuf(tag_data+gotBytes, blocksRead*8, startindex); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, tag_data+gotBytes, blocksRead*8, startindex); + WaitForResponse(conn, CMD_ACK,NULL); gotBytes += blocksRead*8; } else { //field is still on - turn it off... - ul_switch_off_field(); + ul_switch_off_field(conn); } } @@ -806,10 +806,10 @@ int CmdHFiClassReader_Dump(const char *Cmd) { return 1; } -static int WriteBlock(uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_credit_key, bool elite, bool rawkey, bool verbose) { +static int WriteBlock(pm3_connection* conn, uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_credit_key, bool elite, bool rawkey, bool verbose) { uint8_t MAC[4]={0x00,0x00,0x00,0x00}; uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, rawkey, verbose)) + if (!select_and_auth(conn, KEY, MAC, div_key, use_credit_key, elite, rawkey, verbose)) return 0; UsbCommand resp; @@ -819,9 +819,9 @@ static int WriteBlock(uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_c memcpy(w.d.asBytes, bldata, 8); memcpy(w.d.asBytes + 8, MAC, 4); - clearCommandBuffer(); - SendCommand(&w); - if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + clearCommandBuffer(conn); + SendCommand(conn, &w); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,4500)) { PrintAndLog("Write Command execute timeout"); return 0; @@ -850,7 +850,7 @@ int usage_hf_iclass_writeblock(void) { return 0; } -int CmdHFiClass_WriteBlock(const char *Cmd) { +int CmdHFiClass_WriteBlock(pm3_connection* conn, const char *Cmd) { uint8_t blockno=0; uint8_t bldata[8]={0,0,0,0,0,0,0,0}; uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; @@ -929,8 +929,8 @@ int CmdHFiClass_WriteBlock(const char *Cmd) { } if (cmdp < 6) return usage_hf_iclass_writeblock(); - int ans = WriteBlock(blockno, bldata, KEY, use_credit_key, elite, rawkey, true); - ul_switch_off_field(); + int ans = WriteBlock(conn, blockno, bldata, KEY, use_credit_key, elite, rawkey, true); + ul_switch_off_field(conn); return ans; } @@ -951,7 +951,7 @@ int usage_hf_iclass_clone(void) { return -1; } -int CmdHFiClassCloneTag(const char *Cmd) { +int CmdHFiClassCloneTag(pm3_connection* conn, const char *Cmd) { char filename[FILE_PATH_SIZE] = {0}; char tempStr[50]={0}; uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; @@ -1075,7 +1075,7 @@ int CmdHFiClassCloneTag(const char *Cmd) { uint8_t MAC[4]={0x00,0x00,0x00,0x00}; uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, rawkey, true)) + if (!select_and_auth(conn, KEY, MAC, div_key, use_credit_key, elite, rawkey, true)) return 0; UsbCommand w = {CMD_ICLASS_CLONE,{startblock,endblock}}; @@ -1099,8 +1099,8 @@ int CmdHFiClassCloneTag(const char *Cmd) { printf(" MAC |%02x%02x%02x%02x|\n",p[8],p[9],p[10],p[11]); } UsbCommand resp; - SendCommand(&w); - if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + SendCommand(conn, &w); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,4500)) { PrintAndLog("Command execute timeout"); return 0; @@ -1108,25 +1108,25 @@ int CmdHFiClassCloneTag(const char *Cmd) { return 1; } -static int ReadBlock(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, bool rawkey, bool verbose, bool auth) { +static int ReadBlock(pm3_connection* conn, uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, bool rawkey, bool verbose, bool auth) { uint8_t MAC[4]={0x00,0x00,0x00,0x00}; uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; if (auth) { - if (!select_and_auth(KEY, MAC, div_key, (keyType==0x18), elite, rawkey, verbose)) + if (!select_and_auth(conn, KEY, MAC, div_key, (keyType==0x18), elite, rawkey, verbose)) return 0; } else { uint8_t CSN[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t CCNR[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - if (!select_only(CSN, CCNR, (keyType==0x18), verbose)) + if (!select_only(conn, CSN, CCNR, (keyType==0x18), verbose)) return 0; } UsbCommand resp; UsbCommand w = {CMD_ICLASS_READBLOCK, {blockno}}; - clearCommandBuffer(); - SendCommand(&w); - if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + clearCommandBuffer(conn); + SendCommand(conn, &w); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,4500)) { PrintAndLog("Command execute timeout"); return 0; @@ -1156,7 +1156,7 @@ int usage_hf_iclass_readblock(void) { return 0; } -int CmdHFiClass_ReadBlock(const char *Cmd) { +int CmdHFiClass_ReadBlock(pm3_connection* conn, const char *Cmd) { uint8_t blockno=0; uint8_t keyType = 0x88; //debit key uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; @@ -1229,10 +1229,10 @@ int CmdHFiClass_ReadBlock(const char *Cmd) { if (cmdp < 2) return usage_hf_iclass_readblock(); if (!auth) PrintAndLog("warning: no authentication used with read, only a few specific blocks can be read accurately without authentication."); - return ReadBlock(KEY, blockno, keyType, elite, rawkey, true, auth); + return ReadBlock(conn, KEY, blockno, keyType, elite, rawkey, true, auth); } -int CmdHFiClass_loclass(const char *Cmd) { +int CmdHFiClass_loclass(pm3_connection* conn, const char *Cmd) { char opt = param_getchar(Cmd, 0); if (strlen(Cmd)<1 || opt == 'h') { @@ -1312,7 +1312,7 @@ int usage_hf_iclass_readtagfile() { return 1; } -int CmdHFiClassReadTagFile(const char *Cmd) { +int CmdHFiClassReadTagFile(pm3_connection* conn, const char *Cmd) { int startblock = 0; int endblock = 0; char tempnum[5]; @@ -1435,7 +1435,7 @@ int usage_hf_iclass_calc_newkey(void) { return 1; } -int CmdHFiClassCalcNewKey(const char *Cmd) { +int CmdHFiClassCalcNewKey(pm3_connection* conn, const char *Cmd) { uint8_t OLDKEY[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t NEWKEY[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t xor_div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; @@ -1520,7 +1520,7 @@ int CmdHFiClassCalcNewKey(const char *Cmd) { if (cmdp < 4) return usage_hf_iclass_calc_newkey(); if (!givenCSN) - if (!select_only(CSN, CCNR, false, true)) + if (!select_only(conn, CSN, CCNR, false, true)) return 0; HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, oldElite, true); @@ -1606,7 +1606,7 @@ int usage_hf_iclass_managekeys(void) { return 0; } -int CmdHFiClassManageKeys(const char *Cmd) { +int CmdHFiClassManageKeys(pm3_connection* conn, const char *Cmd) { uint8_t keyNbr = 0; uint8_t dataLen = 0; uint8_t KEY[8] = {0}; @@ -1721,14 +1721,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHFiClass(const char *Cmd) +int CmdHFiClass(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhficlass.h b/client/cmdhficlass.h index 9a3adf50..7a6685c9 100644 --- a/client/cmdhficlass.h +++ b/client/cmdhficlass.h @@ -12,28 +12,28 @@ #ifndef CMDHFICLASS_H__ #define CMDHFICLASS_H__ -int CmdHFiClass(const char *Cmd); +int CmdHFiClass(pm3_connection* conn, const char *Cmd); -int CmdHFiClassCalcNewKey(const char *Cmd); -int CmdHFiClassCloneTag(const char *Cmd); -int CmdHFiClassDecrypt(const char *Cmd); -int CmdHFiClassEncryptBlk(const char *Cmd); -int CmdHFiClassELoad(const char *Cmd); -int CmdHFiClassList(const char *Cmd); -int HFiClassReader(const char *Cmd, bool loop, bool verbose); -int CmdHFiClassReader(const char *Cmd); -int CmdHFiClassReader_Dump(const char *Cmd); -int CmdHFiClassReader_Replay(const char *Cmd); -int CmdHFiClassReadKeyFile(const char *filename); -int CmdHFiClassReadTagFile(const char *Cmd); -int CmdHFiClass_ReadBlock(const char *Cmd); -int CmdHFiClass_TestMac(const char *Cmd); -int CmdHFiClassManageKeys(const char *Cmd); -int CmdHFiClass_loclass(const char *Cmd); -int CmdHFiClassSnoop(const char *Cmd); -int CmdHFiClassSim(const char *Cmd); -int CmdHFiClassWriteKeyFile(const char *Cmd); -int CmdHFiClass_WriteBlock(const char *Cmd); +int CmdHFiClassCalcNewKey(pm3_connection* conn, const char *Cmd); +int CmdHFiClassCloneTag(pm3_connection* conn, const char *Cmd); +int CmdHFiClassDecrypt(pm3_connection* conn, const char *Cmd); +int CmdHFiClassEncryptBlk(pm3_connection* conn, const char *Cmd); +int CmdHFiClassELoad(pm3_connection* conn, const char *Cmd); +int CmdHFiClassList(pm3_connection* conn, const char *Cmd); +int HFiClassReader(pm3_connection* conn, const char *Cmd, bool loop, bool verbose); +int CmdHFiClassReader(pm3_connection* conn, const char *Cmd); +int CmdHFiClassReader_Dump(pm3_connection* conn, const char *Cmd); +int CmdHFiClassReader_Replay(pm3_connection* conn, const char *Cmd); +int CmdHFiClassReadKeyFile(pm3_connection* conn, const char *filename); +int CmdHFiClassReadTagFile(pm3_connection* conn, const char *Cmd); +int CmdHFiClass_ReadBlock(pm3_connection* conn, const char *Cmd); +int CmdHFiClass_TestMac(pm3_connection* conn, const char *Cmd); +int CmdHFiClassManageKeys(pm3_connection* conn, const char *Cmd); +int CmdHFiClass_loclass(pm3_connection* conn, const char *Cmd); +int CmdHFiClassSnoop(pm3_connection* conn, const char *Cmd); +int CmdHFiClassSim(pm3_connection* conn, const char *Cmd); +int CmdHFiClassWriteKeyFile(pm3_connection* conn, const char *Cmd); +int CmdHFiClass_WriteBlock(pm3_connection* conn, const char *Cmd); void printIclassDumpContents(uint8_t *iclass_dump, uint8_t startblock, uint8_t endblock, size_t filesize); void HFiClassCalcDivKey(uint8_t *CSN, uint8_t *KEY, uint8_t *div_key, bool elite); #endif diff --git a/client/cmdhflegic.c b/client/cmdhflegic.c index c9f3485e..95daf677 100644 --- a/client/cmdhflegic.c +++ b/client/cmdhflegic.c @@ -18,7 +18,7 @@ #include "cmdhflegic.h" #include "cmdmain.h" #include "util.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); static command_t CommandTable[] = { @@ -33,15 +33,15 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHFLegic(const char *Cmd) +int CmdHFLegic(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } @@ -50,7 +50,7 @@ int CmdHelp(const char *Cmd) * This is based on information given in the talk held * by Henryk Ploetz and Karsten Nohl at 26c3 */ -int CmdLegicDecode(const char *Cmd) +int CmdLegicDecode(pm3_connection* conn, const char *Cmd) { int i, j, k, n; int segment_len = 0; @@ -64,8 +64,8 @@ int CmdLegicDecode(const char *Cmd) char token_type[4]; // copy data from proxmark into buffer - GetFromBigBuf(data_buf,sizeof(data_buf),0); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, data_buf,sizeof(data_buf),0); + WaitForResponse(conn, CMD_ACK,NULL); // Output CDF System area (9 bytes) plus remaining header area (12 bytes) @@ -206,18 +206,18 @@ int CmdLegicDecode(const char *Cmd) return 0; } -int CmdLegicRFRead(const char *Cmd) +int CmdLegicRFRead(pm3_connection* conn, const char *Cmd) { int byte_count=0,offset=0; sscanf(Cmd, "%i %i", &offset, &byte_count); if(byte_count == 0) byte_count = -1; if(byte_count + offset > 1024) byte_count = 1024 - offset; UsbCommand c={CMD_READER_LEGIC_RF, {offset, byte_count, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLegicLoad(const char *Cmd) +int CmdLegicLoad(pm3_connection* conn, const char *Cmd) { char filename[FILE_PATH_SIZE] = {0x00}; int len = 0; @@ -255,8 +255,8 @@ int CmdLegicLoad(const char *Cmd) int j; for(j = 0; j < 8; j++) { c.d.asBytes[j] = data[j]; } - SendCommand(&c); - WaitForResponse(CMD_ACK, NULL); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK, NULL); offset += 8; } fclose(f); @@ -264,7 +264,7 @@ int CmdLegicLoad(const char *Cmd) return 0; } -int CmdLegicSave(const char *Cmd) +int CmdLegicSave(pm3_connection* conn, const char *Cmd) { int requested = 1024; int offset = 0; @@ -294,8 +294,8 @@ int CmdLegicSave(const char *Cmd) return -1; } - GetFromBigBuf(got,requested,offset); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, got,requested,offset); + WaitForResponse(conn, CMD_ACK,NULL); for (int j = 0; j < requested; j += 8) { fprintf(f, "%02x %02x %02x %02x %02x %02x %02x %02x\n", @@ -318,18 +318,18 @@ int CmdLegicSave(const char *Cmd) return 0; } -int CmdLegicRfSim(const char *Cmd) +int CmdLegicRfSim(pm3_connection* conn, const char *Cmd) { UsbCommand c={CMD_SIMULATE_TAG_LEGIC_RF}; c.arg[0] = 6; c.arg[1] = 3; c.arg[2] = 0; sscanf(Cmd, " %" SCNi64 " %" SCNi64 " %" SCNi64, &c.arg[0], &c.arg[1], &c.arg[2]); - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLegicRfWrite(const char *Cmd) +int CmdLegicRfWrite(pm3_connection* conn, const char *Cmd) { UsbCommand c={CMD_WRITER_LEGIC_RF}; int res = sscanf(Cmd, " 0x%" SCNx64 " 0x%" SCNx64, &c.arg[0], &c.arg[1]); @@ -337,11 +337,11 @@ int CmdLegicRfWrite(const char *Cmd) PrintAndLog("Please specify the offset and length as two hex strings"); return -1; } - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLegicRfFill(const char *Cmd) +int CmdLegicRfFill(pm3_connection* conn, const char *Cmd) { UsbCommand cmd ={CMD_WRITER_LEGIC_RF}; int res = sscanf(Cmd, " 0x%" SCNx64 " 0x%" SCNx64 " 0x%" SCNx64, &cmd.arg[0], &cmd.arg[1], &cmd.arg[2]); @@ -357,10 +357,10 @@ int CmdLegicRfFill(const char *Cmd) } for(i = 0; i < 22; i++) { c.arg[0] = i*48; - SendCommand(&c); - WaitForResponse(CMD_ACK,NULL); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK,NULL); } - SendCommand(&cmd); + SendCommand(conn, &cmd); return 0; } diff --git a/client/cmdhflegic.h b/client/cmdhflegic.h index ab8bc6fd..ca28430e 100644 --- a/client/cmdhflegic.h +++ b/client/cmdhflegic.h @@ -11,14 +11,16 @@ #ifndef CMDHFLEGIC_H__ #define CMDHFLEGIC_H__ -int CmdHFLegic(const char *Cmd); +#include "comms.h" -int CmdLegicRFRead(const char *Cmd); -int CmdLegicDecode(const char *Cmd); -int CmdLegicLoad(const char *Cmd); -int CmdLegicSave(const char *Cmd); -int CmdLegicRfSim(const char *Cmd); -int CmdLegicRfWrite(const char *Cmd); -int CmdLegicRfFill(const char *Cmd); +int CmdHFLegic(pm3_connection* conn, const char *Cmd); + +int CmdLegicRFRead(pm3_connection* conn, const char *Cmd); +int CmdLegicDecode(pm3_connection* conn, const char *Cmd); +int CmdLegicLoad(pm3_connection* conn, const char *Cmd); +int CmdLegicSave(pm3_connection* conn, const char *Cmd); +int CmdLegicRfSim(pm3_connection* conn, const char *Cmd); +int CmdLegicRfWrite(pm3_connection* conn, const char *Cmd); +int CmdLegicRfFill(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 12fb0b78..0b6128fc 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -22,19 +22,20 @@ #include "util_posix.h" #include "usb_cmd.h" #include "ui.h" +#include "mifaredefault.h" #include "mifarehost.h" #include "mifare.h" #include "mfkey.h" #define NESTED_SECTOR_RETRY 10 // how often we try mfested() until we give up -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); -int CmdHF14AMifare(const char *Cmd) +int CmdHF14AMifare(pm3_connection* conn, const char *Cmd) { int isOK = 0; uint64_t key = 0; - isOK = mfDarkside(&key); + isOK = mfDarkside(conn, &key); switch (isOK) { case -1 : PrintAndLog("Button pressed. Aborted."); return 1; case -2 : PrintAndLog("Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests)."); return 1; @@ -50,7 +51,7 @@ int CmdHF14AMifare(const char *Cmd) } -int CmdHF14AMfWrBl(const char *Cmd) +int CmdHF14AMfWrBl(pm3_connection* conn, const char *Cmd) { uint8_t blockNo = 0; uint8_t keyType = 0; @@ -86,10 +87,10 @@ int CmdHF14AMfWrBl(const char *Cmd) UsbCommand c = {CMD_MIFARE_WRITEBL, {blockNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); memcpy(c.d.asBytes + 10, bldata, 16); - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; PrintAndLog("isOk:%02x", isOK); } else { @@ -99,7 +100,7 @@ int CmdHF14AMfWrBl(const char *Cmd) return 0; } -int CmdHF14AMfRdBl(const char *Cmd) +int CmdHF14AMfRdBl(pm3_connection* conn, const char *Cmd) { uint8_t blockNo = 0; uint8_t keyType = 0; @@ -129,10 +130,10 @@ int CmdHF14AMfRdBl(const char *Cmd) UsbCommand c = {CMD_MIFARE_READBL, {blockNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; uint8_t *data = resp.d.asBytes; @@ -147,7 +148,7 @@ int CmdHF14AMfRdBl(const char *Cmd) return 0; } -int CmdHF14AMfRdSc(const char *Cmd) +int CmdHF14AMfRdSc(pm3_connection* conn, const char *Cmd) { int i; uint8_t sectorNo = 0; @@ -182,11 +183,11 @@ int CmdHF14AMfRdSc(const char *Cmd) UsbCommand c = {CMD_MIFARE_READSC, {sectorNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); - SendCommand(&c); + SendCommand(conn, &c); PrintAndLog(" "); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { isOK = resp.arg[0] & 0xff; data = resp.d.asBytes; @@ -244,7 +245,7 @@ static int ParamCardSizeBlocks(const char c) { return numBlocks; } -int CmdHF14AMfDump(const char *Cmd) +int CmdHF14AMfDump(pm3_connection* conn, const char *Cmd) { uint8_t sectorNo, blockNo; @@ -306,9 +307,9 @@ int CmdHF14AMfDump(const char *Cmd) for (tries = 0; tries < 3; tries++) { UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 0, 0}}; memcpy(c.d.asBytes, keyA[sectorNo], 6); - SendCommand(&c); + SendCommand(conn, &c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; uint8_t *data = resp.d.asBytes; if (isOK){ @@ -342,15 +343,15 @@ int CmdHF14AMfDump(const char *Cmd) if (blockNo == NumBlocksPerSector(sectorNo) - 1) { // sector trailer. At least the Access Conditions can always be read with key A. UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 0, 0}}; memcpy(c.d.asBytes, keyA[sectorNo], 6); - SendCommand(&c); - received = WaitForResponseTimeout(CMD_ACK,&resp,1500); + SendCommand(conn, &c); + received = WaitForResponseTimeout(conn, CMD_ACK,&resp,1500); } else { // data block. Check if it can be read with key A or key B uint8_t data_area = sectorNo<32?blockNo:blockNo/5; if ((rights[sectorNo][data_area] == 0x03) || (rights[sectorNo][data_area] == 0x05)) { // only key B would work UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 1, 0}}; memcpy(c.d.asBytes, keyB[sectorNo], 6); - SendCommand(&c); - received = WaitForResponseTimeout(CMD_ACK,&resp,1500); + SendCommand(conn, &c); + received = WaitForResponseTimeout(conn, CMD_ACK,&resp,1500); } else if (rights[sectorNo][data_area] == 0x07) { // no key would work isOK = false; PrintAndLog("Access rights do not allow reading of sector %2d block %3d", sectorNo, blockNo); @@ -358,8 +359,8 @@ int CmdHF14AMfDump(const char *Cmd) } else { // key A would work UsbCommand c = {CMD_MIFARE_READBL, {FirstBlockOfSector(sectorNo) + blockNo, 0, 0}}; memcpy(c.d.asBytes, keyA[sectorNo], 6); - SendCommand(&c); - received = WaitForResponseTimeout(CMD_ACK,&resp,1500); + SendCommand(conn, &c); + received = WaitForResponseTimeout(conn, CMD_ACK,&resp,1500); } } if (received) { @@ -415,7 +416,7 @@ int CmdHF14AMfDump(const char *Cmd) return 0; } -int CmdHF14AMfRestore(const char *Cmd) +int CmdHF14AMfRestore(pm3_connection* conn, const char *Cmd) { uint8_t sectorNo,blockNo; uint8_t keyType = 0; @@ -508,10 +509,10 @@ int CmdHF14AMfRestore(const char *Cmd) PrintAndLog("Writing to block %3d: %s", FirstBlockOfSector(sectorNo) + blockNo, sprint_hex(bldata, 16)); memcpy(c.d.asBytes + 10, bldata, 16); - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; PrintAndLog("isOk:%02x", isOK); } else { @@ -525,7 +526,7 @@ int CmdHF14AMfRestore(const char *Cmd) } # define NESTED_KEY_COUNT 15 -int CmdHF14AMfNested(const char *Cmd) +int CmdHF14AMfNested(pm3_connection* conn, const char *Cmd) { int i, j, res, iterations; sector_t *e_sector = NULL; @@ -603,7 +604,7 @@ int CmdHF14AMfNested(const char *Cmd) } // check if we can authenticate to sector - res = mfCheckKeys(blockNo, keyType, true, 1, key, &key64); + res = mfCheckKeys(conn, blockNo, keyType, true, 1, key, &key64); if (res) { PrintAndLog("Can't authenticate to block:%3d key type:%c key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6)); return 3; @@ -636,7 +637,7 @@ int CmdHF14AMfNested(const char *Cmd) // one-sector nested if (cmdp == 'o') { // ------------------------------------ one sector working PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A'); - int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true); + int16_t isOK = mfnested(conn, blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true); if (isOK) { switch (isOK) { case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; @@ -658,13 +659,13 @@ int CmdHF14AMfNested(const char *Cmd) } else { // 16 block sector sectortrailer = (trgBlockNo & 0x0f) + 15; } - mfEmlGetMem(keyBlock, sectortrailer, 1); - + mfEmlGetMem(conn, keyBlock, sectortrailer, 1); + if (!trgKeyType) num_to_bytes(key64, 6, keyBlock); else num_to_bytes(key64, 6, &keyBlock[10]); - mfEmlSetMem(keyBlock, sectortrailer, 1); + mfEmlSetMem(conn, keyBlock, sectortrailer, 1); PrintAndLog("Key transferred to emulator memory."); } } else { @@ -684,7 +685,7 @@ int CmdHF14AMfNested(const char *Cmd) } PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt); - mfCheckKeysSec(SectorsCnt, 2, MF_CHKKEYS_DEFTIMEOUT, true, NESTED_KEY_COUNT, keyBlock, e_sector); + mfCheckKeysSec(conn, SectorsCnt, 2, MF_CHKKEYS_DEFTIMEOUT, true, NESTED_KEY_COUNT, keyBlock, e_sector); // get known key from array bool keyFound = false; @@ -721,7 +722,7 @@ int CmdHF14AMfNested(const char *Cmd) for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) { if (e_sector[sectorNo].foundKey[trgKeyType]) continue; PrintAndLog("-----------------------------------------------"); - int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); + int16_t isOK = mfnested(conn, blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); if(isOK) { switch (isOK) { case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; @@ -744,7 +745,7 @@ int CmdHF14AMfNested(const char *Cmd) e_sector[sectorNo].Key[trgKeyType] = key64; // try to check this key as a key to the other sectors - mfCheckKeysSec(SectorsCnt, 2, MF_CHKKEYS_DEFTIMEOUT, true, 1, keyBlock, e_sector); + mfCheckKeysSec(conn, SectorsCnt, 2, MF_CHKKEYS_DEFTIMEOUT, true, 1, keyBlock, e_sector); } } } @@ -767,12 +768,12 @@ int CmdHF14AMfNested(const char *Cmd) // transfer keys to the emulator memory if (transferToEml) { for (i = 0; i < SectorsCnt; i++) { - mfEmlGetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1); + mfEmlGetMem(conn, keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1); if (e_sector[i].foundKey[0]) num_to_bytes(e_sector[i].Key[0], 6, keyBlock); if (e_sector[i].foundKey[1]) num_to_bytes(e_sector[i].Key[1], 6, &keyBlock[10]); - mfEmlSetMem(keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1); + mfEmlSetMem(conn, keyBlock, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1); } PrintAndLog("Keys transferred to emulator memory."); } @@ -812,7 +813,7 @@ int CmdHF14AMfNested(const char *Cmd) } -int CmdHF14AMfNestedHard(const char *Cmd) +int CmdHF14AMfNestedHard(pm3_connection* conn, const char *Cmd) { uint8_t blockNo = 0; uint8_t keyType = 0; @@ -917,7 +918,7 @@ int CmdHF14AMfNestedHard(const char *Cmd) slow?"Yes":"No", tests); - int16_t isOK = mfnestedhard(blockNo, keyType, key, trgBlockNo, trgKeyType, know_target_key?trgkey:NULL, nonce_file_read, nonce_file_write, slow, tests); + int16_t isOK = mfnestedhard(conn, blockNo, keyType, key, trgBlockNo, trgKeyType, know_target_key?trgkey:NULL, nonce_file_read, nonce_file_write, slow, tests); if (isOK) { switch (isOK) { @@ -932,7 +933,7 @@ int CmdHF14AMfNestedHard(const char *Cmd) } -int CmdHF14AMfChk(const char *Cmd) +int CmdHF14AMfChk(pm3_connection* conn, const char *Cmd) { if (strlen(Cmd)<3) { PrintAndLog("Usage: hf mf chk |<*card memory> [t|d|s|ss] [] []"); @@ -1122,7 +1123,7 @@ int CmdHF14AMfChk(const char *Cmd) for (uint32_t c = 0; c < keycnt; c += max_keys) { uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c; - res = mfCheckKeysSec(SectorsCnt, keyType, timeout14a * 1.06 / 100, true, size, &keyBlock[6 * c], e_sector); // timeout is (ms * 106)/10 or us*0.0106 + res = mfCheckKeysSec(conn, SectorsCnt, keyType, timeout14a * 1.06 / 100, true, size, &keyBlock[6 * c], e_sector); // timeout is (ms * 106)/10 or us*0.0106 if (res != 1) { if (!res) { @@ -1140,10 +1141,8 @@ int CmdHF14AMfChk(const char *Cmd) int keyAB = keyType; do { for (uint32_t c = 0; c < keycnt; c+=max_keys) { - uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c; - res = mfCheckKeys(blockNo, keyAB & 0x01, true, size, &keyBlock[6 * c], &key64); - + res = mfCheckKeys(conn, blockNo, keyAB & 0x01, true, size, &keyBlock[6 * c], &key64); if (res != 1) { if (!res) { PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64); @@ -1178,13 +1177,13 @@ int CmdHF14AMfChk(const char *Cmd) uint8_t block[16]; for (uint16_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) { if (e_sector[sectorNo].foundKey[0] || e_sector[sectorNo].foundKey[1]) { - mfEmlGetMem(block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1); + mfEmlGetMem(conn, block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1); for (uint16_t t = 0; t < 2; t++) { if (e_sector[sectorNo].foundKey[t]) { num_to_bytes(e_sector[sectorNo].Key[t], 6, block + t * 10); } } - mfEmlSetMem(block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1); + mfEmlSetMem(conn, block, FirstBlockOfSector(sectorNo) + NumBlocksPerSector(sectorNo) - 1, 1); } } PrintAndLog("Found keys have been transferred to the emulator memory"); @@ -1215,7 +1214,7 @@ int CmdHF14AMfChk(const char *Cmd) return 0; } -void readerAttack(nonces_t ar_resp[], bool setEmulatorMem, bool doStandardAttack) { +void readerAttack(pm3_connection* conn, nonces_t ar_resp[], bool setEmulatorMem, bool doStandardAttack) { #define ATTACK_KEY_COUNT 7 // keep same as define in iso14443a.c -> Mifare1ksim() // cannot be more than 7 or it will overrun c.d.asBytes(512) uint64_t key = 0; @@ -1302,8 +1301,8 @@ void readerAttack(nonces_t ar_resp[], bool setEmulatorMem, bool doStandardAttack UsbCommand c = {CMD_MIFARE_EML_MEMSET, {(stSector[i]*4+3), 1, 0}}; memcpy(c.d.asBytes, memBlock, 16); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); } } } @@ -1339,7 +1338,7 @@ int usage_hf14_mf1ksim(void) { return 0; } -int CmdHF14AMf1kSim(const char *Cmd) { +int CmdHF14AMf1kSim(pm3_connection* conn, const char *Cmd) { UsbCommand resp; uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t exitAfterNReads = 0; @@ -1470,10 +1469,10 @@ int CmdHF14AMf1kSim(const char *Cmd) { UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads,0}}; memcpy(c.d.asBytes, uid, sizeof(uid)); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); - while(! WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + while(! WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { //We're waiting only 1.5 s at a time, otherwise we get the // annoying message about "Waiting for a response... " } @@ -1481,7 +1480,7 @@ int CmdHF14AMf1kSim(const char *Cmd) { nonces_t ar_resp[ATTACK_KEY_COUNT*2]; memcpy(ar_resp, resp.d.asBytes, sizeof(ar_resp)); // We can skip the standard attack if we have RANDOM_NONCE set. - readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE)); + readerAttack(conn, ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE)); if ((bool)resp.arg[1]) { PrintAndLog("Device button pressed - quitting"); fclose(f); @@ -1500,12 +1499,12 @@ int CmdHF14AMf1kSim(const char *Cmd) { UsbCommand c = {CMD_SIMULATE_MIFARE_CARD, {flags, exitAfterNReads,0}}; memcpy(c.d.asBytes, uid, sizeof(uid)); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); if(flags & FLAG_INTERACTIVE) { PrintAndLog("Press pm3-button to abort simulation"); - while(! WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + while(! WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { //We're waiting only 1.5 s at a time, otherwise we get the // annoying message about "Waiting for a response... " } @@ -1514,7 +1513,7 @@ int CmdHF14AMf1kSim(const char *Cmd) { nonces_t ar_resp[ATTACK_KEY_COUNT*2]; memcpy(ar_resp, resp.d.asBytes, sizeof(ar_resp)); // We can skip the standard attack if we have RANDOM_NONCE set. - readerAttack(ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE)); + readerAttack(conn, ar_resp, setEmulatorMem, !(flags & FLAG_RANDOM_NONCE)); } } } @@ -1522,7 +1521,7 @@ int CmdHF14AMf1kSim(const char *Cmd) { return 0; } -int CmdHF14AMfDbg(const char *Cmd) +int CmdHF14AMfDbg(pm3_connection* conn, const char *Cmd) { int dbgMode = param_get32ex(Cmd, 0, 0, 10); if (dbgMode > 4) { @@ -1541,12 +1540,12 @@ int CmdHF14AMfDbg(const char *Cmd) } UsbCommand c = {CMD_MIFARE_SET_DBGMODE, {dbgMode, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF14AMfEGet(const char *Cmd) +int CmdHF14AMfEGet(pm3_connection* conn, const char *Cmd) { uint8_t blockNo = 0; uint8_t data[16] = {0x00}; @@ -1560,7 +1559,7 @@ int CmdHF14AMfEGet(const char *Cmd) blockNo = param_get8(Cmd, 0); PrintAndLog(" "); - if (!mfEmlGetMem(data, blockNo, 1)) { + if (!mfEmlGetMem(conn, data, blockNo, 1)) { PrintAndLog("data[%3d]:%s", blockNo, sprint_hex(data, 16)); } else { PrintAndLog("Command execute timeout"); @@ -1569,7 +1568,7 @@ int CmdHF14AMfEGet(const char *Cmd) return 0; } -int CmdHF14AMfEClear(const char *Cmd) +int CmdHF14AMfEClear(pm3_connection* conn, const char *Cmd) { if (param_getchar(Cmd, 0) == 'h') { PrintAndLog("Usage: hf mf eclr"); @@ -1578,12 +1577,12 @@ int CmdHF14AMfEClear(const char *Cmd) } UsbCommand c = {CMD_MIFARE_EML_MEMCLR, {0, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF14AMfESet(const char *Cmd) +int CmdHF14AMfESet(pm3_connection* conn, const char *Cmd) { uint8_t memBlock[16]; uint8_t blockNo = 0; @@ -1606,12 +1605,12 @@ int CmdHF14AMfESet(const char *Cmd) // 1 - blocks count UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNo, 1, 0}}; memcpy(c.d.asBytes, memBlock, 16); - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF14AMfELoad(const char *Cmd) +int CmdHF14AMfELoad(pm3_connection* conn, const char *Cmd) { FILE * f; char filename[FILE_PATH_SIZE]; @@ -1684,8 +1683,8 @@ int CmdHF14AMfELoad(const char *Cmd) for (i = 0; i < 32; i += 2) { sscanf(&buf[i], "%02x", (unsigned int *)&buf8[i / 2]); } - - if (mfEmlSetMem(buf8, blockNum, 1)) { + + if (mfEmlSetMem(conn, buf8, blockNum, 1)) { PrintAndLog("Cant set emul block: %3d", blockNum); fclose(f); return 3; @@ -1707,7 +1706,7 @@ int CmdHF14AMfELoad(const char *Cmd) } -int CmdHF14AMfESave(const char *Cmd) +int CmdHF14AMfESave(pm3_connection* conn, const char *Cmd) { FILE * f; char filename[FILE_PATH_SIZE]; @@ -1751,7 +1750,7 @@ int CmdHF14AMfESave(const char *Cmd) // user supplied filename? if (len < 1) { // get filename (UID from memory) - if (mfEmlGetMem(buf, 0, 1)) { + if (mfEmlGetMem(conn, buf, 0, 1)) { PrintAndLog("Can\'t get UID from block: %d", 0); len = sprintf(fnameptr, "dump"); fnameptr += len; @@ -1777,7 +1776,7 @@ int CmdHF14AMfESave(const char *Cmd) // put hex for (i = 0; i < numBlocks; i++) { - if (mfEmlGetMem(buf, i, 1)) { + if (mfEmlGetMem(conn, buf, i, 1)) { PrintAndLog("Cant get block: %d", i); break; } @@ -1793,7 +1792,7 @@ int CmdHF14AMfESave(const char *Cmd) } -int CmdHF14AMfECFill(const char *Cmd) +int CmdHF14AMfECFill(pm3_connection* conn, const char *Cmd) { uint8_t keyType = 0; uint8_t numSectors = 16; @@ -1828,11 +1827,11 @@ int CmdHF14AMfECFill(const char *Cmd) printf("--params: numSectors: %d, keyType:%d", numSectors, keyType); UsbCommand c = {CMD_MIFARE_EML_CARDLOAD, {numSectors, keyType, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHF14AMfEKeyPrn(const char *Cmd) +int CmdHF14AMfEKeyPrn(pm3_connection* conn, const char *Cmd) { int i; uint8_t numSectors; @@ -1863,7 +1862,7 @@ int CmdHF14AMfEKeyPrn(const char *Cmd) PrintAndLog("|sec|key A |key B |"); PrintAndLog("|---|----------------|----------------|"); for (i = 0; i < numSectors; i++) { - if (mfEmlGetMem(data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) { + if (mfEmlGetMem(conn, data, FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1, 1)) { PrintAndLog("error get block %d", FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1); break; } @@ -1876,7 +1875,7 @@ int CmdHF14AMfEKeyPrn(const char *Cmd) return 0; } -int CmdHF14AMfCSetUID(const char *Cmd) +int CmdHF14AMfCSetUID(pm3_connection* conn, const char *Cmd) { uint8_t uid[8] = {0x00}; uint8_t oldUid[8] = {0x00}; @@ -1938,7 +1937,7 @@ int CmdHF14AMfCSetUID(const char *Cmd) PrintAndLog("--atqa:%s sak:%02x", sprint_hex(atqa, 2), sak[0]); } - res = mfCSetUID(uid, (atqaPresent)?atqa:NULL, (atqaPresent)?sak:NULL, oldUid); + res = mfCSetUID(conn, uid, (atqaPresent)?atqa:NULL, (atqaPresent)?sak:NULL, oldUid); if (res) { PrintAndLog("Can't set UID. Error=%d", res); return 1; @@ -1949,7 +1948,7 @@ int CmdHF14AMfCSetUID(const char *Cmd) return 0; } -int CmdHF14AMfCWipe(const char *Cmd) +int CmdHF14AMfCWipe(pm3_connection* conn, const char *Cmd) { int res, gen = 0; int numBlocks = 16 * 4; @@ -1965,7 +1964,7 @@ int CmdHF14AMfCWipe(const char *Cmd) return 0; } - gen = mfCIdentify(); + gen = mfCIdentify(conn); if ((gen != 1) && (gen != 2)) return 1; @@ -1998,10 +1997,10 @@ int CmdHF14AMfCWipe(const char *Cmd) if (wipeCard) { PrintAndLog("WARNING: can't wipe magic card 1b generation"); } - res = mfCWipe(numBlocks, true, false, fillCard); + res = mfCWipe(conn, numBlocks, true, false, fillCard); } else { /* generation 1a magic card by default */ - res = mfCWipe(numBlocks, false, wipeCard, fillCard); + res = mfCWipe(conn, numBlocks, false, wipeCard, fillCard); } if (res) { @@ -2012,7 +2011,7 @@ int CmdHF14AMfCWipe(const char *Cmd) return 0; } -int CmdHF14AMfCSetBlk(const char *Cmd) +int CmdHF14AMfCSetBlk(pm3_connection* conn, const char *Cmd) { uint8_t memBlock[16] = {0x00}; uint8_t blockNo = 0; @@ -2044,10 +2043,10 @@ int CmdHF14AMfCSetBlk(const char *Cmd) if (gen == 2) { /* generation 1b magic card */ - res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B); + res = mfCSetBlock(conn, blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B); } else { /* generation 1a magic card by default */ - res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER); + res = mfCSetBlock(conn, blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER); } if (res) { @@ -2058,7 +2057,7 @@ int CmdHF14AMfCSetBlk(const char *Cmd) } -int CmdHF14AMfCLoad(const char *Cmd) +int CmdHF14AMfCLoad(pm3_connection* conn, const char *Cmd) { FILE * f; char filename[FILE_PATH_SIZE] = {0x00}; @@ -2090,7 +2089,7 @@ int CmdHF14AMfCLoad(const char *Cmd) if (fillFromEmulator) { for (blockNum = 0; blockNum < numblock; blockNum += 1) { - if (mfEmlGetMem(buf8, blockNum, 1)) { + if (mfEmlGetMem(conn, buf8, blockNum, 1)) { PrintAndLog("Cant get block: %d", blockNum); return 2; } @@ -2101,7 +2100,7 @@ int CmdHF14AMfCLoad(const char *Cmd) if (gen == 2) /* generation 1b magic card */ flags |= CSETBLOCK_MAGIC_1B; - if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) { + if (mfCSetBlock(conn, blockNum, buf8, NULL, 0, flags)) { PrintAndLog("Cant set magic card block: %d", blockNum); return 3; } @@ -2153,7 +2152,7 @@ int CmdHF14AMfCLoad(const char *Cmd) if (gen == 2) /* generation 1b magic card */ flags |= CSETBLOCK_MAGIC_1B; - if (mfCSetBlock(blockNum, buf8, NULL, 0, flags)) { + if (mfCSetBlock(conn, blockNum, buf8, NULL, 0, flags)) { PrintAndLog("Can't set magic card block: %d", blockNum); fclose(f); return 3; @@ -2175,7 +2174,7 @@ int CmdHF14AMfCLoad(const char *Cmd) return 0; } -int CmdHF14AMfCGetBlk(const char *Cmd) { +int CmdHF14AMfCGetBlk(pm3_connection* conn, const char *Cmd) { uint8_t memBlock[16]; uint8_t blockNo = 0; int res, gen = 0; @@ -2196,10 +2195,10 @@ int CmdHF14AMfCGetBlk(const char *Cmd) { if (gen == 2) { /* generation 1b magic card */ - res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B); + res = mfCGetBlock(conn, blockNo, memBlock, CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B); } else { /* generation 1a magic card by default */ - res = mfCGetBlock(blockNo, memBlock, CSETBLOCK_SINGLE_OPER); + res = mfCGetBlock(conn, blockNo, memBlock, CSETBLOCK_SINGLE_OPER); } if (res) { PrintAndLog("Can't read block. error=%d", res); @@ -2210,7 +2209,7 @@ int CmdHF14AMfCGetBlk(const char *Cmd) { return 0; } -int CmdHF14AMfCGetSc(const char *Cmd) { +int CmdHF14AMfCGetSc(pm3_connection* conn, const char *Cmd) { uint8_t memBlock[16] = {0x00}; uint8_t sectorNo = 0; int i, res, flags, gen = 0, baseblock = 0, sect_size = 4; @@ -2250,7 +2249,7 @@ int CmdHF14AMfCGetSc(const char *Cmd) { /* generation 1b magic card */ flags |= CSETBLOCK_MAGIC_1B; - res = mfCGetBlock(baseblock + i, memBlock, flags); + res = mfCGetBlock(conn, baseblock + i, memBlock, flags); if (res) { PrintAndLog("Can't read block. %d error=%d", baseblock + i, res); return 1; @@ -2262,7 +2261,7 @@ int CmdHF14AMfCGetSc(const char *Cmd) { } -int CmdHF14AMfCSave(const char *Cmd) { +int CmdHF14AMfCSave(pm3_connection* conn, const char *Cmd) { FILE * f; char filename[FILE_PATH_SIZE] = {0x00}; @@ -2307,12 +2306,12 @@ int CmdHF14AMfCSave(const char *Cmd) { /* generation 1b magic card */ flags |= CSETBLOCK_MAGIC_1B; - if (mfCGetBlock(i, buf, flags)) { + if (mfCGetBlock(conn, i, buf, flags)) { PrintAndLog("Cant get block: %d", i); break; } - if (mfEmlSetMem(buf, i, 1)) { + if (mfEmlSetMem(conn, buf, i, 1)) { PrintAndLog("Cant set emul block: %d", i); return 3; } @@ -2332,7 +2331,7 @@ int CmdHF14AMfCSave(const char *Cmd) { if (gen == 2) /* generation 1b magic card */ flags |= CSETBLOCK_MAGIC_1B; - if (mfCGetBlock(0, buf, flags)) { + if (mfCGetBlock(conn, 0, buf, flags)) { PrintAndLog("Cant get block: %d", 0); len = sprintf(fnameptr, "dump"); fnameptr += len; @@ -2365,7 +2364,7 @@ int CmdHF14AMfCSave(const char *Cmd) { if (gen == 2) /* generation 1b magic card */ flags |= CSETBLOCK_MAGIC_1B; - if (mfCGetBlock(i, buf, flags)) { + if (mfCGetBlock(conn, i, buf, flags)) { PrintAndLog("Cant get block: %d", i); break; } @@ -2382,7 +2381,7 @@ int CmdHF14AMfCSave(const char *Cmd) { } -int CmdHF14AMfSniff(const char *Cmd){ +int CmdHF14AMfSniff(pm3_connection* conn, const char *Cmd){ bool wantLogToFile = 0; bool wantDecrypt = 0; @@ -2432,8 +2431,8 @@ int CmdHF14AMfSniff(const char *Cmd){ printf("-------------------------------------------------------------------------\n"); UsbCommand c = {CMD_MIFARE_SNIFFER, {0, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); // wait cycle while (true) { @@ -2446,7 +2445,7 @@ int CmdHF14AMfSniff(const char *Cmd){ } UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,2000)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,2000)) { res = resp.arg[0] & 0xff; uint16_t traceLen = resp.arg[1]; len = resp.arg[2]; @@ -2533,7 +2532,7 @@ int CmdHF14AMfSniff(const char *Cmd){ } //needs nt, ar, at, Data to decrypt -int CmdDecryptTraceCmds(const char *Cmd){ +int CmdDecryptTraceCmds(pm3_connection* conn, const char *Cmd){ uint8_t data[50]; int len = 0; param_gethex_ex(Cmd,3,data,&len); @@ -2573,17 +2572,17 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHFMF(const char *Cmd) +int CmdHFMF(pm3_connection* conn, const char *Cmd) { // flush - WaitForResponseTimeout(CMD_ACK,NULL,100); + WaitForResponseTimeout(conn, CMD_ACK,NULL,100); - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhfmf.h b/client/cmdhfmf.h index 3bd3e95a..e5b1eba8 100644 --- a/client/cmdhfmf.h +++ b/client/cmdhfmf.h @@ -1,47 +1,46 @@ -//----------------------------------------------------------------------------- -// Copyright (C) 2011 Merlok -// -// 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. -//----------------------------------------------------------------------------- -// High frequency MIFARE commands -//----------------------------------------------------------------------------- - -#ifndef CMDHFMF_H__ -#define CMDHFMF_H__ - -#include "mifaredefault.h" - -extern int CmdHFMF(const char *Cmd); +//----------------------------------------------------------------------------- +// Copyright (C) 2011 Merlok +// +// 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. +//----------------------------------------------------------------------------- +// High frequency MIFARE commands +//----------------------------------------------------------------------------- + +#ifndef CMDHFMF_H__ +#define CMDHFMF_H__ +#include "comms.h" + +extern int CmdHFMF(pm3_connection* conn, const char *Cmd); + +extern int CmdHF14AMfDbg(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfRdBl(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfURdBl(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfRdSc(pm3_connection* conn, const char* cmd); +extern int CmdHF14SMfURdCard(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfDump(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfRestore(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfWrBl(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfUWrBl(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfChk(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMifare(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfNested(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfSniff(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMf1kSim(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfEClear(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfEGet(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfESet(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfELoad(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfESave(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfECFill(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfEKeyPrn(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfCSetUID(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfCSetBlk(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfCGetBlk(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfCGetSc(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfCLoad(pm3_connection* conn, const char* cmd); +extern int CmdHF14AMfCSave(pm3_connection* conn, const char* cmd); + +#endif -extern int CmdHF14AMfDbg(const char* cmd); -extern int CmdHF14AMfRdBl(const char* cmd); -extern int CmdHF14AMfURdBl(const char* cmd); -extern int CmdHF14AMfRdSc(const char* cmd); -extern int CmdHF14SMfURdCard(const char* cmd); -extern int CmdHF14AMfDump(const char* cmd); -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 CmdHF14AMifare(const char* cmd); -extern int CmdHF14AMfNested(const char* cmd); -extern int CmdHF14AMfSniff(const char* cmd); -extern int CmdHF14AMf1kSim(const char* cmd); -extern int CmdHF14AMfEClear(const char* cmd); -extern int CmdHF14AMfEGet(const char* cmd); -extern int CmdHF14AMfESet(const char* cmd); -extern int CmdHF14AMfELoad(const char* cmd); -extern int CmdHF14AMfESave(const char* cmd); -extern int CmdHF14AMfECFill(const char* cmd); -extern int CmdHF14AMfEKeyPrn(const char* cmd); -extern int CmdHF14AMfCWipe(const char* cmd); -extern int CmdHF14AMfCSetUID(const char* cmd); -extern int CmdHF14AMfCSetBlk(const char* cmd); -extern int CmdHF14AMfCGetBlk(const char* cmd); -extern int CmdHF14AMfCGetSc(const char* cmd); -extern int CmdHF14AMfCLoad(const char* cmd); -extern int CmdHF14AMfCSave(const char* cmd); - -#endif diff --git a/client/cmdhfmfhard.c b/client/cmdhfmfhard.c index 0153541e..92d4ff2f 100644 --- a/client/cmdhfmfhard.c +++ b/client/cmdhfmfhard.c @@ -26,6 +26,7 @@ #include #include "proxmark3.h" #include "cmdmain.h" +#include "comms.h" #include "ui.h" #include "util.h" #include "util_posix.h" @@ -55,6 +56,8 @@ typedef enum { ODD_STATE = 1 } odd_even_t; +// TODO: This module is not thread-safe. All the global state needs to be refactored here. + static uint32_t num_acquired_nonces = 0; static uint64_t start_time = 0; static uint16_t effective_bitflip[2][0x400]; @@ -1444,7 +1447,7 @@ static void simulate_acquire_nonces() } -static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, bool nonce_file_write, bool slow) +static int acquire_nonces(pm3_connection* conn, uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, bool nonce_file_write, bool slow) { last_sample_clock = msclock(); sample_period = 2000; // initial rough estimate. Will be refined. @@ -1462,7 +1465,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ num_acquired_nonces = 0; - clearCommandBuffer(); + clearCommandBuffer(conn); do { flags = 0; @@ -1472,12 +1475,12 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ UsbCommand c = {CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, flags}}; memcpy(c.d.asBytes, key, 6); - SendCommand(&c); + SendCommand(conn, &c); if (field_off) break; if (initialize) { - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) return 1; + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 3000)) return 1; if (resp.arg[0]) return resp.arg[0]; // error during nested_hard @@ -1551,7 +1554,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ } if (!initialize) { - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 3000)) { if (nonce_file_write) { fclose(fnonces); } @@ -2525,7 +2528,7 @@ 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) +int mfnestedhard(pm3_connection* conn, 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) { char progress_text[80]; @@ -2670,7 +2673,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc float brute_force; shrink_key_space(&brute_force); } else { // acquire nonces. - uint16_t is_OK = acquire_nonces(blockNo, keyType, key, trgBlockNo, trgKeyType, nonce_file_write, slow); + uint16_t is_OK = acquire_nonces(conn, blockNo, keyType, key, trgBlockNo, trgKeyType, nonce_file_write, slow); if (is_OK != 0) { free_bitflip_bitarrays(); free_nonces_memory(); diff --git a/client/cmdhfmfhard.h b/client/cmdhfmfhard.h index bcbc3db4..3369f8f9 100644 --- a/client/cmdhfmfhard.h +++ b/client/cmdhfmfhard.h @@ -13,6 +13,7 @@ #include #include +#include "comms.h" #define NUM_SUMS 19 // number of possible sum property values @@ -41,7 +42,7 @@ typedef struct noncelist { noncelistentry_t *first; } noncelist_t; -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); +int mfnestedhard(pm3_connection* conn, 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); void hardnested_print_progress(uint32_t nonces, char *activity, float brute_force, uint64_t min_diff_print_time); #endif diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 3021631a..1bcf09c5 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -69,7 +69,7 @@ uint8_t UL_MEMORY_ARRAY[MAX_UL_TYPES] = {MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_ULC_B MAX_NTAG_215, MAX_NTAG_216, MAX_UL_BLOCKS, MAX_MY_D_NFC, MAX_MY_D_MOVE, MAX_MY_D_MOVE, MAX_MY_D_MOVE_LEAN, MAX_UL_BLOCKS}; -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); // get version nxp product type char *getProductTypeStr( uint8_t id){ @@ -107,25 +107,25 @@ char *getUlev1CardSizeStr( uint8_t fsize ){ return buf; } -static void ul_switch_on_field(void) { +static void ul_switch_on_field(pm3_connection* conn) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT | ISO14A_NO_RATS, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); } -void ul_switch_off_field(void) { +void ul_switch_off_field(pm3_connection* conn) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); } -static int ul_send_cmd_raw( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uint16_t responseLength ) { +static int ul_send_cmd_raw(pm3_connection* conn, uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uint16_t responseLength ) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_APPEND_CRC, cmdlen, 0}}; memcpy(c.d.asBytes, cmd, cmdlen); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1500)) return -1; if (!resp.arg[0] && responseLength) return -1; uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; @@ -139,10 +139,10 @@ static int ul_send_cmd_raw_crc( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, c.arg[0] |= ISO14A_APPEND_CRC; memcpy(c.d.asBytes, cmd, cmdlen); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1500)) return -1; if (!resp.arg[0] && responseLength) return -1; uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; @@ -150,16 +150,16 @@ static int ul_send_cmd_raw_crc( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, return resplen; } */ -static int ul_select( iso14a_card_select_t *card ){ +static int ul_select(pm3_connection* conn, iso14a_card_select_t *card ){ - ul_switch_on_field(); + ul_switch_on_field(conn); UsbCommand resp; bool ans = false; - ans = WaitForResponseTimeout(CMD_ACK, &resp, 1500); + ans = WaitForResponseTimeout(conn, CMD_ACK, &resp, 1500); if (!ans || resp.arg[0] < 1) { PrintAndLog("iso14443a card select failed"); - ul_switch_off_field(); + ul_switch_off_field(conn); return 0; } @@ -168,14 +168,14 @@ static int ul_select( iso14a_card_select_t *card ){ } // This read command will at least return 16bytes. -static int ul_read( uint8_t page, uint8_t *response, uint16_t responseLength ){ +static int ul_read(pm3_connection* conn, uint8_t page, uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {ISO14443A_CMD_READBLOCK, page}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), response, responseLength); return len; } -static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ +static int ul_comp_write(pm3_connection* conn, uint8_t page, uint8_t *data, uint8_t datalen ){ uint8_t cmd[18]; memset(cmd, 0x00, sizeof(cmd)); @@ -186,53 +186,53 @@ static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ memcpy(cmd+2, data, datalen); uint8_t response[1] = {0xff}; - ul_send_cmd_raw(cmd, 2+datalen, response, sizeof(response)); + ul_send_cmd_raw(conn, cmd, 2+datalen, response, sizeof(response)); // ACK if ( response[0] == 0x0a ) return 0; // NACK return -1; } -static int ulc_requestAuthentication( uint8_t *nonce, uint16_t nonceLength ){ +static int ulc_requestAuthentication(pm3_connection* conn, uint8_t *nonce, uint16_t nonceLength ){ uint8_t cmd[] = {MIFARE_ULC_AUTH_1, 0x00}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), nonce, nonceLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), nonce, nonceLength); return len; } -static int ulc_authentication( uint8_t *key, bool switch_off_field ){ +static int ulc_authentication(pm3_connection* conn, uint8_t *key, bool switch_off_field ){ UsbCommand c = {CMD_MIFAREUC_AUTH, {switch_off_field}}; memcpy(c.d.asBytes, key, 16); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return 0; + if ( !WaitForResponseTimeout(conn, CMD_ACK, &resp, 1500) ) return 0; if ( resp.arg[0] == 1 ) return 1; return 0; } -static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ +static int ulev1_requestAuthentication(pm3_connection* conn, uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ uint8_t cmd[] = {MIFARE_ULEV1_AUTH, pwd[0], pwd[1], pwd[2], pwd[3]}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), pack, packLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), pack, packLength); return len; } -static int ul_auth_select( iso14a_card_select_t *card, TagTypeUL_t tagtype, bool hasAuthKey, uint8_t *authenticationkey, uint8_t *pack, uint8_t packSize){ +static int ul_auth_select(pm3_connection* conn, iso14a_card_select_t *card, TagTypeUL_t tagtype, bool hasAuthKey, uint8_t *authenticationkey, uint8_t *pack, uint8_t packSize){ if ( hasAuthKey && (tagtype & UL_C)) { //will select card automatically and close connection on error - if (!ulc_authentication(authenticationkey, false)) { + if (!ulc_authentication(conn, authenticationkey, false)) { PrintAndLog("Error: Authentication Failed UL-C"); return 0; } } else { - if ( !ul_select(card) ) return 0; + if ( !ul_select(conn, card) ) return 0; if (hasAuthKey) { - if (ulev1_requestAuthentication(authenticationkey, pack, packSize) < 1) { - ul_switch_off_field(); + if (ulev1_requestAuthentication(conn, authenticationkey, pack, packSize) < 1) { + ul_switch_off_field(conn); PrintAndLog("Error: Authentication Failed UL-EV1/NTAG"); return 0; } @@ -241,10 +241,10 @@ static int ul_auth_select( iso14a_card_select_t *card, TagTypeUL_t tagtype, bool return 1; } -static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ +static int ulev1_getVersion(pm3_connection* conn, uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_VERSION}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), response, responseLength); return len; } @@ -252,30 +252,30 @@ static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ // uint8_t cmd[] = {MIFARE_ULEV1_FASTREAD, startblock, endblock}; - // if ( !ul_send_cmd_raw(cmd, sizeof(cmd), response)){ + // if ( !ul_send_cmd_raw(conn, cmd, sizeof(cmd), response)){ // return -1; // } // return 0; // } -static int ulev1_readCounter( uint8_t counter, uint8_t *response, uint16_t responseLength ){ +static int ulev1_readCounter(pm3_connection* conn, uint8_t counter, uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_READ_CNT, counter}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), response, responseLength); return len; } -static int ulev1_readTearing( uint8_t counter, uint8_t *response, uint16_t responseLength ){ +static int ulev1_readTearing(pm3_connection* conn, uint8_t counter, uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_CHECKTEAR, counter}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), response, responseLength); return len; } -static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ +static int ulev1_readSignature(pm3_connection* conn, uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_READSIG, 0x00}; - int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + int len = ul_send_cmd_raw(conn, cmd, sizeof(cmd), response, responseLength); return len; } @@ -293,19 +293,19 @@ static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ // UL responds with read of page 0, fudan doesn't respond. // // make sure field is off before calling this function -static int ul_fudan_check( void ){ +static int ul_fudan_check(pm3_connection* conn){ iso14a_card_select_t card; - if ( !ul_select(&card) ) + if ( !ul_select(conn, &card) ) return UL_ERROR; UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT, 4, 0}}; uint8_t cmd[4] = {0x30,0x00,0x02,0xa7}; //wrong crc on purpose should be 0xa8 memcpy(c.d.asBytes, cmd, 4); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return UL_ERROR; + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1500)) return UL_ERROR; if (resp.arg[0] != 1) return UL_ERROR; return (!resp.d.asBytes[0]) ? FUDAN_UL : UL; //if response == 0x00 then Fudan, else Genuine NXP @@ -493,14 +493,14 @@ static int ulev1_print_configuration( uint8_t *data, uint8_t startPage){ return 0; } -static int ulev1_print_counters(){ +static int ulev1_print_counters(pm3_connection* conn){ PrintAndLog("--- Tag Counters"); uint8_t tear[1] = {0}; uint8_t counter[3] = {0,0,0}; uint16_t len = 0; for ( uint8_t i = 0; i<3; ++i) { - ulev1_readTearing(i,tear,sizeof(tear)); - len = ulev1_readCounter(i,counter, sizeof(counter) ); + ulev1_readTearing(conn, i,tear,sizeof(tear)); + len = ulev1_readCounter(conn, i,counter, sizeof(counter) ); if (len == 3) { PrintAndLog(" [%0d] : %s", i, sprint_hex(counter,3)); PrintAndLog(" - %02X tearing %s", tear[0], ( tear[0]==0xBD)?"Ok":"failure"); @@ -534,7 +534,7 @@ static int ulev1_print_version(uint8_t *data){ } /* -static int ulc_magic_test(){ +static int ulc_magic_test(pm3_connection* conn){ // Magic Ultralight test // Magic UL-C, by observation, // 1) it seems to have a static nonce response to 0x1A command. @@ -545,37 +545,37 @@ static int ulc_magic_test(){ iso14a_card_select_t card; uint8_t nonce1[11] = {0x00}; uint8_t nonce2[11] = {0x00}; - int status = ul_select(&card); + int status = ul_select(conn, &card); if ( !status ){ return UL_ERROR; } - status = ulc_requestAuthentication(nonce1, sizeof(nonce1)); + status = ulc_requestAuthentication(conn, nonce1, sizeof(nonce1)); if ( status > 0 ) { - status = ulc_requestAuthentication(nonce2, sizeof(nonce2)); + status = ulc_requestAuthentication(conn, nonce2, sizeof(nonce2)); returnValue = ( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; } else { returnValue = UL; } - ul_switch_off_field(); + ul_switch_off_field(conn); return returnValue; } */ -static int ul_magic_test(){ +static int ul_magic_test(pm3_connection* conn){ // Magic Ultralight tests // 1) take present UID, and try to write it back. OBSOLETE // 2) make a wrong length write to page0, and see if tag answers with ACK/NACK: iso14a_card_select_t card; - if ( !ul_select(&card) ) + if ( !ul_select(conn, &card) ) return UL_ERROR; - int status = ul_comp_write(0, NULL, 0); - ul_switch_off_field(); + int status = ul_comp_write(conn, 0, NULL, 0); + ul_switch_off_field(conn); if ( status == 0 ) return MAGIC; return 0; } -uint32_t GetHF14AMfU_Type(void){ +uint32_t GetHF14AMfU_Type(pm3_connection* conn){ TagTypeUL_t tagtype = UNKNOWN; iso14a_card_select_t card; @@ -583,19 +583,19 @@ uint32_t GetHF14AMfU_Type(void){ int status = 0; int len; - if (!ul_select(&card)) return UL_ERROR; + if (!ul_select(conn, &card)) return UL_ERROR; // Ultralight - ATQA / SAK if ( card.atqa[1] != 0x00 || card.atqa[0] != 0x44 || card.sak != 0x00 ) { PrintAndLog("Tag is not Ultralight | NTAG | MY-D [ATQA: %02X %02X SAK: %02X]\n", card.atqa[1], card.atqa[0], card.sak); - ul_switch_off_field(); + ul_switch_off_field(conn); return UL_ERROR; } if ( card.uid[0] != 0x05) { - len = ulev1_getVersion(version, sizeof(version)); - ul_switch_off_field(); + len = ulev1_getVersion(conn, version, sizeof(version)); + ul_switch_off_field(conn); switch (len) { case 0x0A: { @@ -630,41 +630,41 @@ uint32_t GetHF14AMfU_Type(void){ } // UL vs UL-C vs ntag203 test if (tagtype & (UL | UL_C | NTAG_203)) { - if ( !ul_select(&card) ) return UL_ERROR; + if ( !ul_select(conn, &card) ) return UL_ERROR; // do UL_C check first... uint8_t nonce[11] = {0x00}; - status = ulc_requestAuthentication(nonce, sizeof(nonce)); - ul_switch_off_field(); + status = ulc_requestAuthentication(conn, nonce, sizeof(nonce)); + ul_switch_off_field(conn); if (status > 1) { tagtype = UL_C; } else { // need to re-select after authentication error - if ( !ul_select(&card) ) return UL_ERROR; + if ( !ul_select(conn, &card) ) return UL_ERROR; uint8_t data[16] = {0x00}; // read page 0x26-0x29 (last valid ntag203 page) - status = ul_read(0x26, data, sizeof(data)); + status = ul_read(conn, 0x26, data, sizeof(data)); if ( status <= 1 ) { tagtype = UL; } else { // read page 0x30 (should error if it is a ntag203) - status = ul_read(0x30, data, sizeof(data)); + status = ul_read(conn, 0x30, data, sizeof(data)); if ( status <= 1 ){ tagtype = NTAG_203; } else { tagtype = UNKNOWN; } } - ul_switch_off_field(); + ul_switch_off_field(conn); } } if (tagtype & UL) { - tagtype = ul_fudan_check(); - ul_switch_off_field(); + tagtype = ul_fudan_check(conn); + ul_switch_off_field(conn); } } else { - ul_switch_off_field(); + ul_switch_off_field(conn); // Infinition MY-D tests Exam high nibble uint8_t nib = (card.uid[1] & 0xf0) >> 4; switch ( nib ){ @@ -676,12 +676,12 @@ uint32_t GetHF14AMfU_Type(void){ } } - tagtype |= ul_magic_test(); + tagtype |= ul_magic_test(conn); if (tagtype == (UNKNOWN | MAGIC)) tagtype = (UL_MAGIC); return tagtype; } -int CmdHF14AMfUInfo(const char *Cmd){ +int CmdHF14AMfUInfo(pm3_connection* conn, const char *Cmd){ uint8_t authlim = 0xff; uint8_t data[16] = {0x00}; @@ -736,7 +736,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ //Validations if(errors) return usage_hf_mfu_info(); - TagTypeUL_t tagtype = GetHF14AMfU_Type(); + TagTypeUL_t tagtype = GetHF14AMfU_Type(conn); if (tagtype == UL_ERROR) return -1; PrintAndLog("\n--- Tag Information ---------"); @@ -746,12 +746,12 @@ int CmdHF14AMfUInfo(const char *Cmd){ // Swap endianness if (swapEndian && hasAuthKey) authkeyptr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4 ); - if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; + if (!ul_auth_select(conn, &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; // read pages 0,1,2,3 (should read 4pages) - status = ul_read(0, data, sizeof(data)); + status = ul_read(conn, 0, data, sizeof(data)); if ( status == -1 ) { - ul_switch_off_field(); + ul_switch_off_field(conn); PrintAndLog("Error: tag didn't answer to READ"); return status; } else if (status == 16) { @@ -766,10 +766,10 @@ int CmdHF14AMfUInfo(const char *Cmd){ // read pages 0x28, 0x29, 0x2A, 0x2B uint8_t ulc_conf[16] = {0x00}; - status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); + status = ul_read(conn, 0x28, ulc_conf, sizeof(ulc_conf)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ UL-C"); - ul_switch_off_field(); + ul_switch_off_field(conn); return status; } if (status == 16) ulc_print_configuration(ulc_conf); @@ -778,16 +778,16 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ((tagtype & MAGIC)) { //just read key uint8_t ulc_deskey[16] = {0x00}; - status = ul_read(0x2C, ulc_deskey, sizeof(ulc_deskey)); + status = ul_read(conn, 0x2C, ulc_deskey, sizeof(ulc_deskey)); if ( status == -1 ) { - ul_switch_off_field(); + ul_switch_off_field(conn); PrintAndLog("Error: tag didn't answer to READ magic"); return status; } if (status == 16) ulc_print_3deskey(ulc_deskey); } else { - ul_switch_off_field(); + ul_switch_off_field(conn); // if we called info with key, just return if ( hasAuthKey ) return 1; @@ -795,7 +795,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("Trying some default 3des keys"); for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ) { key = default_3des_keys[i]; - if (ulc_authentication(key, true)) { + if (ulc_authentication(conn, key, true)) { PrintAndLog("Found default 3des key: "); uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); @@ -811,39 +811,39 @@ int CmdHF14AMfUInfo(const char *Cmd){ // ul counters are different than ntag counters if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { - if (ulev1_print_counters() != 3) { + if (ulev1_print_counters(conn) != 3) { // failed - re-select - if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; + if (!ul_auth_select(conn, &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } } if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216 | NTAG_I2C_1K | NTAG_I2C_2K ))) { uint8_t ulev1_signature[32] = {0x00}; - status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); + status = ulev1_readSignature(conn, ulev1_signature, sizeof(ulev1_signature)); if ( status == -1 ) { PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); - ul_switch_off_field(); + ul_switch_off_field(conn); return status; } if (status == 32) ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); else { // re-select - if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; + if (!ul_auth_select(conn, &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } } if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_210 | NTAG_212 | NTAG_213 | NTAG_215 | NTAG_216 | NTAG_I2C_1K | NTAG_I2C_2K))) { uint8_t version[10] = {0x00}; - status = ulev1_getVersion(version, sizeof(version)); + status = ulev1_getVersion(conn, version, sizeof(version)); if ( status == -1 ) { PrintAndLog("Error: tag didn't answer to GETVERSION"); - ul_switch_off_field(); + ul_switch_off_field(conn); return status; } else if (status == 10) { ulev1_print_version(version); } else { locked = true; - if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; + if (!ul_auth_select(conn, &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } uint8_t startconfigblock = 0; @@ -854,10 +854,10 @@ int CmdHF14AMfUInfo(const char *Cmd){ startconfigblock = UL_MEMORY_ARRAY[idx]-3; if (startconfigblock){ // if we know where the config block is... - status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); + status = ul_read(conn, startconfigblock, ulev1_conf, sizeof(ulev1_conf)); if ( status == -1 ) { PrintAndLog("Error: tag didn't answer to READ EV1"); - ul_switch_off_field(); + ul_switch_off_field(conn); return status; } else if (status == 16) { // save AUTHENTICATION LIMITS for later: @@ -875,19 +875,19 @@ int CmdHF14AMfUInfo(const char *Cmd){ len = 0; for (uint8_t i = 0; i < KEYS_PWD_COUNT; ++i ) { key = default_pwd_pack[i]; - len = ulev1_requestAuthentication(key, pack, sizeof(pack)); + len = ulev1_requestAuthentication(conn, key, pack, sizeof(pack)); if (len >= 1) { PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); break; } else { - if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; + if (!ul_auth_select(conn, &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } } if (len < 1) PrintAndLog("password not known"); } } - ul_switch_off_field(); + ul_switch_off_field(conn); if (locked) PrintAndLog("\nTag appears to be locked, try using the key to get more info"); PrintAndLog(""); return 1; @@ -896,7 +896,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ // // Write Single Block // -int CmdHF14AMfUWrBl(const char *Cmd){ +int CmdHF14AMfUWrBl(pm3_connection* conn, const char *Cmd){ int blockNo = -1; bool errors = false; @@ -973,7 +973,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ if ( blockNo == -1 ) return usage_hf_mfu_wrbl(); // starting with getting tagtype - TagTypeUL_t tagtype = GetHF14AMfU_Type(); + TagTypeUL_t tagtype = GetHF14AMfU_Type(conn); if (tagtype == UL_ERROR) return -1; uint8_t maxblockno = 0; @@ -1008,10 +1008,10 @@ int CmdHF14AMfUWrBl(const char *Cmd){ memcpy(c.d.asBytes+4,authKeyPtr,4); } - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; PrintAndLog("isOk:%02x", isOK); } else { @@ -1023,7 +1023,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ // // Read Single Block // -int CmdHF14AMfURdBl(const char *Cmd){ +int CmdHF14AMfURdBl(pm3_connection* conn, const char *Cmd){ int blockNo = -1; bool errors = false; @@ -1089,7 +1089,7 @@ int CmdHF14AMfURdBl(const char *Cmd){ if ( blockNo == -1 ) return usage_hf_mfu_rdbl(); // start with getting tagtype - TagTypeUL_t tagtype = GetHF14AMfU_Type(); + TagTypeUL_t tagtype = GetHF14AMfU_Type(conn); if (tagtype == UL_ERROR) return -1; uint8_t maxblockno = 0; @@ -1117,10 +1117,10 @@ int CmdHF14AMfURdBl(const char *Cmd){ memcpy(c.d.asBytes,authKeyPtr,4); } - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; if (isOK) { uint8_t *data = resp.d.asBytes; @@ -1207,7 +1207,7 @@ int usage_hf_mfu_wrbl(void) { // // Mifare Ultralight / Ultralight-C / Ultralight-EV1 // Read and Dump Card Contents, using auto detection of tag size. -int CmdHF14AMfUDump(const char *Cmd){ +int CmdHF14AMfUDump(pm3_connection* conn, const char *Cmd){ FILE *fout; char filename[FILE_PATH_SIZE] = {0x00}; @@ -1293,7 +1293,7 @@ int CmdHF14AMfUDump(const char *Cmd){ if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4); - TagTypeUL_t tagtype = GetHF14AMfU_Type(); + TagTypeUL_t tagtype = GetHF14AMfU_Type(conn); if (tagtype == UL_ERROR) return -1; if (!manualPages) //get number of pages to read @@ -1313,10 +1313,10 @@ int CmdHF14AMfUDump(const char *Cmd){ memcpy(c.d.asBytes, authKeyPtr, dataLen); } - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp,1500)) { + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp,1500)) { PrintAndLog("Command execute time-out"); return 1; } @@ -1331,8 +1331,8 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLog("Data exceeded Buffer size!"); bufferSize = sizeof(data); } - GetFromBigBuf(data, bufferSize, startindex); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, data, bufferSize, startindex); + WaitForResponse(conn, CMD_ACK, NULL); Pages = bufferSize/4; // Load lock bytes. @@ -1459,7 +1459,7 @@ int CmdHF14AMfUDump(const char *Cmd){ // // Ultralight C Authentication Demo {currently uses hard-coded key} // -int CmdHF14AMfucAuth(const char *Cmd){ +int CmdHF14AMfucAuth(pm3_connection* conn, const char *Cmd){ uint8_t keyNo = 3; bool errors = false; @@ -1491,7 +1491,7 @@ int CmdHF14AMfucAuth(const char *Cmd){ } uint8_t *key = default_3des_keys[keyNo]; - if (ulc_authentication(key, true)) + if (ulc_authentication(conn, key, true)) PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 16)); else PrintAndLog("Authentication failed"); @@ -1504,7 +1504,7 @@ A test function to validate that the polarssl-function works the same was as the openssl-implementation. Commented out, since it requires openssl -int CmdTestDES(const char * cmd) +int CmdTestDES(pm3_connection* conn, const char * cmd) { uint8_t key[16] = {0x00}; @@ -1599,7 +1599,7 @@ int CmdTestDES(const char * cmd) // // Mifare Ultralight C - Set password // -int CmdHF14AMfucSetPwd(const char *Cmd){ +int CmdHF14AMfucSetPwd(pm3_connection* conn, const char *Cmd){ uint8_t pwd[16] = {0x00}; @@ -1621,12 +1621,12 @@ int CmdHF14AMfucSetPwd(const char *Cmd){ UsbCommand c = {CMD_MIFAREUC_SETPWD}; memcpy( c.d.asBytes, pwd, 16); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500) ) { if ( (resp.arg[0] & 0xff) == 1) PrintAndLog("Ultralight-C new password: %s", sprint_hex(pwd,16)); else{ @@ -1645,7 +1645,7 @@ int CmdHF14AMfucSetPwd(const char *Cmd){ // // Magic UL / UL-C tags - Set UID // -int CmdHF14AMfucSetUid(const char *Cmd){ +int CmdHF14AMfucSetUid(pm3_connection* conn, const char *Cmd){ UsbCommand c; UsbCommand resp; @@ -1670,9 +1670,9 @@ int CmdHF14AMfucSetUid(const char *Cmd){ // read block2. c.cmd = CMD_MIFAREU_READBL; c.arg[0] = 2; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { PrintAndLog("Command execute timeout"); return 2; } @@ -1688,9 +1688,9 @@ int CmdHF14AMfucSetUid(const char *Cmd){ c.d.asBytes[1] = uid[1]; c.d.asBytes[2] = uid[2]; c.d.asBytes[3] = 0x88 ^ uid[0] ^ uid[1] ^ uid[2]; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { PrintAndLog("Command execute timeout"); return 3; } @@ -1701,9 +1701,9 @@ int CmdHF14AMfucSetUid(const char *Cmd){ c.d.asBytes[1] = uid[4]; c.d.asBytes[2] = uid[5]; c.d.asBytes[3] = uid[6]; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,1500) ) { PrintAndLog("Command execute timeout"); return 4; } @@ -1714,9 +1714,9 @@ int CmdHF14AMfucSetUid(const char *Cmd){ c.d.asBytes[1] = oldblock2[1]; c.d.asBytes[2] = oldblock2[2]; c.d.asBytes[3] = oldblock2[3]; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,1500) ) { PrintAndLog("Command execute timeout"); return 5; } @@ -1724,7 +1724,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ return 0; } -int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ +int CmdHF14AMfuGenDiverseKeys(pm3_connection* conn, const char *Cmd){ uint8_t iv[8] = { 0x00 }; uint8_t block = 0x07; @@ -1841,13 +1841,13 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHFMFUltra(const char *Cmd){ - WaitForResponseTimeout(CMD_ACK,NULL,100); - CmdsParse(CommandTable, Cmd); +int CmdHFMFUltra(pm3_connection* conn, const char *Cmd){ + WaitForResponseTimeout(conn, CMD_ACK,NULL,100); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd){ - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd){ + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 6c9e3ea1..d26c9afa 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -4,26 +4,26 @@ #ifndef CMDHFMFU_H__ #define CMDHFMFU_H__ -int CmdHF14AMfUWrBl(const char *Cmd); -int CmdHF14AMfURdBl(const char *Cmd); +int CmdHF14AMfUWrBl(pm3_connection* conn, const char *Cmd); +int CmdHF14AMfURdBl(pm3_connection* conn, const char *Cmd); //Crypto Cards -int CmdHF14AMfucAuth(const char *Cmd); +int CmdHF14AMfucAuth(pm3_connection* conn, const char *Cmd); //general stuff -int CmdHF14AMfUDump(const char *Cmd); -int CmdHF14AMfUInfo(const char *Cmd); +int CmdHF14AMfUDump(pm3_connection* conn, const char *Cmd); +int CmdHF14AMfUInfo(pm3_connection* conn, const char *Cmd); -uint32_t GetHF14AMfU_Type(void); +uint32_t GetHF14AMfU_Type(pm3_connection* conn); int ul_print_type(uint32_t tagtype, uint8_t spacer); -void ul_switch_off_field(void); +void ul_switch_off_field(pm3_connection* conn); int usage_hf_mfu_dump(void); int usage_hf_mfu_info(void); int usage_hf_mfu_rdbl(void); int usage_hf_mfu_wrbl(void); -int CmdHFMFUltra(const char *Cmd); +int CmdHFMFUltra(pm3_connection* conn, const char *Cmd); typedef enum TAGTYPE_UL { UNKNOWN = 0x000000, diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c index 39ff1804..9f4353fb 100644 --- a/client/cmdhftopaz.c +++ b/client/cmdhftopaz.c @@ -44,29 +44,29 @@ static struct { } topaz_tag; -static void topaz_switch_on_field(void) +static void topaz_switch_on_field(pm3_connection* conn) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_SELECT | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); } -static void topaz_switch_off_field(void) +static void topaz_switch_off_field(pm3_connection* conn) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); } // send a raw topaz command, returns the length of the response (0 in case of error) -static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) +static int topaz_send_cmd_raw(pm3_connection* conn, uint8_t *cmd, uint8_t len, uint8_t *response) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, len, 0}}; memcpy(c.d.asBytes, cmd, len); - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK, &resp); + WaitForResponse(conn, CMD_ACK, &resp); if (resp.arg[0] > 0) { memcpy(response, resp.d.asBytes, resp.arg[0]); @@ -77,7 +77,7 @@ static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) // calculate CRC bytes and send topaz command, returns the length of the response (0 in case of error) -static int topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) +static int topaz_send_cmd(pm3_connection* conn, uint8_t *cmd, uint8_t len, uint8_t *response) { if (len > 1) { uint8_t first, second; @@ -86,27 +86,27 @@ static int topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) cmd[len-1] = second; } - return topaz_send_cmd_raw(cmd, len, response); + return topaz_send_cmd_raw(conn, cmd, len, response); } // select a topaz tag. Send WUPA and RID. -static int topaz_select(uint8_t *atqa, uint8_t *rid_response) +static int topaz_select(pm3_connection* conn, uint8_t *atqa, uint8_t *rid_response) { - // ToDo: implement anticollision + // TODO: implement anticollision uint8_t wupa_cmd[] = {TOPAZ_WUPA}; uint8_t rid_cmd[] = {TOPAZ_RID, 0, 0, 0, 0, 0, 0, 0, 0}; - topaz_switch_on_field(); + topaz_switch_on_field(conn); - if (!topaz_send_cmd(wupa_cmd, sizeof(wupa_cmd), atqa)) { - topaz_switch_off_field(); + if (!topaz_send_cmd(conn, wupa_cmd, sizeof(wupa_cmd), atqa)) { + topaz_switch_off_field(conn); return -1; // WUPA failed } - if (!topaz_send_cmd(rid_cmd, sizeof(rid_cmd), rid_response)) { - topaz_switch_off_field(); + if (!topaz_send_cmd(conn, rid_cmd, sizeof(rid_cmd), rid_response)) { + topaz_switch_off_field(conn); return -2; // RID failed } @@ -115,13 +115,13 @@ static int topaz_select(uint8_t *atqa, uint8_t *rid_response) // read all of the static memory of a selected Topaz tag. -static int topaz_rall(uint8_t *uid, uint8_t *response) +static int topaz_rall(pm3_connection* conn, uint8_t *uid, uint8_t *response) { uint8_t rall_cmd[] = {TOPAZ_RALL, 0, 0, 0, 0, 0, 0, 0, 0}; memcpy(&rall_cmd[3], uid, 4); - if (!topaz_send_cmd(rall_cmd, sizeof(rall_cmd), response)) { - topaz_switch_off_field(); + if (!topaz_send_cmd(conn, rall_cmd, sizeof(rall_cmd), response)) { + topaz_switch_off_field(conn); return -1; // RALL failed } @@ -130,15 +130,15 @@ static int topaz_rall(uint8_t *uid, uint8_t *response) // read a block (8 Bytes) of a selected Topaz tag. -static int topaz_read_block(uint8_t *uid, uint8_t blockno, uint8_t *block_data) +static int topaz_read_block(pm3_connection* conn, uint8_t *uid, uint8_t blockno, uint8_t *block_data) { uint8_t read8_cmd[] = {TOPAZ_READ8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t read8_response[11]; read8_cmd[1] = blockno; memcpy(&read8_cmd[10], uid, 4); - if (!topaz_send_cmd(read8_cmd, sizeof(read8_cmd), read8_response)) { - topaz_switch_off_field(); + if (!topaz_send_cmd(conn, read8_cmd, sizeof(read8_cmd), read8_response)) { + topaz_switch_off_field(conn); return -1; // READ8 failed } @@ -149,15 +149,15 @@ static int topaz_read_block(uint8_t *uid, uint8_t blockno, uint8_t *block_data) // read a segment (16 blocks = 128 Bytes) of a selected Topaz tag. Works only for tags with dynamic memory. -static int topaz_read_segment(uint8_t *uid, uint8_t segno, uint8_t *segment_data) +static int topaz_read_segment(pm3_connection* conn, uint8_t *uid, uint8_t segno, uint8_t *segment_data) { uint8_t rseg_cmd[] = {TOPAZ_RSEG, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t rseg_response[131]; rseg_cmd[1] = segno << 4; memcpy(&rseg_cmd[10], uid, 4); - if (!topaz_send_cmd(rseg_cmd, sizeof(rseg_cmd), rseg_response)) { - topaz_switch_off_field(); + if (!topaz_send_cmd(conn, rseg_cmd, sizeof(rseg_cmd), rseg_response)) { + topaz_switch_off_field(conn); return -1; // RSEG failed } @@ -362,10 +362,10 @@ static void topaz_print_control_TLVs(uint8_t *memory) // read all of the dynamic memory -static int topaz_read_dynamic_data(void) +static int topaz_read_dynamic_data(pm3_connection* conn) { // first read the remaining block of segment 0 - if(topaz_read_block(topaz_tag.uid, 0x0f, &topaz_tag.dynamic_memory[0]) == -1) { + if(topaz_read_block(conn, topaz_tag.uid, 0x0f, &topaz_tag.dynamic_memory[0]) == -1) { PrintAndLog("Error while reading dynamic memory block %02x. Aborting...", 0x0f); return -1; } @@ -373,7 +373,7 @@ static int topaz_read_dynamic_data(void) // read the remaining segments uint8_t max_segment = topaz_tag.size / 128 - 1; for(uint8_t segment = 1; segment <= max_segment; segment++) { - if(topaz_read_segment(topaz_tag.uid, segment, &topaz_tag.dynamic_memory[(segment-1)*128+8]) == -1) { + if(topaz_read_segment(conn, topaz_tag.uid, segment, &topaz_tag.dynamic_memory[(segment-1)*128+8]) == -1) { PrintAndLog("Error while reading dynamic memory block %02x. Aborting...", 0x0f); return -1; } @@ -384,11 +384,11 @@ static int topaz_read_dynamic_data(void) // read and print the dynamic memory -static void topaz_print_dynamic_data(void) +static void topaz_print_dynamic_data(pm3_connection* conn) { if (topaz_tag.size > TOPAZ_STATIC_MEMORY) { PrintAndLog("Dynamic Data blocks:"); - if (topaz_read_dynamic_data() == 0) { + if (topaz_read_dynamic_data(conn) == 0) { PrintAndLog("block# | offset | Data | Locked(y/n)"); char line[80]; for (uint16_t blockno = 0x0f; blockno < topaz_tag.size/8; blockno++) { @@ -419,7 +419,7 @@ static void topaz_print_NDEF(uint8_t *data) // read a Topaz tag and print some usefull information -int CmdHFTopazReader(const char *Cmd) +int CmdHFTopazReader(pm3_connection* conn, const char *Cmd) { int status; uint8_t atqa[2]; @@ -427,7 +427,7 @@ int CmdHFTopazReader(const char *Cmd) uint8_t *uid_echo = &rid_response[2]; uint8_t rall_response[124]; - status = topaz_select(atqa, rid_response); + status = topaz_select(conn, atqa, rid_response); if (status == -1) { PrintAndLog("Error: couldn't receive ATQA"); @@ -437,13 +437,13 @@ int CmdHFTopazReader(const char *Cmd) PrintAndLog("ATQA : %02x %02x", atqa[1], atqa[0]); if (atqa[1] != 0x0c && atqa[0] != 0x00) { PrintAndLog("Tag doesn't support the Topaz protocol."); - topaz_switch_off_field(); + topaz_switch_off_field(conn); return -1; } if (status == -2) { PrintAndLog("Error: tag didn't answer to RID"); - topaz_switch_off_field(); + topaz_switch_off_field(conn); return -1; } @@ -457,11 +457,11 @@ int CmdHFTopazReader(const char *Cmd) (rid_response[0] & 0x0F) == 0x10 ? "static" : "dynamic"); PrintAndLog("HR1 : %02x", rid_response[1]); - status = topaz_rall(uid_echo, rall_response); + status = topaz_rall(conn, uid_echo, rall_response); if(status == -1) { PrintAndLog("Error: tag didn't answer to RALL"); - topaz_switch_off_field(); + topaz_switch_off_field(conn); return -1; } @@ -513,7 +513,7 @@ int CmdHFTopazReader(const char *Cmd) if (status == -1) { PrintAndLog("No NDEF message data present"); - topaz_switch_off_field(); + topaz_switch_off_field(conn); return 0; } @@ -521,25 +521,25 @@ int CmdHFTopazReader(const char *Cmd) topaz_print_control_TLVs(&topaz_tag.data_blocks[1][4]); PrintAndLog(""); - topaz_print_dynamic_data(); + topaz_print_dynamic_data(conn); topaz_print_lifecycle_state(&topaz_tag.data_blocks[1][0]); topaz_print_NDEF(&topaz_tag.data_blocks[1][0]); - topaz_switch_off_field(); + topaz_switch_off_field(conn); return 0; } -int CmdHFTopazCmdRaw(const char *Cmd) +int CmdHFTopazCmdRaw(pm3_connection* conn, const char *Cmd) { PrintAndLog("not yet implemented. Use hf 14 raw with option -T."); return 0; } -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); static command_t CommandTable[] = @@ -552,19 +552,19 @@ static command_t CommandTable[] = }; -int CmdHFTopaz(const char *Cmd) { +int CmdHFTopaz(pm3_connection* conn, const char *Cmd) { // flush - WaitForResponseTimeout(CMD_ACK,NULL,100); + WaitForResponseTimeout(conn, CMD_ACK,NULL,100); // parse - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -static int CmdHelp(const char *Cmd) +static int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhftopaz.h b/client/cmdhftopaz.h index 8d5428dd..875a4a4d 100644 --- a/client/cmdhftopaz.h +++ b/client/cmdhftopaz.h @@ -11,6 +11,6 @@ #ifndef CMDHFTOPAZ_H__ #define CMDHFTOPAZ_H__ -int CmdHFTopaz(const char *Cmd); +int CmdHFTopaz(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdhw.c b/client/cmdhw.c index 8f7243ad..ab061457 100644 --- a/client/cmdhw.c +++ b/client/cmdhw.c @@ -22,7 +22,7 @@ /* low-level hardware control */ -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection *conn, const char *Cmd); static void lookupChipID(uint32_t iChipID, uint32_t mem_used) { @@ -308,7 +308,7 @@ static void lookupChipID(uint32_t iChipID, uint32_t mem_used) PrintAndLog("Nonvolatile Program Memory Type: %s",asBuff); } -int CmdDetectReader(const char *Cmd) +int CmdDetectReader(pm3_connection *conn, const char *Cmd) { UsbCommand c={CMD_LISTEN_READER_FIELD}; // 'l' means LF - 125/134 kHz @@ -320,19 +320,19 @@ int CmdDetectReader(const char *Cmd) PrintAndLog("use 'detectreader' or 'detectreader l' or 'detectreader h'"); return 0; } - SendCommand(&c); + SendCommand(conn, &c); return 0; } // ## FPGA Control -int CmdFPGAOff(const char *Cmd) +int CmdFPGAOff(pm3_connection *conn, const char *Cmd) { UsbCommand c = {CMD_FPGA_MAJOR_MODE_OFF}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLCD(const char *Cmd) +int CmdLCD(pm3_connection *conn, const char *Cmd) { int i, j; @@ -340,29 +340,29 @@ int CmdLCD(const char *Cmd) sscanf(Cmd, "%x %d", &i, &j); while (j--) { c.arg[0] = i & 0x1ff; - SendCommand(&c); + SendCommand(conn, &c); } return 0; } -int CmdLCDReset(const char *Cmd) +int CmdLCDReset(pm3_connection *conn, const char *Cmd) { UsbCommand c = {CMD_LCD_RESET, {strtol(Cmd, NULL, 0), 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdReadmem(const char *Cmd) +int CmdReadmem(pm3_connection *conn, const char *Cmd) { UsbCommand c = {CMD_READ_MEM, {strtol(Cmd, NULL, 0), 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdReset(const char *Cmd) +int CmdReset(pm3_connection *conn, const char *Cmd) { UsbCommand c = {CMD_HARDWARE_RESET}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -370,19 +370,19 @@ int CmdReset(const char *Cmd) * Sets the divisor for LF frequency clock: lets the user choose any LF frequency below * 600kHz. */ -int CmdSetDivisor(const char *Cmd) +int CmdSetDivisor(pm3_connection *conn, const char *Cmd) { UsbCommand c = {CMD_SET_LF_DIVISOR, {strtol(Cmd, NULL, 0), 0, 0}}; if (c.arg[0] < 19 || c.arg[0] > 255) { PrintAndLog("divisor must be between 19 and 255"); } else { - SendCommand(&c); + SendCommand(conn, &c); PrintAndLog("Divisor set, expected freq=%dHz", 12000000 / (c.arg[0]+1)); } return 0; } -int CmdSetMux(const char *Cmd) +int CmdSetMux(pm3_connection *conn, const char *Cmd) { UsbCommand c={CMD_SET_ADC_MUX}; if (strcmp(Cmd, "lopkd") == 0) { @@ -394,25 +394,24 @@ int CmdSetMux(const char *Cmd) } else if (strcmp(Cmd, "hiraw") == 0) { c.arg[0] = 3; } - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdTune(const char *Cmd) +int CmdTune(pm3_connection *conn, const char *Cmd) { - return CmdTuneSamples(Cmd); + return CmdTuneSamples(conn, Cmd); } -int CmdVersion(const char *Cmd) +int CmdVersion(pm3_connection* conn, const char *Cmd) { - - clearCommandBuffer(); + clearCommandBuffer(conn); UsbCommand c = {CMD_VERSION}; static UsbCommand resp = {0, {0, 0, 0}}; if (resp.arg[0] == 0 && resp.arg[1] == 0) { // no cached information available - SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + SendCommand(conn, &c); + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1000)) { PrintAndLog("Prox/RFID mark3 RFID instrument"); PrintAndLog((char*)resp.d.asBytes); lookupChipID(resp.arg[0], resp.arg[1]); @@ -427,28 +426,30 @@ int CmdVersion(const char *Cmd) return 0; } -int CmdStatus(const char *Cmd) +int CmdStatus(pm3_connection *conn, const char *Cmd) { uint8_t speed_test_buffer[USB_CMD_DATA_SIZE]; - sample_buf = speed_test_buffer; + conn->sample_buf = speed_test_buffer; - clearCommandBuffer(); + clearCommandBuffer(conn); UsbCommand c = {CMD_STATUS}; - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK,&c,1900)) { + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK,&c,1900)) { PrintAndLog("Status command failed. USB Speed Test timed out"); } + + conn->sample_buf = NULL; return 0; } -int CmdPing(const char *Cmd) +int CmdPing(pm3_connection *conn, const char *Cmd) { - clearCommandBuffer(); + clearCommandBuffer(conn); UsbCommand resp; UsbCommand c = {CMD_PING}; - SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + SendCommand(conn, &c); + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1000)) { PrintAndLog("Ping successful"); }else{ PrintAndLog("Ping failed"); @@ -474,14 +475,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdHW(const char *Cmd) +int CmdHW(pm3_connection *conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection *conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdhw.h b/client/cmdhw.h index b8e10f74..dfe80885 100644 --- a/client/cmdhw.h +++ b/client/cmdhw.h @@ -11,17 +11,19 @@ #ifndef CMDHW_H__ #define CMDHW_H__ -int CmdHW(const char *Cmd); +#include "comms.h" -int CmdDetectReader(const char *Cmd); -int CmdFPGAOff(const char *Cmd); -int CmdLCD(const char *Cmd); -int CmdLCDReset(const char *Cmd); -int CmdReadmem(const char *Cmd); -int CmdReset(const char *Cmd); -int CmdSetDivisor(const char *Cmd); -int CmdSetMux(const char *Cmd); -int CmdTune(const char *Cmd); -int CmdVersion(const char *Cmd); +int CmdHW(pm3_connection *conn, const char *Cmd); + +int CmdDetectReader(pm3_connection *conn, const char *Cmd); +int CmdFPGAOff(pm3_connection *conn, const char *Cmd); +int CmdLCD(pm3_connection *conn, const char *Cmd); +int CmdLCDReset(pm3_connection *conn, const char *Cmd); +int CmdReadmem(pm3_connection *conn, const char *Cmd); +int CmdReset(pm3_connection *conn, const char *Cmd); +int CmdSetDivisor(pm3_connection *conn, const char *Cmd); +int CmdSetMux(pm3_connection *conn, const char *Cmd); +int CmdTune(pm3_connection *conn, const char *Cmd); +int CmdVersion(pm3_connection *conn, const char *Cmd); #endif diff --git a/client/cmdlf.c b/client/cmdlf.c index 501bfaed..6e900d71 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -46,9 +46,10 @@ #include "cmdlfnoralsy.h"// for noralsy menu #include "cmdlfsecurakey.h"//for securakey menu #include "cmdlfpac.h" // for pac menu +#include "comms.h" // for pm3_connection bool g_lf_threshold_set = false; -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); @@ -71,7 +72,7 @@ int usage_lf_cmdread(void) } /* send a command before reading */ -int CmdLFCommandRead(const char *Cmd) +int CmdLFCommandRead(pm3_connection* conn, const char *Cmd) { static char dummy[3] = {0x20,0x00,0x00}; UsbCommand c = {CMD_MOD_THEN_ACQUIRE_RAW_ADC_SAMPLES_125K}; @@ -124,28 +125,28 @@ int CmdLFCommandRead(const char *Cmd) // in case they specified 'H' strcpy((char *)&c.d.asBytes + strlen((char *)c.d.asBytes), dummy); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } -int CmdFlexdemod(const char *Cmd) +int CmdFlexdemod(pm3_connection* conn, const char *Cmd) { int i; - for (i = 0; i < GraphTraceLen; ++i) { - if (GraphBuffer[i] < 0) { - GraphBuffer[i] = -1; + for (i = 0; i < conn->GraphTraceLen; ++i) { + if (conn->GraphBuffer[i] < 0) { + conn->GraphBuffer[i] = -1; } else { - GraphBuffer[i] = 1; + conn->GraphBuffer[i] = 1; } } #define LONG_WAIT 100 int start; - for (start = 0; start < GraphTraceLen - LONG_WAIT; start++) { - int first = GraphBuffer[start]; + for (start = 0; start < conn->GraphTraceLen - LONG_WAIT; start++) { + int first = conn->GraphBuffer[start]; for (i = start; i < start + LONG_WAIT; i++) { - if (GraphBuffer[i] != first) { + if (conn->GraphBuffer[i] != first) { break; } } @@ -153,13 +154,13 @@ int CmdFlexdemod(const char *Cmd) break; } } - if (start == GraphTraceLen - LONG_WAIT) { + if (start == conn->GraphTraceLen - LONG_WAIT) { PrintAndLog("nothing to wait for"); return 0; } - GraphBuffer[start] = 2; - GraphBuffer[start+1] = -2; + conn->GraphBuffer[start] = 2; + conn->GraphBuffer[start+1] = -2; uint8_t bits[64] = {0x00}; int bit, sum; @@ -167,7 +168,7 @@ int CmdFlexdemod(const char *Cmd) for (bit = 0; bit < 64; bit++) { sum = 0; for (int j = 0; j < 16; j++) { - sum += GraphBuffer[i++]; + sum += conn->GraphBuffer[i++]; } bits[bit] = (sum > 0) ? 1 : 0; @@ -179,7 +180,7 @@ int CmdFlexdemod(const char *Cmd) int j; int sum = 0; for (j = 0; j < 16; j++) { - sum += GraphBuffer[i++]; + sum += conn->GraphBuffer[i++]; } if (sum > 0 && bits[bit] != 1) { PrintAndLog("oops1 at %d", bit); @@ -190,7 +191,7 @@ int CmdFlexdemod(const char *Cmd) } // HACK writing back to graphbuffer. - GraphTraceLen = 32*64; + conn->GraphTraceLen = 32*64; i = 0; int phase = 0; for (bit = 0; bit < 64; bit++) { @@ -199,12 +200,12 @@ int CmdFlexdemod(const char *Cmd) int j; for (j = 0; j < 32; j++) { - GraphBuffer[i++] = phase; + conn->GraphBuffer[i++] = phase; phase = !phase; } } - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 0; } @@ -253,7 +254,7 @@ int usage_lf_config(void) return 0; } -int CmdLFSetConfig(const char *Cmd) +int CmdLFSetConfig(pm3_connection* conn, const char *Cmd) { uint8_t divisor = 0;//Frequency divisor @@ -329,34 +330,34 @@ int CmdLFSetConfig(const char *Cmd) //Averaging is a flag on high-bit of arg[1] UsbCommand c = {CMD_SET_LF_SAMPLING_CONFIG}; memcpy(c.d.asBytes,&config,sizeof(sample_config)); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } -bool lf_read(bool silent, uint32_t samples) { - if (IsOffline()) return false; +bool lf_read(pm3_connection* conn, bool silent, uint32_t samples) { + if (conn->offline) return false; UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_125K, {silent,samples,0}}; - clearCommandBuffer(); + clearCommandBuffer(conn); //And ship it to device - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; if (g_lf_threshold_set) { - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); } else { - if ( !WaitForResponseTimeout(CMD_ACK,&resp,2500) ) { + if ( !WaitForResponseTimeout(conn, CMD_ACK,&resp,2500) ) { PrintAndLog("command execution time out"); return false; } } // resp.arg[0] is bits read not bytes read. - getSamples(resp.arg[0]/8, silent); + getSamples(conn, resp.arg[0]/8, silent); return true; } -int CmdLFRead(const char *Cmd) +int CmdLFRead(pm3_connection* conn, const char *Cmd) { uint8_t cmdp = 0; bool silent = false; @@ -369,10 +370,10 @@ int CmdLFRead(const char *Cmd) cmdp++; } uint32_t samples = param_get32ex(Cmd, cmdp, 0, 10); - return lf_read(silent, samples); + return lf_read(conn, silent, samples); } -int CmdLFSnoop(const char *Cmd) +int CmdLFSnoop(pm3_connection* conn, const char *Cmd) { uint8_t cmdp =0; if(param_getchar(Cmd, cmdp) == 'h') @@ -381,29 +382,29 @@ int CmdLFSnoop(const char *Cmd) } UsbCommand c = {CMD_LF_SNOOP_RAW_ADC_SAMPLES}; - clearCommandBuffer(); - SendCommand(&c); - WaitForResponse(CMD_ACK,NULL); - getSamples(0, true); + clearCommandBuffer(conn); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK,NULL); + getSamples(conn, 0, true); return 0; } -static void ChkBitstream(const char *str) +static void ChkBitstream(pm3_connection* conn, const char *str) { int i; /* convert to bitstream if necessary */ - for (i = 0; i < (int)(GraphTraceLen / 2); i++){ - if (GraphBuffer[i] > 1 || GraphBuffer[i] < 0) { - CmdGetBitStream(""); + for (i = 0; i < (int)(conn->GraphTraceLen / 2); i++){ + if (conn->GraphBuffer[i] > 1 || conn->GraphBuffer[i] < 0) { + CmdGetBitStream(conn, ""); break; } } } //Attempt to simulate any wave in buffer (one bit per output sample) -// converts GraphBuffer to bitstream (based on zero crossings) if needed. -int CmdLFSim(const char *Cmd) +// converts conn->GraphBuffer to bitstream (based on zero crossings) if needed. +int CmdLFSim(pm3_connection* conn, const char *Cmd) { int i,j; static int gap; @@ -411,26 +412,26 @@ int CmdLFSim(const char *Cmd) sscanf(Cmd, "%i", &gap); // convert to bitstream if necessary - ChkBitstream(Cmd); + ChkBitstream(conn, Cmd); //can send only 512 bits at a time (1 byte sent per bit...) - printf("Sending [%d bytes]", GraphTraceLen); - for (i = 0; i < GraphTraceLen; i += USB_CMD_DATA_SIZE) { + printf("Sending [%d bytes]", conn->GraphTraceLen); + for (i = 0; i < conn->GraphTraceLen; i += USB_CMD_DATA_SIZE) { UsbCommand c = {CMD_DOWNLOADED_SIM_SAMPLES_125K, {i, 0, 0}}; for (j = 0; j < USB_CMD_DATA_SIZE; j++) { - c.d.asBytes[j] = GraphBuffer[i+j]; + c.d.asBytes[j] = conn->GraphBuffer[i+j]; } - SendCommand(&c); - WaitForResponse(CMD_ACK,NULL); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK,NULL); printf("."); } printf("\n"); PrintAndLog("Starting to simulate"); - UsbCommand c = {CMD_SIMULATE_TAG_125K, {GraphTraceLen, gap, 0}}; - clearCommandBuffer(); - SendCommand(&c); + UsbCommand c = {CMD_SIMULATE_TAG_125K, {conn->GraphTraceLen, gap, 0}}; + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -440,12 +441,12 @@ int usage_lf_simfsk(void) PrintAndLog("Usage: lf simfsk [c ] [i] [H ] [L ] [d ]"); PrintAndLog("Options: "); PrintAndLog(" h This help"); - PrintAndLog(" c Manually set clock - can autodetect if using DemodBuffer"); + PrintAndLog(" c Manually set clock - can autodetect if using conn->DemodBuffer"); PrintAndLog(" i invert data"); PrintAndLog(" H Manually set the larger Field Clock"); PrintAndLog(" L Manually set the smaller Field Clock"); //PrintAndLog(" s TBD- -to enable a gap between playback repetitions - default: no gap"); - PrintAndLog(" d Data to sim as hex - omit to sim from DemodBuffer"); + PrintAndLog(" d Data to sim as hex - omit to sim from conn->DemodBuffer"); PrintAndLog("\n NOTE: if you set one clock manually set them all manually"); return 0; } @@ -456,13 +457,13 @@ int usage_lf_simask(void) PrintAndLog("Usage: lf simask [c ] [i] [b|m|r] [s] [d ]"); PrintAndLog("Options: "); PrintAndLog(" h This help"); - PrintAndLog(" c Manually set clock - can autodetect if using DemodBuffer"); + PrintAndLog(" c Manually set clock - can autodetect if using conn->DemodBuffer"); PrintAndLog(" i invert data"); PrintAndLog(" b sim ask/biphase"); PrintAndLog(" m sim ask/manchester - Default"); PrintAndLog(" r sim ask/raw"); PrintAndLog(" s add t55xx Sequence Terminator gap - default: no gaps (only manchester)"); - PrintAndLog(" d Data to sim as hex - omit to sim from DemodBuffer"); + PrintAndLog(" d Data to sim as hex - omit to sim from conn->DemodBuffer"); return 0; } @@ -472,19 +473,19 @@ int usage_lf_simpsk(void) PrintAndLog("Usage: lf simpsk [1|2|3] [c ] [i] [r ] [d ]"); PrintAndLog("Options: "); PrintAndLog(" h This help"); - PrintAndLog(" c Manually set clock - can autodetect if using DemodBuffer"); + PrintAndLog(" c Manually set clock - can autodetect if using conn->DemodBuffer"); PrintAndLog(" i invert data"); PrintAndLog(" 1 set PSK1 (default)"); PrintAndLog(" 2 set PSK2"); PrintAndLog(" 3 set PSK3"); PrintAndLog(" r 2|4|8 are valid carriers: default = 2"); - PrintAndLog(" d Data to sim as hex - omit to sim from DemodBuffer"); + PrintAndLog(" d Data to sim as hex - omit to sim from conn->DemodBuffer"); return 0; } // by marshmellow - sim fsk data given clock, fcHigh, fcLow, invert -// - allow pull data from DemodBuffer -int CmdLFfskSim(const char *Cmd) +// - allow pull data from conn->DemodBuffer +int CmdLFfskSim(pm3_connection* conn, const char *Cmd) { //might be able to autodetect FCs and clock from Graphbuffer if using demod buffer // otherwise will need FChigh, FClow, Clock, and bitstream @@ -539,7 +540,7 @@ int CmdLFfskSim(const char *Cmd) } if(errors) break; } - if(cmdp == 0 && DemodBufferLen == 0) + if(cmdp == 0 && conn->DemodBufferLen == 0) { errors = true;// No args } @@ -550,9 +551,9 @@ int CmdLFfskSim(const char *Cmd) return usage_lf_simfsk(); } int firstClockEdge = 0; - if (dataLen == 0){ //using DemodBuffer + if (dataLen == 0){ //using conn->DemodBuffer if (clk==0 || fcHigh==0 || fcLow==0){ //manual settings must set them all - uint8_t ans = fskClocks(&fcHigh, &fcLow, &clk, 0, &firstClockEdge); + uint8_t ans = fskClocks(conn, &fcHigh, &fcLow, &clk, 0, &firstClockEdge); if (ans==0){ if (!fcHigh) fcHigh=10; if (!fcLow) fcLow=8; @@ -560,7 +561,7 @@ int CmdLFfskSim(const char *Cmd) } } } else { - setDemodBuf(data, dataLen, 0); + setDemodBuf(conn, data, dataLen, 0); } //default if not found @@ -571,22 +572,22 @@ int CmdLFfskSim(const char *Cmd) uint16_t arg1, arg2; arg1 = fcHigh << 8 | fcLow; arg2 = invert << 8 | clk; - size_t size = DemodBufferLen; + size_t size = conn->DemodBufferLen; if (size > USB_CMD_DATA_SIZE) { - PrintAndLog("DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); + PrintAndLog("conn->DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); size = USB_CMD_DATA_SIZE; } UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; - memcpy(c.d.asBytes, DemodBuffer, size); - clearCommandBuffer(); - SendCommand(&c); + memcpy(c.d.asBytes, conn->DemodBuffer, size); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } // by marshmellow - sim ask data given clock, invert, manchester or raw, separator -// - allow pull data from DemodBuffer -int CmdLFaskSim(const char *Cmd) +// - allow pull data from conn->DemodBuffer +int CmdLFaskSim(pm3_connection* conn, const char *Cmd) { //autodetect clock from Graphbuffer if using demod buffer // needs clock, invert, manchester/raw as m or r, separator as s, and bitstream @@ -645,7 +646,7 @@ int CmdLFaskSim(const char *Cmd) } if(errors) break; } - if(cmdp == 0 && DemodBufferLen == 0) + if(cmdp == 0 && conn->DemodBufferLen == 0) { errors = true;// No args } @@ -655,32 +656,32 @@ int CmdLFaskSim(const char *Cmd) { return usage_lf_simask(); } - if (dataLen == 0){ //using DemodBuffer - if (clk == 0) clk = GetAskClock("0", false, false); + if (dataLen == 0){ //using conn->DemodBuffer + if (clk == 0) clk = GetAskClock(conn, "0", false, false); } else { - setDemodBuf(data, dataLen, 0); + setDemodBuf(conn, data, dataLen, 0); } if (clk == 0) clk = 64; if (encoding == 0) clk = clk/2; //askraw needs to double the clock speed uint16_t arg1, arg2; - size_t size=DemodBufferLen; + size_t size=conn->DemodBufferLen; arg1 = clk << 8 | encoding; arg2 = invert << 8 | separator; if (size > USB_CMD_DATA_SIZE) { - PrintAndLog("DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); + PrintAndLog("conn->DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); size = USB_CMD_DATA_SIZE; } UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; PrintAndLog("preparing to sim ask data: %d bits", size); - memcpy(c.d.asBytes, DemodBuffer, size); - clearCommandBuffer(); - SendCommand(&c); + memcpy(c.d.asBytes, conn->DemodBuffer, size); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } // by marshmellow - sim psk data given carrier, clock, invert -// - allow pull data from DemodBuffer or parameters -int CmdLFpskSim(const char *Cmd) +// - allow pull data from conn->DemodBuffer or parameters +int CmdLFpskSim(pm3_connection* conn, const char *Cmd) { //might be able to autodetect FC and clock from Graphbuffer if using demod buffer //will need carrier, Clock, and bitstream @@ -740,7 +741,7 @@ int CmdLFpskSim(const char *Cmd) } if (errors) break; } - if (cmdp == 0 && DemodBufferLen == 0) + if (cmdp == 0 && conn->DemodBufferLen == 0) { errors = true;// No args } @@ -750,14 +751,14 @@ int CmdLFpskSim(const char *Cmd) { return usage_lf_simpsk(); } - if (dataLen == 0){ //using DemodBuffer + if (dataLen == 0){ //using conn->DemodBuffer PrintAndLog("Getting Clocks"); - if (clk==0) clk = GetPskClock("", false, false); + if (clk==0) clk = GetPskClock(conn, "", false, false); PrintAndLog("clk: %d",clk); - if (!carrier) carrier = GetPskCarrier("", false, false); + if (!carrier) carrier = GetPskCarrier(conn, "", false, false); PrintAndLog("carrier: %d", carrier); } else { - setDemodBuf(data, dataLen, 0); + setDemodBuf(conn, data, dataLen, 0); } if (clk <= 0) clk = 32; @@ -765,7 +766,7 @@ int CmdLFpskSim(const char *Cmd) if (pskType != 1){ if (pskType == 2){ //need to convert psk2 to psk1 data before sim - psk2TOpsk1(DemodBuffer, DemodBufferLen); + psk2TOpsk1(conn->DemodBuffer, conn->DemodBufferLen); } else { PrintAndLog("Sorry, PSK3 not yet available"); } @@ -773,31 +774,31 @@ int CmdLFpskSim(const char *Cmd) uint16_t arg1, arg2; arg1 = clk << 8 | carrier; arg2 = invert; - size_t size=DemodBufferLen; + size_t size=conn->DemodBufferLen; if (size > USB_CMD_DATA_SIZE) { - PrintAndLog("DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); + PrintAndLog("conn->DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); size=USB_CMD_DATA_SIZE; } UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}}; - PrintAndLog("DEBUG: Sending DemodBuffer Length: %d", size); - memcpy(c.d.asBytes, DemodBuffer, size); - clearCommandBuffer(); - SendCommand(&c); + PrintAndLog("DEBUG: Sending conn->DemodBuffer Length: %d", size); + memcpy(c.d.asBytes, conn->DemodBuffer, size); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } -int CmdLFSimBidir(const char *Cmd) +int CmdLFSimBidir(pm3_connection* conn, const char *Cmd) { // Set ADC to twice the carrier for a slight supersampling // HACK: not implemented in ARMSRC. PrintAndLog("Not implemented yet."); UsbCommand c = {CMD_LF_SIMULATE_BIDIR, {47, 384, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdVchDemod(const char *Cmd) +int CmdVchDemod(pm3_connection* conn, const char *Cmd) { // Is this the entire sync pattern, or does this also include some // data bits that happen to be the same everywhere? That would be @@ -820,11 +821,11 @@ int CmdVchDemod(const char *Cmd) int i; // It does us no good to find the sync pattern, with fewer than // 2048 samples after it... - for (i = 0; i < (GraphTraceLen-2048); i++) { + for (i = 0; i < (conn->GraphTraceLen-2048); i++) { int sum = 0; int j; for (j = 0; j < arraylen(SyncPattern); j++) { - sum += GraphBuffer[i+j]*SyncPattern[j]; + sum += conn->GraphBuffer[i+j]*SyncPattern[j]; } if (sum > bestCorrel) { bestCorrel = sum; @@ -843,7 +844,7 @@ int CmdVchDemod(const char *Cmd) int sum = 0; int j; for (j = 0; j < 8; j++) { - sum += GraphBuffer[bestPos+i+j]; + sum += conn->GraphBuffer[bestPos+i+j]; } if (sum < 0) { bits[i/8] = '.'; @@ -860,50 +861,50 @@ int CmdVchDemod(const char *Cmd) PrintAndLog("worst metric: %d at pos %d", worst, worstPos); if (strcmp(Cmd, "clone")==0) { - GraphTraceLen = 0; + conn->GraphTraceLen = 0; char *s; for(s = bits; *s; s++) { int j; for(j = 0; j < 16; j++) { - GraphBuffer[GraphTraceLen++] = (*s == '1') ? 1 : 0; + conn->GraphBuffer[conn->GraphTraceLen++] = (*s == '1') ? 1 : 0; } } - RepaintGraphWindow(); + RepaintGraphWindow(conn); } return 0; } //by marshmellow -int CheckChipType(char cmdp) { +int CheckChipType(pm3_connection* conn, char cmdp) { uint32_t wordData = 0; - if (IsOffline() || cmdp == '1') return 0; + if (conn->offline || cmdp == '1') return 0; - save_restoreGB(GRAPH_SAVE); - save_restoreDB(GRAPH_SAVE); + save_restoreGB(conn, GRAPH_SAVE); + save_restoreDB(conn, GRAPH_SAVE); //check for em4x05/em4x69 chips first - if (EM4x05Block0Test(&wordData)) { + if (EM4x05Block0Test(conn, &wordData)) { PrintAndLog("\nValid EM4x05/EM4x69 Chip Found\nTry lf em 4x05... commands\n"); - save_restoreGB(GRAPH_RESTORE); - save_restoreDB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); + save_restoreDB(conn, GRAPH_RESTORE); return 1; } //check for t55xx chip... - if (tryDetectP1(true)) { + if (tryDetectP1(conn, true)) { PrintAndLog("\nValid T55xx Chip Found\nTry lf t55xx ... commands\n"); - save_restoreGB(GRAPH_RESTORE); - save_restoreDB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); + save_restoreDB(conn, GRAPH_RESTORE); return 1; } - save_restoreGB(GRAPH_RESTORE); - save_restoreDB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); + save_restoreDB(conn, GRAPH_RESTORE); return 0; } //by marshmellow -int CmdLFfind(const char *Cmd) +int CmdLFfind(pm3_connection* conn, const char *Cmd) { uint32_t wordData = 0; int ans=0; @@ -916,16 +917,16 @@ int CmdLFfind(const char *Cmd) PrintAndLog(" [Search for Unknown tags] , if not set, reads only known tags."); PrintAndLog(""); PrintAndLog(" sample: lf search = try reading data from tag & search for known tags"); - PrintAndLog(" : lf search 1 = use data from GraphBuffer & search for known tags"); + PrintAndLog(" : lf search 1 = use data from conn->GraphBuffer & search for known tags"); PrintAndLog(" : lf search u = try reading data from tag & search for known and unknown tags"); - PrintAndLog(" : lf search 1 u = use data from GraphBuffer & search for known and unknown tags"); + PrintAndLog(" : lf search 1 u = use data from conn->GraphBuffer & search for known and unknown tags"); return 0; } - if (!IsOffline() && (cmdp != '1')) { - lf_read(true, 30000); - } else if (GraphTraceLen < minLength) { + if (!conn->offline && (cmdp != '1')) { + lf_read(conn, true, 30000); + } else if (conn->GraphTraceLen < minLength) { PrintAndLog("Data in Graphbuffer was too small."); return 0; } @@ -937,19 +938,19 @@ int CmdLFfind(const char *Cmd) size_t testLen = minLength; // only run if graphbuffer is just noise as it should be for hitag/cotag - if (graphJustNoise(GraphBuffer, testLen)) { + if (graphJustNoise(conn->GraphBuffer, testLen)) { // only run these tests if we are in online mode - if (!IsOffline() && (cmdp != '1')) { + if (!conn->offline && (cmdp != '1')) { // test for em4x05 in reader talk first mode. - if (EM4x05Block0Test(&wordData)) { + if (EM4x05Block0Test(conn, &wordData)) { PrintAndLog("\nValid EM4x05/EM4x69 Chip Found\nUse lf em 4x05readword/dump commands to read\n"); return 1; } - ans=CmdLFHitagReader("26"); + ans=CmdLFHitagReader(conn, "26"); if (ans==0) { return 1; } - ans=CmdCOTAGRead(""); + ans=CmdCOTAGRead(conn, ""); if (ans>0) { PrintAndLog("\nValid COTAG ID Found!"); return 1; @@ -960,138 +961,138 @@ int CmdLFfind(const char *Cmd) // TODO test for modulation then only test formats that use that modulation - ans=CmdFSKdemodIO(""); + ans=CmdFSKdemodIO(conn, ""); if (ans>0) { PrintAndLog("\nValid IO Prox ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdFSKdemodPyramid(""); + ans=CmdFSKdemodPyramid(conn, ""); if (ans>0) { PrintAndLog("\nValid Pyramid ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdFSKdemodParadox(""); + ans=CmdFSKdemodParadox(conn, ""); if (ans>0) { PrintAndLog("\nValid Paradox ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdFSKdemodAWID(""); + ans=CmdFSKdemodAWID(conn, ""); if (ans>0) { PrintAndLog("\nValid AWID ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdFSKdemodHID(""); + ans=CmdFSKdemodHID(conn, ""); if (ans>0) { PrintAndLog("\nValid HID Prox ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdAskEM410xDemod(""); + ans=CmdAskEM410xDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid EM410x ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdVisa2kDemod(""); + ans=CmdVisa2kDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid Visa2000 ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdG_Prox_II_Demod(""); + ans=CmdG_Prox_II_Demod(conn, ""); if (ans>0) { PrintAndLog("\nValid G Prox II ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdFdxDemod(""); //biphase + ans=CmdFdxDemod(conn, ""); //biphase if (ans>0) { PrintAndLog("\nValid FDX-B ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=EM4x50Read("", false); //ask + ans=EM4x50Read(conn, "", false); //ask if (ans>0) { PrintAndLog("\nValid EM4x50 ID Found!"); return 1; } - ans=CmdJablotronDemod(""); + ans=CmdJablotronDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid Jablotron ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdNoralsyDemod(""); + ans=CmdNoralsyDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid Noralsy ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdSecurakeyDemod(""); + ans=CmdSecurakeyDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid Securakey ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdVikingDemod(""); + ans=CmdVikingDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid Viking ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdIndalaDecode(""); //psk + ans=CmdIndalaDecode(conn, ""); //psk if (ans>0) { PrintAndLog("\nValid Indala ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdPSKNexWatch(""); + ans=CmdPSKNexWatch(conn, ""); if (ans>0) { PrintAndLog("\nValid NexWatch ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdPacDemod(""); + ans=CmdPacDemod(conn, ""); if (ans>0) { PrintAndLog("\nValid PAC/Stanley ID Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } PrintAndLog("\nNo Known Tags Found!\n"); if (testRaw=='u' || testRaw=='U') { - //ans=CheckChipType(cmdp); + //ans=CheckChipType(conn, cmdp); //test unknown tag formats (raw mode)0 PrintAndLog("\nChecking for Unknown tags:\n"); - ans=AutoCorrelate(GraphBuffer, GraphBuffer, GraphTraceLen, 4000, false, false); + ans=AutoCorrelate(conn, conn->GraphBuffer, conn->GraphBuffer, conn->GraphTraceLen, 4000, false, false); if (ans > 0) PrintAndLog("Possible Auto Correlation of %d repeating samples",ans); - ans=GetFskClock("",false,false); + ans=GetFskClock(conn, "", false, false); if (ans != 0) { //fsk - ans=FSKrawDemod("",true); + ans=FSKrawDemod(conn, "", true); if (ans>0) { PrintAndLog("\nUnknown FSK Modulated Tag Found!"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } } bool st = true; - ans=ASKDemod_ext("0 0 0",true,false,1,&st); + ans=ASKDemod_ext(conn, "0 0 0",true,false,1,&st); if (ans>0) { PrintAndLog("\nUnknown ASK Modulated and Manchester encoded Tag Found!"); PrintAndLog("\nif it does not look right it could instead be ASK/Biphase - try 'data rawdemod ab'"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans=CmdPSK1rawDemod(""); + ans=CmdPSK1rawDemod(conn, ""); if (ans>0) { PrintAndLog("Possible unknown PSK1 Modulated Tag Found above!\n\nCould also be PSK2 - try 'data rawdemod p2'"); PrintAndLog("\nCould also be PSK3 - [currently not supported]"); PrintAndLog("\nCould also be NRZ - try 'data rawdemod nr'"); - return CheckChipType(cmdp); + return CheckChipType(conn, cmdp); } - ans = CheckChipType(cmdp); + ans = CheckChipType(conn, cmdp); PrintAndLog("\nNo Data Found!\n"); } return 0; @@ -1122,29 +1123,29 @@ static command_t CommandTable[] = {"ti", CmdLFTI, 1, "{ TI CHIPs... }"}, {"viking", CmdLFViking, 1, "{ Viking RFIDs... }"}, {"visa2000", CmdLFVisa2k, 1, "{ Visa2000 RFIDs... }"}, - {"cmdread", CmdLFCommandRead, 0, " ['H'] -- Modulate LF reader field to send command before read (all periods in microseconds) (option 'H' for 134)"}, + {"cmdread", CmdLFCommandRead, 0, " ['H'] -- Modulate LF reader field to send command before read (conn, all periods in microseconds) (option 'H' for 134)"}, {"config", CmdLFSetConfig, 0, "Set config for LF sampling, bit/sample, decimation, frequency"}, {"flexdemod", CmdFlexdemod, 1, "Demodulate samples for FlexPass"}, {"read", CmdLFRead, 0, "['s' silent] Read 125/134 kHz LF ID-only tag. Do 'lf read h' for help"}, - {"search", CmdLFfind, 1, "[offline] ['u'] Read and Search for valid known tag (in offline mode it you can load first then search) - 'u' to search for unknown tags"}, - {"sim", CmdLFSim, 0, "[GAP] -- Simulate LF tag from buffer with optional GAP (in microseconds)"}, + {"search", CmdLFfind, 1, "[offline] ['u'] Read and Search for valid known tag (conn, in offline mode it you can load first then search) - 'u' to search for unknown tags"}, + {"sim", CmdLFSim, 0, "[GAP] -- Simulate LF tag from buffer with optional GAP (conn, in microseconds)"}, {"simask", CmdLFaskSim, 0, "[clock] [invert <1|0>] [biphase/manchester/raw <'b'|'m'|'r'>] [msg separator 's'] [d ] -- Simulate LF ASK tag from demodbuffer or input"}, {"simfsk", CmdLFfskSim, 0, "[c ] [i] [H ] [L ] [d ] -- Simulate LF FSK tag from demodbuffer or input"}, {"simpsk", CmdLFpskSim, 0, "[1|2|3] [c ] [i] [r ] [d ] -- Simulate LF PSK tag from demodbuffer or input"}, - {"simbidir", CmdLFSimBidir, 0, "Simulate LF tag (with bidirectional data transmission between reader and tag)"}, - {"snoop", CmdLFSnoop, 0, "['l'|'h'|] [trigger threshold]-- Snoop LF (l:125khz, h:134khz)"}, + {"simbidir", CmdLFSimBidir, 0, "Simulate LF tag (conn, with bidirectional data transmission between reader and tag)"}, + {"snoop", CmdLFSnoop, 0, "['l'|'h'|] [trigger threshold]-- Snoop LF (conn, l:125khz, h:134khz)"}, {"vchdemod", CmdVchDemod, 1, "['clone'] -- Demodulate samples for VeriChip"}, {NULL, NULL, 0, NULL} }; -int CmdLF(const char *Cmd) +int CmdLF(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlf.h b/client/cmdlf.h index 9f446ee0..dc1181d6 100644 --- a/client/cmdlf.h +++ b/client/cmdlf.h @@ -13,22 +13,23 @@ #include #include +#include "comms.h" -extern int CmdLF(const char *Cmd); +extern int CmdLF(pm3_connection* conn, const char *Cmd); -extern int CmdLFCommandRead(const char *Cmd); -extern int CmdFlexdemod(const char *Cmd); -extern int CmdIndalaDemod(const char *Cmd); -extern int CmdIndalaClone(const char *Cmd); -extern int CmdLFRead(const char *Cmd); -extern int CmdLFSim(const char *Cmd); -extern int CmdLFaskSim(const char *Cmd); -extern int CmdLFfskSim(const char *Cmd); -extern int CmdLFpskSim(const char *Cmd); -extern int CmdLFSimBidir(const char *Cmd); -extern int CmdLFSnoop(const char *Cmd); -extern int CmdVchDemod(const char *Cmd); -extern int CmdLFfind(const char *Cmd); -extern bool lf_read(bool silent, uint32_t samples); +extern int CmdLFCommandRead(pm3_connection* conn, const char *Cmd); +extern int CmdFlexdemod(pm3_connection* conn, const char *Cmd); +extern int CmdIndalaDemod(pm3_connection* conn, const char *Cmd); +extern int CmdIndalaClone(pm3_connection* conn, const char *Cmd); +extern int CmdLFRead(pm3_connection* conn, const char *Cmd); +extern int CmdLFSim(pm3_connection* conn, const char *Cmd); +extern int CmdLFaskSim(pm3_connection* conn, const char *Cmd); +extern int CmdLFfskSim(pm3_connection* conn, const char *Cmd); +extern int CmdLFpskSim(pm3_connection* conn, const char *Cmd); +extern int CmdLFSimBidir(pm3_connection* conn, const char *Cmd); +extern int CmdLFSnoop(pm3_connection* conn, const char *Cmd); +extern int CmdVchDemod(pm3_connection* conn, const char *Cmd); +extern int CmdLFfind(pm3_connection* conn, const char *Cmd); +extern bool lf_read(pm3_connection* conn, bool silent, uint32_t samples); #endif diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c index 141ba172..4a7ffe72 100644 --- a/client/cmdlfawid.c +++ b/client/cmdlfawid.c @@ -23,8 +23,9 @@ #include "cmddata.h" // for printDemod and demodbuffer commands #include "graph.h" // for getFromGraphBuff cmds #include "cmdmain.h" +#include "comms.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_awid_read(void) { PrintAndLog("Enables AWID26 compatible reader mode printing details of scanned AWID26 tags."); @@ -69,23 +70,23 @@ int usage_lf_awid_clone(void) { return 0; } -int CmdAWIDReadFSK(const char *Cmd) { +int CmdAWIDReadFSK(pm3_connection* conn, const char *Cmd) { int findone=0; if (Cmd[0] == 'h' || Cmd[0] == 'H') return usage_lf_awid_read(); if (Cmd[0] == '1') findone = 1; UsbCommand c = {CMD_AWID_DEMOD_FSK, {findone, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } //by marshmellow //AWID Prox demod - FSK RF/50 with preamble of 00000001 (always a 96 bit data stream) //print full AWID Prox ID and some bit format details if found -int CmdFSKdemodAWID(const char *Cmd) +int CmdFSKdemodAWID(pm3_connection* conn, const char *Cmd) { uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(BitStream); + size_t size = getFromGraphBuf(conn, BitStream); if (size==0) return 0; int waveIdx = 0; @@ -126,8 +127,8 @@ int CmdFSKdemodAWID(const char *Cmd) uint32_t rawLo = bytebits_to_byte(BitStream+idx+64,32); uint32_t rawHi = bytebits_to_byte(BitStream+idx+32,32); uint32_t rawHi2 = bytebits_to_byte(BitStream+idx,32); - setDemodBuf(BitStream,96,idx); - setClockGrid(50, waveIdx + (idx*50)); + setDemodBuf(conn, BitStream, 96, idx); + setClockGrid(conn, 50, waveIdx + (idx*50)); size = removeParity(BitStream, idx+8, 4, 1, 88); if (size != 66){ @@ -172,7 +173,7 @@ int CmdFSKdemodAWID(const char *Cmd) } if (g_debugMode){ PrintAndLog("DEBUG: idx: %d, Len: %d Printing Demod Buffer:", idx, 96); - printDemodBuff(); + printDemodBuff(conn); } //todo - convert hi2, hi, lo to demodbuffer for future sim/clone commands return 1; @@ -199,7 +200,7 @@ int getAWIDBits(uint32_t fc, uint32_t cn, uint8_t *AWIDBits) { return 1; } -int CmdAWIDSim(const char *Cmd) { +int CmdAWIDSim(pm3_connection* conn, const char *Cmd) { uint32_t fcode = 0, cnum = 0, fc=0, cn=0; uint8_t BitStream[96]; uint8_t *bs = BitStream; @@ -227,12 +228,12 @@ int CmdAWIDSim(const char *Cmd) { // AWID uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 0 UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bs, size); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } -int CmdAWIDClone(const char *Cmd) { +int CmdAWIDClone(pm3_connection* conn, const char *Cmd) { uint32_t blocks[4] = {T55x7_MODULATION_FSK2a | T55x7_BITRATE_RF_50 | 3< // for uint_32+ +#include "comms.h" -int CmdLFAWID(const char *Cmd); -int CmdAWIDReadFSK(const char *Cmd); -int CmdAWIDSim(const char *Cmd); -int CmdAWIDClone(const char *Cmd); -int CmdFSKdemodAWID(const char *Cmd); +int CmdLFAWID(pm3_connection* conn, const char *Cmd); +int CmdAWIDReadFSK(pm3_connection* conn, const char *Cmd); +int CmdAWIDSim(pm3_connection* conn, const char *Cmd); +int CmdAWIDClone(pm3_connection* conn, const char *Cmd); +int CmdFSKdemodAWID(pm3_connection* conn, const char *Cmd); int getAWIDBits(unsigned int fc, unsigned int cn, uint8_t *AWIDBits); int usage_lf_awid_fskdemod(void); int usage_lf_awid_clone(void); diff --git a/client/cmdlfcotag.c b/client/cmdlfcotag.c index 6d035e8c..a8aea536 100644 --- a/client/cmdlfcotag.c +++ b/client/cmdlfcotag.c @@ -19,7 +19,7 @@ #include "usb_cmd.h" #include "cmdmain.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_cotag_read(void){ PrintAndLog("Usage: lf COTAG read [h] "); @@ -37,11 +37,11 @@ int usage_lf_cotag_read(void){ // COTAG demod should be able to use GraphBuffer, // when data load samples -int CmdCOTAGDemod(const char *Cmd) { +int CmdCOTAGDemod(pm3_connection* conn, const char *Cmd) { uint8_t bits[COTAG_BITS] = {0}; size_t bitlen = COTAG_BITS; - memcpy(bits, DemodBuffer, COTAG_BITS); + memcpy(bits, conn->DemodBuffer, COTAG_BITS); uint8_t alignPos = 0; int err = manrawdecode(bits, &bitlen, 1, &alignPos); @@ -50,7 +50,7 @@ int CmdCOTAGDemod(const char *Cmd) { return -1; } - setDemodBuf(bits, bitlen, 0); + setDemodBuf(conn, bits, bitlen, 0); //got a good demod uint16_t cn = bytebits_to_byteLSBF(bits+1, 16); @@ -76,7 +76,7 @@ int CmdCOTAGDemod(const char *Cmd) { // 0 = HIGH/LOW signal - maxlength bigbuff // 1 = translation for HI/LO into bytes with manchester 0,1 - length 300 // 2 = raw signal - maxlength bigbuff -int CmdCOTAGRead(const char *Cmd) { +int CmdCOTAGRead(pm3_connection* conn, const char *Cmd) { if (Cmd[0] == 'h' || Cmd[0] == 'H') return usage_lf_cotag_read(); @@ -84,9 +84,9 @@ int CmdCOTAGRead(const char *Cmd) { sscanf(Cmd, "%u", &rawsignal); UsbCommand c = {CMD_COTAG, {rawsignal, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); - if ( !WaitForResponseTimeout(CMD_ACK, NULL, 7000) ) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if ( !WaitForResponseTimeout(conn, CMD_ACK, NULL, 7000) ) { PrintAndLog("command execution time out"); return -1; } @@ -94,19 +94,20 @@ int CmdCOTAGRead(const char *Cmd) { switch ( rawsignal ){ case 0: case 2: { - CmdPlot(""); - CmdGrid("384"); - getSamples(0, true); break; + CmdPlot(conn, ""); + CmdGrid(conn, "384"); + getSamples(conn, 0, true); + break; } case 1: { - GetFromBigBuf(DemodBuffer, COTAG_BITS, 0); - DemodBufferLen = COTAG_BITS; + GetFromBigBuf(conn, conn->DemodBuffer, COTAG_BITS, 0); + conn->DemodBufferLen = COTAG_BITS; UsbCommand response; - if ( !WaitForResponseTimeout(CMD_ACK, &response, 1000) ) { + if ( !WaitForResponseTimeout(conn, CMD_ACK, &response, 1000) ) { PrintAndLog("timeout while waiting for reply."); return -1; } - return CmdCOTAGDemod(""); + return CmdCOTAGDemod(conn, ""); } } return 0; @@ -119,13 +120,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFCOTAG(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFCOTAG(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfcotag.h b/client/cmdlfcotag.h index f0d0e75f..507a52f5 100644 --- a/client/cmdlfcotag.h +++ b/client/cmdlfcotag.h @@ -15,9 +15,9 @@ #define COTAG_BITS 264 #endif -int CmdLFCOTAG(const char *Cmd); -int CmdCOTAGRead(const char *Cmd); -int CmdCOTAGDemod(const char *Cmd); +int CmdLFCOTAG(pm3_connection* conn, const char *Cmd); +int CmdCOTAGRead(pm3_connection* conn, const char *Cmd); +int CmdCOTAGDemod(pm3_connection* conn, const char *Cmd); int usage_lf_cotag_read(void); #endif diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index f5dfee35..97a7e939 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -27,16 +27,16 @@ uint64_t g_em410xId=0; -static int CmdHelp(const char *Cmd); -void ConstructEM410xEmulGraph(const char *uid,const uint8_t clock); +static int CmdHelp(pm3_connection* conn, const char *Cmd); +void ConstructEM410xEmulGraph(pm3_connection* conn, const char *uid, const uint8_t clock); -int CmdEMdemodASK(const char *Cmd) +int CmdEMdemodASK(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); int findone = (cmdp == '1') ? 1 : 0; UsbCommand c={CMD_EM410X_DEMOD}; c.arg[0]=findone; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -145,21 +145,21 @@ void printEM410x(uint32_t hi, uint64_t id) * CCCC <-- each bit here is parity for the 10 bits above in corresponding column * 0 <-- stop bit, end of tag */ -int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) +int AskEm410xDecode(pm3_connection* conn, bool verbose, uint32_t *hi, uint64_t *lo ) { size_t idx = 0; uint8_t BitStream[512]={0}; size_t BitLen = sizeof(BitStream); - if ( !getDemodBuf(BitStream, &BitLen) ) return 0; + if ( !getDemodBuf(conn, BitStream, &BitLen) ) return 0; if (Em410xDecode(BitStream, &BitLen, &idx, hi, lo)) { - //set GraphBuffer for clone or sim command - setDemodBuf(DemodBuffer, (BitLen==40) ? 64 : 128, idx+1); - setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx+1)*g_DemodClock)); + //set conn->GraphBuffer for clone or sim command + setDemodBuf(conn, conn->DemodBuffer, (BitLen==40) ? 64 : 128, idx+1); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + ((idx+1)*conn->g_DemodClock)); if (g_debugMode) { PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen); - printDemodBuff(); + printDemodBuff(conn); } if (verbose) { PrintAndLog("EM410x pattern found: "); @@ -172,18 +172,18 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) } //askdemod then call Em410xdecode -int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose) +int AskEm410xDemod(pm3_connection* conn, const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose) { bool st = true; - if (!ASKDemod_ext(Cmd, false, false, 1, &st)) return 0; - return AskEm410xDecode(verbose, hi, lo); + if (!ASKDemod_ext(conn, Cmd, false, false, 1, &st)) return 0; + return AskEm410xDecode(conn, verbose, hi, lo); } //by marshmellow //takes 3 arguments - clock, invert and maxErr as integers //attempts to demodulate ask while decoding manchester //prints binary found and saves in graphbuffer for further commands -int CmdAskEM410xDemod(const char *Cmd) +int CmdAskEM410xDemod(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') { @@ -192,16 +192,16 @@ int CmdAskEM410xDemod(const char *Cmd) PrintAndLog(" , 1 for invert output"); PrintAndLog(" [set maximum allowed errors], default = 100."); PrintAndLog(""); - PrintAndLog(" sample: lf em 410xdemod = demod an EM410x Tag ID from GraphBuffer"); - PrintAndLog(" : lf em 410xdemod 32 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/32"); - PrintAndLog(" : lf em 410xdemod 32 1 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/32 and inverting data"); - PrintAndLog(" : lf em 410xdemod 1 = demod an EM410x Tag ID from GraphBuffer while inverting data"); - PrintAndLog(" : lf em 410xdemod 64 1 0 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/64 and inverting data and allowing 0 demod errors"); + PrintAndLog(" sample: lf em 410xdemod = demod an EM410x Tag ID from conn->GraphBuffer"); + PrintAndLog(" : lf em 410xdemod 32 = demod an EM410x Tag ID from conn->GraphBuffer using a clock of RF/32"); + PrintAndLog(" : lf em 410xdemod 32 1 = demod an EM410x Tag ID from conn->GraphBuffer using a clock of RF/32 and inverting data"); + PrintAndLog(" : lf em 410xdemod 1 = demod an EM410x Tag ID from conn->GraphBuffer while inverting data"); + PrintAndLog(" : lf em 410xdemod 64 1 0 = demod an EM410x Tag ID from conn->GraphBuffer using a clock of RF/64 and inverting data and allowing 0 demod errors"); return 0; } uint64_t lo = 0; uint32_t hi = 0; - return AskEm410xDemod(Cmd, &hi, &lo, true); + return AskEm410xDemod(conn, Cmd, &hi, &lo, true); } int usage_lf_em410x_sim(void) { @@ -219,15 +219,15 @@ int usage_lf_em410x_sim(void) { } // Construct the graph for emulating an EM410X tag -void ConstructEM410xEmulGraph(const char *uid,const uint8_t clock) +void ConstructEM410xEmulGraph(pm3_connection* conn, const char *uid,const uint8_t clock) { int i, n, j, binary[4], parity[4]; /* clear our graph */ - ClearGraph(0); + ClearGraph(conn, 0); /* write 9 start bits */ for (i = 0; i < 9; i++) - AppendGraph(0, clock, 1); + AppendGraph(conn, 0, clock, 1); /* for each hex char */ parity[0] = parity[1] = parity[2] = parity[3] = 0; @@ -238,13 +238,13 @@ void ConstructEM410xEmulGraph(const char *uid,const uint8_t clock) binary[j] = n % 2; /* append each bit */ - AppendGraph(0, clock, binary[0]); - AppendGraph(0, clock, binary[1]); - AppendGraph(0, clock, binary[2]); - AppendGraph(0, clock, binary[3]); + AppendGraph(conn, 0, clock, binary[0]); + AppendGraph(conn, 0, clock, binary[1]); + AppendGraph(conn, 0, clock, binary[2]); + AppendGraph(conn, 0, clock, binary[3]); /* append parity bit */ - AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); + AppendGraph(conn, 0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); /* keep track of column parity */ parity[0] ^= binary[0]; @@ -254,17 +254,17 @@ void ConstructEM410xEmulGraph(const char *uid,const uint8_t clock) } /* parity columns */ - AppendGraph(0, clock, parity[0]); - AppendGraph(0, clock, parity[1]); - AppendGraph(0, clock, parity[2]); - AppendGraph(0, clock, parity[3]); + AppendGraph(conn, 0, clock, parity[0]); + AppendGraph(conn, 0, clock, parity[1]); + AppendGraph(conn, 0, clock, parity[2]); + AppendGraph(conn, 0, clock, parity[3]); /* stop bit */ - AppendGraph(1, clock, 0); + AppendGraph(conn, 1, clock, 0); } // emulate an EM410X tag -int CmdEM410xSim(const char *Cmd) +int CmdEM410xSim(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); uint8_t uid[5] = {0x00}; @@ -282,9 +282,9 @@ int CmdEM410xSim(const char *Cmd) PrintAndLog("Starting simulating UID %02X%02X%02X%02X%02X clock: %d", uid[0],uid[1],uid[2],uid[3],uid[4],clock); PrintAndLog("Press pm3-button to abort simulation"); - ConstructEM410xEmulGraph(Cmd, clock); + ConstructEM410xEmulGraph(conn, Cmd, clock); - CmdLFSim("0"); //240 start_gap. + CmdLFSim(conn, "0"); //240 start_gap. return 0; } @@ -305,7 +305,7 @@ int usage_lf_em410x_brute(void) { return 0; } -int CmdEM410xBrute(const char *Cmd) +int CmdEM410xBrute(pm3_connection* conn, const char *Cmd) { char filename[FILE_PATH_SIZE]={0}; FILE *f = NULL; @@ -408,9 +408,9 @@ int CmdEM410xBrute(const char *Cmd) sprintf(testuid, "%010" PRIX64, bytes_to_num(uidBlock + 5*c, 5)); PrintAndLog("Bruteforce %d / %d: simulating UID %s, clock %d", c + 1, uidcnt, testuid, clock); - ConstructEM410xEmulGraph(testuid, clock); + ConstructEM410xEmulGraph(conn, testuid, clock); - CmdLFSim("0"); //240 start_gap. + CmdLFSim(conn, "0"); //240 start_gap. msleep(delay); } @@ -431,29 +431,29 @@ int CmdEM410xBrute(const char *Cmd) * * EDIT -- capture enough to get 2 complete preambles at the slowest data rate known to be used (rf/64) (64*64*2+9 = 8201) marshmellow */ -int CmdEM410xWatch(const char *Cmd) +int CmdEM410xWatch(pm3_connection* conn, const char *Cmd) { do { if (ukbhit()) { printf("\naborted via keyboard!\n"); break; } - lf_read(true, 8201); - } while (!CmdAskEM410xDemod("")); + lf_read(conn, true, 8201); + } while (!CmdAskEM410xDemod(conn, "")); return 0; } //currently only supports manchester modulations -int CmdEM410xWatchnSpoof(const char *Cmd) +int CmdEM410xWatchnSpoof(pm3_connection* conn, const char *Cmd) { - CmdEM410xWatch(Cmd); + CmdEM410xWatch(conn, Cmd); PrintAndLog("# Replaying captured ID: %010"PRIx64, g_em410xId); - CmdLFaskSim(""); + CmdLFaskSim(conn, ""); return 0; } -int CmdEM410xWrite(const char *Cmd) +int CmdEM410xWrite(pm3_connection* conn, const char *Cmd) { uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value int card = 0xFF; // invalid card value @@ -508,7 +508,7 @@ int CmdEM410xWrite(const char *Cmd) } UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -542,7 +542,7 @@ bool EM_ByteParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t co return true; } -uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool pTest) +uint32_t OutputEM4x50_Block(pm3_connection* conn, uint8_t *BitStream, size_t size, bool verbose, bool pTest) { if (size<45) return 0; uint32_t code = bytebits_to_byte(BitStream,8); @@ -592,7 +592,7 @@ uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool * Word Read values. UID is stored in block 32. */ //completed by Marshmellow -int EM4x50Read(const char *Cmd, bool verbose) +int EM4x50Read(pm3_connection* conn, const char *Cmd, bool verbose) { uint8_t fndClk[] = {8,16,32,40,50,64,128}; int clk = 0; @@ -612,38 +612,38 @@ int EM4x50Read(const char *Cmd, bool verbose) sscanf(Cmd, "%i %i", &clk, &invert); // first get high and low values - for (i = 0; i < GraphTraceLen; i++) { - if (GraphBuffer[i] > high) - high = GraphBuffer[i]; - else if (GraphBuffer[i] < low) - low = GraphBuffer[i]; + for (i = 0; i < conn->GraphTraceLen; i++) { + if (conn->GraphBuffer[i] > high) + high = conn->GraphBuffer[i]; + else if (conn->GraphBuffer[i] < low) + low = conn->GraphBuffer[i]; } i = 0; j = 0; minClk = 255; // get to first full low to prime loop and skip incomplete first pulse - while ((GraphBuffer[i] < high) && (i < GraphTraceLen)) + while ((conn->GraphBuffer[i] < high) && (i < conn->GraphTraceLen)) ++i; - while ((GraphBuffer[i] > low) && (i < GraphTraceLen)) + while ((conn->GraphBuffer[i] > low) && (i < conn->GraphTraceLen)) ++i; skip = i; // populate tmpbuff buffer with pulse lengths - while (i < GraphTraceLen) { + while (i < conn->GraphTraceLen) { // measure from low to low - while ((GraphBuffer[i] > low) && (i < GraphTraceLen)) + while ((conn->GraphBuffer[i] > low) && (i < conn->GraphTraceLen)) ++i; start= i; - while ((GraphBuffer[i] < high) && (i < GraphTraceLen)) + while ((conn->GraphBuffer[i] < high) && (i < conn->GraphTraceLen)) ++i; - while ((GraphBuffer[i] > low) && (i < GraphTraceLen)) + while ((conn->GraphBuffer[i] > low) && (i < conn->GraphTraceLen)) ++i; if (j>=(MAX_GRAPH_TRACE_LEN/64)) { break; } tmpbuff[j++]= i - start; - if (i-start < minClk && i < GraphTraceLen) { + if (i-start < minClk && i < conn->GraphTraceLen) { minClk = i - start; } } @@ -707,11 +707,11 @@ int EM4x50Read(const char *Cmd, bool verbose) } else if (start < 0) return 0; start = skip; snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk*47); - // save GraphBuffer - to restore it later - save_restoreGB(GRAPH_SAVE); - // get rid of leading crap + // save GraphBuffer - to restore it later + save_restoreGB(conn, GRAPH_SAVE); + // get rid of leading crap snprintf(tmp, sizeof(tmp), "%i", skip); - CmdLtrim(tmp); + CmdLtrim(conn, tmp); bool pTest; bool AllPTest = true; // now work through remaining buffer printing out data blocks @@ -735,22 +735,22 @@ int EM4x50Read(const char *Cmd, bool verbose) else phaseoff = 0; i += 2; - if (ASKDemod(tmp2, false, false, 1) < 1) { - save_restoreGB(GRAPH_RESTORE); + if (ASKDemod(conn, tmp2, false, false, 1) < 1) { + save_restoreGB(conn, GRAPH_RESTORE); return 0; } - //set DemodBufferLen to just one block - DemodBufferLen = skip/clk; + //set conn->DemodBufferLen to just one block + conn->DemodBufferLen = skip/clk; //test parities - pTest = EM_ByteParityTest(DemodBuffer,DemodBufferLen,5,9,0); - pTest &= EM_EndParityTest(DemodBuffer,DemodBufferLen,5,9,0); + pTest = EM_ByteParityTest(conn->DemodBuffer,conn->DemodBufferLen,5,9,0); + pTest &= EM_EndParityTest(conn->DemodBuffer,conn->DemodBufferLen,5,9,0); AllPTest &= pTest; //get output - Code[block] = OutputEM4x50_Block(DemodBuffer,DemodBufferLen,verbose, pTest); + Code[block] = OutputEM4x50_Block(conn, conn->DemodBuffer,conn->DemodBufferLen,verbose, pTest); if (g_debugMode) PrintAndLog("\nskipping %d samples, bits:%d", skip, skip/clk); //skip to start of next block snprintf(tmp,sizeof(tmp),"%i",skip); - CmdLtrim(tmp); + CmdLtrim(conn, tmp); block++; if (i >= end) break; //in case chip doesn't output 6 blocks } @@ -775,13 +775,13 @@ int EM4x50Read(const char *Cmd, bool verbose) } //restore GraphBuffer - save_restoreGB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); return (int)AllPTest; } -int CmdEM4x50Read(const char *Cmd) +int CmdEM4x50Read(pm3_connection* conn, const char *Cmd) { - return EM4x50Read(Cmd, true); + return EM4x50Read(conn, Cmd, true); } //**************** Start of EM4x05/EM4x69 Code ************************ @@ -801,19 +801,19 @@ int usage_lf_em_read(void) { // for command responses from em4x05 or em4x69 // download samples from device and copy them to the Graphbuffer -bool downloadSamplesEM() { +bool downloadSamplesEM(pm3_connection* conn) { // 8 bit preamble + 32 bit word response (max clock (128) * 40bits = 5120 samples) - uint8_t got[6000]; - GetFromBigBuf(got, sizeof(got), 0); - if ( !WaitForResponseTimeout(CMD_ACK, NULL, 4000) ) { + uint8_t got[6000]; + GetFromBigBuf(conn, got, sizeof(got), 0); + if ( !WaitForResponseTimeout(conn, CMD_ACK, NULL, 4000) ) { PrintAndLog("command execution time out"); return false; } - setGraphBuf(got, sizeof(got)); + setGraphBuf(conn, got, sizeof(got)); return true; } -bool EM4x05testDemodReadData(uint32_t *word, bool readCmd) { +bool EM4x05testDemodReadData(pm3_connection* conn, uint32_t *word, bool readCmd) { // em4x05/em4x69 command response preamble is 00001010 // skip first two 0 bits as they might have been missed in the demod uint8_t preamble[] = {0,0,1,0,1,0}; @@ -822,28 +822,28 @@ bool EM4x05testDemodReadData(uint32_t *word, bool readCmd) { // set size to 20 to only test first 14 positions for the preamble or less if not a read command size_t size = (readCmd) ? 20 : 11; // sanity check - size = (size > DemodBufferLen) ? DemodBufferLen : size; + size = (size > conn->DemodBufferLen) ? conn->DemodBufferLen : size; // test preamble - if ( !preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx, true) ) { + if ( !preambleSearchEx(conn->DemodBuffer, preamble, sizeof(preamble), &size, &startIdx, true) ) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305 preamble not found :: %d", startIdx); return false; } // if this is a readword command, get the read bytes and test the parities if (readCmd) { - if (!EM_EndParityTest(DemodBuffer + startIdx + sizeof(preamble), 45, 5, 9, 0)) { + if (!EM_EndParityTest(conn->DemodBuffer + startIdx + sizeof(preamble), 45, 5, 9, 0)) { if (g_debugMode) PrintAndLog("DEBUG: Error - End Parity check failed"); return false; } // test for even parity bits and remove them. (leave out the end row of parities so 36 bits) - if ( removeParity(DemodBuffer, startIdx + sizeof(preamble),9,0,36) == 0 ) { + if ( removeParity(conn->DemodBuffer, startIdx + sizeof(preamble),9,0,36) == 0 ) { if (g_debugMode) PrintAndLog("DEBUG: Error - Parity not detected"); return false; } - setDemodBuf(DemodBuffer, 32, 0); - //setClockGrid(0,0); + setDemodBuf(conn, conn->DemodBuffer, 32, 0); + //setClockGrid(conn, 0,0); - *word = bytebits_to_byteLSBF(DemodBuffer, 32); + *word = bytebits_to_byteLSBF(conn->DemodBuffer, 32); } return true; } @@ -851,49 +851,49 @@ bool EM4x05testDemodReadData(uint32_t *word, bool readCmd) { // FSK, PSK, ASK/MANCHESTER, ASK/BIPHASE, ASK/DIPHASE // should cover 90% of known used configs // the rest will need to be manually demoded for now... -int demodEM4x05resp(uint32_t *word, bool readCmd) { +int demodEM4x05resp(pm3_connection* conn, uint32_t *word, bool readCmd) { int ans = 0; // test for FSK wave (easiest to 99% ID) - if (GetFskClock("", false, false)) { + if (GetFskClock(conn, "", false, false)) { //valid fsk clocks found - ans = FSKrawDemod("0 0", false); + ans = FSKrawDemod(conn, "0 0", false); if (!ans) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: FSK Demod failed, ans: %d", ans); } else { - if (EM4x05testDemodReadData(word, readCmd)) { + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } } } // PSK clocks should be easy to detect ( but difficult to demod a non-repeating pattern... ) - ans = GetPskClock("", false, false); + ans = GetPskClock(conn, "", false, false); if (ans>0) { //try psk1 - ans = PSKDemod("0 0 6", false); + ans = PSKDemod(conn, "0 0 6", false); if (!ans) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: PSK1 Demod failed, ans: %d", ans); } else { - if (EM4x05testDemodReadData(word, readCmd)) { + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } else { //try psk2 - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (EM4x05testDemodReadData(word, readCmd)) { + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } } //try psk1 inverted - ans = PSKDemod("0 1 6", false); + ans = PSKDemod(conn, "0 1 6", false); if (!ans) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: PSK1 Demod failed, ans: %d", ans); } else { - if (EM4x05testDemodReadData(word, readCmd)) { + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } else { //try psk2 - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (EM4x05testDemodReadData(word, readCmd)) { + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } } @@ -904,31 +904,31 @@ int demodEM4x05resp(uint32_t *word, bool readCmd) { // manchester is more common than biphase... try first bool stcheck = false; // try manchester - NOTE: ST only applies to T55x7 tags. - ans = ASKDemod_ext("0,0,1", false, false, 1, &stcheck); + ans = ASKDemod_ext(conn, "0,0,1", false, false, 1, &stcheck); if (!ans) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: ASK/Manchester Demod failed, ans: %d", ans); } else { - if (EM4x05testDemodReadData(word, readCmd)) { + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } } //try biphase - ans = ASKbiphaseDemod("0 0 1", false); - if (!ans) { + ans = ASKbiphaseDemod(conn, "0 0 1", false); + if (!ans) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: ASK/biphase Demod failed, ans: %d", ans); } else { - if (EM4x05testDemodReadData(word, readCmd)) { + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } } //try diphase (differential biphase or inverted) - ans = ASKbiphaseDemod("0 1 1", false); - if (!ans) { + ans = ASKbiphaseDemod(conn, "0 1 1", false); + if (!ans) { if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: ASK/biphase Demod failed, ans: %d", ans); } else { - if (EM4x05testDemodReadData(word, readCmd)) { + if (EM4x05testDemodReadData(conn, word, readCmd)) { return 1; } } @@ -936,30 +936,30 @@ int demodEM4x05resp(uint32_t *word, bool readCmd) { return -1; } -int EM4x05ReadWord_ext(uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *wordData) { +int EM4x05ReadWord_ext(pm3_connection* conn, uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *wordData) { UsbCommand c = {CMD_EM4X_READ_WORD, {addr, pwd, usePwd}}; - clearCommandBuffer(); - SendCommand(&c); - UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 2500)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + UsbCommand resp; + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 2500)){ PrintAndLog("Command timed out"); return -1; } - if ( !downloadSamplesEM() ) { + if ( !downloadSamplesEM(conn) ) { return -1; } - int testLen = (GraphTraceLen < 1000) ? GraphTraceLen : 1000; - if (graphJustNoise(GraphBuffer, testLen)) { + int testLen = (conn->GraphTraceLen < 1000) ? conn->GraphTraceLen : 1000; + if (graphJustNoise(conn->GraphBuffer, testLen)) { PrintAndLog("no tag not found"); return -1; } //attempt demod: - return demodEM4x05resp(wordData, true); + return demodEM4x05resp(conn, wordData, true); } -int EM4x05ReadWord(uint8_t addr, uint32_t pwd, bool usePwd) { +int EM4x05ReadWord(pm3_connection* conn, uint8_t addr, uint32_t pwd, bool usePwd) { uint32_t wordData = 0; - int success = EM4x05ReadWord_ext(addr, pwd, usePwd, &wordData); + int success = EM4x05ReadWord_ext(conn, addr, pwd, usePwd, &wordData); if (success == 1) PrintAndLog("%s Address %02d | %08X", (addr>13) ? "Lock":" Got",addr,wordData); else @@ -968,7 +968,7 @@ int EM4x05ReadWord(uint8_t addr, uint32_t pwd, bool usePwd) { return success; } -int CmdEM4x05ReadWord(const char *Cmd) { +int CmdEM4x05ReadWord(pm3_connection* conn, const char *Cmd) { uint8_t addr; uint32_t pwd; bool usePwd = false; @@ -990,7 +990,7 @@ int CmdEM4x05ReadWord(const char *Cmd) { PrintAndLog("Reading address %02u | password %08X", addr, pwd); } - return EM4x05ReadWord(addr, pwd, usePwd); + return EM4x05ReadWord(conn, addr, pwd, usePwd); } int usage_lf_em_dump(void) { @@ -1006,7 +1006,7 @@ int usage_lf_em_dump(void) { return 0; } -int CmdEM4x05dump(const char *Cmd) { +int CmdEM4x05dump(pm3_connection* conn, const char *Cmd) { uint8_t addr = 0; uint32_t pwd; bool usePwd = false; @@ -1028,7 +1028,7 @@ int CmdEM4x05dump(const char *Cmd) { PrintAndLog(" PWD Address 02 | cannot read"); } } else { - success &= EM4x05ReadWord(addr, pwd, usePwd); + success &= EM4x05ReadWord(conn, addr, pwd, usePwd); } } @@ -1056,7 +1056,7 @@ int usage_lf_em_write(void) { // note: em4x05 doesn't have a way to invert data output so we must invert the data prior to writing // it if invertion is needed. (example FSK2a vs FSK) // also em4x05 requires swapping word data when compared to the data used for t55xx chips. -int EM4x05WriteWord(uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool swap, bool invert) { +int EM4x05WriteWord(pm3_connection* conn, uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool swap, bool invert) { if (swap) data = SwapBits(data, 32); if (invert) data ^= 0xFFFFFFFF; @@ -1074,20 +1074,20 @@ int EM4x05WriteWord(uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool uint16_t flag = (addr << 8 ) | usePwd; UsbCommand c = {CMD_EM4X_WRITE_WORD, {flag, data, pwd}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)){ + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 2000)){ PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } - if ( !downloadSamplesEM() ) { + if ( !downloadSamplesEM(conn) ) { return -1; } //check response for 00001010 for write confirmation! //attempt demod: uint32_t dummy = 0; - int result = demodEM4x05resp(&dummy,false); + int result = demodEM4x05resp(conn, &dummy, false); if (result == 1) { PrintAndLog("Write Verified"); } else { @@ -1096,7 +1096,7 @@ int EM4x05WriteWord(uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool return result; } -int CmdEM4x05WriteWord(const char *Cmd) { +int CmdEM4x05WriteWord(pm3_connection* conn, const char *Cmd) { bool errors = false; bool usePwd = false; uint32_t data = 0xFFFFFFFF; @@ -1160,7 +1160,7 @@ int CmdEM4x05WriteWord(const char *Cmd) { PrintAndLog("You must enter the data you want to write"); return usage_lf_em_write(); } - return EM4x05WriteWord(addr, data, pwd, usePwd, swap, invert); + return EM4x05WriteWord(conn, addr, data, pwd, usePwd, swap, invert); } void printEM4x05config(uint32_t wordData) { @@ -1262,14 +1262,14 @@ void printEM4x05ProtectionBits(uint32_t wordData) { } //quick test for EM4x05/EM4x69 tag -bool EM4x05Block0Test(uint32_t *wordData) { - if (EM4x05ReadWord_ext(0,0,false,wordData) == 1) { +bool EM4x05Block0Test(pm3_connection* conn, uint32_t *wordData) { + if (EM4x05ReadWord_ext(conn, 0,0,false,wordData) == 1) { return true; } return false; } -int CmdEM4x05info(const char *Cmd) { +int CmdEM4x05info(pm3_connection* conn, const char *Cmd) { //uint8_t addr = 0; uint32_t pwd; uint32_t wordData = 0; @@ -1286,7 +1286,7 @@ int CmdEM4x05info(const char *Cmd) { // read word 0 (chip info) // block 0 can be read even without a password. - if ( !EM4x05Block0Test(&wordData) ) + if ( !EM4x05Block0Test(conn, &wordData) ) return -1; uint8_t chipType = (wordData >> 1) & 0xF; @@ -1295,7 +1295,7 @@ int CmdEM4x05info(const char *Cmd) { // read word 1 (serial #) doesn't need pwd wordData = 0; - if (EM4x05ReadWord_ext(1, 0, false, &wordData) != 1) { + if (EM4x05ReadWord_ext(conn, 1, 0, false, &wordData) != 1) { //failed, but continue anyway... } printEM4x05info(chipType, cap, custCode, wordData); @@ -1303,7 +1303,7 @@ int CmdEM4x05info(const char *Cmd) { // read word 4 (config block) // needs password if one is set wordData = 0; - if ( EM4x05ReadWord_ext(4, pwd, usePwd, &wordData) != 1 ) { + if ( EM4x05ReadWord_ext(conn, 4, pwd, usePwd, &wordData) != 1 ) { //failed PrintAndLog("Config block read failed - might be password protected."); return 0; @@ -1312,13 +1312,13 @@ int CmdEM4x05info(const char *Cmd) { // read word 14 and 15 to see which is being used for the protection bits wordData = 0; - if ( EM4x05ReadWord_ext(14, pwd, usePwd, &wordData) != 1 ) { + if ( EM4x05ReadWord_ext(conn, 14, pwd, usePwd, &wordData) != 1 ) { //failed return 0; } // if status bit says this is not the used protection word if (!(wordData & 0x8000)) { - if ( EM4x05ReadWord_ext(15, pwd, usePwd, &wordData) != 1 ) { + if ( EM4x05ReadWord_ext(conn, 15, pwd, usePwd, &wordData) != 1 ) { //failed return 0; } @@ -1351,14 +1351,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdLFEM4X(const char *Cmd) +int CmdLFEM4X(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfem4x.h b/client/cmdlfem4x.h index c4c4c2b2..ce39acca 100644 --- a/client/cmdlfem4x.h +++ b/client/cmdlfem4x.h @@ -13,27 +13,28 @@ #include // for bool #include +#include "comms.h" -extern int CmdLFEM4X(const char *Cmd); +extern int CmdLFEM4X(pm3_connection* conn, const char *Cmd); extern void printEM410x(uint32_t hi, uint64_t id); -extern int CmdEMdemodASK(const char *Cmd); -extern int CmdAskEM410xDemod(const char *Cmd); -extern int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ); -extern int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose); -extern int CmdEM410xSim(const char *Cmd); -extern int CmdEM410xBrute(const char *Cmd); -extern int CmdEM410xWatch(const char *Cmd); -extern int CmdEM410xWatchnSpoof(const char *Cmd); -extern int CmdEM410xWrite(const char *Cmd); -extern bool EM4x05Block0Test(uint32_t *wordData); -extern int CmdEM4x05info(const char *Cmd); -extern int EM4x05WriteWord(uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool swap, bool invert); -extern int CmdEM4x05WriteWord(const char *Cmd); -extern int CmdEM4x05dump(const char *Cmd); -extern int CmdEM4x05ReadWord(const char *Cmd); -extern int EM4x05ReadWord_ext(uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *wordData); -extern int EM4x50Read(const char *Cmd, bool verbose); -extern int CmdEM4x50Read(const char *Cmd); +extern int CmdEMdemodASK(pm3_connection* conn, const char *Cmd); +extern int CmdAskEM410xDemod(pm3_connection* conn, const char *Cmd); +extern int AskEm410xDecode(pm3_connection* conn, bool verbose, uint32_t *hi, uint64_t *lo ); +extern int AskEm410xDemod(pm3_connection* conn, const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose); +extern int CmdEM410xSim(pm3_connection* conn, const char *Cmd); +extern int CmdEM410xBrute(pm3_connection* conn, const char *Cmd); +extern int CmdEM410xWatch(pm3_connection* conn, const char *Cmd); +extern int CmdEM410xWatchnSpoof(pm3_connection* conn, const char *Cmd); +extern int CmdEM410xWrite(pm3_connection* conn, const char *Cmd); +extern bool EM4x05Block0Test(pm3_connection* conn, uint32_t *wordData); +extern int CmdEM4x05info(pm3_connection* conn, const char *Cmd); +extern int EM4x05WriteWord(pm3_connection* conn, uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool swap, bool invert); +extern int CmdEM4x05WriteWord(pm3_connection* conn, const char *Cmd); +extern int CmdEM4x05dump(pm3_connection* conn, const char *Cmd); +extern int CmdEM4x05ReadWord(pm3_connection* conn, const char *Cmd); +extern int EM4x05ReadWord_ext(pm3_connection* conn, uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *wordData); +extern int EM4x50Read(pm3_connection* conn, const char *Cmd, bool verbose); +extern int CmdEM4x50Read(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlffdx.c b/client/cmdlffdx.c index 2e2ee9fd..892415fa 100644 --- a/client/cmdlffdx.c +++ b/client/cmdlffdx.c @@ -43,7 +43,7 @@ sample: 985121004515220 [ 37FF65B88EF94 ] */ -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_fdx_clone(void){ PrintAndLog("Clone a FDX-B animal tag to a T55x7 tag."); @@ -133,16 +133,16 @@ int getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t return 1; } -int CmdFdxDemod(const char *Cmd){ +int CmdFdxDemod(pm3_connection* conn, const char *Cmd){ //Differential Biphase / di-phase (inverted biphase) //get binary from ask wave - if (!ASKbiphaseDemod("0 32 1 0", false)) { + if (!ASKbiphaseDemod(conn, "0 32 1 0", false)) { if (g_debugMode) PrintAndLog("DEBUG: Error - FDX-B ASKbiphaseDemod failed"); return 0; } - size_t size = DemodBufferLen; - int preambleIndex = FDXBdemodBI(DemodBuffer, &size); + size_t size = conn->DemodBufferLen; + int preambleIndex = FDXBdemodBI(conn->DemodBuffer, &size); if (preambleIndex < 0){ if (g_debugMode){ if (preambleIndex == -1) @@ -157,12 +157,12 @@ int CmdFdxDemod(const char *Cmd){ return 0; } - // set and leave DemodBuffer intact - setDemodBuf(DemodBuffer, 128, preambleIndex); - setClockGrid(g_DemodClock, g_DemodStartIdx + (preambleIndex*g_DemodClock)); + // set and leave conn->DemodBuffer intact + setDemodBuf(conn, conn->DemodBuffer, 128, preambleIndex); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (preambleIndex*conn->g_DemodClock)); uint8_t bits_no_spacer[117]; - memcpy(bits_no_spacer, DemodBuffer + 11, 117); + memcpy(bits_no_spacer, conn->DemodBuffer + 11, 117); // remove marker bits (1's every 9th digit after preamble) (pType = 2) size = removeParity(bits_no_spacer, 0, 9, 2, 117); @@ -205,12 +205,12 @@ int CmdFdxDemod(const char *Cmd){ return 1; } -int CmdFdxRead(const char *Cmd) { - lf_read(true, 10000); - return CmdFdxDemod(Cmd); +int CmdFdxRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 10000); + return CmdFdxDemod(conn, Cmd); } -int CmdFdxClone(const char *Cmd) { +int CmdFdxClone(pm3_connection* conn, const char *Cmd) { uint32_t countryid = 0; uint64_t animalid = 0; @@ -260,9 +260,9 @@ int CmdFdxClone(const char *Cmd) { for (int i = 4; i >= 0; --i) { c.arg[0] = blocks[i]; c.arg[1] = i; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){ PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } @@ -270,7 +270,7 @@ int CmdFdxClone(const char *Cmd) { return 0; } -int CmdFdxSim(const char *Cmd) { +int CmdFdxSim(pm3_connection* conn, const char *Cmd) { uint32_t countryid = 0; uint64_t animalid = 0; @@ -294,8 +294,8 @@ int CmdFdxSim(const char *Cmd) { //getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t isextended, uint32_t extended, uint8_t *bits) getFDXBits(animalid, countryid, 1, 0, 0, c.d.asBytes); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -308,13 +308,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFFdx(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFFdx(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlffdx.h b/client/cmdlffdx.h index d11daec4..fd18a9ba 100644 --- a/client/cmdlffdx.h +++ b/client/cmdlffdx.h @@ -8,10 +8,11 @@ //----------------------------------------------------------------------------- #ifndef CMDLFFDX_H__ #define CMDLFFDX_H__ +#include "comms.h" -extern int CmdLFFdx(const char *Cmd); -extern int CmdFdxClone(const char *Cmd); -extern int CmdFdxSim(const char *Cmd); -extern int CmdFdxRead(const char *Cmd); -extern int CmdFdxDemod(const char *Cmd); +extern int CmdLFFdx(pm3_connection* conn, const char *Cmd); +extern int CmdFdxClone(pm3_connection* conn, const char *Cmd); +extern int CmdFdxSim(pm3_connection* conn, const char *Cmd); +extern int CmdFdxRead(pm3_connection* conn, const char *Cmd); +extern int CmdFdxDemod(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfgproxii.c b/client/cmdlfgproxii.c index 71c5f391..35f83f57 100644 --- a/client/cmdlfgproxii.c +++ b/client/cmdlfgproxii.c @@ -20,22 +20,22 @@ #include "cmdmain.h" #include "cmdlf.h" #include "lfdemod.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); //by marshmellow //attempts to demodulate and identify a G_Prox_II verex/chubb card -//WARNING: if it fails during some points it will destroy the DemodBuffer data +//WARNING: if it fails during some points it will destroy the conn->DemodBuffer data // but will leave the GraphBuffer intact. //if successful it will push askraw data back to demod buffer ready for emulation -int CmdG_Prox_II_Demod(const char *Cmd) +int CmdG_Prox_II_Demod(pm3_connection* conn, const char *Cmd) { - if (!ASKbiphaseDemod(Cmd, false)){ + if (!ASKbiphaseDemod(conn, Cmd, false)){ if (g_debugMode) PrintAndLog("Error gProxII: ASKbiphaseDemod failed 1st try"); return 0; } - size_t size = DemodBufferLen; + size_t size = conn->DemodBufferLen; //call lfdemod.c demod for gProxII - int ans = gProxII_Demod(DemodBuffer, &size); + int ans = gProxII_Demod(conn->DemodBuffer, &size); if (ans < 0){ if (g_debugMode) PrintAndLog("Error gProxII_Demod"); return 0; @@ -46,8 +46,8 @@ int CmdG_Prox_II_Demod(const char *Cmd) size_t startIdx = ans + 6; //start after 6 bit preamble uint8_t bits_no_spacer[90]; - //so as to not mess with raw DemodBuffer copy to a new sample array - memcpy(bits_no_spacer, DemodBuffer + startIdx, 90); + //so as to not mess with raw conn->DemodBuffer copy to a new sample array + memcpy(bits_no_spacer, conn->DemodBuffer + startIdx, 90); // remove the 18 (90/5=18) parity bits (down to 72 bits (96-6-18=72)) size_t bitLen = removeParity(bits_no_spacer, 0, 5, 3, 90); //source, startloc, paritylen, ptype, length_to_run if (bitLen != 72) { @@ -66,9 +66,9 @@ int CmdG_Prox_II_Demod(const char *Cmd) uint32_t FC = 0; uint32_t Card = 0; //get raw 96 bits to print - uint32_t raw1 = bytebits_to_byte(DemodBuffer+ans,32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+ans+32, 32); - uint32_t raw3 = bytebits_to_byte(DemodBuffer+ans+64, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer+ans,32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+ans+32, 32); + uint32_t raw3 = bytebits_to_byte(conn->DemodBuffer+ans+64, 32); if (fmtLen==36){ FC = ((ByteStream[3] & 0x7F)<<7) | (ByteStream[4]>>1); @@ -83,18 +83,18 @@ int CmdG_Prox_II_Demod(const char *Cmd) PrintAndLog("Decoded Raw: %s", sprint_hex(ByteStream, 8)); } PrintAndLog("Raw: %08x%08x%08x", raw1,raw2,raw3); - setDemodBuf(DemodBuffer, 96, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 96, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); return 1; } //by marshmellow //see ASKDemod for what args are accepted -int CmdG_Prox_II_Read(const char *Cmd) { +int CmdG_Prox_II_Read(pm3_connection* conn, const char *Cmd) { // read lf silently - lf_read(true, 10000); + lf_read(conn, true, 10000); // demod and output viking ID - return CmdG_Prox_II_Demod(Cmd); + return CmdG_Prox_II_Demod(conn, Cmd); } static command_t CommandTable[] = { @@ -104,12 +104,12 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLF_G_Prox_II(const char *Cmd) { - CmdsParse(CommandTable, Cmd); +int CmdLF_G_Prox_II(pm3_connection* conn, const char *Cmd) { + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfgproxii.h b/client/cmdlfgproxii.h index 35d982f4..465f4e2c 100644 --- a/client/cmdlfgproxii.h +++ b/client/cmdlfgproxii.h @@ -8,7 +8,9 @@ //----------------------------------------------------------------------------- #ifndef CMDLFGPROXII_H__ #define CMDLFGPROXII_H__ -extern int CmdLF_G_Prox_II(const char *Cmd); -extern int CmdG_Prox_II_Demod(const char *Cmd); -extern int CmdG_Prox_II_Read(const char *Cmd); +#include "comms.h" + +extern int CmdLF_G_Prox_II(pm3_connection* conn, const char *Cmd); +extern int CmdG_Prox_II_Demod(pm3_connection* conn, const char *Cmd); +extern int CmdG_Prox_II_Read(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfhid.c b/client/cmdlfhid.c index 19b5a142..44fdb2b3 100644 --- a/client/cmdlfhid.c +++ b/client/cmdlfhid.c @@ -18,18 +18,18 @@ #include "cmddata.h" //for g_debugMode, demodbuff cmds #include "lfdemod.h" // for HIDdemodFSK -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); //by marshmellow (based on existing demod + holiman's refactor) //HID Prox demod - FSK RF/50 with preamble of 00011101 (then manchester encoded) //print full HID Prox ID and some bit format details if found -int CmdFSKdemodHID(const char *Cmd) +int CmdFSKdemodHID(pm3_connection* conn, const char *Cmd) { //raw fsk demod no manchester decoding no start bit finding just get binary from wave uint32_t hi2=0, hi=0, lo=0; uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (BitLen==0) return 0; //get binary from fsk wave int waveIdx = 0; @@ -99,26 +99,26 @@ int CmdFSKdemodHID(const char *Cmd) (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF, (unsigned int) fmtLen, (unsigned int) fc, (unsigned int) cardnum); } - setDemodBuf(BitStream,BitLen,idx); - setClockGrid(50, waveIdx + (idx*50)); + setDemodBuf(conn, BitStream,BitLen,idx); + setClockGrid(conn, 50, waveIdx + (idx*50)); if (g_debugMode){ PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen); - printDemodBuff(); + printDemodBuff(conn); } return 1; } -int CmdHIDReadFSK(const char *Cmd) +int CmdHIDReadFSK(pm3_connection* conn, const char *Cmd) { int findone=0; if(Cmd[0]=='1') findone=1; UsbCommand c={CMD_HID_DEMOD_FSK}; c.arg[0]=findone; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHIDSim(const char *Cmd) +int CmdHIDSim(pm3_connection* conn, const char *Cmd) { uint32_t hi = 0, lo = 0; int n = 0, i = 0; @@ -132,11 +132,11 @@ int CmdHIDSim(const char *Cmd) PrintAndLog("Press pm3-button to abort simulation"); UsbCommand c = {CMD_HID_SIM_TAG, {hi, lo, 0}}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdHIDClone(const char *Cmd) +int CmdHIDClone(pm3_connection* conn, const char *Cmd) { unsigned int hi2 = 0, hi = 0, lo = 0; int n = 0, i = 0; @@ -170,7 +170,7 @@ int CmdHIDClone(const char *Cmd) c.arg[1] = hi; c.arg[2] = lo; - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -184,14 +184,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdLFHID(const char *Cmd) +int CmdLFHID(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfhid.h b/client/cmdlfhid.h index b03f7041..f29e765f 100644 --- a/client/cmdlfhid.h +++ b/client/cmdlfhid.h @@ -10,11 +10,12 @@ #ifndef CMDLFHID_H__ #define CMDLFHID_H__ +#include "comms.h" -int CmdLFHID(const char *Cmd); -int CmdFSKdemodHID(const char *Cmd); -int CmdHIDReadDemod(const char *Cmd); -int CmdHIDSim(const char *Cmd); -int CmdHIDClone(const char *Cmd); +int CmdLFHID(pm3_connection* conn, const char *Cmd); +int CmdFSKdemodHID(pm3_connection* conn, const char *Cmd); +int CmdHIDReadDemod(pm3_connection* conn, const char *Cmd); +int CmdHIDSim(pm3_connection* conn, const char *Cmd); +int CmdHIDClone(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfhitag.c b/client/cmdlfhitag.c index 103f2b77..c392d8df 100644 --- a/client/cmdlfhitag.c +++ b/client/cmdlfhitag.c @@ -22,20 +22,20 @@ #include "hitagS.h" #include "cmdmain.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); size_t nbytes(size_t nbits) { return (nbits/8)+((nbits%8)>0); } -int CmdLFHitagList(const char *Cmd) +int CmdLFHitagList(pm3_connection* conn, const char *Cmd) { uint8_t *got = malloc(USB_CMD_DATA_SIZE); // Query for the actual size of the trace UsbCommand response; - GetFromBigBuf(got, USB_CMD_DATA_SIZE, 0); - WaitForResponse(CMD_ACK, &response); + GetFromBigBuf(conn, got, USB_CMD_DATA_SIZE, 0); + WaitForResponse(conn, CMD_ACK, &response); uint16_t traceLen = response.arg[2]; if (traceLen > USB_CMD_DATA_SIZE) { uint8_t *p = realloc(got, traceLen); @@ -45,8 +45,8 @@ int CmdLFHitagList(const char *Cmd) return 2; } got = p; - GetFromBigBuf(got, traceLen, 0); - WaitForResponse(CMD_ACK,NULL); + GetFromBigBuf(conn, got, traceLen, 0); + WaitForResponse(conn, CMD_ACK,NULL); } PrintAndLog("recorded activity (TraceLen = %d bytes):"); @@ -145,13 +145,13 @@ int CmdLFHitagList(const char *Cmd) return 0; } -int CmdLFHitagSnoop(const char *Cmd) { +int CmdLFHitagSnoop(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_SNOOP_HITAG}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLFHitagSim(const char *Cmd) { +int CmdLFHitagSim(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_SIMULATE_HITAG}; char filename[FILE_PATH_SIZE] = { 0x00 }; @@ -180,11 +180,11 @@ int CmdLFHitagSim(const char *Cmd) { // Does the tag comes with memory c.arg[0] = (uint32_t)tag_mem_supplied; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLFHitagReader(const char *Cmd) { +int CmdLFHitagReader(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_READER_HITAG};//, {param_get32ex(Cmd,0,0,10),param_get32ex(Cmd,1,0,16),param_get32ex(Cmd,2,0,16),param_get32ex(Cmd,3,0,16)}}; hitag_data* htd = (hitag_data*)c.d.asBytes; hitag_function htf = param_get32ex(Cmd,0,0,10); @@ -239,10 +239,10 @@ int CmdLFHitagReader(const char *Cmd) { c.arg[0] = htf; // Send the command to the proxmark - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); // Check the return status, stored in the first argument if (resp.arg[0] == false) return 1; @@ -273,7 +273,7 @@ int CmdLFHitagReader(const char *Cmd) { } -int CmdLFHitagSimS(const char *Cmd) { +int CmdLFHitagSimS(pm3_connection* conn, const char *Cmd) { UsbCommand c = { CMD_SIMULATE_HITAG_S }; char filename[FILE_PATH_SIZE] = { 0x00 }; FILE* pf; @@ -302,11 +302,11 @@ int CmdLFHitagSimS(const char *Cmd) { // Does the tag comes with memory c.arg[0] = (uint32_t) tag_mem_supplied; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLFHitagCheckChallenges(const char *Cmd) { +int CmdLFHitagCheckChallenges(pm3_connection* conn, const char *Cmd) { UsbCommand c = { CMD_TEST_HITAGS_TRACES }; char filename[FILE_PATH_SIZE] = { 0x00 }; FILE* pf; @@ -334,12 +334,12 @@ int CmdLFHitagCheckChallenges(const char *Cmd) { //file with all the challenges to try c.arg[0] = (uint32_t)file_given; - SendCommand(&c); + SendCommand(conn, &c); return 0; } -int CmdLFHitagWP(const char *Cmd) { +int CmdLFHitagWP(pm3_connection* conn, const char *Cmd) { UsbCommand c = { CMD_WR_HITAG_S }; hitag_data* htd = (hitag_data*)c.d.asBytes; hitag_function htf = param_get32ex(Cmd,0,0,10); @@ -373,10 +373,10 @@ int CmdLFHitagWP(const char *Cmd) { c.arg[0] = htf; // Send the command to the proxmark - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); // Check the return status, stored in the first argument if (resp.arg[0] == false) return 1; @@ -397,14 +397,14 @@ static command_t CommandTable[] = NULL,NULL, 0, NULL } }; -int CmdLFHitag(const char *Cmd) +int CmdLFHitag(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfhitag.h b/client/cmdlfhitag.h index 22b6bb06..80f49aa8 100644 --- a/client/cmdlfhitag.h +++ b/client/cmdlfhitag.h @@ -10,12 +10,13 @@ #ifndef CMDLFHITAG_H__ #define CMDLFHITAG_H__ +#include "comms.h" -int CmdLFHitag(const char *Cmd); +int CmdLFHitag(pm3_connection* conn, const char *Cmd); -int CmdLFHitagList(const char *Cmd); -int CmdLFHitagSnoop(const char *Cmd); -int CmdLFHitagSim(const char *Cmd); -int CmdLFHitagReader(const char *Cmd); +int CmdLFHitagList(pm3_connection* conn, const char *Cmd); +int CmdLFHitagSnoop(pm3_connection* conn, const char *Cmd); +int CmdLFHitagSim(pm3_connection* conn, const char *Cmd); +int CmdLFHitagReader(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfindala.c b/client/cmdlfindala.c index 0a4f7834..53bf63c1 100644 --- a/client/cmdlfindala.c +++ b/client/cmdlfindala.c @@ -15,23 +15,23 @@ #include "ui.h" #include "graph.h" #include "cmdparser.h" -#include "cmddata.h" //for g_debugMode, demodbuff cmds +#include "cmddata.h" //for demodbuff cmds #include "lfdemod.h" //for indala26decode #include "util.h" //for sprint_bin_break #include "cmdlf.h" //for CmdLFRead #include "cmdmain.h" //for clearCommandBuffer -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); // Indala 26 bit decode // by marshmellow // optional arguments - same as PSKDemod (clock & invert & maxerr) -int CmdIndalaDecode(const char *Cmd) { +int CmdIndalaDecode(pm3_connection* conn, const char *Cmd) { int ans; if (strlen(Cmd)>0) { - ans = PSKDemod(Cmd, 0); + ans = PSKDemod(conn, Cmd, 0); } else { //default to RF/32 - ans = PSKDemod("32", 0); + ans = PSKDemod(conn, "32", 0); } if (!ans) { @@ -39,64 +39,64 @@ int CmdIndalaDecode(const char *Cmd) { return 0; } uint8_t invert=0; - size_t size = DemodBufferLen; - int startIdx = indala64decode(DemodBuffer, &size, &invert); + size_t size = conn->DemodBufferLen; + int startIdx = indala64decode(conn->DemodBuffer, &size, &invert); if (startIdx < 0 || size != 64) { // try 224 indala invert = 0; - size = DemodBufferLen; - startIdx = indala224decode(DemodBuffer, &size, &invert); + size = conn->DemodBufferLen; + startIdx = indala224decode(conn->DemodBuffer, &size, &invert); if (startIdx < 0 || size != 224) { if (g_debugMode) PrintAndLog("Error2: %i",startIdx); return -1; } } - setDemodBuf(DemodBuffer, size, (size_t)startIdx); - setClockGrid(g_DemodClock, g_DemodStartIdx + (startIdx*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, size, (size_t)startIdx); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (startIdx*conn->g_DemodClock)); if (invert) if (g_debugMode) PrintAndLog("Had to invert bits"); - PrintAndLog("BitLen: %d",DemodBufferLen); + PrintAndLog("BitLen: %d",conn->DemodBufferLen); //convert UID to HEX uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7; - uid1=bytebits_to_byte(DemodBuffer,32); - uid2=bytebits_to_byte(DemodBuffer+32,32); - if (DemodBufferLen==64) { - PrintAndLog("Indala UID=%s (%x%08x)", sprint_bin_break(DemodBuffer,DemodBufferLen,16), uid1, uid2); - } else if (DemodBufferLen==224) { - uid3=bytebits_to_byte(DemodBuffer+64,32); - uid4=bytebits_to_byte(DemodBuffer+96,32); - uid5=bytebits_to_byte(DemodBuffer+128,32); - uid6=bytebits_to_byte(DemodBuffer+160,32); - uid7=bytebits_to_byte(DemodBuffer+192,32); + uid1=bytebits_to_byte(conn->DemodBuffer,32); + uid2=bytebits_to_byte(conn->DemodBuffer+32,32); + if (conn->DemodBufferLen==64) { + PrintAndLog("Indala UID=%s (%x%08x)", sprint_bin_break(conn->DemodBuffer,conn->DemodBufferLen,16), uid1, uid2); + } else if (conn->DemodBufferLen==224) { + uid3=bytebits_to_byte(conn->DemodBuffer+64,32); + uid4=bytebits_to_byte(conn->DemodBuffer+96,32); + uid5=bytebits_to_byte(conn->DemodBuffer+128,32); + uid6=bytebits_to_byte(conn->DemodBuffer+160,32); + uid7=bytebits_to_byte(conn->DemodBuffer+192,32); PrintAndLog("Indala UID=%s (%x%08x%08x%08x%08x%08x%08x)", - sprint_bin_break(DemodBuffer,DemodBufferLen,16), uid1, uid2, uid3, uid4, uid5, uid6, uid7); + sprint_bin_break(conn->DemodBuffer,conn->DemodBufferLen,16), uid1, uid2, uid3, uid4, uid5, uid6, uid7); } if (g_debugMode) { PrintAndLog("DEBUG: printing demodbuffer:"); - printDemodBuff(); + printDemodBuff(conn); } return 1; } -int CmdIndalaRead(const char *Cmd) { - lf_read(true, 30000); - return CmdIndalaDecode(""); +int CmdIndalaRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 30000); + return CmdIndalaDecode(conn, ""); } // older alternative indala demodulate (has some positives and negatives) // returns false positives more often - but runs against more sets of samples // poor psk signal can be difficult to demod this approach might succeed when the other fails // but the other appears to currently be more accurate than this approach most of the time. -int CmdIndalaDemod(const char *Cmd) { +int CmdIndalaDemod(pm3_connection* conn, const char *Cmd) { // Usage: recover 64bit UID by default, specify "224" as arg to recover a 224bit UID int state = -1; int count = 0; int i, j; - // worst case with GraphTraceLen=64000 is < 4096 + // worst case with conn->GraphTraceLen=64000 is < 4096 // under normal conditions it's < 2048 uint8_t rawbits[4096]; @@ -104,14 +104,14 @@ int CmdIndalaDemod(const char *Cmd) { int worst = 0, worstPos = 0; //clear clock grid and demod plot - setClockGrid(0, 0); - DemodBufferLen = 0; + setClockGrid(conn, 0, 0); + conn->DemodBufferLen = 0; // PrintAndLog("Expecting a bit less than %d raw bits", GraphTraceLen / 32); // loop through raw signal - since we know it is psk1 rf/32 fc/2 skip every other value (+=2) - for (i = 0; i < GraphTraceLen-1; i += 2) { + for (i = 0; i < conn->GraphTraceLen-1; i += 2) { count += 1; - if ((GraphBuffer[i] > GraphBuffer[i + 1]) && (state != 1)) { + if ((conn->GraphBuffer[i] > conn->GraphBuffer[i + 1]) && (state != 1)) { // appears redundant - marshmellow if (state == 0) { for (j = 0; j < count - 8; j += 16) { @@ -124,7 +124,7 @@ int CmdIndalaDemod(const char *Cmd) { } state = 1; count = 0; - } else if ((GraphBuffer[i] < GraphBuffer[i + 1]) && (state != 0)) { + } else if ((conn->GraphBuffer[i] < conn->GraphBuffer[i + 1]) && (state != 0)) { //appears redundant if (state == 1) { for (j = 0; j < count - 8; j += 16) { @@ -141,7 +141,7 @@ int CmdIndalaDemod(const char *Cmd) { } if (rawbit>0){ - PrintAndLog("Recovered %d raw bits, expected: %d", rawbit, GraphTraceLen/32); + PrintAndLog("Recovered %d raw bits, expected: %d", rawbit, conn->GraphTraceLen/32); PrintAndLog("worst metric (0=best..7=worst): %d at pos %d", worst, worstPos); } else { return 0; @@ -265,7 +265,7 @@ int CmdIndalaDemod(const char *Cmd) { // Remodulating for tag cloning // HACK: 2015-01-04 this will have an impact on our new way of seening lf commands (demod) // since this changes graphbuffer data. - GraphTraceLen = 32*uidlen; + conn->GraphTraceLen = 32*uidlen; i = 0; int phase = 0; for (bit = 0; bit < uidlen; bit++) { @@ -276,16 +276,16 @@ int CmdIndalaDemod(const char *Cmd) { } int j; for (j = 0; j < 32; j++) { - GraphBuffer[i++] = phase; + conn->GraphBuffer[i++] = phase; phase = !phase; } } - RepaintGraphWindow(); + RepaintGraphWindow(conn); return 1; } -int CmdIndalaClone(const char *Cmd) { +int CmdIndalaClone(pm3_connection* conn, const char *Cmd) { UsbCommand c; unsigned int uid1, uid2, uid3, uid4, uid5, uid6, uid7; @@ -322,14 +322,14 @@ int CmdIndalaClone(const char *Cmd) { c.arg[1] = uid2; } - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdIndalaDecode, 1, "[clock] [invert<0|1>] -- Demodulate an indala tag (PSK1) from GraphBuffer (args optional)"}, + {"demod", CmdIndalaDecode, 1, "[clock] [invert<0|1>] -- Demodulate an indala tag (PSK1) from conn->GraphBuffer (args optional)"}, {"read", CmdIndalaRead, 0, "Read an Indala Prox tag from the antenna"}, {"clone", CmdIndalaClone, 0, " ['l']-- Clone Indala to T55x7 (tag must be on antenna)(UID in HEX)(option 'l' for 224 UID"}, {"altdemod", CmdIndalaDemod, 1, "['224'] -- Alternative method to Demodulate samples for Indala 64 bit UID (option '224' for 224 bit)"}, @@ -337,12 +337,12 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFINDALA(const char *Cmd) { - CmdsParse(CommandTable, Cmd); +int CmdLFINDALA(pm3_connection* conn, const char *Cmd) { + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfindala.h b/client/cmdlfindala.h index 78502419..bca29710 100644 --- a/client/cmdlfindala.h +++ b/client/cmdlfindala.h @@ -9,10 +9,11 @@ #ifndef CMDLFINDALA_H__ #define CMDLFINDALA_H__ +#include "comms.h" -extern int CmdLFINDALA(const char *Cmd); -extern int CmdIndalaDecode(const char *Cmd); -extern int CmdIndalaRead(const char *Cmd); -extern int CmdIndalaClone(const char *Cmd); +extern int CmdLFINDALA(pm3_connection* conn, const char *Cmd); +extern int CmdIndalaDecode(pm3_connection* conn, const char *Cmd); +extern int CmdIndalaRead(pm3_connection* conn, const char *Cmd); +extern int CmdIndalaClone(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfio.c b/client/cmdlfio.c index 4ccd5538..428da34a 100644 --- a/client/cmdlfio.c +++ b/client/cmdlfio.c @@ -25,32 +25,32 @@ #include "lfdemod.h" //for IOdemodFSK + bytebits_to_byte #include "util.h" //for sprint_bin_break -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); -int CmdIOReadFSK(const char *Cmd) +int CmdIOReadFSK(pm3_connection* conn, const char *Cmd) { int findone=0; if(Cmd[0]=='1') findone=1; UsbCommand c={CMD_IO_DEMOD_FSK}; c.arg[0]=findone; - SendCommand(&c); + SendCommand(conn, &c); return 0; } //by marshmellow //IO-Prox demod - FSK RF/64 with preamble of 000000001 //print ioprox ID and some format details -int CmdFSKdemodIO(const char *Cmd) +int CmdFSKdemodIO(pm3_connection* conn, const char *Cmd) { int idx=0; //something in graphbuffer? - if (GraphTraceLen < 65) { - if (g_debugMode)PrintAndLog("DEBUG: not enough samples in GraphBuffer"); + if (conn->GraphTraceLen < 65) { + if (g_debugMode)PrintAndLog("DEBUG: not enough samples in conn->GraphBuffer"); return 0; } uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (BitLen==0) return 0; int waveIdx = 0; @@ -119,17 +119,17 @@ int CmdFSKdemodIO(const char *Cmd) char *crcStr = (crc == calccrc) ? "crc ok": "!crc"; PrintAndLog("IO Prox XSF(%02d)%02x:%05d (%08x%08x) [%02x %s]",version,facilitycode,number,code,code2, crc, crcStr); - setDemodBuf(BitStream,64,idx); - setClockGrid(64, waveIdx + (idx*64)); + setDemodBuf(conn, BitStream,64,idx); + setClockGrid(conn, 64, waveIdx + (idx*64)); if (g_debugMode){ PrintAndLog("DEBUG: idx: %d, Len: %d, Printing demod buffer:",idx,64); - printDemodBuff(); + printDemodBuff(conn); } return 1; } -int CmdIOClone(const char *Cmd) +int CmdIOClone(pm3_connection* conn, const char *Cmd) { unsigned int hi = 0, lo = 0; int n = 0, i = 0; @@ -152,27 +152,27 @@ int CmdIOClone(const char *Cmd) c.arg[0] = hi; c.arg[1] = lo; - SendCommand(&c); + SendCommand(conn, &c); return 0; } static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdFSKdemodIO, 1, "Demodulate IO Prox tag from the GraphBuffer"}, + {"demod", CmdFSKdemodIO, 1, "Demodulate IO Prox tag from the conn->GraphBuffer"}, {"read", CmdIOReadFSK, 0, "['1'] Realtime IO FSK demodulate from antenna (option '1' for one tag only)"}, {"clone", CmdIOClone, 0, "Clone ioProx Tag"}, {NULL, NULL, 0, NULL} }; -int CmdLFIO(const char *Cmd) +int CmdLFIO(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfio.h b/client/cmdlfio.h index 3b89c939..f98b060e 100644 --- a/client/cmdlfio.h +++ b/client/cmdlfio.h @@ -4,8 +4,10 @@ #ifndef CMDLFIO_H__ #define CMDLFIO_H__ -extern int CmdLFIO(const char *Cmd); -extern int CmdFSKdemodIO(const char *Cmd); -extern int CmdIOReadFSK(const char *Cmd); +#include "comms.h" + +extern int CmdLFIO(pm3_connection* conn, const char *Cmd); +extern int CmdFSKdemodIO(pm3_connection* conn, const char *Cmd); +extern int CmdIOReadFSK(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfjablotron.c b/client/cmdlfjablotron.c index 9c69099e..c37e5b55 100644 --- a/client/cmdlfjablotron.c +++ b/client/cmdlfjablotron.c @@ -23,7 +23,7 @@ #include "protocols.h" // for T55xx config register definitions #include "lfdemod.h" // parityTest -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_jablotron_clone(void) { PrintAndLog("clone a Jablotron tag to a T55x7 tag."); @@ -91,16 +91,16 @@ int JablotronDetect(uint8_t *bits, size_t *size) { } //see ASKDemod for what args are accepted -int CmdJablotronDemod(const char *Cmd) { +int CmdJablotronDemod(pm3_connection* conn, const char *Cmd) { //Differential Biphase / di-phase (inverted biphase) //get binary from ask wave - if (!ASKbiphaseDemod("0 64 1 0", false)) { + if (!ASKbiphaseDemod(conn, "0 64 1 0", false)) { if (g_debugMode) PrintAndLog("DEBUG: Error - Jablotron ASKbiphaseDemod failed"); return 0; } - size_t size = DemodBufferLen; - int ans = JablotronDetect(DemodBuffer, &size); + size_t size = conn->DemodBufferLen; + int ans = JablotronDetect(conn->DemodBuffer, &size); if (ans < 0) { if (g_debugMode) { if (ans == -1) @@ -117,14 +117,14 @@ int CmdJablotronDemod(const char *Cmd) { return 0; } - setDemodBuf(DemodBuffer, 64, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 64, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer, 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+32, 32); - uint64_t id = (( (uint64_t)bytebits_to_byte(DemodBuffer+16, 8) )<< 32) | bytebits_to_byte(DemodBuffer+24,32); + uint64_t id = (( (uint64_t)bytebits_to_byte(conn->DemodBuffer+16, 8) )<< 32) | bytebits_to_byte(conn->DemodBuffer+24,32); PrintAndLog("Jablotron Tag Found: Card ID: %"PRIx64" :: Raw: %08X%08X", id, raw1, raw2); @@ -140,12 +140,12 @@ int CmdJablotronDemod(const char *Cmd) { return 1; } -int CmdJablotronRead(const char *Cmd) { - lf_read(true, 10000); - return CmdJablotronDemod(Cmd); +int CmdJablotronRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 10000); + return CmdJablotronDemod(conn, Cmd); } -int CmdJablotronClone(const char *Cmd) { +int CmdJablotronClone(pm3_connection* conn, const char *Cmd) { uint64_t fullcode = 0; uint32_t blocks[3] = {T55x7_MODULATION_DIPHASE | T55x7_BITRATE_RF_64 | 2 << T55x7_MAXBLOCK_SHIFT, 0, 0}; @@ -192,9 +192,9 @@ int CmdJablotronClone(const char *Cmd) { for (int i = 2; i >= 0; --i) { c.arg[0] = blocks[i]; c.arg[1] = i; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)) { PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } @@ -202,7 +202,7 @@ int CmdJablotronClone(const char *Cmd) { return 0; } -int CmdJablotronSim(const char *Cmd) { +int CmdJablotronSim(pm3_connection* conn, const char *Cmd) { uint64_t fullcode = 0; char cmdp = param_getchar(Cmd, 0); @@ -226,8 +226,8 @@ int CmdJablotronSim(const char *Cmd) { UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; getJablotronBits(fullcode, c.d.asBytes); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -240,13 +240,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFJablotron(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFJablotron(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfjablotron.h b/client/cmdlfjablotron.h index 8e1e3364..ba2a08d8 100644 --- a/client/cmdlfjablotron.h +++ b/client/cmdlfjablotron.h @@ -9,11 +9,13 @@ #ifndef CMDLFJABLOTRON_H__ #define CMDLFJABLOTRON_H__ -extern int CmdLFJablotron(const char *Cmd); -extern int CmdJablotronClone(const char *Cmd); -extern int CmdJablotronSim(const char *Cmd); -extern int CmdJablotronRead(const char *Cmd); -extern int CmdJablotronDemod(const char *Cmd); +#include "comms.h" + +extern int CmdLFJablotron(pm3_connection* conn, const char *Cmd); +extern int CmdJablotronClone(pm3_connection* conn, const char *Cmd); +extern int CmdJablotronSim(pm3_connection* conn, const char *Cmd); +extern int CmdJablotronRead(pm3_connection* conn, const char *Cmd); +extern int CmdJablotronDemod(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfnexwatch.c b/client/cmdlfnexwatch.c index caabe835..159cf262 100644 --- a/client/cmdlfnexwatch.c +++ b/client/cmdlfnexwatch.c @@ -21,30 +21,30 @@ #include "cmdlf.h" #include "lfdemod.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); -int CmdPSKNexWatch(const char *Cmd) +int CmdPSKNexWatch(pm3_connection* conn, const char *Cmd) { - if (!PSKDemod("", false)) return 0; + if (!PSKDemod(conn, "", false)) return 0; uint8_t preamble[28] = {0,0,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - size_t startIdx = 0, size = DemodBufferLen; + size_t startIdx = 0, size = conn->DemodBufferLen; bool invert = false; - if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)){ + if (!preambleSearch(conn->DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)){ // if didn't find preamble try again inverting - if (!PSKDemod("1", false)) return 0; - size = DemodBufferLen; - if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)) return 0; + if (!PSKDemod(conn, "1", false)) return 0; + size = conn->DemodBufferLen; + if (!preambleSearch(conn->DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)) return 0; invert = true; } if (size != 128) return 0; - setDemodBuf(DemodBuffer, size, startIdx+4); - setClockGrid(g_DemodClock, g_DemodStartIdx + ((startIdx+4)*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, size, startIdx+4); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + ((startIdx+4)*conn->g_DemodClock)); startIdx = 8+32; // 8 = preamble, 32 = reserved bits (always 0) //get ID uint32_t ID = 0; for (uint8_t wordIdx=0; wordIdx<4; wordIdx++){ for (uint8_t idx=0; idx<8; idx++){ - ID = (ID << 1) | DemodBuffer[startIdx+wordIdx+(idx*4)]; + ID = (ID << 1) | conn->DemodBuffer[startIdx+wordIdx+(idx*4)]; } } //parity check (TBD) @@ -56,20 +56,20 @@ int CmdPSKNexWatch(const char *Cmd) if (invert){ PrintAndLog("Had to Invert - probably NexKey"); for (uint8_t idx=0; idxDemodBuffer[idx] ^= 1; } - CmdPrintDemodBuff("x"); + CmdPrintDemodBuff(conn, "x"); return 1; } //by marshmellow //see ASKDemod for what args are accepted -int CmdNexWatchRead(const char *Cmd) { +int CmdNexWatchRead(pm3_connection* conn, const char *Cmd) { // read lf silently - lf_read(true, 10000); + lf_read(conn, true, 10000); // demod and output viking ID - return CmdPSKNexWatch(Cmd); + return CmdPSKNexWatch(conn, Cmd); } static command_t CommandTable[] = { @@ -79,12 +79,12 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFNexWatch(const char *Cmd) { - CmdsParse(CommandTable, Cmd); +int CmdLFNexWatch(pm3_connection* conn, const char *Cmd) { + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfnexwatch.h b/client/cmdlfnexwatch.h index 99d54003..2355e987 100644 --- a/client/cmdlfnexwatch.h +++ b/client/cmdlfnexwatch.h @@ -8,7 +8,10 @@ //----------------------------------------------------------------------------- #ifndef CMDLFNEXWATCH_H__ #define CMDLFNEXWATCH_H__ -extern int CmdLFNexWatch(const char *Cmd); -extern int CmdPSKNexWatch(const char *Cmd); -extern int CmdNexWatchRead(const char *Cmd); + +#include "comms.h" + +extern int CmdLFNexWatch(pm3_connection* conn, const char *Cmd); +extern int CmdPSKNexWatch(pm3_connection* conn, const char *Cmd); +extern int CmdNexWatchRead(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfnoralsy.c b/client/cmdlfnoralsy.c index 2c90fa14..e3a2ad29 100644 --- a/client/cmdlfnoralsy.c +++ b/client/cmdlfnoralsy.c @@ -22,7 +22,7 @@ #include "protocols.h" // for T55xx config register definitions #include "lfdemod.h" // parityTest -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_noralsy_clone(void){ PrintAndLog("clone a Noralsy tag to a T55x7 tag."); @@ -109,18 +109,18 @@ int NoralsyDemod_AM(uint8_t *dest, size_t *size) { **/ //see ASKDemod for what args are accepted -int CmdNoralsyDemod(const char *Cmd) { +int CmdNoralsyDemod(pm3_connection* conn, const char *Cmd) { //ASK / Manchester bool st = true; - if (!ASKDemod_ext("32 0 0", false, false, 1, &st)) { + if (!ASKDemod_ext(conn, "32 0 0", false, false, 1, &st)) { if (g_debugMode) PrintAndLog("DEBUG: Error - Noralsy: ASK/Manchester Demod failed"); return 0; } if (!st) return 0; - size_t size = DemodBufferLen; - int ans = NoralsyDemod_AM(DemodBuffer, &size); + size_t size = conn->DemodBufferLen; + int ans = NoralsyDemod_AM(conn->DemodBuffer, &size); if (ans < 0){ if (g_debugMode){ if (ans == -1) @@ -134,26 +134,26 @@ int CmdNoralsyDemod(const char *Cmd) { } return 0; } - setDemodBuf(DemodBuffer, 96, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 96, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); //setGrid_Clock(32); //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); - uint32_t raw3 = bytebits_to_byte(DemodBuffer+64, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer, 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+32, 32); + uint32_t raw3 = bytebits_to_byte(conn->DemodBuffer+64, 32); - uint32_t cardid = (bytebits_to_byte(DemodBuffer+32, 12)<<16) | bytebits_to_byte(DemodBuffer+32+24, 16); + uint32_t cardid = (bytebits_to_byte(conn->DemodBuffer+32, 12)<<16) | bytebits_to_byte(conn->DemodBuffer+32+24, 16); uint16_t year = (raw2 & 0x000ff000) >> 12; year += ( year > 0x60 ) ? 0x1900: 0x2000; // calc checksums - uint8_t calc1 = noralsy_chksum(DemodBuffer+32, 40); - uint8_t calc2 = noralsy_chksum(DemodBuffer, 76); + uint8_t calc1 = noralsy_chksum(conn->DemodBuffer+32, 40); + uint8_t calc2 = noralsy_chksum(conn->DemodBuffer, 76); uint8_t chk1 = 0, chk2 = 0; - chk1 = bytebits_to_byte(DemodBuffer+72, 4); - chk2 = bytebits_to_byte(DemodBuffer+76, 4); + chk1 = bytebits_to_byte(conn->DemodBuffer+72, 4); + chk2 = bytebits_to_byte(conn->DemodBuffer+76, 4); // test checksums if ( chk1 != calc1 ) { if (g_debugMode) PrintAndLog("DEBUG: Error - Noralsy: checksum 1 failed %x - %x\n", chk1, calc1); @@ -172,12 +172,12 @@ int CmdNoralsyDemod(const char *Cmd) { return 1; } -int CmdNoralsyRead(const char *Cmd) { - lf_read(true, 8000); - return CmdNoralsyDemod(Cmd); +int CmdNoralsyRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 8000); + return CmdNoralsyDemod(conn, Cmd); } -int CmdNoralsyClone(const char *Cmd) { +int CmdNoralsyClone(pm3_connection* conn, const char *Cmd) { uint16_t year = 0; uint32_t id = 0; @@ -222,9 +222,9 @@ int CmdNoralsyClone(const char *Cmd) { for (int i = 3; i >= 0; --i) { c.arg[0] = blocks[i]; c.arg[1] = i; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){ PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } @@ -232,7 +232,7 @@ int CmdNoralsyClone(const char *Cmd) { return 0; } -int CmdNoralsySim(const char *Cmd) { +int CmdNoralsySim(pm3_connection* conn, const char *Cmd) { uint8_t bits[96]; uint8_t *bs = bits; @@ -262,8 +262,8 @@ int CmdNoralsySim(const char *Cmd) { UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bs, size); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -276,13 +276,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFNoralsy(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFNoralsy(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfnoralsy.h b/client/cmdlfnoralsy.h index 743c14ec..f751a956 100644 --- a/client/cmdlfnoralsy.h +++ b/client/cmdlfnoralsy.h @@ -9,11 +9,13 @@ #ifndef CMDLFNORALSY_H__ #define CMDLFNORALSY_H__ -extern int CmdLFNoralsy(const char *Cmd); -extern int CmdNoralsyClone(const char *Cmd); -extern int CmdNoralsySim(const char *Cmd); -extern int CmdNoralsyRead(const char *Cmd); -extern int CmdNoralsyDemod(const char *Cmd); +#include "comms.h" + +extern int CmdLFNoralsy(pm3_connection* conn, const char *Cmd); +extern int CmdNoralsyClone(pm3_connection* conn, const char *Cmd); +extern int CmdNoralsySim(pm3_connection* conn, const char *Cmd); +extern int CmdNoralsyRead(pm3_connection* conn, const char *Cmd); +extern int CmdNoralsyDemod(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfpac.c b/client/cmdlfpac.c index ef6b394b..23bf59cc 100644 --- a/client/cmdlfpac.c +++ b/client/cmdlfpac.c @@ -20,7 +20,7 @@ #include "cmdlf.h" #include "lfdemod.h" // preamble test -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); // by marshmellow // find PAC preamble in already demoded data @@ -36,15 +36,15 @@ int PacFind(uint8_t *dest, size_t *size) { } //see NRZDemod for what args are accepted -int CmdPacDemod(const char *Cmd) { +int CmdPacDemod(pm3_connection* conn, const char *Cmd) { //NRZ - if (!NRZrawDemod(Cmd, false)) { + if (!NRZrawDemod(conn, Cmd, false)) { if (g_debugMode) PrintAndLog("DEBUG: Error - PAC: NRZ Demod failed"); return 0; } - size_t size = DemodBufferLen; - int ans = PacFind(DemodBuffer, &size); + size_t size = conn->DemodBufferLen; + int ans = PacFind(conn->DemodBuffer, &size); if (ans < 0) { if (g_debugMode) { if (ans == -1) @@ -58,14 +58,14 @@ int CmdPacDemod(const char *Cmd) { } return 0; } - setDemodBuf(DemodBuffer, 128, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 128, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans * conn->g_DemodClock)); //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer , 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); - uint32_t raw3 = bytebits_to_byte(DemodBuffer+64, 32); - uint32_t raw4 = bytebits_to_byte(DemodBuffer+96, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer , 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+32, 32); + uint32_t raw3 = bytebits_to_byte(conn->DemodBuffer+64, 32); + uint32_t raw4 = bytebits_to_byte(conn->DemodBuffer+96, 32); // preamble then appears to have marker bits of "10" CS? // 11111111001000000 10 01001100 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 10001100 10 100000001 @@ -76,9 +76,9 @@ int CmdPacDemod(const char *Cmd) { return 1; } -int CmdPacRead(const char *Cmd) { - lf_read(true, 4096*2 + 20); - return CmdPacDemod(Cmd); +int CmdPacRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 4096*2 + 20); + return CmdPacDemod(conn, Cmd); } static command_t CommandTable[] = { @@ -88,13 +88,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFPac(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFPac(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfpac.h b/client/cmdlfpac.h index 99b35a53..bb439f4d 100644 --- a/client/cmdlfpac.h +++ b/client/cmdlfpac.h @@ -9,9 +9,11 @@ #ifndef CMDLFPAC_H__ #define CMDLFPAC_H__ -extern int CmdLFPac(const char *Cmd); -extern int CmdPacRead(const char *Cmd); -extern int CmdPacDemod(const char *Cmd); +#include "comms.h" + +extern int CmdLFPac(pm3_connection* conn, const char *Cmd); +extern int CmdPacRead(pm3_connection* conn, const char *Cmd); +extern int CmdPacDemod(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfparadox.c b/client/cmdlfparadox.c index e918c7fe..dac5f903 100644 --- a/client/cmdlfparadox.c +++ b/client/cmdlfparadox.c @@ -19,18 +19,18 @@ #include "cmddata.h" #include "cmdlf.h" #include "lfdemod.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); //by marshmellow //Paradox Prox demod - FSK RF/50 with preamble of 00001111 (then manchester encoded) //print full Paradox Prox ID and some bit format details if found -int CmdFSKdemodParadox(const char *Cmd) +int CmdFSKdemodParadox(pm3_connection* conn, const char *Cmd) { //raw fsk demod no manchester decoding no start bit finding just get binary from wave uint32_t hi2=0, hi=0, lo=0; uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t BitLen = getFromGraphBuf(BitStream); + size_t BitLen = getFromGraphBuf(conn, BitStream); if (BitLen==0) return 0; int waveIdx=0; //get binary from fsk wave @@ -63,21 +63,21 @@ int CmdFSKdemodParadox(const char *Cmd) PrintAndLog("Paradox TAG ID: %x%08x - FC: %d - Card: %d - Checksum: %02x - RAW: %08x%08x%08x", hi>>10, (hi & 0x3)<<26 | (lo>>10), fc, cardnum, (lo>>2) & 0xFF, rawHi2, rawHi, rawLo); - setDemodBuf(BitStream,BitLen,idx); - setClockGrid(50, waveIdx + (idx*50)); + setDemodBuf(conn, BitStream,BitLen,idx); + setClockGrid(conn, 50, waveIdx + (idx*50)); if (g_debugMode){ PrintAndLog("DEBUG: idx: %d, len: %d, Printing Demod Buffer:", idx, BitLen); - printDemodBuff(); + printDemodBuff(conn); } return 1; } //by marshmellow //see ASKDemod for what args are accepted -int CmdParadoxRead(const char *Cmd) { +int CmdParadoxRead(pm3_connection* conn, const char *Cmd) { // read lf silently - lf_read(true, 10000); + lf_read(conn, true, 10000); // demod and output viking ID - return CmdFSKdemodParadox(Cmd); + return CmdFSKdemodParadox(conn, Cmd); } static command_t CommandTable[] = { @@ -87,12 +87,12 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFParadox(const char *Cmd) { - CmdsParse(CommandTable, Cmd); +int CmdLFParadox(pm3_connection* conn, const char *Cmd) { + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfparadox.h b/client/cmdlfparadox.h index 997787f2..a1db4338 100644 --- a/client/cmdlfparadox.h +++ b/client/cmdlfparadox.h @@ -8,7 +8,10 @@ //----------------------------------------------------------------------------- #ifndef CMDLFPARADOX_H__ #define CMDLFPARADOX_H__ -extern int CmdLFParadox(const char *Cmd); -extern int CmdFSKdemodParadox(const char *Cmd); -extern int CmdParadoxRead(const char *Cmd); + +#include "comms.h" + +extern int CmdLFParadox(pm3_connection* conn, const char *Cmd); +extern int CmdFSKdemodParadox(pm3_connection* conn, const char *Cmd); +extern int CmdParadoxRead(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfpcf7931.c b/client/cmdlfpcf7931.c index ffaf946f..9449fc63 100644 --- a/client/cmdlfpcf7931.c +++ b/client/cmdlfpcf7931.c @@ -20,7 +20,7 @@ #include "cmdlf.h" #include "cmdlfpcf7931.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); #define PCF7931_DEFAULT_INITDELAY 17500 #define PCF7931_DEFAULT_OFFSET_WIDTH 0 @@ -94,23 +94,23 @@ int usage_pcf7931_config(){ return 0; } -int CmdLFPCF7931Read(const char *Cmd){ +int CmdLFPCF7931Read(pm3_connection* conn, const char *Cmd){ uint8_t ctmp = param_getchar(Cmd, 0); if ( ctmp == 'H' || ctmp == 'h' ) return usage_pcf7931_read(); UsbCommand resp; UsbCommand c = {CMD_PCF7931_READ, {0, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); - if ( !WaitForResponseTimeout(CMD_ACK, &resp, 2500) ) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if ( !WaitForResponseTimeout(conn, CMD_ACK, &resp, 2500) ) { PrintAndLog("command execution time out"); return 1; } return 0; } -int CmdLFPCF7931Config(const char *Cmd){ +int CmdLFPCF7931Config(pm3_connection* conn, const char *Cmd){ uint8_t ctmp = param_getchar(Cmd, 0); if ( ctmp == 0) return pcf7931_printConfig(); @@ -127,7 +127,7 @@ int CmdLFPCF7931Config(const char *Cmd){ return 0; } -int CmdLFPCF7931Write(const char *Cmd){ +int CmdLFPCF7931Write(pm3_connection* conn, const char *Cmd){ uint8_t ctmp = param_getchar(Cmd, 0); if (strlen(Cmd) < 1 || ctmp == 'h' || ctmp == 'H') return usage_pcf7931_write(); @@ -151,8 +151,8 @@ int CmdLFPCF7931Write(const char *Cmd){ c.d.asDwords[8] = (configPcf.OffsetPosition + 128); c.d.asDwords[9] = configPcf.InitDelay; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); //no ack? return 0; } @@ -166,14 +166,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdLFPCF7931(const char *Cmd) +int CmdLFPCF7931(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfpcf7931.h b/client/cmdlfpcf7931.h index e093039c..2d233abb 100644 --- a/client/cmdlfpcf7931.h +++ b/client/cmdlfpcf7931.h @@ -12,6 +12,8 @@ #ifndef CMDLFPCF7931_H__ #define CMDLFPCF7931_H__ +#include "comms.h" + struct pcf7931_config{ uint8_t Pwd[7]; uint16_t InitDelay; @@ -26,10 +28,10 @@ int usage_pcf7931_read(); int usage_pcf7931_write(); int usage_pcf7931_config(); -int CmdLFPCF7931(const char *Cmd); +int CmdLFPCF7931(pm3_connection* conn, const char *Cmd); -int CmdLFPCF7931Read(const char *Cmd); -int CmdLFPCF7931Write(const char *Cmd); -int CmdLFPCF7931Config(const char *Cmd); +int CmdLFPCF7931Read(pm3_connection* conn, const char *Cmd); +int CmdLFPCF7931Write(pm3_connection* conn, const char *Cmd); +int CmdLFPCF7931Config(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfpresco.c b/client/cmdlfpresco.c index 29fc81f2..56b9b6a3 100644 --- a/client/cmdlfpresco.c +++ b/client/cmdlfpresco.c @@ -22,7 +22,7 @@ #include "protocols.h" // for T55xx config register definitions #include "lfdemod.h" // parityTest -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_presco_clone(void){ PrintAndLog("clone a Presco tag to a T55x7 tag."); @@ -124,28 +124,28 @@ int GetPrescoBits(uint32_t fullcode, uint8_t *prescoBits) { } //see ASKDemod for what args are accepted -int CmdPrescoDemod(const char *Cmd) { - if (!ASKDemod(Cmd, false, false, 1)) { +int CmdPrescoDemod(pm3_connection* conn, const char *Cmd) { + if (!ASKDemod(conn, Cmd, false, false, 1)) { if (g_debugMode) PrintAndLog("ASKDemod failed"); return 0; } - size_t size = DemodBufferLen; + size_t size = conn->DemodBufferLen; //call lfdemod.c demod for presco - int ans = PrescoDemod(DemodBuffer, &size); + int ans = PrescoDemod(conn->DemodBuffer, &size); if (ans < 0) { if (g_debugMode) PrintAndLog("Error Presco_Demod %d", ans); return 0; } //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer+ans, 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+ans+32, 32); - uint32_t raw3 = bytebits_to_byte(DemodBuffer+ans+64, 32); - uint32_t raw4 = bytebits_to_byte(DemodBuffer+ans+96, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer+ans, 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+ans+32, 32); + uint32_t raw3 = bytebits_to_byte(conn->DemodBuffer+ans+64, 32); + uint32_t raw4 = bytebits_to_byte(conn->DemodBuffer+ans+96, 32); uint32_t cardid = raw4; PrintAndLog("Presco Tag Found: Card ID %08X", cardid); PrintAndLog("Raw: %08X%08X%08X%08X", raw1,raw2,raw3,raw4); - setDemodBuf(DemodBuffer, 128, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 128, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); uint32_t sitecode = 0, usercode = 0, fullcode = 0; bool Q5=false; @@ -158,18 +158,18 @@ int CmdPrescoDemod(const char *Cmd) { } //see ASKDemod for what args are accepted -int CmdPrescoRead(const char *Cmd) { +int CmdPrescoRead(pm3_connection* conn, const char *Cmd) { // Presco Number: 123456789 --> Sitecode 30 | usercode 8665 // read lf silently - lf_read(true, 10000); + lf_read(conn, true, 10000); // demod and output Presco ID - return CmdPrescoDemod(Cmd); + return CmdPrescoDemod(conn, Cmd); } // takes base 12 ID converts to hex // Or takes 8 digit hex ID -int CmdPrescoClone(const char *Cmd) { +int CmdPrescoClone(pm3_connection* conn, const char *Cmd) { bool Q5 = false; uint32_t sitecode=0, usercode=0, fullcode=0; @@ -211,9 +211,9 @@ int CmdPrescoClone(const char *Cmd) { for (int i=4; i>=0; i--) { c.arg[0] = blocks[i]; c.arg[1] = i; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)){ PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } @@ -223,7 +223,7 @@ int CmdPrescoClone(const char *Cmd) { // takes base 12 ID converts to hex // Or takes 8 digit hex ID -int CmdPrescoSim(const char *Cmd) { +int CmdPrescoSim(pm3_connection* conn, const char *Cmd) { uint32_t sitecode=0, usercode=0, fullcode=0; bool Q5=false; // get wiegand from printed number. @@ -239,8 +239,8 @@ int CmdPrescoSim(const char *Cmd) { UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; GetPrescoBits(fullcode, c.d.asBytes); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -252,13 +252,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFPresco(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFPresco(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfpresco.h b/client/cmdlfpresco.h index 5e80fbb1..e98e9465 100644 --- a/client/cmdlfpresco.h +++ b/client/cmdlfpresco.h @@ -11,10 +11,11 @@ #include //uint_32+ #include //bool +#include "comms.h" -int CmdLFPresco(const char *Cmd); -int CmdPrescoClone(const char *Cmd); -int CmdPrescoSim(const char *Cmd); +int CmdLFPresco(pm3_connection* conn, const char *Cmd); +int CmdPrescoClone(pm3_connection* conn, const char *Cmd); +int CmdPrescoSim(pm3_connection* conn, const char *Cmd); int GetWiegandFromPresco(const char *id, uint32_t *sitecode, uint32_t *usercode, uint32_t *fullcode, bool *Q5); diff --git a/client/cmdlfpyramid.c b/client/cmdlfpyramid.c index 366889f3..ede28fe1 100644 --- a/client/cmdlfpyramid.c +++ b/client/cmdlfpyramid.c @@ -23,7 +23,7 @@ #include "lfdemod.h" // parityTest #include "crc.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_pyramid_clone(void){ PrintAndLog("clone a Farpointe/Pyramid tag to a T55x7 tag."); @@ -89,11 +89,11 @@ int GetPyramidBits(uint32_t fc, uint32_t cn, uint8_t *pyramidBits) { //by marshmellow //Pyramid Prox demod - FSK RF/50 with preamble of 0000000000000001 (always a 128 bit data stream) //print full Farpointe Data/Pyramid Prox ID and some bit format details if found -int CmdFSKdemodPyramid(const char *Cmd) +int CmdFSKdemodPyramid(pm3_connection* conn, const char *Cmd) { //raw fsk demod no manchester decoding no start bit finding just get binary from wave uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(BitStream); + size_t size = getFromGraphBuf(conn, BitStream); if (size==0) return 0; int waveIdx=0; @@ -152,8 +152,8 @@ int CmdFSKdemodPyramid(const char *Cmd) uint32_t rawHi = bytebits_to_byte(BitStream+idx+64,32); uint32_t rawHi2 = bytebits_to_byte(BitStream+idx+32,32); uint32_t rawHi3 = bytebits_to_byte(BitStream+idx,32); - setDemodBuf(BitStream,128,idx); - setClockGrid(50, waveIdx + (idx*50)); + setDemodBuf(conn, BitStream,128,idx); + setClockGrid(conn, 50, waveIdx + (idx*50)); size = removeParity(BitStream, idx+8, 8, 1, 120); if (size != 105){ @@ -222,17 +222,17 @@ int CmdFSKdemodPyramid(const char *Cmd) if (g_debugMode){ PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, 128); - printDemodBuff(); + printDemodBuff(conn); } return 1; } -int CmdPyramidRead(const char *Cmd) { - lf_read(true, 15000); - return CmdFSKdemodPyramid(""); +int CmdPyramidRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 15000); + return CmdFSKdemodPyramid(conn, ""); } -int CmdPyramidClone(const char *Cmd) { +int CmdPyramidClone(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_pyramid_clone(); @@ -276,9 +276,9 @@ int CmdPyramidClone(const char *Cmd) { for ( i = 0; i<5; ++i ) { c.arg[0] = blocks[i]; c.arg[1] = i; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)){ PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } @@ -286,7 +286,7 @@ int CmdPyramidClone(const char *Cmd) { return 0; } -int CmdPyramidSim(const char *Cmd) { +int CmdPyramidSim(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_pyramid_sim(); @@ -316,8 +316,8 @@ int CmdPyramidSim(const char *Cmd) { UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bs, size); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -330,13 +330,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFPyramid(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFPyramid(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfpyramid.h b/client/cmdlfpyramid.h index 786e5db8..beac53a9 100644 --- a/client/cmdlfpyramid.h +++ b/client/cmdlfpyramid.h @@ -9,10 +9,12 @@ #ifndef CMDLFPYRAMID_H__ #define CMDLFPYRAMID_H__ -extern int CmdLFPyramid(const char *Cmd); -extern int CmdPyramidClone(const char *Cmd); -extern int CmdPyramidSim(const char *Cmd); -extern int CmdFSKdemodPyramid(const char *Cmd); -extern int CmdPyramidRead(const char *Cmd); +#include "comms.h" + +extern int CmdLFPyramid(pm3_connection* conn, const char *Cmd); +extern int CmdPyramidClone(pm3_connection* conn, const char *Cmd); +extern int CmdPyramidSim(pm3_connection* conn, const char *Cmd); +extern int CmdFSKdemodPyramid(pm3_connection* conn, const char *Cmd); +extern int CmdPyramidRead(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfsecurakey.c b/client/cmdlfsecurakey.c index 8ae81250..9ce34eb1 100644 --- a/client/cmdlfsecurakey.c +++ b/client/cmdlfsecurakey.c @@ -23,7 +23,7 @@ #include "lfdemod.h" // preamble test #include "parity.h" // for wiegand parity test -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); // by marshmellow // find Securakey preamble in already demoded data @@ -39,17 +39,17 @@ int SecurakeyFind(uint8_t *dest, size_t *size) { } //see ASKDemod for what args are accepted -int CmdSecurakeyDemod(const char *Cmd) { +int CmdSecurakeyDemod(pm3_connection* conn, const char *Cmd) { //ASK / Manchester bool st = false; - if (!ASKDemod_ext("40 0 0", false, false, 1, &st)) { - if (g_debugMode) PrintAndLog("DEBUG: Error - Securakey: ASK/Manchester Demod failed"); + if (!ASKDemod_ext(conn, "40 0 0", false, false, 1, &st)) { + if (g_debugMode) PrintAndLog("DEBUG: Error - Noralsy: ASK/Manchester Demod failed"); return 0; } if (st) return 0; - size_t size = DemodBufferLen; - int ans = SecurakeyFind(DemodBuffer, &size); + size_t size = conn->DemodBufferLen; + int ans = SecurakeyFind(conn->DemodBuffer, &size); if (ans < 0) { if (g_debugMode) { if (ans == -1) @@ -63,13 +63,13 @@ int CmdSecurakeyDemod(const char *Cmd) { } return 0; } - setDemodBuf(DemodBuffer, 96, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 96, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer , 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); - uint32_t raw3 = bytebits_to_byte(DemodBuffer+64, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer , 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+32, 32); + uint32_t raw3 = bytebits_to_byte(conn->DemodBuffer+64, 32); // 26 bit format // preamble ??bitlen reserved EPx xxxxxxxy yyyyyyyy yyyyyyyOP CS? CS2? @@ -84,7 +84,7 @@ int CmdSecurakeyDemod(const char *Cmd) { // standard wiegand parities. // unknown checksum 11 bits? at the end uint8_t bits_no_spacer[85]; - memcpy(bits_no_spacer, DemodBuffer + 11, 85); + memcpy(bits_no_spacer, conn->DemodBuffer + 11, 85); // remove marker bits (0's every 9th digit after preamble) (pType = 3 (always 0s)) size = removeParity(bits_no_spacer, 0, 9, 3, 85); @@ -122,9 +122,9 @@ int CmdSecurakeyDemod(const char *Cmd) { return 1; } -int CmdSecurakeyRead(const char *Cmd) { - lf_read(true, 8000); - return CmdSecurakeyDemod(Cmd); +int CmdSecurakeyRead(pm3_connection* conn, const char *Cmd) { + lf_read(conn, true, 8000); + return CmdSecurakeyDemod(conn, Cmd); } static command_t CommandTable[] = { @@ -134,13 +134,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFSecurakey(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFSecurakey(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfsecurakey.h b/client/cmdlfsecurakey.h index f3c0cf88..2a819baf 100644 --- a/client/cmdlfsecurakey.h +++ b/client/cmdlfsecurakey.h @@ -9,11 +9,13 @@ #ifndef CMDLFSECURAKEY_H__ #define CMDLFSECURAKEY_H__ -extern int CmdLFSecurakey(const char *Cmd); -extern int CmdSecurakeyClone(const char *Cmd); -extern int CmdSecurakeySim(const char *Cmd); -extern int CmdSecurakeyRead(const char *Cmd); -extern int CmdSecurakeyDemod(const char *Cmd); +#include "comms.h" + +extern int CmdLFSecurakey(pm3_connection* conn, const char *Cmd); +extern int CmdSecurakeyClone(pm3_connection* conn, const char *Cmd); +extern int CmdSecurakeySim(pm3_connection* conn, const char *Cmd); +extern int CmdSecurakeyRead(pm3_connection* conn, const char *Cmd); +extern int CmdSecurakeyDemod(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index 252aaaa2..c0d055e4 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -196,7 +196,7 @@ int usage_t55xx_wipe(){ } -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); void printT5xxHeader(uint8_t page){ PrintAndLog("Reading Page %d:", page); @@ -204,7 +204,7 @@ void printT5xxHeader(uint8_t page){ PrintAndLog("----+----------+---------------------------------"); } -int CmdT55xxSetConfig(const char *Cmd) { +int CmdT55xxSetConfig(pm3_connection* conn, const char *Cmd) { uint8_t offset = 0; char modulation[5] = {0x00}; @@ -311,13 +311,13 @@ int CmdT55xxSetConfig(const char *Cmd) { return printConfiguration ( config ); } -int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32_t password){ +int T55xxReadBlock(pm3_connection* conn, uint8_t block, bool page1, bool usepwd, bool override, uint32_t password){ //Password mode if ( usepwd ) { // try reading the config block and verify that PWD bit is set before doing this! if ( !override ) { - if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, false, 0 ) ) return 0; - if ( !tryDetectModulation() ) { + if ( !AcquireData(conn, T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, false, 0 ) ) return 0; + if ( !tryDetectModulation(conn) ) { PrintAndLog("Safety Check: Could not detect if PWD bit is set in config block. Exits."); return 0; } else { @@ -330,16 +330,16 @@ int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32 } } - if (!AquireData(page1, block, usepwd, password) ) return 0; - if (!DecodeT55xxBlock()) return 0; + if (!AcquireData(conn, page1, block, usepwd, password) ) return 0; + if (!DecodeT55xxBlock(conn)) return 0; char blk[10]={0}; sprintf(blk,"%d", block); - printT55xxBlock(blk); + printT55xxBlock(conn, blk); return 1; } -int CmdT55xxReadBlock(const char *Cmd) { +int CmdT55xxReadBlock(pm3_connection* conn, const char *Cmd) { uint8_t block = REGULAR_READ_MODE_BLOCK; uint32_t password = 0; //default to blank Block 7 bool usepwd = false; @@ -386,65 +386,65 @@ int CmdT55xxReadBlock(const char *Cmd) { } printT5xxHeader(page1); - return T55xxReadBlock(block, page1, usepwd, override, password); + return T55xxReadBlock(conn, block, page1, usepwd, override, password); } -bool DecodeT55xxBlock(){ +bool DecodeT55xxBlock(pm3_connection* conn){ char buf[30] = {0x00}; char *cmdStr = buf; int ans = 0; bool ST = config.ST; uint8_t bitRate[8] = {8,16,32,40,50,64,100,128}; - DemodBufferLen = 0x00; + conn->DemodBufferLen = 0x00; switch( config.modulation ){ case DEMOD_FSK: snprintf(cmdStr, sizeof(buf),"%d %d", bitRate[config.bitrate], config.inverted ); - ans = FSKrawDemod(cmdStr, false); + ans = FSKrawDemod(conn, cmdStr, false); break; case DEMOD_FSK1: case DEMOD_FSK1a: snprintf(cmdStr, sizeof(buf),"%d %d 8 5", bitRate[config.bitrate], config.inverted ); - ans = FSKrawDemod(cmdStr, false); + ans = FSKrawDemod(conn, cmdStr, false); break; case DEMOD_FSK2: case DEMOD_FSK2a: snprintf(cmdStr, sizeof(buf),"%d %d 10 8", bitRate[config.bitrate], config.inverted ); - ans = FSKrawDemod(cmdStr, false); + ans = FSKrawDemod(conn, cmdStr, false); break; case DEMOD_ASK: snprintf(cmdStr, sizeof(buf),"%d %d 1", bitRate[config.bitrate], config.inverted ); - ans = ASKDemod_ext(cmdStr, false, false, 1, &ST); + ans = ASKDemod_ext(conn, cmdStr, false, false, 1, &ST); break; case DEMOD_PSK1: // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - save_restoreGB(GRAPH_SAVE); - CmdLtrim("160"); + save_restoreGB(conn, GRAPH_SAVE); + CmdLtrim(conn, "160"); snprintf(cmdStr, sizeof(buf),"%d %d 6", bitRate[config.bitrate], config.inverted ); - ans = PSKDemod(cmdStr, false); + ans = PSKDemod(conn, cmdStr, false); //undo trim samples - save_restoreGB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); break; case DEMOD_PSK2: //inverted won't affect this case DEMOD_PSK3: //not fully implemented // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - save_restoreGB(GRAPH_SAVE); - CmdLtrim("160"); + save_restoreGB(conn, GRAPH_SAVE); + CmdLtrim(conn, "160"); snprintf(cmdStr, sizeof(buf),"%d 0 6", bitRate[config.bitrate] ); - ans = PSKDemod(cmdStr, false); - psk1TOpsk2(DemodBuffer, DemodBufferLen); + ans = PSKDemod(conn, cmdStr, false); + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); //undo trim samples - save_restoreGB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); break; case DEMOD_NRZ: snprintf(cmdStr, sizeof(buf),"%d %d 1", bitRate[config.bitrate], config.inverted ); - ans = NRZrawDemod(cmdStr, false); + ans = NRZrawDemod(conn, cmdStr, false); break; case DEMOD_BI: case DEMOD_BIa: snprintf(cmdStr, sizeof(buf),"0 %d %d 1", bitRate[config.bitrate], config.inverted ); - ans = ASKbiphaseDemod(cmdStr, false); + ans = ASKbiphaseDemod(conn, cmdStr, false); break; default: return false; @@ -452,14 +452,14 @@ bool DecodeT55xxBlock(){ return (bool) ans; } -bool DecodeT5555TraceBlock() { - DemodBufferLen = 0x00; +bool DecodeT5555TraceBlock(pm3_connection* conn) { + conn->DemodBufferLen = 0x00; // According to datasheet. Always: RF/64, not inverted, Manchester - return (bool) ASKDemod("64 0 1", false, false, 1); + return (bool) ASKDemod(conn, "64 0 1", false, false, 1); } -int CmdT55xxDetect(const char *Cmd){ +int CmdT55xxDetect(pm3_connection* conn, const char *Cmd){ bool errors = false; bool useGB = false; bool usepwd = false; @@ -491,26 +491,26 @@ int CmdT55xxDetect(const char *Cmd){ if (errors) return usage_t55xx_detect(); if ( !useGB) { - if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password) ) + if ( !AcquireData(conn, T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password) ) return 0; } - if ( !tryDetectModulation() ) + if ( !tryDetectModulation(conn) ) PrintAndLog("Could not detect modulation automatically. Try setting it manually with \'lf t55xx config\'"); return 1; } // detect configuration? -bool tryDetectModulation(){ +bool tryDetectModulation(pm3_connection* conn){ uint8_t hits = 0; t55xx_conf_block_t tests[15]; int bitRate=0; uint8_t fc1 = 0, fc2 = 0, ans = 0; int clk = 0, firstClockEdge = 0; - ans = fskClocks(&fc1, &fc2, (uint8_t *)&clk, false, &firstClockEdge); + ans = fskClocks(conn, &fc1, &fc2, (uint8_t *)&clk, false, &firstClockEdge); if (ans && ((fc1==10 && fc2==8) || (fc1==8 && fc2==5))) { - if ( FSKrawDemod("0 0", false) && test(DEMOD_FSK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( FSKrawDemod(conn, "0 0", false) && test(conn, DEMOD_FSK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_FSK; if (fc1==8 && fc2 == 5) tests[hits].modulation = DEMOD_FSK1a; @@ -518,11 +518,11 @@ bool tryDetectModulation(){ tests[hits].modulation = DEMOD_FSK2; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } - if ( FSKrawDemod("0 1", false) && test(DEMOD_FSK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( FSKrawDemod(conn, "0 1", false) && test(conn, DEMOD_FSK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_FSK; if (fc1 == 8 && fc2 == 5) tests[hits].modulation = DEMOD_FSK1; @@ -530,115 +530,115 @@ bool tryDetectModulation(){ tests[hits].modulation = DEMOD_FSK2a; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } } else { - clk = GetAskClock("", false, false); + clk = GetAskClock(conn, "", false, false); if (clk>0) { tests[hits].ST = true; - if ( ASKDemod_ext("0 0 1", false, false, 1, &tests[hits].ST) && test(DEMOD_ASK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( ASKDemod_ext(conn, "0 0 1", false, false, 1, &tests[hits].ST) && test(conn, DEMOD_ASK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); ++hits; } tests[hits].ST = true; - if ( ASKDemod_ext("0 1 1", false, false, 1, &tests[hits].ST) && test(DEMOD_ASK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( ASKDemod_ext(conn, "0 1 1", false, false, 1, &tests[hits].ST) && test(conn, DEMOD_ASK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); ++hits; } - if ( ASKbiphaseDemod("0 0 0 2", false) && test(DEMOD_BI, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5) ) { + if ( ASKbiphaseDemod(conn, "0 0 0 2", false) && test(conn, DEMOD_BI, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5) ) { tests[hits].modulation = DEMOD_BI; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } - if ( ASKbiphaseDemod("0 0 1 2", false) && test(DEMOD_BIa, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5) ) { + if ( ASKbiphaseDemod(conn, "0 0 1 2", false) && test(conn, DEMOD_BIa, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5) ) { tests[hits].modulation = DEMOD_BIa; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } } - clk = GetNrzClock("", false, false); + clk = GetNrzClock(conn, "", false, false); if (clk>8) { //clock of rf/8 is likely a false positive, so don't use it. - if ( NRZrawDemod("0 0 1", false) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( NRZrawDemod(conn, "0 0 1", false) && test(conn, DEMOD_NRZ, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_NRZ; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } - if ( NRZrawDemod("0 1 1", false) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( NRZrawDemod(conn, "0 1 1", false) && test(conn, DEMOD_NRZ, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_NRZ; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } } - clk = GetPskClock("", false, false); + clk = GetPskClock(conn, "", false, false); if (clk>0) { // allow undo - save_restoreGB(GRAPH_SAVE); + save_restoreGB(conn, GRAPH_SAVE); // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - CmdLtrim("160"); - if ( PSKDemod("0 0 6", false) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + CmdLtrim(conn, "160"); + if ( PSKDemod(conn, "0 0 6", false) && test(conn, DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } - if ( PSKDemod("0 1 6", false) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { + if ( PSKDemod(conn, "0 1 6", false) && test(conn, DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } // PSK2 - needs a call to psk1TOpsk2. - if ( PSKDemod("0 0 6", false)) { - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (test(DEMOD_PSK2, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){ + if ( PSKDemod(conn, "0 0 6", false)) { + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); + if (test(conn, DEMOD_PSK2, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){ tests[hits].modulation = DEMOD_PSK2; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } } // inverse waves does not affect this demod // PSK3 - needs a call to psk1TOpsk2. - if ( PSKDemod("0 0 6", false)) { - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (test(DEMOD_PSK3, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){ + if ( PSKDemod(conn, "0 0 6", false)) { + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); + if (test(conn, DEMOD_PSK3, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){ tests[hits].modulation = DEMOD_PSK3; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + tests[hits].block0 = PackBits(tests[hits].offset, 32, conn->DemodBuffer); tests[hits].ST = false; ++hits; } } // inverse waves does not affect this demod //undo trim samples - save_restoreGB(GRAPH_RESTORE); + save_restoreGB(conn, GRAPH_RESTORE); } } if ( hits == 1) { @@ -733,33 +733,33 @@ int convertQ5bitRate(uint8_t bitRateRead) { return -1; } -bool testQ5(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk){ +bool testQ5(pm3_connection* conn, uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk){ - if ( DemodBufferLen < 64 ) return false; + if ( conn->DemodBufferLen < 64 ) return false; uint8_t si = 0; for (uint8_t idx = 28; idx < 64; idx++){ si = idx; - if ( PackBits(si, 28, DemodBuffer) == 0x00 ) continue; + if ( PackBits(si, 28, conn->DemodBuffer) == 0x00 ) continue; - uint8_t safer = PackBits(si, 4, DemodBuffer); si += 4; //master key - uint8_t resv = PackBits(si, 8, DemodBuffer); si += 8; + uint8_t safer = PackBits(si, 4, conn->DemodBuffer); si += 4; //master key + uint8_t resv = PackBits(si, 8, conn->DemodBuffer); si += 8; // 2nibble must be zeroed. if (safer != 0x6 && safer != 0x9) continue; if ( resv > 0x00) continue; - //uint8_t pageSel = PackBits(si, 1, DemodBuffer); si += 1; - //uint8_t fastWrite = PackBits(si, 1, DemodBuffer); si += 1; + //uint8_t pageSel = PackBits(si, 1, conn->DemodBuffer); si += 1; + //uint8_t fastWrite = PackBits(si, 1, conn->DemodBuffer); si += 1; si += 1+1; - int bitRate = PackBits(si, 6, DemodBuffer)*2 + 2; si += 6; //bit rate + int bitRate = PackBits(si, 6, conn->DemodBuffer)*2 + 2; si += 6; //bit rate if (bitRate > 128 || bitRate < 8) continue; - //uint8_t AOR = PackBits(si, 1, DemodBuffer); si += 1; - //uint8_t PWD = PackBits(si, 1, DemodBuffer); si += 1; - //uint8_t pskcr = PackBits(si, 2, DemodBuffer); si += 2; //could check psk cr - //uint8_t inverse = PackBits(si, 1, DemodBuffer); si += 1; + //uint8_t AOR = PackBits(si, 1, conn->DemodBuffer); si += 1; + //uint8_t PWD = PackBits(si, 1, conn->DemodBuffer); si += 1; + //uint8_t pskcr = PackBits(si, 2, conn->DemodBuffer); si += 2; //could check psk cr + //uint8_t inverse = PackBits(si, 1, conn->DemodBuffer); si += 1; si += 1+1+2+1; - uint8_t modread = PackBits(si, 3, DemodBuffer); si += 3; - uint8_t maxBlk = PackBits(si, 3, DemodBuffer); si += 3; - //uint8_t ST = PackBits(si, 1, DemodBuffer); si += 1; + uint8_t modread = PackBits(si, 3, conn->DemodBuffer); si += 3; + uint8_t maxBlk = PackBits(si, 3, conn->DemodBuffer); si += 3; + //uint8_t ST = PackBits(si, 1, conn->DemodBuffer); si += 1; if (maxBlk == 0) continue; //test modulation if (!testQ5Modulation(mode, modread)) continue; @@ -781,26 +781,26 @@ bool testBitRate(uint8_t readRate, uint8_t clk){ return false; } -bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5){ +bool test(pm3_connection* conn, uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5){ - if ( DemodBufferLen < 64 ) return false; + if ( conn->DemodBufferLen < 64 ) return false; uint8_t si = 0; for (uint8_t idx = 28; idx < 64; idx++){ si = idx; - if ( PackBits(si, 28, DemodBuffer) == 0x00 ) continue; + if ( PackBits(si, 28, conn->DemodBuffer) == 0x00 ) continue; - uint8_t safer = PackBits(si, 4, DemodBuffer); si += 4; //master key - uint8_t resv = PackBits(si, 4, DemodBuffer); si += 4; //was 7 & +=7+3 //should be only 4 bits if extended mode + uint8_t safer = PackBits(si, 4, conn->DemodBuffer); si += 4; //master key + uint8_t resv = PackBits(si, 4, conn->DemodBuffer); si += 4; //was 7 & +=7+3 //should be only 4 bits if extended mode // 2nibble must be zeroed. // moved test to here, since this gets most faults first. if ( resv > 0x00) continue; - int bitRate = PackBits(si, 6, DemodBuffer); si += 6; //bit rate (includes extended mode part of rate) - uint8_t extend = PackBits(si, 1, DemodBuffer); si += 1; //bit 15 extended mode - uint8_t modread = PackBits(si, 5, DemodBuffer); si += 5+2+1; - //uint8_t pskcr = PackBits(si, 2, DemodBuffer); si += 2+1; //could check psk cr - //uint8_t nml01 = PackBits(si, 1, DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode - //uint8_t nml02 = PackBits(si, 2, DemodBuffer); si += 2; + int bitRate = PackBits(si, 6, conn->DemodBuffer); si += 6; //bit rate (includes extended mode part of rate) + uint8_t extend = PackBits(si, 1, conn->DemodBuffer); si += 1; //bit 15 extended mode + uint8_t modread = PackBits(si, 5, conn->DemodBuffer); si += 5+2+1; + //uint8_t pskcr = PackBits(si, 2, conn->DemodBuffer); si += 2+1; //could check psk cr + //uint8_t nml01 = PackBits(si, 1, conn->DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode + //uint8_t nml02 = PackBits(si, 2, conn->DemodBuffer); si += 2; //if extended mode bool extMode =( (safer == 0x6 || safer == 0x9) && extend) ? true : false; @@ -819,36 +819,36 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5) *Q5 = false; return true; } - if (testQ5(mode, offset, fndBitRate, clk)) { + if (testQ5(conn, mode, offset, fndBitRate, clk)) { *Q5 = true; return true; } return false; } -void printT55xxBlock(const char *blockNum){ +void printT55xxBlock(pm3_connection* conn, const char *blockNum){ uint8_t i = config.offset; uint8_t endpos = 32 + i; uint32_t blockData = 0; uint8_t bits[64] = {0x00}; - if ( !DemodBufferLen) return; + if ( !conn->DemodBufferLen) return; - if ( endpos > DemodBufferLen){ - PrintAndLog("The configured offset %d is too big. Possible offset: %d)", i, DemodBufferLen-32); + if ( endpos > conn->DemodBufferLen){ + PrintAndLog("The configured offset %d is too big. Possible offset: %d)", i, conn->DemodBufferLen-32); return; } for (; i < endpos; ++i) - bits[i - config.offset]=DemodBuffer[i]; + bits[i - config.offset]=conn->DemodBuffer[i]; blockData = PackBits(0, 32, bits); PrintAndLog(" %s | %08X | %s", blockNum, blockData, sprint_bin(bits,32)); } -int special(const char *Cmd) { +int special(pm3_connection* conn, const char *Cmd) { uint32_t blockData = 0; uint8_t bits[32] = {0x00}; @@ -858,7 +858,7 @@ int special(const char *Cmd) { for (; j < 64; ++j){ for (i = 0; i < 32; ++i) - bits[i]=DemodBuffer[j+i]; + bits[i]=conn->DemodBuffer[j+i]; blockData = PackBits(0, 32, bits); @@ -879,7 +879,7 @@ int printConfiguration( t55xx_conf_block_t b){ return 0; } -int CmdT55xxWakeUp(const char *Cmd) { +int CmdT55xxWakeUp(pm3_connection* conn, const char *Cmd) { uint32_t password = 0; if ( strlen(Cmd) <= 0 ) return usage_t55xx_wakup(); char cmdp = param_getchar(Cmd, 0); @@ -888,13 +888,13 @@ int CmdT55xxWakeUp(const char *Cmd) { password = param_get32ex(Cmd, 0, 0, 16); UsbCommand c = {CMD_T55XX_WAKEUP, {password, 0, 0}}; - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); PrintAndLog("Wake up command sent. Try read now"); return 0; } -int CmdT55xxWriteBlock(const char *Cmd) { +int CmdT55xxWriteBlock(pm3_connection* conn, const char *Cmd) { uint8_t block = 0xFF; //default to invalid block uint32_t data = 0; //default to blank Block uint32_t password = 0; //default to blank Block 7 @@ -963,16 +963,16 @@ int CmdT55xxWriteBlock(const char *Cmd) { c.arg[2] = password; c.d.asBytes[0] |= 0x1; } - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)){ PrintAndLog("Error occurred, device did not ACK write operation. (May be due to old firmware)"); return 0; } return 1; } -int CmdT55xxReadTrace(const char *Cmd) { +int CmdT55xxReadTrace(pm3_connection* conn, const char *Cmd) { char cmdp = param_getchar(Cmd, 0); bool pwdmode = false; uint32_t password = 0; @@ -980,26 +980,26 @@ int CmdT55xxReadTrace(const char *Cmd) { return usage_t55xx_trace(); if (strlen(Cmd)==0) - if ( !AquireData( T55x7_PAGE1, REGULAR_READ_MODE_BLOCK, pwdmode, password ) ) + if ( !AcquireData(conn, T55x7_PAGE1, REGULAR_READ_MODE_BLOCK, pwdmode, password ) ) return 0; if ( config.Q5 ) { - if (!DecodeT5555TraceBlock()) return 0; + if (!DecodeT5555TraceBlock(conn)) return 0; } else { - if (!DecodeT55xxBlock()) return 0; + if (!DecodeT55xxBlock(conn)) return 0; } - if ( !DemodBufferLen ) return 0; + if ( !conn->DemodBufferLen ) return 0; - RepaintGraphWindow(); + RepaintGraphWindow(conn); uint8_t repeat = (config.offset > 5) ? 32 : 0; uint8_t si = config.offset+repeat; - uint32_t bl1 = PackBits(si, 32, DemodBuffer); - uint32_t bl2 = PackBits(si+32, 32, DemodBuffer); + uint32_t bl1 = PackBits(si, 32, conn->DemodBuffer); + uint32_t bl2 = PackBits(si+32, 32, conn->DemodBuffer); if (config.Q5) { - uint32_t hdr = PackBits(si, 9, DemodBuffer); si += 9; + uint32_t hdr = PackBits(si, 9, conn->DemodBuffer); si += 9; if (hdr != 0x1FF) { PrintAndLog("Invalid Q5 Trace data header (expected 0x1FF, found %X)", hdr); @@ -1008,65 +1008,66 @@ int CmdT55xxReadTrace(const char *Cmd) { t5555_tracedata_t data = {.bl1 = bl1, .bl2 = bl2, .icr = 0, .lotidc = '?', .lotid = 0, .wafer = 0, .dw =0}; - data.icr = PackBits(si, 2, DemodBuffer); si += 2; - data.lotidc = 'Z' - PackBits(si, 2, DemodBuffer); si += 3; + data.icr = PackBits(si, 2, conn->DemodBuffer); si += 2; + data.lotidc = 'Z' - PackBits(si, 2, conn->DemodBuffer); si += 3; - data.lotid = PackBits(si, 4, DemodBuffer); si += 5; + data.lotid = PackBits(si, 4, conn->DemodBuffer); si += 5; data.lotid <<= 4; - data.lotid |= PackBits(si, 4, DemodBuffer); si += 5; + data.lotid |= PackBits(si, 4, conn->DemodBuffer); si += 5; data.lotid <<= 4; - data.lotid |= PackBits(si, 4, DemodBuffer); si += 5; + data.lotid |= PackBits(si, 4, conn->DemodBuffer); si += 5; data.lotid <<= 4; - data.lotid |= PackBits(si, 4, DemodBuffer); si += 5; + data.lotid |= PackBits(si, 4, conn->DemodBuffer); si += 5; data.lotid <<= 1; - data.lotid |= PackBits(si, 1, DemodBuffer); si += 1; + data.lotid |= PackBits(si, 1, conn->DemodBuffer); si += 1; - data.wafer = PackBits(si, 3, DemodBuffer); si += 4; + data.wafer = PackBits(si, 3, conn->DemodBuffer); si += 4; data.wafer <<= 2; - data.wafer |= PackBits(si, 2, DemodBuffer); si += 2; + data.wafer |= PackBits(si, 2, conn->DemodBuffer); si += 2; - data.dw = PackBits(si, 2, DemodBuffer); si += 3; + data.dw = PackBits(si, 2, conn->DemodBuffer); si += 3; data.dw <<= 4; - data.dw |= PackBits(si, 4, DemodBuffer); si += 5; + data.dw |= PackBits(si, 4, conn->DemodBuffer); si += 5; data.dw <<= 4; - data.dw |= PackBits(si, 4, DemodBuffer); si += 5; + data.dw |= PackBits(si, 4, conn->DemodBuffer); si += 5; data.dw <<= 4; - data.dw |= PackBits(si, 4, DemodBuffer); si += 5; + data.dw |= PackBits(si, 4, conn->DemodBuffer); si += 5; - printT5555Trace(data, repeat); + printT5555Trace(conn, data, repeat); } else { t55x7_tracedata_t data = {.bl1 = bl1, .bl2 = bl2, .acl = 0, .mfc = 0, .cid = 0, .year = 0, .quarter = 0, .icr = 0, .lotid = 0, .wafer = 0, .dw = 0}; - data.acl = PackBits(si, 8, DemodBuffer); si += 8; + data.acl = PackBits(si, 8, conn->DemodBuffer); si += 8; if ( data.acl != 0xE0 ) { PrintAndLog("The modulation is most likely wrong since the ACL is not 0xE0. "); return 0; } - data.mfc = PackBits(si, 8, DemodBuffer); si += 8; - data.cid = PackBits(si, 5, DemodBuffer); si += 5; - data.icr = PackBits(si, 3, DemodBuffer); si += 3; - data.year = PackBits(si, 4, DemodBuffer); si += 4; - data.quarter = PackBits(si, 2, DemodBuffer); si += 2; - data.lotid = PackBits(si, 14, DemodBuffer); si += 14; - data.wafer = PackBits(si, 5, DemodBuffer); si += 5; - data.dw = PackBits(si, 15, DemodBuffer); + data.mfc = PackBits(si, 8, conn->DemodBuffer); si += 8; + data.cid = PackBits(si, 5, conn->DemodBuffer); si += 5; + data.icr = PackBits(si, 3, conn->DemodBuffer); si += 3; + data.year = PackBits(si, 4, conn->DemodBuffer); si += 4; + data.quarter = PackBits(si, 2, conn->DemodBuffer); si += 2; + data.lotid = PackBits(si, 14, conn->DemodBuffer); si += 14; + data.wafer = PackBits(si, 5, conn->DemodBuffer); si += 5; + data.dw = PackBits(si, 15, conn->DemodBuffer); time_t t = time(NULL); struct tm tm = *localtime(&t); + // FIXME: this might break in the future. if ( data.year > tm.tm_year-110) data.year += 2000; else data.year += 2010; - printT55x7Trace(data, repeat); + printT55x7Trace(conn, data, repeat); } return 0; } -void printT55x7Trace( t55x7_tracedata_t data, uint8_t repeat ){ +void printT55x7Trace(pm3_connection* conn, t55x7_tracedata_t data, uint8_t repeat ){ PrintAndLog("-- T55x7 Trace Information ----------------------------------"); PrintAndLog("-------------------------------------------------------------"); PrintAndLog(" ACL Allocation class (ISO/IEC 15963-1) : 0x%02X (%d)", data.acl, data.acl); @@ -1080,8 +1081,8 @@ void printT55x7Trace( t55x7_tracedata_t data, uint8_t repeat ){ PrintAndLog(" Die Number : %d", data.dw); PrintAndLog("-------------------------------------------------------------"); PrintAndLog(" Raw Data - Page 1"); - PrintAndLog(" Block 1 : 0x%08X %s", data.bl1, sprint_bin(DemodBuffer+config.offset+repeat,32) ); - PrintAndLog(" Block 2 : 0x%08X %s", data.bl2, sprint_bin(DemodBuffer+config.offset+repeat+32,32) ); + PrintAndLog(" Block 1 : 0x%08X %s", data.bl1, sprint_bin(conn->DemodBuffer+config.offset+repeat,32) ); + PrintAndLog(" Block 2 : 0x%08X %s", data.bl2, sprint_bin(conn->DemodBuffer+config.offset+repeat+32,32) ); PrintAndLog("-------------------------------------------------------------"); /* @@ -1102,7 +1103,7 @@ void printT55x7Trace( t55x7_tracedata_t data, uint8_t repeat ){ */ } -void printT5555Trace( t5555_tracedata_t data, uint8_t repeat ){ +void printT5555Trace(pm3_connection* conn, t5555_tracedata_t data, uint8_t repeat ){ PrintAndLog("-- T5555 (Q5) Trace Information -----------------------------"); PrintAndLog("-------------------------------------------------------------"); PrintAndLog(" ICR IC Revision : %d", data.icr ); @@ -1111,8 +1112,8 @@ void printT5555Trace( t5555_tracedata_t data, uint8_t repeat ){ PrintAndLog(" Die Number : %d", data.dw); PrintAndLog("-------------------------------------------------------------"); PrintAndLog(" Raw Data - Page 1"); - PrintAndLog(" Block 1 : 0x%08X %s", data.bl1, sprint_bin(DemodBuffer+config.offset+repeat,32) ); - PrintAndLog(" Block 2 : 0x%08X %s", data.bl2, sprint_bin(DemodBuffer+config.offset+repeat+32,32) ); + PrintAndLog(" Block 1 : 0x%08X %s", data.bl1, sprint_bin(conn->DemodBuffer+config.offset+repeat,32) ); + PrintAndLog(" Block 2 : 0x%08X %s", data.bl2, sprint_bin(conn->DemodBuffer+config.offset+repeat+32,32) ); /* ** Q5 ** @@ -1130,7 +1131,7 @@ void printT5555Trace( t5555_tracedata_t data, uint8_t repeat ){ } //need to add Q5 info... -int CmdT55xxInfo(const char *Cmd){ +int CmdT55xxInfo(pm3_connection* conn, const char *Cmd){ /* Page 0 Block 0 Configuration data. Normal mode @@ -1144,31 +1145,31 @@ int CmdT55xxInfo(const char *Cmd){ return usage_t55xx_info(); if (strlen(Cmd)==0) - if ( !AquireData( T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, pwdmode, password ) ) + if ( !AcquireData(conn, T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, pwdmode, password ) ) return 1; - if (!DecodeT55xxBlock()) return 1; + if (!DecodeT55xxBlock(conn)) return 1; // too little space to start with - if ( DemodBufferLen < 32) return 1; + if ( conn->DemodBufferLen < 32) return 1; uint8_t si = config.offset; - uint32_t bl0 = PackBits(si, 32, DemodBuffer); + uint32_t bl0 = PackBits(si, 32, conn->DemodBuffer); - uint32_t safer = PackBits(si, 4, DemodBuffer); si += 4; - uint32_t resv = PackBits(si, 7, DemodBuffer); si += 7; - uint32_t dbr = PackBits(si, 3, DemodBuffer); si += 3; - uint32_t extend = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t datamod = PackBits(si, 5, DemodBuffer); si += 5; - uint32_t pskcf = PackBits(si, 2, DemodBuffer); si += 2; - uint32_t aor = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t otp = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t maxblk = PackBits(si, 3, DemodBuffer); si += 3; - uint32_t pwd = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t sst = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t fw = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t inv = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t por = PackBits(si, 1, DemodBuffer); si += 1; + uint32_t safer = PackBits(si, 4, conn->DemodBuffer); si += 4; + uint32_t resv = PackBits(si, 7, conn->DemodBuffer); si += 7; + uint32_t dbr = PackBits(si, 3, conn->DemodBuffer); si += 3; + uint32_t extend = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t datamod = PackBits(si, 5, conn->DemodBuffer); si += 5; + uint32_t pskcf = PackBits(si, 2, conn->DemodBuffer); si += 2; + uint32_t aor = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t otp = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t maxblk = PackBits(si, 3, conn->DemodBuffer); si += 3; + uint32_t pwd = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t sst = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t fw = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t inv = PackBits(si, 1, conn->DemodBuffer); si += 1; + uint32_t por = PackBits(si, 1, conn->DemodBuffer); si += 1; if (config.Q5) PrintAndLog("*** Warning *** Config Info read off a Q5 will not display as expected"); PrintAndLog(""); @@ -1190,13 +1191,13 @@ int CmdT55xxInfo(const char *Cmd){ PrintAndLog(" POR-Delay : %s", (por) ? "Yes":"No"); PrintAndLog("-------------------------------------------------------------"); PrintAndLog(" Raw Data - Page 0"); - PrintAndLog(" Block 0 : 0x%08X %s", bl0, sprint_bin(DemodBuffer+config.offset,32) ); + PrintAndLog(" Block 0 : 0x%08X %s", bl0, sprint_bin(conn->DemodBuffer+config.offset,32) ); PrintAndLog("-------------------------------------------------------------"); return 0; } -int CmdT55xxDump(const char *Cmd){ +int CmdT55xxDump(pm3_connection* conn, const char *Cmd){ uint32_t password = 0; char cmdp = param_getchar(Cmd, 0); @@ -1212,29 +1213,29 @@ int CmdT55xxDump(const char *Cmd){ printT5xxHeader(0); for ( uint8_t i = 0; i <8; ++i) - T55xxReadBlock(i, 0, usepwd, override, password); + T55xxReadBlock(conn, i, 0, usepwd, override, password); printT5xxHeader(1); for ( uint8_t i = 0; i<4; i++) - T55xxReadBlock(i, 1, usepwd, override, password); + T55xxReadBlock(conn, i, 1, usepwd, override, password); return 1; } -int AquireData( uint8_t page, uint8_t block, bool pwdmode, uint32_t password ){ +int AcquireData(pm3_connection* conn, uint8_t page, uint8_t block, bool pwdmode, uint32_t password ){ // arg0 bitmodes: // bit0 = pwdmode // bit1 = page to read from uint8_t arg0 = (page<<1) | pwdmode; UsbCommand c = {CMD_T55XX_READ_BLOCK, {arg0, block, password}}; - clearCommandBuffer(); - SendCommand(&c); - if ( !WaitForResponseTimeout(CMD_ACK,NULL,2500) ) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if ( !WaitForResponseTimeout(conn, CMD_ACK, NULL, 2500) ) { PrintAndLog("command execution time out"); return 0; } - getSamples(12000,true); + getSamples(conn, 12000, true); return 1; } @@ -1344,24 +1345,24 @@ uint32_t PackBits(uint8_t start, uint8_t len, uint8_t* bits){ return tmp; } -int CmdResetRead(const char *Cmd) { +int CmdResetRead(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_T55XX_RESET_READ, {0,0,0}}; - clearCommandBuffer(); - SendCommand(&c); - if ( !WaitForResponseTimeout(CMD_ACK,NULL,2500) ) { + clearCommandBuffer(conn); + SendCommand(conn, &c); + if ( !WaitForResponseTimeout(conn, CMD_ACK,NULL,2500) ) { PrintAndLog("command execution time out"); return 0; } uint8_t got[BIGBUF_SIZE-1]; - GetFromBigBuf(got,sizeof(got),0); - WaitForResponse(CMD_ACK,NULL); - setGraphBuf(got, sizeof(got)); + GetFromBigBuf(conn, got,sizeof(got),0); + WaitForResponse(conn, CMD_ACK,NULL); + setGraphBuf(conn, got, sizeof(got)); return 1; } -int CmdT55xxWipe(const char *Cmd) { +int CmdT55xxWipe(pm3_connection* conn, const char *Cmd) { char writeData[20] = {0}; char *ptrData = writeData; @@ -1380,11 +1381,11 @@ int CmdT55xxWipe(const char *Cmd) { snprintf(ptrData,sizeof(writeData),"b 0 d 00088040 p 0"); } - if (!CmdT55xxWriteBlock(ptrData)) PrintAndLog("Error writing blk 0"); + if (!CmdT55xxWriteBlock(conn, ptrData)) PrintAndLog("Error writing blk 0"); for (uint8_t blk = 1; blk<8; blk++) { snprintf(ptrData,sizeof(writeData),"b %d d 0", blk); - if (!CmdT55xxWriteBlock(ptrData)) + if (!CmdT55xxWriteBlock(conn, ptrData)) PrintAndLog("Error writing blk %d", blk); memset(writeData, 0x00, sizeof(writeData)); @@ -1392,7 +1393,7 @@ int CmdT55xxWipe(const char *Cmd) { return 0; } -int CmdT55xxBruteForce(const char *Cmd) { +int CmdT55xxBruteForce(pm3_connection* conn, const char *Cmd) { // load a default pwd file. char buf[9]; @@ -1481,13 +1482,13 @@ int CmdT55xxBruteForce(const char *Cmd) { PrintAndLog("Testing %08X", testpwd); - if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, testpwd)) { - PrintAndLog("Aquireing data from device failed. Quitting"); + if ( !AcquireData(conn, T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, testpwd)) { + PrintAndLog("Acquiring data from device failed. Quitting"); free(keyBlock); return 0; } - found = tryDetectModulation(); + found = tryDetectModulation(conn); if ( found ) { PrintAndLog("Found valid password: [%08X]", testpwd); @@ -1526,12 +1527,12 @@ int CmdT55xxBruteForce(const char *Cmd) { return 0; } - if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, i)) { - PrintAndLog("Aquireing data from device failed. Quitting"); + if (!AcquireData(conn, T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, i)) { + PrintAndLog("Acquiring data from device failed. Quitting"); free(keyBlock); return 0; } - found = tryDetectModulation(); + found = tryDetectModulation(conn); if (found) break; i++; @@ -1551,7 +1552,7 @@ int CmdT55xxBruteForce(const char *Cmd) { // note length of data returned is different for different chips. // some return all page 1 (64 bits) and others return just that block (32 bits) // unfortunately the 64 bits makes this more likely to get a false positive... -bool tryDetectP1(bool getData) { +bool tryDetectP1(pm3_connection* conn, bool getData) { uint8_t preamble[] = {1,1,1,0,0,0,0,0,0,0,0,1,0,1,0,1}; size_t startIdx = 0; uint8_t fc1 = 0, fc2 = 0, ans = 0; @@ -1559,50 +1560,50 @@ bool tryDetectP1(bool getData) { bool st = true; if ( getData ) { - if ( !AquireData(T55x7_PAGE1, 1, false, 0) ) + if ( !AcquireData(conn, T55x7_PAGE1, 1, false, 0) ) return false; } // try fsk clock detect. if successful it cannot be any other type of modulation... (in theory...) - ans = fskClocks(&fc1, &fc2, (uint8_t *)&clk, false, &firstClockEdge); + ans = fskClocks(conn, &fc1, &fc2, (uint8_t *)&clk, false, &firstClockEdge); if (ans && ((fc1==10 && fc2==8) || (fc1==8 && fc2==5))) { - if ( FSKrawDemod("0 0", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( FSKrawDemod(conn, "0 0", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } - if ( FSKrawDemod("0 1", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( FSKrawDemod(conn, "0 1", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } return false; } // try psk clock detect. if successful it cannot be any other type of modulation... (in theory...) - clk = GetPskClock("", false, false); + clk = GetPskClock(conn, "", false, false); if (clk>0) { // allow undo // save_restoreGB(1); // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) //CmdLtrim("160"); - if ( PSKDemod("0 0 6", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( PSKDemod(conn, "0 0 6", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { //save_restoreGB(0); return true; } - if ( PSKDemod("0 1 6", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( PSKDemod(conn, "0 1 6", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { //save_restoreGB(0); return true; } // PSK2 - needs a call to psk1TOpsk2. - if ( PSKDemod("0 0 6", false)) { - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( PSKDemod(conn, "0 0 6", false)) { + psk1TOpsk2(conn->DemodBuffer, conn->DemodBufferLen); + if (preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { //save_restoreGB(0); return true; } @@ -1614,49 +1615,49 @@ bool tryDetectP1(bool getData) { } // try ask clock detect. it could be another type even if successful. - clk = GetAskClock("", false, false); + clk = GetAskClock(conn, "", false, false); if (clk>0) { - if ( ASKDemod_ext("0 0 1", false, false, 1, &st) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( ASKDemod_ext(conn, "0 0 1", false, false, 1, &st) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } st = true; - if ( ASKDemod_ext("0 1 1", false, false, 1, &st) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( ASKDemod_ext(conn, "0 1 1", false, false, 1, &st) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } - if ( ASKbiphaseDemod("0 0 0 2", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( ASKbiphaseDemod(conn, "0 0 0 2", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } - if ( ASKbiphaseDemod("0 0 1 2", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( ASKbiphaseDemod(conn, "0 0 1 2", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } } // try NRZ clock detect. it could be another type even if successful. - clk = GetNrzClock("", false, false); //has the most false positives :( + clk = GetNrzClock(conn, "", false, false); //has the most false positives :( if (clk>0) { - if ( NRZrawDemod("0 0 1", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( NRZrawDemod(conn, "0 0 1", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } - if ( NRZrawDemod("0 1 1", false) && - preambleSearchEx(DemodBuffer,preamble,sizeof(preamble),&DemodBufferLen,&startIdx,false) && - (DemodBufferLen == 32 || DemodBufferLen == 64) ) { + if ( NRZrawDemod(conn, "0 1 1", false) && + preambleSearchEx(conn->DemodBuffer,preamble,sizeof(preamble),&conn->DemodBufferLen,&startIdx,false) && + (conn->DemodBufferLen == 32 || conn->DemodBufferLen == 64) ) { return true; } } return false; } // does this need to be a callable command? -int CmdT55xxDetectPage1(const char *Cmd){ +int CmdT55xxDetectPage1(pm3_connection* conn, const char *Cmd){ bool errors = false; bool useGB = false; bool usepwd = false; @@ -1688,10 +1689,10 @@ int CmdT55xxDetectPage1(const char *Cmd){ if (errors) return usage_t55xx_detectP1(); if ( !useGB ) { - if ( !AquireData(T55x7_PAGE1, 1, usepwd, password) ) + if ( !AcquireData(conn, T55x7_PAGE1, 1, usepwd, password) ) return false; } - bool success = tryDetectP1(false); + bool success = tryDetectP1(conn, false); if (success) PrintAndLog("T55xx chip found!"); return success; } @@ -1714,12 +1715,12 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFT55XX(const char *Cmd) { - CmdsParse(CommandTable, Cmd); +int CmdLFT55XX(pm3_connection* conn, const char *Cmd) { + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlft55xx.h b/client/cmdlft55xx.h index 4f0fd21d..638e94d4 100644 --- a/client/cmdlft55xx.h +++ b/client/cmdlft55xx.h @@ -10,6 +10,8 @@ #ifndef CMDLFT55XX_H__ #define CMDLFT55XX_H__ +#include "comms.h" + typedef struct { uint32_t bl1; uint32_t bl2; @@ -69,16 +71,16 @@ typedef struct { t55xx_conf_block_t Get_t55xx_Config(void); void Set_t55xx_Config(t55xx_conf_block_t conf); -extern int CmdLFT55XX(const char *Cmd); -extern int CmdT55xxBruteForce(const char *Cmd); -extern int CmdT55xxSetConfig(const char *Cmd); -extern int CmdT55xxReadBlock(const char *Cmd); -extern int CmdT55xxWriteBlock(const char *Cmd); -extern int CmdT55xxReadTrace(const char *Cmd); -extern int CmdT55xxInfo(const char *Cmd); -extern int CmdT55xxDetect(const char *Cmd); -extern int CmdResetRead(const char *Cmd); -extern int CmdT55xxWipe(const char *Cmd); +extern int CmdLFT55XX(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxBruteForce(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxSetConfig(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxReadBlock(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxWriteBlock(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxReadTrace(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxInfo(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxDetect(pm3_connection* conn, const char *Cmd); +extern int CmdResetRead(pm3_connection* conn, const char *Cmd); +extern int CmdT55xxWipe(pm3_connection* conn, const char *Cmd); char * GetBitRateStr(uint32_t id, bool xmode); char * GetSaferStr(uint32_t id); @@ -87,17 +89,17 @@ char * GetModelStrFromCID(uint32_t cid); char * GetSelectedModulationStr( uint8_t id); uint32_t PackBits(uint8_t start, uint8_t len, uint8_t *bitstream); void printT5xxHeader(uint8_t page); -void printT55xxBlock(const char *demodStr); +void printT55xxBlock(pm3_connection* conn, const char *demodStr); int printConfiguration( t55xx_conf_block_t b); -bool DecodeT55xxBlock(void); -bool tryDetectModulation(void); -extern bool tryDetectP1(bool getData); -bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5); -int special(const char *Cmd); -int AquireData( uint8_t page, uint8_t block, bool pwdmode, uint32_t password ); +bool DecodeT55xxBlock(pm3_connection* conn); +bool tryDetectModulation(pm3_connection* conn); +extern bool tryDetectP1(pm3_connection* conn, bool getData); +bool test(pm3_connection* conn, uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5); +int special(pm3_connection* conn, const char *Cmd); +int AcquireData(pm3_connection* conn, uint8_t page, uint8_t block, bool pwdmode, uint32_t password ); -void printT55x7Trace( t55x7_tracedata_t data, uint8_t repeat ); -void printT5555Trace( t5555_tracedata_t data, uint8_t repeat ); +void printT55x7Trace(pm3_connection* conn, t55x7_tracedata_t data, uint8_t repeat ); +void printT5555Trace(pm3_connection* conn, t5555_tracedata_t data, uint8_t repeat ); #endif diff --git a/client/cmdlfti.c b/client/cmdlfti.c index 5dae9c0e..47f6171d 100644 --- a/client/cmdlfti.c +++ b/client/cmdlfti.c @@ -19,9 +19,9 @@ #include "cmdparser.h" #include "cmdlfti.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); -int CmdTIDemod(const char *Cmd) +int CmdTIDemod(pm3_connection* conn, const char *Cmd) { /* MATLAB as follows: f_s = 2000000; % sampling frequency @@ -85,40 +85,40 @@ int CmdTIDemod(const char *Cmd) int lowSum = 0, highSum = 0;; int lowTot = 0, highTot = 0; - for (i = 0; i < GraphTraceLen - convLen; i++) { + for (i = 0; i < conn->GraphTraceLen - convLen; i++) { lowSum = 0; highSum = 0;; for (j = 0; j < lowLen; j++) { - lowSum += LowTone[j]*GraphBuffer[i+j]; + lowSum += LowTone[j]*conn->GraphBuffer[i+j]; } for (j = 0; j < highLen; j++) { - highSum += HighTone[j]*GraphBuffer[i+j]; + highSum += HighTone[j]*conn->GraphBuffer[i+j]; } lowSum = abs((100*lowSum) / lowLen); highSum = abs((100*highSum) / highLen); lowSum = (lowSum<0)?-lowSum:lowSum; highSum = (highSum<0)?-highSum:highSum; - GraphBuffer[i] = (highSum << 16) | lowSum; + conn->GraphBuffer[i] = (highSum << 16) | lowSum; } - for (i = 0; i < GraphTraceLen - convLen - 16; i++) { + for (i = 0; i < conn->GraphTraceLen - convLen - 16; i++) { lowTot = 0; highTot = 0; // 16 and 15 are f_s divided by f_l and f_h, rounded for (j = 0; j < 16; j++) { - lowTot += (GraphBuffer[i+j] & 0xffff); + lowTot += (conn->GraphBuffer[i+j] & 0xffff); } for (j = 0; j < 15; j++) { - highTot += (GraphBuffer[i+j] >> 16); + highTot += (conn->GraphBuffer[i+j] >> 16); } - GraphBuffer[i] = lowTot - highTot; + conn->GraphBuffer[i] = lowTot - highTot; } - GraphTraceLen -= (convLen + 16); + conn->GraphTraceLen -= (convLen + 16); - RepaintGraphWindow(); + RepaintGraphWindow(conn); // TI tag data format is 16 prebits, 8 start bits, 64 data bits, // 16 crc CCITT bits, 8 stop bits, 15 end bits @@ -139,11 +139,11 @@ int CmdTIDemod(const char *Cmd) int dec = 0; // searching 17 consecutive lows for (j = 0; j < 17*lowLen; j++) { - dec -= GraphBuffer[i+j]; + dec -= conn->GraphBuffer[i+j]; } // searching 7 consecutive highs for (; j < 17*lowLen + 6*highLen; j++) { - dec += GraphBuffer[i+j]; + dec += conn->GraphBuffer[i+j]; } if (dec > max) { max = dec; @@ -153,8 +153,8 @@ int CmdTIDemod(const char *Cmd) // place a marker in the buffer to visually aid location // of the start of sync - GraphBuffer[maxPos] = 800; - GraphBuffer[maxPos+1] = -800; + conn->GraphBuffer[maxPos] = 800; + conn->GraphBuffer[maxPos+1] = -800; // advance pointer to start of actual data stream (after 16 pre and 8 start bits) maxPos += 17*lowLen; @@ -162,8 +162,8 @@ int CmdTIDemod(const char *Cmd) // place a marker in the buffer to visually aid location // of the end of sync - GraphBuffer[maxPos] = 800; - GraphBuffer[maxPos+1] = -800; + conn->GraphBuffer[maxPos] = 800; + conn->GraphBuffer[maxPos+1] = -800; PrintAndLog("actual data bits start at sample %d", maxPos); @@ -179,10 +179,10 @@ int CmdTIDemod(const char *Cmd) int low = 0; int j; for (j = 0; j < lowLen; j++) { - low -= GraphBuffer[maxPos+j]; + low -= conn->GraphBuffer[maxPos+j]; } for (j = 0; j < highLen; j++) { - high += GraphBuffer[maxPos+j]; + high += conn->GraphBuffer[maxPos+j]; } if (high > low) { @@ -202,8 +202,8 @@ int CmdTIDemod(const char *Cmd) shift3 >>= 1; // place a marker in the buffer between bits to visually aid location - GraphBuffer[maxPos] = 800; - GraphBuffer[maxPos+1] = -800; + conn->GraphBuffer[maxPos] = 800; + conn->GraphBuffer[maxPos+1] = -800; } PrintAndLog("Info: raw tag bits = %s", bits); @@ -261,15 +261,15 @@ int CmdTIDemod(const char *Cmd) } // read a TI tag and return its ID -int CmdTIRead(const char *Cmd) +int CmdTIRead(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_READ_TI_TYPE}; - SendCommand(&c); + SendCommand(conn, &c); return 0; } // write new data to a r/w TI tag -int CmdTIWrite(const char *Cmd) +int CmdTIWrite(pm3_connection* conn, const char *Cmd) { UsbCommand c = {CMD_WRITE_TI_TYPE}; int res = 0; @@ -280,7 +280,7 @@ int CmdTIWrite(const char *Cmd) if (res < 2) PrintAndLog("Please specify the data as two hex strings, optionally the CRC as a third"); else - SendCommand(&c); + SendCommand(conn, &c); return 0; } @@ -293,14 +293,14 @@ static command_t CommandTable[] = {NULL, NULL, 0, NULL} }; -int CmdLFTI(const char *Cmd) +int CmdLFTI(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfti.h b/client/cmdlfti.h index e4bbc3a0..274cce53 100644 --- a/client/cmdlfti.h +++ b/client/cmdlfti.h @@ -11,10 +11,12 @@ #ifndef CMDLFTI_H__ #define CMDLFTI_H__ -int CmdLFTI(const char *Cmd); +#include "comms.h" -int CmdTIDemod(const char *Cmd); -int CmdTIRead(const char *Cmd); -int CmdTIWrite(const char *Cmd); +int CmdLFTI(pm3_connection* conn, const char *Cmd); + +int CmdTIDemod(pm3_connection* conn, const char *Cmd); +int CmdTIRead(pm3_connection* conn, const char *Cmd); +int CmdTIWrite(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfviking.c b/client/cmdlfviking.c index 779156c8..5f643ab6 100644 --- a/client/cmdlfviking.c +++ b/client/cmdlfviking.c @@ -20,7 +20,7 @@ #include "cmdmain.h" #include "cmdlf.h" #include "lfdemod.h" -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_viking_clone(void) { PrintAndLog("clone a Viking AM tag to a T55x7 tag."); @@ -54,40 +54,40 @@ uint64_t getVikingBits(uint32_t id) { //by marshmellow //see ASKDemod for what args are accepted -int CmdVikingDemod(const char *Cmd) { - if (!ASKDemod(Cmd, false, false, 1)) { +int CmdVikingDemod(pm3_connection* conn, const char *Cmd) { + if (!ASKDemod(conn, Cmd, false, false, 1)) { if (g_debugMode) PrintAndLog("ASKDemod failed"); return 0; } - size_t size = DemodBufferLen; + size_t size = conn->DemodBufferLen; //call lfdemod.c demod for Viking - int ans = VikingDemod_AM(DemodBuffer, &size); + int ans = VikingDemod_AM(conn->DemodBuffer, &size); if (ans < 0) { if (g_debugMode) PrintAndLog("Error Viking_Demod %d", ans); return 0; } //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer+ans, 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+ans+32, 32); - uint32_t cardid = bytebits_to_byte(DemodBuffer+ans+24, 32); - uint8_t checksum = bytebits_to_byte(DemodBuffer+ans+32+24, 8); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer+ans, 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+ans+32, 32); + uint32_t cardid = bytebits_to_byte(conn->DemodBuffer+ans+24, 32); + uint8_t checksum = bytebits_to_byte(conn->DemodBuffer+ans+32+24, 8); PrintAndLog("Viking Tag Found: Card ID %08X, Checksum: %02X", cardid, (unsigned int) checksum); PrintAndLog("Raw: %08X%08X", raw1,raw2); - setDemodBuf(DemodBuffer, 64, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 64, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); return 1; } //by marshmellow //see ASKDemod for what args are accepted -int CmdVikingRead(const char *Cmd) { +int CmdVikingRead(pm3_connection* conn, const char *Cmd) { // read lf silently - lf_read(true, 10000); + lf_read(conn, true, 10000); // demod and output viking ID - return CmdVikingDemod(Cmd); + return CmdVikingDemod(conn, Cmd); } -int CmdVikingClone(const char *Cmd) { +int CmdVikingClone(pm3_connection* conn, const char *Cmd) { uint32_t id = 0; uint64_t rawID = 0; bool Q5 = false; @@ -102,14 +102,14 @@ int CmdVikingClone(const char *Cmd) { rawID = getVikingBits(id); PrintAndLog("Cloning - 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(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); //check for ACK - WaitForResponse(CMD_ACK,NULL); + WaitForResponse(conn, CMD_ACK,NULL); return 0; } -int CmdVikingSim(const char *Cmd) { +int CmdVikingSim(pm3_connection* conn, const char *Cmd) { uint32_t id = 0; uint64_t rawID = 0; uint8_t clk = 32, encoding = 1, separator = 0, invert = 0; @@ -129,8 +129,8 @@ int CmdVikingSim(const char *Cmd) { UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; PrintAndLog("preparing to sim ask data: %d bits", size); num_to_bytebits(rawID, 64, c.d.asBytes); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -143,12 +143,12 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFViking(const char *Cmd) { - CmdsParse(CommandTable, Cmd); +int CmdLFViking(pm3_connection* conn, const char *Cmd) { + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfviking.h b/client/cmdlfviking.h index a45dd9a8..b69b5a90 100644 --- a/client/cmdlfviking.h +++ b/client/cmdlfviking.h @@ -8,9 +8,12 @@ //----------------------------------------------------------------------------- #ifndef CMDLFVIKING_H__ #define CMDLFVIKING_H__ -extern int CmdLFViking(const char *Cmd); -extern int CmdVikingDemod(const char *Cmd); -extern int CmdVikingRead(const char *Cmd); -extern int CmdVikingClone(const char *Cmd); -extern int CmdVikingSim(const char *Cmd); + +#include "comms.h" + +extern int CmdLFViking(pm3_connection* conn, const char *Cmd); +extern int CmdVikingDemod(pm3_connection* conn, const char *Cmd); +extern int CmdVikingRead(pm3_connection* conn, const char *Cmd); +extern int CmdVikingClone(pm3_connection* conn, const char *Cmd); +extern int CmdVikingSim(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdlfvisa2000.c b/client/cmdlfvisa2000.c index 04589ba5..e5f064a1 100644 --- a/client/cmdlfvisa2000.c +++ b/client/cmdlfvisa2000.c @@ -17,7 +17,7 @@ #include "ui.h" #include "util.h" #include "graph.h" -#include "cmddata.h" // for ASKDemod_ext, g_debugMode, DemodBuffer ... +#include "cmddata.h" // for ASKDemod_ext, g_debugMode, conn->DemodBuffer ... #include "cmdmain.h" // for clearCommandBuffer and WaitForResponseTimeout #include "cmdlf.h" #include "protocols.h" // for T55xx config register definitions @@ -25,7 +25,7 @@ #define BL0CK1 0x56495332 -static int CmdHelp(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); int usage_lf_visa2k_clone(void){ PrintAndLog("clone a Visa2000 tag to a T55x7 tag."); @@ -93,18 +93,18 @@ static uint8_t visa_parity( uint32_t id) { * **/ //see ASKDemod for what args are accepted -int CmdVisa2kDemod(const char *Cmd) { +int CmdVisa2kDemod(pm3_connection* conn, const char *Cmd) { //sCmdAskEdgeDetect(""); //ASK / Manchester bool st = true; - if (!ASKDemod_ext("64 0 0", false, false, 1, &st)) { - if (g_debugMode) PrintAndLog("DEBUG: Error - Visa2000: ASK/Manchester Demod failed"); + if (!ASKDemod_ext(conn, "64 0 0", false, false, 1, &st)) { + if (g_debugMode) PrintAndLog("DEBUG: Error - Visa2k: ASK/Manchester Demod failed"); return 0; } - size_t size = DemodBufferLen; - int ans = Visa2kDemod_AM(DemodBuffer, &size); + size_t size = conn->DemodBufferLen; + int ans = Visa2kDemod_AM(conn->DemodBuffer, &size); if (ans < 0){ if (g_debugMode){ if (ans == -1) @@ -118,13 +118,13 @@ int CmdVisa2kDemod(const char *Cmd) { } return 0; } - setDemodBuf(DemodBuffer, 96, ans); - setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); + setDemodBuf(conn, conn->DemodBuffer, 96, ans); + setClockGrid(conn, conn->g_DemodClock, conn->g_DemodStartIdx + (ans*conn->g_DemodClock)); //got a good demod - uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); - uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); - uint32_t raw3 = bytebits_to_byte(DemodBuffer+64, 32); + uint32_t raw1 = bytebits_to_byte(conn->DemodBuffer, 32); + uint32_t raw2 = bytebits_to_byte(conn->DemodBuffer+32, 32); + uint32_t raw3 = bytebits_to_byte(conn->DemodBuffer+64, 32); // chksum uint8_t calc = visa_chksum(raw2); @@ -146,13 +146,13 @@ int CmdVisa2kDemod(const char *Cmd) { return 1; } -int CmdVisa2kRead(const char *Cmd) { +int CmdVisa2kRead(pm3_connection* conn, const char *Cmd) { //64*96*2=12288 samples just in case we just missed the first preamble we can still catch 2 of them - lf_read(true, 12500); - return CmdVisa2kDemod(Cmd); + lf_read(conn, true, 12500); + return CmdVisa2kDemod(conn, Cmd); } -int CmdVisa2kClone(const char *Cmd) { +int CmdVisa2kClone(pm3_connection* conn, 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}; @@ -183,9 +183,9 @@ int CmdVisa2kClone(const char *Cmd) { for (int i = 3; i >= 0; --i) { c.arg[0] = blocks[i]; c.arg[1] = i; - clearCommandBuffer(); - SendCommand(&c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){ + clearCommandBuffer(conn); + SendCommand(conn, &c); + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, T55XX_WRITE_TIMEOUT)){ PrintAndLog("Error occurred, device did not respond during write operation."); return -1; } @@ -193,7 +193,7 @@ int CmdVisa2kClone(const char *Cmd) { return 0; } -int CmdVisa2kSim(const char *Cmd) { +int CmdVisa2kSim(pm3_connection* conn, const char *Cmd) { uint32_t id = 0; char cmdp = param_getchar(Cmd, 0); @@ -216,8 +216,8 @@ int CmdVisa2kSim(const char *Cmd) { for(int i=0; i<3; ++i) num_to_bytebits(blocks[i], 32, c.d.asBytes + i*32); - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); return 0; } @@ -230,13 +230,13 @@ static command_t CommandTable[] = { {NULL, NULL, 0, NULL} }; -int CmdLFVisa2k(const char *Cmd) { - clearCommandBuffer(); - CmdsParse(CommandTable, Cmd); +int CmdLFVisa2k(pm3_connection* conn, const char *Cmd) { + clearCommandBuffer(conn); + CmdsParse(conn, CommandTable, Cmd); return 0; } -int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); +int CmdHelp(pm3_connection* conn, const char *Cmd) { + CmdsHelp(conn, CommandTable); return 0; } diff --git a/client/cmdlfvisa2000.h b/client/cmdlfvisa2000.h index e54ded3b..93f6e089 100644 --- a/client/cmdlfvisa2000.h +++ b/client/cmdlfvisa2000.h @@ -8,12 +8,15 @@ //----------------------------------------------------------------------------- #ifndef CMDLFVISA2000_H__ #define CMDLFVISA2000_H__ + #include -extern int CmdLFVisa2k(const char *Cmd); -extern int CmdVisa2kClone(const char *Cmd); -extern int CmdVisa2kSim(const char *Cmd); -extern int CmdVisa2kRead(const char *Cmd); -extern int CmdVisa2kDemod(const char *Cmd); +#include "comms.h" + +extern int CmdLFVisa2k(pm3_connection* conn, const char *Cmd); +extern int CmdVisa2kClone(pm3_connection* conn, const char *Cmd); +extern int CmdVisa2kSim(pm3_connection* conn, const char *Cmd); +extern int CmdVisa2kRead(pm3_connection* conn, const char *Cmd); +extern int CmdVisa2kDemod(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/cmdmain.c b/client/cmdmain.c index 94174f99..aab0bf93 100644 --- a/client/cmdmain.c +++ b/client/cmdmain.c @@ -5,7 +5,8 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// Main command parser entry point +// This module handles the main entry point into the command parser for the +// proxmark3 CLI. //----------------------------------------------------------------------------- #include @@ -27,12 +28,9 @@ #include "cmdscript.h" #include "cmdcrc.h" - -unsigned int current_command = CMD_UNKNOWN; - -static int CmdHelp(const char *Cmd); -static int CmdQuit(const char *Cmd); -static int CmdRev(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); +static int CmdQuit(pm3_connection* conn, const char *Cmd); +static int CmdRev(pm3_connection* conn, const char *Cmd); static command_t CommandTable[] = { @@ -53,20 +51,20 @@ command_t* getTopLevelCommandTable() return CommandTable; } -int CmdHelp(const char *Cmd) +int CmdHelp(pm3_connection* conn, const char *Cmd) { - CmdsHelp(CommandTable); + CmdsHelp(conn, CommandTable); return 0; } -int CmdQuit(const char *Cmd) +int CmdQuit(pm3_connection* conn, const char *Cmd) { return 99; } -int CmdRev(const char *Cmd) +int CmdRev(pm3_connection* conn, const char *Cmd) { - CmdCrc(Cmd); + CmdCrc(conn, Cmd); return 0; } @@ -74,7 +72,7 @@ int CmdRev(const char *Cmd) // Entry point into our code: called whenever the user types a command and // then presses Enter, which the full command line that they typed. //----------------------------------------------------------------------------- -int CommandReceived(char *Cmd) { - return CmdsParse(CommandTable, Cmd); +int CommandReceived(pm3_connection* conn, char *Cmd) { + return CmdsParse(conn, CommandTable, Cmd); } diff --git a/client/cmdmain.h b/client/cmdmain.h index a833b41e..edca6636 100644 --- a/client/cmdmain.h +++ b/client/cmdmain.h @@ -17,8 +17,7 @@ #include "cmdparser.h" #include "comms.h" - -extern int CommandReceived(char *Cmd); +extern int CommandReceived(pm3_connection* conn, char *Cmd); extern command_t* getTopLevelCommandTable(); #endif diff --git a/client/cmdparser.c b/client/cmdparser.c index 28ca2196..89ab07ab 100644 --- a/client/cmdparser.c +++ b/client/cmdparser.c @@ -17,21 +17,21 @@ #include "comms.h" -void CmdsHelp(const command_t Commands[]) +void CmdsHelp(pm3_connection* conn, const command_t Commands[]) { if (Commands[0].Name == NULL) return; int i = 0; while (Commands[i].Name) { - if (!IsOffline() || Commands[i].Offline) + if (!(conn->offline) || Commands[i].Offline) PrintAndLog("%-16s %s", Commands[i].Name, Commands[i].Help); ++i; } } -int CmdsParse(const command_t Commands[], const char *Cmd) +int CmdsParse(pm3_connection* conn, const command_t Commands[], const char *Cmd) { if(strcmp( Cmd, "XX_internal_command_dump_XX") == 0) {// Help dump children @@ -68,10 +68,10 @@ int CmdsParse(const command_t Commands[], const char *Cmd) if (Commands[i].Name) { while (Cmd[len] == ' ') ++len; - return Commands[i].Parse(Cmd + len); + return Commands[i].Parse(conn, Cmd + len); } else { // show help for selected hierarchy or if command not recognised - CmdsHelp(Commands); + CmdsHelp(conn, Commands); } return 0; @@ -127,9 +127,9 @@ void dumpCommandsRecursive(const command_t cmds[], int markdown) // This is what causes the recursion, since commands Parse-implementation // in turn calls the CmdsParse above. if (markdown) - cmds[i].Parse("XX_internal_command_dump_markdown_XX"); + cmds[i].Parse(NULL, "XX_internal_command_dump_markdown_XX"); else - cmds[i].Parse("XX_internal_command_dump_XX"); + cmds[i].Parse(NULL, "XX_internal_command_dump_XX"); parent = old_parent; ++i; } diff --git a/client/cmdparser.h b/client/cmdparser.h index 5217d04b..dc84e40b 100644 --- a/client/cmdparser.h +++ b/client/cmdparser.h @@ -11,10 +11,12 @@ #ifndef CMDPARSER_H__ #define CMDPARSER_H__ +#include "comms.h" + typedef struct command_s { const char * Name; - int (*Parse)(const char *Cmd); + int (*Parse)(pm3_connection *conn, const char *Cmd); int Offline; const char * Help; } command_t; @@ -22,9 +24,9 @@ typedef struct command_s // command_t array are expected to be NULL terminated // Print help for each command in the command array -void CmdsHelp(const command_t Commands[]); +void CmdsHelp(pm3_connection* conn, const command_t Commands[]); // Parse a command line -int CmdsParse(const command_t Commands[], const char *Cmd); +int CmdsParse(pm3_connection* conn, const command_t Commands[], const char *Cmd); void dumpCommandsRecursive(const command_t cmds[], int markdown); #endif diff --git a/client/cmdscript.c b/client/cmdscript.c index 23163aa9..94b206ed 100644 --- a/client/cmdscript.c +++ b/client/cmdscript.c @@ -30,9 +30,9 @@ #include #include -static int CmdHelp(const char *Cmd); -static int CmdList(const char *Cmd); -static int CmdRun(const char *Cmd); +static int CmdHelp(pm3_connection* conn, const char *Cmd); +static int CmdList(pm3_connection* conn, const char *Cmd); +static int CmdRun(pm3_connection* conn, const char *Cmd); command_t CommandTable[] = { @@ -61,7 +61,7 @@ int str_ends_with(const char * str, const char * suffix) { * @param Cmd * @return */ -int CmdHelp(const char * Cmd) +int CmdHelp(pm3_connection* conn, const char * Cmd) { PrintAndLog("This is a feature to run Lua-scripts. You can place lua-scripts within the scripts/-folder. "); return 0; @@ -72,7 +72,7 @@ int CmdHelp(const char * Cmd) * generate a file listing of the script-directory for files * ending with .lua */ -int CmdList(const char *Cmd) +int CmdList(pm3_connection* conn, const char *Cmd) { DIR *dp; struct dirent *ep; @@ -100,9 +100,9 @@ int CmdList(const char *Cmd) * @param Cmd * @return */ -int CmdScript(const char *Cmd) +int CmdScript(pm3_connection* conn, const char *Cmd) { - CmdsParse(CommandTable, Cmd); + CmdsParse(conn, CommandTable, Cmd); return 0; } /** @@ -120,7 +120,7 @@ bool endsWith (char* base, char* str) { * @param argv * @return */ -int CmdRun(const char *Cmd) +int CmdRun(pm3_connection* conn, const char *Cmd) { // create new Lua state lua_State *lua_state; @@ -130,7 +130,7 @@ int CmdRun(const char *Cmd) luaL_openlibs(lua_state); //Sets the pm3 core libraries, that go a bit 'under the hood' - set_pm3_libraries(lua_state); + set_pm3_libraries(lua_state, conn); //Add the 'bin' library set_bin_library(lua_state); diff --git a/client/cmdscript.h b/client/cmdscript.h index 7bd7e9f8..bea66409 100644 --- a/client/cmdscript.h +++ b/client/cmdscript.h @@ -12,7 +12,8 @@ #ifndef CMDSCRIPT_H__ #define CMDSCRIPT_H__ +#include "comms.h" -int CmdScript(const char *Cmd); +int CmdScript(pm3_connection* conn, const char *Cmd); #endif diff --git a/client/comms.c b/client/comms.c index a1f85799..41414e92 100644 --- a/client/comms.c +++ b/client/comms.c @@ -14,61 +14,13 @@ #include "comms.h" #include "uart.h" #include "ui.h" -#include "common.h" -#include "data.h" -#include "util_posix.h" -// Declare globals. - -// Serial port that we are communicating with the PM3 on. -static serial_port* port; - -// If TRUE, then there is no active connection to the PM3, and we will drop commands sent. -static bool offline; - -// Transmit buffer. -// TODO: Use locks and execute this on the main thread, rather than the receiver -// thread. Running on the main thread means we need to be careful in the -// flasher, as it means SendCommand is no longer async, and can't be used as a -// buffer for a pending command when the connection is re-established. -static UsbCommand txcmd; -static bool txcmd_pending; - -// Used by UsbReceiveCommand as a ring buffer for messages that are yet to be -// processed by a command handler (WaitForResponse{,Timeout}) -static UsbCommand cmdBuffer[CMD_BUFFER_SIZE]; - -// Points to the next empty position to write to -static int cmd_head = 0; - -// Points to the position of the last unread command -static int cmd_tail = 0; - -// These wrappers are required because it is not possible to access a static -// global variable outside of the context of a single file. - -void SetSerialPort(serial_port* new_port) { - port = new_port; -} - -serial_port* GetSerialPort() { - return port; -} - -void SetOffline(bool new_offline) { - offline = new_offline; -} - -bool IsOffline() { - return offline; -} - -void SendCommand(UsbCommand *c) { +void SendCommand(pm3_connection *conn, UsbCommand *c) { #ifdef COMMS_DEBUG printf("Sending %04x cmd\n", c->cmd); #endif - if (offline) { + if (conn->offline) { PrintAndLog("Sending bytes to proxmark failed - offline"); return; } @@ -77,9 +29,9 @@ void SendCommand(UsbCommand *c) { or disconnected. The main console thread is alive, but comm thread just spins here. Not good.../holiman **/ - while(txcmd_pending); - txcmd = *c; - txcmd_pending = true; + while(conn->txcmd_pending); + conn->txcmd = *c; + conn->txcmd_pending = true; } /** @@ -88,48 +40,51 @@ void SendCommand(UsbCommand *c) { * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which * operation. Right now we'll just have to live with this. */ -void clearCommandBuffer() +void clearCommandBuffer(pm3_connection* conn) { + if (!conn) return; //This is a very simple operation - cmd_tail = cmd_head; + conn->cmd_tail = conn->cmd_head; } /** * @brief storeCommand stores a USB command in a circular buffer * @param UC */ -void storeCommand(UsbCommand *command) +void storeCommand(pm3_connection *conn, UsbCommand *command) { - if( (cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail) + if (!conn) return; + if( (conn->cmd_head+1) % CMD_BUFFER_SIZE == conn->cmd_tail) { //If these two are equal, we're about to overwrite in the // circular buffer. PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!"); } //Store the command at the 'head' location - UsbCommand* destination = &cmdBuffer[cmd_head]; + UsbCommand* destination = &conn->cmdBuffer[conn->cmd_head]; memcpy(destination, command, sizeof(UsbCommand)); - cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap + conn->cmd_head = (conn->cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap } /** * @brief getCommand gets a command from an internal circular buffer. + * @param conn reference to Proxmark3 connection * @param response location to write command * @return 1 if response was returned, 0 if nothing has been received */ -int getCommand(UsbCommand* response) +int getCommand(pm3_connection *conn, UsbCommand* response) { //If head == tail, there's nothing to read, or if we just got initialized - if (cmd_head == cmd_tail){ + if (!conn || conn->cmd_head == conn->cmd_tail){ return 0; } //Pick out the next unread command - UsbCommand* last_unread = &cmdBuffer[cmd_tail]; + UsbCommand* last_unread = &conn->cmdBuffer[conn->cmd_tail]; memcpy(response, last_unread, sizeof(UsbCommand)); //Increment tail - this is a circular buffer, so modulo buffer size - cmd_tail = (cmd_tail + 1) % CMD_BUFFER_SIZE; + conn->cmd_tail = (conn->cmd_tail +1 ) % CMD_BUFFER_SIZE; return 1; } @@ -138,7 +93,7 @@ int getCommand(UsbCommand* response) // Entry point into our code: called whenever we received a packet over USB // that we weren't necessarily expecting, for example a debug print. //----------------------------------------------------------------------------- -void UsbCommandReceived(UsbCommand *UC) +void UsbCommandReceived(pm3_connection* conn, UsbCommand *UC) { switch(UC->cmd) { @@ -160,14 +115,14 @@ void UsbCommandReceived(UsbCommand *UC) case CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K: { // FIXME: This does unsanitised copies into memory when we don't know // the size of the buffer. - if (sample_buf) { - memcpy(sample_buf+(UC->arg[0]),UC->d.asBytes,UC->arg[1]); + if (conn->sample_buf) { + memcpy(conn->sample_buf+(UC->arg[0]),UC->d.asBytes,UC->arg[1]); } return; } - + default: { - storeCommand(UC); + storeCommand(conn, UC); return; } } @@ -176,9 +131,9 @@ void UsbCommandReceived(UsbCommand *UC) // Gets a single command from a proxmark3 device. This should never be used // with the full client. // -// @param conn A receiver_arg structure. +// @param conn A pm3_connection structure. // @param command A buffer to store the received command. -bool ReceiveCommand(receiver_arg* conn, UsbCommand* command) { +bool ReceiveCommand(pm3_connection* conn, UsbCommand* command) { // Local recieve buffer size_t rxlen; byte_t rx[sizeof(UsbCommand)]; @@ -186,18 +141,16 @@ bool ReceiveCommand(receiver_arg* conn, UsbCommand* command) { while (conn->run) { rxlen = 0; - if (uart_receive(port, prx, sizeof(UsbCommand) - (prx-rx), &rxlen)) { + if (uart_receive(conn->port, prx, sizeof(UsbCommand) - (prx-rx), &rxlen)) { prx += rxlen; if (prx-rx < sizeof(UsbCommand)) { - // Keep reading until we have a completed response. continue; } - - // We have a completed response. + memcpy(command, rx, sizeof(UsbCommand)); return true; } - + if (prx == rx) { // We got no complete command while waiting, give up control return false; @@ -210,47 +163,35 @@ bool ReceiveCommand(receiver_arg* conn, UsbCommand* command) { // Worker thread for processing incoming events from the PM3 void *uart_receiver(void *targ) { - receiver_arg *conn = (receiver_arg*)targ; + pm3_connection *conn = (pm3_connection*)targ; UsbCommand rx; while (conn->run) { - #ifdef COMMS_DEBUG - printf("uart_receiver: get lock\n"); - #endif // Lock up receives, in case they try to take it away from us. pthread_mutex_lock(&conn->recv_lock); - #ifdef COMMS_DEBUG - printf("uart_receiver: lock acquired\n"); - #endif - if (port == NULL) { - #ifdef COMMS_DEBUG - printf("uart_receiver: port disappeared\n"); - #endif + if (conn->port == NULL) { // Our port disappeared, stall. This code path matters for the flasher, // where it is fiddling with the serial port under us. pthread_mutex_unlock(&conn->recv_lock); msleep(10); continue; } - + bool got_command = ReceiveCommand(conn, &rx); - #ifdef COMMS_DEBUG - printf("uart_receiver: got command\n"); - #endif pthread_mutex_unlock(&conn->recv_lock); - + if (got_command) { - UsbCommandReceived(&rx); + UsbCommandReceived(conn, &rx); } // We aren't normally trying to transmit in the flasher when the port would // be reset, so we can just keep going at this point. - if (txcmd_pending) { - if (!uart_send(port, (byte_t*) &txcmd, sizeof(UsbCommand))) { + if (conn->txcmd_pending) { + if (!uart_send(conn->port, (byte_t*) &(conn->txcmd), sizeof(UsbCommand))) { PrintAndLog("Sending bytes to proxmark failed"); } - txcmd_pending = false; + conn->txcmd_pending = false; } } @@ -268,7 +209,7 @@ void *uart_receiver(void *targ) { * @param show_warning * @return true if command was returned, otherwise false */ -bool WaitForResponseTimeoutW(uint64_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) { +bool WaitForResponseTimeoutW(pm3_connection *conn, uint64_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) { UsbCommand resp; #ifdef COMMS_DEBUG @@ -281,7 +222,7 @@ bool WaitForResponseTimeoutW(uint64_t cmd, UsbCommand* response, size_t ms_timeo // Wait until the command is received for(size_t dm_seconds=0; dm_seconds < ms_timeout/10; dm_seconds++) { - while(getCommand(response)) { + while(getCommand(conn, response)) { if (cmd == CMD_ANY || response->cmd == cmd) { return true; } @@ -295,10 +236,11 @@ bool WaitForResponseTimeoutW(uint64_t cmd, UsbCommand* response, size_t ms_timeo return false; } -bool WaitForResponseTimeout(uint64_t cmd, UsbCommand* response, size_t ms_timeout) { - return WaitForResponseTimeoutW(cmd, response, ms_timeout, true); +bool WaitForResponseTimeout(pm3_connection* conn, uint64_t cmd, UsbCommand* response, size_t ms_timeout) { + return WaitForResponseTimeoutW(conn, cmd, response, ms_timeout, true); } -bool WaitForResponse(uint64_t cmd, UsbCommand* response) { - return WaitForResponseTimeout(cmd, response, -1); +bool WaitForResponse(pm3_connection* conn, uint64_t cmd, UsbCommand* response) { + return WaitForResponseTimeout(conn, cmd, response, -1); } + diff --git a/client/comms.h b/client/comms.h index 75adeea1..01044b0d 100644 --- a/client/comms.h +++ b/client/comms.h @@ -19,27 +19,76 @@ #define BIGBUF_SIZE 40000 #endif -typedef struct { - // If TRUE, continue running the uart_receiver thread. - bool run; +// Max graph trace len: 40000 (bigbuf) * 8 (at 1 bit per sample) +#define MAX_GRAPH_TRACE_LEN (40000 * 8) +/* pm3_connection: holds state related to a connection to a single PM3 + * All global state related to a single connection should make its way into this struct. + */ +typedef struct { + // If TRUE, continue running the uart_reciever thread. + bool run; + + // Serial port that we are communicating with the PM3 on. + serial_port* port; + // Lock around serial port receives pthread_mutex_t recv_lock; -} receiver_arg; + + // If TRUE, then there is no active connection to the PM3, and we will drop commands sent. + bool offline; + + // Transmit buffer. + UsbCommand txcmd; + bool txcmd_pending; + + // Used by UsbReceiveCommand as a ring buffer for messages that are yet to be + // processed by a command handler (WaitForResponse{,Timeout}) + UsbCommand cmdBuffer[CMD_BUFFER_SIZE]; + // Points to the next empty position to write to + int cmd_head;//Starts as 0 + + // Points to the position of the last unread command + int cmd_tail;//Starts as 0 + + // Demodulation buffer, used by mainly low-frequency tags + uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; + size_t DemodBufferLen; + int g_DemodStartIdx; + int g_DemodClock; + + // Sample buffer, to be supplied in GetFromBigBuf and then written in by the device. + uint8_t* sample_buf; + + // Graphing related globals. + // FIXME: These should eventually make their way into particular UI implementations instead. + int GraphBuffer[MAX_GRAPH_TRACE_LEN]; + int GraphTraceLen; -// Wrappers required as static variables can only be used in one file. -void SetSerialPort(serial_port* new_port); -serial_port* GetSerialPort(); -void SetOffline(bool new_offline); -bool IsOffline(); + int s_Buff[MAX_GRAPH_TRACE_LEN]; + double CursorScaleFactor; + int PlotGridX; + int PlotGridY; + int PlotGridXdefault; + int PlotGridYdefault; + int CursorCPos; + int CursorDPos; + int flushAfterWrite; //buzzy + int GridOffset; + bool GridLocked; + bool showDemod; + +} pm3_connection; -void SendCommand(UsbCommand *c); +void SendCommand(pm3_connection *conn, UsbCommand *c); +bool ReceiveCommand(pm3_connection* conn, UsbCommand* command); // only for flasher void *uart_receiver(void *targ); -void UsbCommandReceived(UsbCommand *UC); -void clearCommandBuffer(); -bool WaitForResponseTimeoutW(uint64_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning); -bool WaitForResponseTimeout(uint64_t cmd, UsbCommand* response, size_t ms_timeout); -bool WaitForResponse(uint64_t cmd, UsbCommand* response); +void UsbCommandReceived(pm3_connection *conn, UsbCommand *UC); +void clearCommandBuffer(pm3_connection *conn); +bool WaitForResponseTimeoutW(pm3_connection* conn, uint64_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning); +bool WaitForResponseTimeout(pm3_connection* conn, uint64_t cmd, UsbCommand* response, size_t ms_timeout); +bool WaitForResponse(pm3_connection* conn, uint64_t cmd, UsbCommand* response); + #endif // COMMS_H_ diff --git a/client/data.c b/client/data.c index 4d7d1e41..8e471b66 100644 --- a/client/data.c +++ b/client/data.c @@ -15,11 +15,11 @@ #include "proxmark3.h" #include "cmdmain.h" -uint8_t* sample_buf; - -void GetFromBigBuf(uint8_t *dest, int bytes, int start_index) +void GetFromBigBuf(pm3_connection* conn, uint8_t *dest, int bytes, int start_index) { - sample_buf = dest; - UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}}; - SendCommand(&c); + // FIXME: This instructs the proxmark3 hardware to write into a buffer, and then + // implicitly trusts that it'll do the right thing in comms.c:UsbCommandReceived. + conn->sample_buf = dest; + UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}}; + SendCommand(conn, &c); } diff --git a/client/data.h b/client/data.h index 7d85e1f1..3647d482 100644 --- a/client/data.h +++ b/client/data.h @@ -12,12 +12,12 @@ #define DATA_H__ #include +#include "comms.h" #define FILE_PATH_SIZE 1000 -extern uint8_t* sample_buf; #define arraylen(x) (sizeof(x)/sizeof((x)[0])) -void GetFromBigBuf(uint8_t *dest, int bytes, int start_index); +void GetFromBigBuf(pm3_connection* conn, uint8_t *dest, int bytes, int start_index); #endif diff --git a/client/flash.c b/client/flash.c index bf01b911..23e974b5 100644 --- a/client/flash.c +++ b/client/flash.c @@ -41,29 +41,29 @@ static const uint8_t elf_ident[] = { EV_CURRENT }; -void CloseProxmark(receiver_arg* conn, char* serial_port_name) { +void CloseProxmark(pm3_connection* conn, char* serial_port_name) { pthread_mutex_lock(&conn->recv_lock); // Block the port from being used by anything - serial_port* my_port = GetSerialPort(); - SetSerialPort(NULL); - + serial_port* port = conn->port; + conn->port = NULL; + // Then close the port. - uart_close(my_port); + uart_close(port); pthread_mutex_unlock(&conn->recv_lock); - + // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/* unlink(serial_port_name); } -bool OpenProxmark(char* serial_port_name) { - serial_port *new_port = uart_open(serial_port_name); - if (new_port == INVALID_SERIAL_PORT || new_port == CLAIMED_SERIAL_PORT) { +bool OpenProxmark(pm3_connection* conn, char* serial_port_name) { + serial_port *port = uart_open(serial_port_name); + if (port == INVALID_SERIAL_PORT || port == CLAIMED_SERIAL_PORT) { //poll once a second return false; } - SetSerialPort(new_port); + conn->port = port; return true; } @@ -297,13 +297,13 @@ fail: } // Get the state of the proxmark, backwards compatible -static int get_proxmark_state(uint32_t *state) +static int get_proxmark_state(pm3_connection *conn, uint32_t *state) { UsbCommand c; c.cmd = CMD_DEVICE_INFO; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - while (!WaitForResponse(CMD_ANY, &resp)) { + while (!WaitForResponse(conn, CMD_ANY, &resp)) { // Keep waiting for a response msleep(100); } @@ -333,11 +333,11 @@ static int get_proxmark_state(uint32_t *state) } // Enter the bootloader to be able to start flashing -static int enter_bootloader(receiver_arg* conn, char *serial_port_name) +static int enter_bootloader(pm3_connection* conn, char *serial_port_name) { uint32_t state; - if (get_proxmark_state(&state) < 0) + if (get_proxmark_state(conn, &state) < 0) return -1; if (state & DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM) { @@ -356,12 +356,12 @@ static int enter_bootloader(receiver_arg* conn, char *serial_port_name) // New style handover: Send CMD_START_FLASH, which will reset the board // and enter the bootrom on the next boot. c.cmd = CMD_START_FLASH; - SendCommand(&c); + SendCommand(conn, &c); fprintf(stderr,"(Press and release the button only to abort)\n"); } else { // Old style handover: Ask the user to press the button, then reset the board c.cmd = CMD_HARDWARE_RESET; - SendCommand(&c); + SendCommand(conn, &c); fprintf(stderr,"Press and hold down button NOW if your bootloader requires it.\n"); } @@ -372,7 +372,7 @@ static int enter_bootloader(receiver_arg* conn, char *serial_port_name) do { sleep(1); fprintf(stderr, "."); - } while (!OpenProxmark(serial_port_name)); + } while (!OpenProxmark(conn, serial_port_name)); fprintf(stderr," Found.\n"); return 0; @@ -382,10 +382,10 @@ static int enter_bootloader(receiver_arg* conn, char *serial_port_name) return -1; } -static int wait_for_ack() +static int wait_for_ack(pm3_connection* conn) { UsbCommand resp; - while (!WaitForResponse(CMD_ANY, &resp)) { + while (!WaitForResponse(conn, CMD_ANY, &resp)) { msleep(100); } if (resp.cmd != CMD_ACK) { @@ -396,14 +396,14 @@ static int wait_for_ack() } // Go into flashing mode -int flash_start_flashing(receiver_arg* conn, int enable_bl_writes,char *serial_port_name) +int flash_start_flashing(pm3_connection* conn, int enable_bl_writes, char *serial_port_name) { uint32_t state; if (enter_bootloader(conn, serial_port_name) < 0) return -1; - if (get_proxmark_state(&state) < 0) + if (get_proxmark_state(conn, &state) < 0) return -1; if (state & DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH) { @@ -420,8 +420,8 @@ int flash_start_flashing(receiver_arg* conn, int enable_bl_writes,char *serial_p c.arg[1] = FLASH_END; c.arg[2] = 0; } - SendCommand(&c); - return wait_for_ack(); + SendCommand(conn, &c); + return wait_for_ack(conn); } else { fprintf(stderr, "Note: Your bootloader does not understand the new START_FLASH command\n"); fprintf(stderr, " It is recommended that you update your bootloader\n\n"); @@ -430,7 +430,7 @@ int flash_start_flashing(receiver_arg* conn, int enable_bl_writes,char *serial_p return 0; } -static int write_block(uint32_t address, uint8_t *data, uint32_t length) +static int write_block(pm3_connection* conn, uint32_t address, uint8_t *data, uint32_t length) { uint8_t block_buf[BLOCK_SIZE]; @@ -440,12 +440,12 @@ static int write_block(uint32_t address, uint8_t *data, uint32_t length) c.cmd = CMD_FINISH_WRITE; c.arg[0] = address; memcpy(c.d.asBytes, block_buf, length); - SendCommand(&c); - return wait_for_ack(); + SendCommand(conn, &c); + return wait_for_ack(conn); } // Write a file's segments to Flash -int flash_write(flash_file_t *ctx) +int flash_write(pm3_connection* conn, flash_file_t *ctx) { fprintf(stderr, "Writing segments for file: %s\n", ctx->filename); for (int i = 0; i < ctx->num_segs; i++) { @@ -467,7 +467,7 @@ int flash_write(flash_file_t *ctx) if (block_size > BLOCK_SIZE) block_size = BLOCK_SIZE; - if (write_block(baddr, data, block_size) < 0) { + if (write_block(conn, baddr, data, block_size) < 0) { fprintf(stderr, " ERROR\n"); fprintf(stderr, "Error writing block %d of %d\n", block, blocks); return -1; @@ -499,9 +499,10 @@ void flash_free(flash_file_t *ctx) } // just reset the unit -int flash_stop_flashing() { +int flash_stop_flashing(pm3_connection* conn) { UsbCommand c = {CMD_HARDWARE_RESET}; - SendCommand(&c); - msleep(100); - return 0; + SendCommand(conn, &c); + msleep(100); + return 0; } + diff --git a/client/flash.h b/client/flash.h index 279062af..6a2e0249 100644 --- a/client/flash.h +++ b/client/flash.h @@ -27,12 +27,12 @@ typedef struct { } flash_file_t; int flash_load(flash_file_t *ctx, const char *name, int can_write_bl); -int flash_start_flashing(receiver_arg* conn, int enable_bl_writes, char *serial_port_name); -int flash_write(flash_file_t *ctx); +int flash_start_flashing(pm3_connection* conn, int enable_bl_writes, char *serial_port_name); +int flash_write(pm3_connection* conn, flash_file_t *ctx); void flash_free(flash_file_t *ctx); -int flash_stop_flashing(void); -void CloseProxmark(receiver_arg* conn, char* serial_port_name); -bool OpenProxmark(char* serial_port_name); +int flash_stop_flashing(pm3_connection* conn); +void CloseProxmark(pm3_connection* conn, char* serial_port_name); +bool OpenProxmark(pm3_connection* conn, char* serial_port_name); #endif diff --git a/client/flasher.c b/client/flasher.c index 40e40524..da06b80d 100644 --- a/client/flasher.c +++ b/client/flasher.c @@ -61,10 +61,10 @@ int main(int argc, char **argv) int num_files = 0; int res; flash_file_t files[MAX_FILES]; - receiver_arg conn; + pm3_connection conn; pthread_t reader_thread; - memset(&conn, 0, sizeof(receiver_arg)); + memset(&conn, 0, sizeof(pm3_connection)); memset(files, 0, sizeof(files)); if (argc < 3) { @@ -94,14 +94,14 @@ int main(int argc, char **argv) pthread_mutex_init(&conn.recv_lock, NULL); char* serial_port_name = argv[1]; - + fprintf(stderr,"Waiting for Proxmark to appear on %s", serial_port_name); do { sleep(1); fprintf(stderr, "."); - } while (!OpenProxmark(serial_port_name)); + } while (!OpenProxmark(&conn, serial_port_name)); fprintf(stderr," Found.\n"); - + // Lets start up the communications thread conn.run = true; pthread_create(&reader_thread, NULL, &uart_receiver, &conn); @@ -113,7 +113,7 @@ int main(int argc, char **argv) fprintf(stderr, "\nFlashing...\n"); for (int i = 0; i < num_files; i++) { - res = flash_write(&files[i]); + res = flash_write(&conn, &files[i]); if (res < 0) return -1; flash_free(&files[i]); @@ -122,7 +122,7 @@ int main(int argc, char **argv) fprintf(stderr, "Resetting hardware...\n"); - res = flash_stop_flashing(); + res = flash_stop_flashing(&conn); if (res < 0) return -1; diff --git a/client/graph.c b/client/graph.c index 3ea47d2d..67aceec4 100644 --- a/client/graph.c +++ b/client/graph.c @@ -14,96 +14,93 @@ #include "ui.h" #include "graph.h" #include "lfdemod.h" -#include "cmddata.h" //for g_debugmode - -int GraphBuffer[MAX_GRAPH_TRACE_LEN]; -int GraphTraceLen; - -int s_Buff[MAX_GRAPH_TRACE_LEN]; +#include "cmddata.h" // SetClockGrid /* write a manchester bit to the graph */ -void AppendGraph(int redraw, int clock, int bit) +void AppendGraph(pm3_connection* conn, int redraw, int clock, int bit) { int i; //set first half the clock bit (all 1's or 0's for a 0 or 1 bit) for (i = 0; i < (int)(clock / 2); ++i) - GraphBuffer[GraphTraceLen++] = bit ; + conn->GraphBuffer[conn->GraphTraceLen++] = bit ; //set second half of the clock bit (all 0's or 1's for a 0 or 1 bit) for (i = (int)(clock / 2); i < clock; ++i) - GraphBuffer[GraphTraceLen++] = bit ^ 1; + conn->GraphBuffer[conn->GraphTraceLen++] = bit ^ 1; if (redraw) - RepaintGraphWindow(); + RepaintGraphWindow(conn); } // clear out our graph window -int ClearGraph(int redraw) +int ClearGraph(pm3_connection* conn, int redraw) { - int gtl = GraphTraceLen; - memset(GraphBuffer, 0x00, GraphTraceLen); + int gtl = conn->GraphTraceLen; + memset(conn->GraphBuffer, 0x00, sizeof(conn->GraphBuffer)); - GraphTraceLen = 0; + conn->GraphTraceLen = 0; if (redraw) - RepaintGraphWindow(); + RepaintGraphWindow(conn); return gtl; } // option '1' to save GraphBuffer any other to restore -void save_restoreGB(uint8_t saveOpt) +void save_restoreGB(pm3_connection* conn, uint8_t saveOpt) { + // FIXME: This function only allows a buffer of 1 graph to be stored. + // FIXME: This function is not thread-safe. static int SavedGB[MAX_GRAPH_TRACE_LEN]; static int SavedGBlen=0; static bool GB_Saved = false; static int SavedGridOffsetAdj=0; if (saveOpt == GRAPH_SAVE) { //save - memcpy(SavedGB, GraphBuffer, sizeof(GraphBuffer)); - SavedGBlen = GraphTraceLen; + memcpy(SavedGB, conn->GraphBuffer, MAX_GRAPH_TRACE_LEN); + SavedGBlen = conn->GraphTraceLen; GB_Saved=true; - SavedGridOffsetAdj = GridOffset; + SavedGridOffsetAdj = conn->GridOffset; } else if (GB_Saved) { //restore - memcpy(GraphBuffer, SavedGB, sizeof(GraphBuffer)); - GraphTraceLen = SavedGBlen; - GridOffset = SavedGridOffsetAdj; - RepaintGraphWindow(); + memcpy(conn->GraphBuffer, SavedGB, MAX_GRAPH_TRACE_LEN); + conn->GraphTraceLen = SavedGBlen; + conn->GridOffset = SavedGridOffsetAdj; + RepaintGraphWindow(conn); } return; } // DETECT CLOCK NOW IN LFDEMOD.C -void setGraphBuf(uint8_t *buff, size_t size) +void setGraphBuf(pm3_connection* conn, uint8_t *buff, size_t size) { if ( buff == NULL ) return; uint16_t i = 0; if ( size > MAX_GRAPH_TRACE_LEN ) size = MAX_GRAPH_TRACE_LEN; - ClearGraph(0); + ClearGraph(conn, 0); for (; i < size; ++i){ - GraphBuffer[i]=buff[i]-128; + conn->GraphBuffer[i]=buff[i]-128; } - GraphTraceLen=size; - RepaintGraphWindow(); + conn->GraphTraceLen=size; + RepaintGraphWindow(conn); return; } -size_t getFromGraphBuf(uint8_t *buff) + +size_t getFromGraphBuf(pm3_connection* conn, uint8_t *buff) { if (buff == NULL ) return 0; uint32_t i; - for (i=0;i127) GraphBuffer[i]=127; //trim - if (GraphBuffer[i]<-127) GraphBuffer[i]=-127; //trim - buff[i]=(uint8_t)(GraphBuffer[i]+128); + for (i=0;iGraphTraceLen;++i){ + if (conn->GraphBuffer[i]>127) conn->GraphBuffer[i]=127; //trim + if (conn->GraphBuffer[i]<-127) conn->GraphBuffer[i]=-127; //trim + buff[i]=(uint8_t)(conn->GraphBuffer[i]+128); } return i; } // A simple test to see if there is any data inside Graphbuffer. -bool HasGraphData(){ - - if ( GraphTraceLen <= 0) { +bool HasGraphData(pm3_connection* conn){ + if (conn->GraphTraceLen <= 0) { PrintAndLog("No data available, try reading something first"); return false; } @@ -112,17 +109,17 @@ bool HasGraphData(){ // Detect high and lows in Grapbuffer. // Only loops the first 256 values. -void DetectHighLowInGraph(int *high, int *low, bool addFuzz) { +void DetectHighLowInGraph(pm3_connection* conn, int *high, int *low, bool addFuzz) { uint8_t loopMax = 255; - if ( loopMax > GraphTraceLen) - loopMax = GraphTraceLen; + if ( loopMax > conn->GraphTraceLen) + loopMax = conn->GraphTraceLen; for (uint8_t i = 0; i < loopMax; ++i) { - if (GraphBuffer[i] > *high) - *high = GraphBuffer[i]; - else if (GraphBuffer[i] < *low) - *low = GraphBuffer[i]; + if (conn->GraphBuffer[i] > *high) + *high = conn->GraphBuffer[i]; + else if (conn->GraphBuffer[i] < *low) + *low = conn->GraphBuffer[i]; } //12% fuzz in case highs and lows aren't clipped @@ -133,9 +130,10 @@ void DetectHighLowInGraph(int *high, int *low, bool addFuzz) { } // Get or auto-detect ask clock rate -int GetAskClock(const char str[], bool printAns, bool verbose) +int GetAskClock(pm3_connection* conn, const char str[], bool printAns, bool verbose) { int clock; + // FIXME: Use atoi instead sscanf(str, "%i", &clock); if (!strcmp(str, "")) clock = 0; @@ -144,7 +142,7 @@ int GetAskClock(const char str[], bool printAns, bool verbose) return clock; // Auto-detect clock uint8_t grph[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(grph); + size_t size = getFromGraphBuf(conn, grph); if (size == 0) { if (verbose) PrintAndLog("Failed to copy from graphbuffer"); @@ -157,7 +155,7 @@ int GetAskClock(const char str[], bool printAns, bool verbose) if (st == false) { start = DetectASKClock(grph, size, &clock, 20); } - setClockGrid(clock, start); + setClockGrid(conn, clock, start); // Only print this message if we're not looping something if (printAns || g_debugMode) { PrintAndLog("Auto-detected clock rate: %d, Best Starting Position: %d", clock, start); @@ -165,11 +163,11 @@ int GetAskClock(const char str[], bool printAns, bool verbose) return clock; } -uint8_t GetPskCarrier(const char str[], bool printAns, bool verbose) +uint8_t GetPskCarrier(pm3_connection* conn, const char str[], bool printAns, bool verbose) { uint8_t carrier=0; uint8_t grph[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(grph); + size_t size = getFromGraphBuf(conn, grph); if ( size == 0 ) { if (verbose) PrintAndLog("Failed to copy from graphbuffer"); @@ -186,9 +184,10 @@ uint8_t GetPskCarrier(const char str[], bool printAns, bool verbose) return carrier; } -int GetPskClock(const char str[], bool printAns, bool verbose) +int GetPskClock(pm3_connection* conn, const char str[], bool printAns, bool verbose) { int clock; + // FIXME: Use atoi instead. sscanf(str, "%i", &clock); if (!strcmp(str, "")) clock = 0; @@ -197,7 +196,7 @@ int GetPskClock(const char str[], bool printAns, bool verbose) return clock; // Auto-detect clock uint8_t grph[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(grph); + size_t size = getFromGraphBuf(conn, grph); if ( size == 0 ) { if (verbose) PrintAndLog("Failed to copy from graphbuffer"); @@ -206,7 +205,7 @@ int GetPskClock(const char str[], bool printAns, bool verbose) size_t firstPhaseShiftLoc = 0; uint8_t curPhase = 0, fc = 0; clock = DetectPSKClock(grph, size, 0, &firstPhaseShiftLoc, &curPhase, &fc); - setClockGrid(clock, firstPhaseShiftLoc); + setClockGrid(conn, clock, firstPhaseShiftLoc); // Only print this message if we're not looping something if (printAns){ PrintAndLog("Auto-detected clock rate: %d", clock); @@ -214,7 +213,7 @@ int GetPskClock(const char str[], bool printAns, bool verbose) return clock; } -uint8_t GetNrzClock(const char str[], bool printAns, bool verbose) +uint8_t GetNrzClock(pm3_connection* conn, const char str[], bool printAns, bool verbose) { int clock; sscanf(str, "%i", &clock); @@ -225,7 +224,7 @@ uint8_t GetNrzClock(const char str[], bool printAns, bool verbose) return clock; // Auto-detect clock uint8_t grph[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(grph); + size_t size = getFromGraphBuf(conn, grph); if ( size == 0 ) { if (verbose) PrintAndLog("Failed to copy from graphbuffer"); @@ -233,7 +232,7 @@ uint8_t GetNrzClock(const char str[], bool printAns, bool verbose) } size_t clkStartIdx = 0; clock = DetectNRZClock(grph, size, 0, &clkStartIdx); - setClockGrid(clock, clkStartIdx); + setClockGrid(conn, clock, clkStartIdx); // Only print this message if we're not looping something if (printAns){ PrintAndLog("Auto-detected clock rate: %d", clock); @@ -242,7 +241,7 @@ uint8_t GetNrzClock(const char str[], bool printAns, bool verbose) } //by marshmellow //attempt to detect the field clock and bit clock for FSK -uint8_t GetFskClock(const char str[], bool printAns, bool verbose) +uint8_t GetFskClock(pm3_connection* conn, const char str[], bool printAns, bool verbose) { int clock; sscanf(str, "%i", &clock); @@ -253,11 +252,11 @@ uint8_t GetFskClock(const char str[], bool printAns, bool verbose) uint8_t fc1=0, fc2=0, rf1=0; int firstClockEdge = 0; - uint8_t ans = fskClocks(&fc1, &fc2, &rf1, verbose, &firstClockEdge); + uint8_t ans = fskClocks(conn, &fc1, &fc2, &rf1, verbose, &firstClockEdge); if (ans == 0) return 0; if ((fc1==10 && fc2==8) || (fc1==8 && fc2==5)){ if (printAns) PrintAndLog("Detected Field Clocks: FC/%d, FC/%d - Bit Clock: RF/%d", fc1, fc2, rf1); - setClockGrid(rf1, firstClockEdge); + setClockGrid(conn, rf1, firstClockEdge); return rf1; } if (verbose){ @@ -266,10 +265,10 @@ uint8_t GetFskClock(const char str[], bool printAns, bool verbose) } return 0; } -uint8_t fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose, int *firstClockEdge) +uint8_t fskClocks(pm3_connection* conn, uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose, int *firstClockEdge) { uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - size_t size = getFromGraphBuf(BitStream); + size_t size = getFromGraphBuf(conn, BitStream); if (size==0) return 0; uint16_t ans = countFC(BitStream, size, 1); if (ans==0) { diff --git a/client/graph.h b/client/graph.h index b20ae4e8..d149959f 100644 --- a/client/graph.h +++ b/client/graph.h @@ -12,31 +12,25 @@ #define GRAPH_H__ #include -void AppendGraph(int redraw, int clock, int bit); -int ClearGraph(int redraw); +void AppendGraph(pm3_connection* conn, int redraw, int clock, int bit); +int ClearGraph(pm3_connection* conn, int redraw); //int DetectClock(int peak); -size_t getFromGraphBuf(uint8_t *buff); -int GetAskClock(const char str[], bool printAns, bool verbose); -int GetPskClock(const char str[], bool printAns, bool verbose); -uint8_t GetPskCarrier(const char str[], bool printAns, bool verbose); -uint8_t GetNrzClock(const char str[], bool printAns, bool verbose); -uint8_t GetFskClock(const char str[], bool printAns, bool verbose); -uint8_t fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose, int *firstClockEdge); +size_t getFromGraphBuf(pm3_connection* conn, uint8_t *buff); +int GetAskClock(pm3_connection* conn, const char str[], bool printAns, bool verbose); +int GetPskClock(pm3_connection* conn, const char str[], bool printAns, bool verbose); +uint8_t GetPskCarrier(pm3_connection* conn, const char str[], bool printAns, bool verbose); +uint8_t GetNrzClock(pm3_connection* conn, const char str[], bool printAns, bool verbose); +uint8_t GetFskClock(pm3_connection* conn, const char str[], bool printAns, bool verbose); +uint8_t fskClocks(pm3_connection* conn, uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose, int *firstClockEdge); //uint8_t fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose); bool graphJustNoise(int *BitStream, int size); -void setGraphBuf(uint8_t *buff, size_t size); -void save_restoreGB(uint8_t saveOpt); +void setGraphBuf(pm3_connection* conn, uint8_t *buff, size_t size); +void save_restoreGB(pm3_connection* conn, uint8_t saveOpt); bool HasGraphData(); -void DetectHighLowInGraph(int *high, int *low, bool addFuzz); +void DetectHighLowInGraph(pm3_connection* conn, int *high, int *low, bool addFuzz); -// Max graph trace len: 40000 (bigbuf) * 8 (at 1 bit per sample) -#define MAX_GRAPH_TRACE_LEN (40000 * 8 ) #define GRAPH_SAVE 1 #define GRAPH_RESTORE 0 -extern int GraphBuffer[MAX_GRAPH_TRACE_LEN]; -extern int GraphTraceLen; -extern int s_Buff[MAX_GRAPH_TRACE_LEN]; - #endif diff --git a/client/guidummy.cpp b/client/guidummy.cpp index 6c24973b..45b28a7e 100644 --- a/client/guidummy.cpp +++ b/client/guidummy.cpp @@ -9,8 +9,9 @@ //----------------------------------------------------------------------------- #include +#include "comms.h" -extern "C" void ShowGraphWindow(void) +extern "C" void ShowGraphWindow(pm3_connection* conn) { static int warned = 0; @@ -20,8 +21,8 @@ extern "C" void ShowGraphWindow(void) } } -extern "C" void HideGraphWindow(void) {} -extern "C" void RepaintGraphWindow(void) {} +extern "C" void HideGraphWindow(pm3_connection* conn) {} +extern "C" void RepaintGraphWindow(pm3_connection* conn) {} extern "C" void MainGraphics() {} extern "C" void InitGraphics(int argc, char **argv) {} extern "C" void ExitGraphics(void) {} diff --git a/client/mifarehost.c b/client/mifarehost.c index a02019a3..51d99869 100644 --- a/client/mifarehost.c +++ b/client/mifarehost.c @@ -113,7 +113,7 @@ static uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint64_t par_i } -int mfDarkside(uint64_t *key) +int mfDarkside(pm3_connection *conn, uint64_t *key) { uint32_t uid = 0; uint32_t nt = 0, nr = 0; @@ -132,8 +132,8 @@ int mfDarkside(uint64_t *key) while (true) { - clearCommandBuffer(); - SendCommand(&c); + clearCommandBuffer(conn); + SendCommand(conn, &c); //flush queue while (ukbhit()) { @@ -150,7 +150,7 @@ int mfDarkside(uint64_t *key) } UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { + if (WaitForResponseTimeout(conn, CMD_ACK, &resp, 1000)) { isOK = resp.arg[0]; if (isOK < 0) { return isOK; @@ -204,7 +204,7 @@ int mfDarkside(uint64_t *key) num_to_bytes(last_keylist[i*max_keys + j], 6, keyBlock); } } - if (!mfCheckKeys(0, 0, false, size, keyBlock, key)) { + if (!mfCheckKeys(conn, 0, 0, false, size, keyBlock, key)) { break; } } @@ -224,22 +224,22 @@ int mfDarkside(uint64_t *key) } -int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ +int mfCheckKeys (pm3_connection* conn, uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ *key = -1; UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType & 0xff) << 8)), clear_trace, keycnt}}; memcpy(c.d.asBytes, keyBlock, 6 * keycnt); - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1; + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,3000)) return 1; if ((resp.arg[0] & 0xff) != 0x01) return 2; *key = bytes_to_num(resp.d.asBytes, 6); return 0; } -int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector){ +int mfCheckKeysSec(pm3_connection* conn, uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector){ uint8_t keyPtr = 0; @@ -248,10 +248,10 @@ int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool UsbCommand c = {CMD_MIFARE_CHKKEYS, {((sectorCnt & 0xff) | ((keyType & 0xff) << 8)), (clear_trace | 0x02)|((timeout14a & 0xff) << 8), keycnt}}; memcpy(c.d.asBytes, keyBlock, 6 * keycnt); - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeoutW(CMD_ACK, &resp, MAX(3000, 1000 + 13 * sectorCnt * keycnt * (keyType == 2 ? 2 : 1)), false)) return 1; // timeout: 13 ms / fail auth + if (!WaitForResponseTimeoutW(conn, CMD_ACK, &resp, MAX(3000, 1000 + 13 * sectorCnt * keycnt * (keyType == 2 ? 2 : 1)), false)) return 1; // timeout: 13 ms / fail auth if ((resp.arg[0] & 0xff) != 0x01) return 2; bool foundAKey = false; @@ -309,7 +309,7 @@ void* nested_worker_thread(void *arg) return statelist->head.slhead; } -int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) +int mfnested(pm3_connection* conn, uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) { uint16_t i; uint32_t uid; @@ -319,13 +319,13 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, struct Crypto1State *p1, *p2, *p3, *p4; // flush queue - WaitForResponseTimeout(CMD_ACK, NULL, 100); + WaitForResponseTimeout(conn, CMD_ACK, NULL, 100); UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}}; memcpy(c.d.asBytes, key, 6); - SendCommand(&c); + SendCommand(conn, &c); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + if (!WaitForResponseTimeout(conn, CMD_ACK, &resp, 1500)) { return -1; } @@ -408,7 +408,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, crypto1_get_lfsr(statelists[0].head.slhead + i, &key64); num_to_bytes(key64, 6, keyBlock); key64 = 0; - if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) { + if (!mfCheckKeys(conn, statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) { num_to_bytes(key64, 6, resultKey); break; } @@ -422,33 +422,33 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, // EMULATOR -int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) { +int mfEmlGetMem(pm3_connection* conn, uint8_t *data, int blockNum, int blocksCount) { UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1; + if (!WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) return 1; memcpy(data, resp.d.asBytes, blocksCount * 16); return 0; } -int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) { +int mfEmlSetMem(pm3_connection* conn, uint8_t *data, int blockNum, int blocksCount) { UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}}; - memcpy(c.d.asBytes, data, blocksCount * 16); - SendCommand(&c); + memcpy(c.d.asBytes, data, blocksCount * 16); + SendCommand(conn, &c); return 0; } // "MAGIC" CARD -int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) { +int mfCGetBlock(pm3_connection* conn, uint8_t blockNo, uint8_t *data, uint8_t params) { uint8_t isOK = 0; UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { isOK = resp.arg[0] & 0xff; memcpy(data, resp.d.asBytes, 16); if (!isOK) return 2; @@ -459,15 +459,15 @@ int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) { return 0; } -int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params) { +int mfCSetBlock(pm3_connection* conn, uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params) { uint8_t isOK = 0; UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}}; - memcpy(c.d.asBytes, data, 16); - SendCommand(&c); + memcpy(c.d.asBytes, data, 16); + SendCommand(conn, &c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + if (WaitForResponseTimeout(conn, CMD_ACK,&resp,1500)) { isOK = resp.arg[0] & 0xff; if (uid != NULL) memcpy(uid, resp.d.asBytes, 4); @@ -481,20 +481,20 @@ int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uin return 0; } -int mfCWipe(uint32_t numSectors, bool gen1b, bool wantWipe, bool wantFill) { +int mfCWipe(pm3_connection* conn, uint32_t numSectors, bool gen1b, bool wantWipe, bool wantFill) { uint8_t isOK = 0; uint8_t cmdParams = wantWipe + wantFill * 0x02 + gen1b * 0x04; UsbCommand c = {CMD_MIFARE_CWIPE, {numSectors, cmdParams, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK,&resp); isOK = resp.arg[0] & 0xff; return isOK; } -int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) { +int mfCSetUID(pm3_connection* conn, uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) { uint8_t oldblock0[16] = {0x00}; uint8_t block0[16] = {0x00}; int gen = 0, res; @@ -508,7 +508,7 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) { cmdParams = CSETBLOCK_SINGLE_OPER | CSETBLOCK_MAGIC_1B; } - res = mfCGetBlock(0, oldblock0, cmdParams); + res = mfCGetBlock(conn, 0, oldblock0, cmdParams); if (res == 0) { memcpy(block0, oldblock0, 16); @@ -531,7 +531,7 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) { } PrintAndLog("new block 0: %s", sprint_hex(block0, 16)); - res = mfCSetBlock(0, block0, oldUID, false, cmdParams); + res = mfCSetBlock(conn, 0, block0, oldUID, false, cmdParams); if (res) { PrintAndLog("Can't set block 0. Error: %d", res); return res; @@ -540,13 +540,13 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID) { return 0; } -int mfCIdentify() +int mfCIdentify(pm3_connection* conn) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}}; - SendCommand(&c); + SendCommand(conn, &c); UsbCommand resp; - WaitForResponse(CMD_ACK,&resp); + WaitForResponse(conn, CMD_ACK, &resp); // iso14a_card_select_t card; // memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); @@ -567,8 +567,8 @@ int mfCIdentify() c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); - WaitForResponse(CMD_ACK,&resp); + SendCommand(conn, &c); + WaitForResponse(conn, CMD_ACK, &resp); uint8_t isGeneration = resp.arg[0] & 0xff; switch( isGeneration ){ @@ -582,7 +582,7 @@ int mfCIdentify() c.arg[0] = 0; c.arg[1] = 0; c.arg[2] = 0; - SendCommand(&c); + SendCommand(conn, &c); return (int) isGeneration; } diff --git a/client/mifarehost.h b/client/mifarehost.h index 118d55cc..8a2c575a 100644 --- a/client/mifarehost.h +++ b/client/mifarehost.h @@ -14,6 +14,7 @@ #include #include #include "data.h" +#include "comms.h" // defaults // timeout in units. (ms * 106)/10 or us*0.0106 @@ -36,18 +37,18 @@ typedef struct { extern char logHexFileName[FILE_PATH_SIZE]; -extern int mfDarkside(uint64_t *key); -extern int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *ResultKeys, bool calibrate); -extern int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key); -extern int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector); +extern int mfDarkside(pm3_connection* conn, uint64_t *key); +extern int mfnested(pm3_connection* conn, uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *ResultKeys, bool calibrate); +extern int mfCheckKeys(pm3_connection* conn, uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key); +extern int mfCheckKeysSec(pm3_connection* conn, uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector); -extern int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); -extern int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); +extern int mfEmlGetMem(pm3_connection* conn, uint8_t *data, int blockNum, int blocksCount); +extern int mfEmlSetMem(pm3_connection* conn, uint8_t *data, int blockNum, int blocksCount); -extern int mfCWipe(uint32_t numSectors, bool gen1b, bool wantWipe, bool wantFill); -extern int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID); -extern int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params); -extern int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params); +extern int mfCWipe(pm3_connection* conn, uint32_t numSectors, bool gen1b, bool wantWipe, bool wantFill); +extern int mfCSetUID(pm3_connection* conn, uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID); +extern int mfCSetBlock(pm3_connection* conn, uint8_t blockNo, uint8_t *data, uint8_t *uid, bool wantWipe, uint8_t params); +extern int mfCGetBlock(pm3_connection* conn, uint8_t blockNo, uint8_t *data, uint8_t params); extern int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile); extern int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile); diff --git a/client/proxgui.cpp b/client/proxgui.cpp index 808c7de5..d99b1b50 100644 --- a/client/proxgui.cpp +++ b/client/proxgui.cpp @@ -16,9 +16,10 @@ static ProxGuiQT *gui = NULL; static WorkerThread *main_loop_thread = NULL; -WorkerThread::WorkerThread(char *script_cmds_file, bool usb_present, serial_port* sp) +WorkerThread::WorkerThread(char *script_cmds_file, bool usb_present, + serial_port* sp, bool flush_after_write) : script_cmds_file(script_cmds_file), usb_present(usb_present), - sp(sp) + sp(sp), flush_after_write(flush_after_write) { } @@ -28,7 +29,7 @@ WorkerThread::~WorkerThread() } void WorkerThread::run() { - main_loop(script_cmds_file, usb_present, sp); + main_loop(script_cmds_file, usb_present, sp, flush_after_write); } extern "C" void ShowGraphWindow(void) @@ -64,7 +65,7 @@ extern "C" void MainGraphics(void) gui->MainLoop(); } -extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* sp) +extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* sp, bool flush_after_write) { #ifdef Q_WS_X11 bool useGUI = getenv("DISPLAY") != 0; @@ -75,7 +76,7 @@ extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool return; gui = new ProxGuiQT(argc, argv); - main_loop_thread = new WorkerThread(script_cmds_file, usb_present, sp); + main_loop_thread = new WorkerThread(script_cmds_file, usb_present, sp, flush_after_write); QObject::connect(main_loop_thread, SIGNAL(finished()), main_loop_thread, SLOT(deleteLater())); QObject::connect(main_loop_thread, SIGNAL(finished()), gui, SLOT(_Exit())); } diff --git a/client/proxgui.h b/client/proxgui.h index 8cc05128..fe6302d3 100644 --- a/client/proxgui.h +++ b/client/proxgui.h @@ -15,39 +15,21 @@ extern "C" { #include #include #include "uart.h" +#include "comms.h" -void ShowGraphWindow(void); -void HideGraphWindow(void); -void RepaintGraphWindow(void); +void ShowGraphWindow(pm3_connection* conn); +void HideGraphWindow(pm3_connection* conn); +void RepaintGraphWindow(pm3_connection* conn); void MainGraphics(void); -void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* sp); +void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write); void ExitGraphics(void); -#define MAX_GRAPH_TRACE_LEN (40000*8) -extern int GraphBuffer[MAX_GRAPH_TRACE_LEN]; -extern int GraphTraceLen; -extern int s_Buff[MAX_GRAPH_TRACE_LEN]; - -extern double CursorScaleFactor; -extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, CursorCPos, CursorDPos, GridOffset; -extern int CommandFinished; -extern bool GridLocked; - //Operations defined in data_operations //extern int autoCorr(const int* in, int *out, size_t len, int window); extern int AskEdgeDetect(const int *in, int *out, int len, int threshold); extern int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose); extern int directionalThreshold(const int* in, int *out, size_t len, int8_t up, int8_t down); -extern void save_restoreGB(uint8_t saveOpt); -#define GRAPH_SAVE 1 -#define GRAPH_RESTORE 0 -#define MAX_DEMOD_BUF_LEN (1024*128) -extern uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; -extern size_t DemodBufferLen; -extern size_t g_DemodStartIdx; -extern bool showDemod; -extern uint8_t g_debugMode; #ifdef __cplusplus } diff --git a/client/proxguiqt.h b/client/proxguiqt.h index 8eb518af..fe5c2973 100644 --- a/client/proxguiqt.h +++ b/client/proxguiqt.h @@ -23,6 +23,8 @@ #include "uart.h" #include "ui/ui_overlays.h" +#include "uart.h" + /** * @brief The actual plot, black area were we paint the graph */ @@ -124,13 +126,14 @@ class ProxGuiQT : public QObject class WorkerThread : public QThread { Q_OBJECT; public: - WorkerThread(char*, bool, serial_port*); + WorkerThread(char*, bool, serial_port*, bool); ~WorkerThread(); void run(); private: char *script_cmds_file = NULL; bool usb_present; serial_port *sp = NULL; + bool flush_after_write = false; }; #endif // PROXGUI_QT diff --git a/client/proxmark3.c b/client/proxmark3.c index 09c60ee0..09472c51 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -27,28 +27,33 @@ #include "whereami.h" #include "comms.h" -void main_loop(char *script_cmds_file, bool usb_present, serial_port* sp) { - receiver_arg conn; + +void main_loop(char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write) { + pm3_connection conn; char *cmd = NULL; pthread_t reader_thread; - memset(&conn, 0, sizeof(receiver_arg)); + memset(&conn, 0, sizeof(pm3_connection)); pthread_mutex_init(&conn.recv_lock, NULL); - + // TODO: Move this into comms.c - PlotGridXdefault = 64; - PlotGridYdefault = 64; - showDemod = true; - CursorScaleFactor = 1; + conn.PlotGridXdefault = 64; + conn.PlotGridYdefault = 64; + conn.showDemod = true; + conn.CursorScaleFactor = 1; + + // TODO: Make logging better + conn.flushAfterWrite = flush_after_write; + SetFlushAfterWrite(flush_after_write); if (usb_present) { conn.run = true; - SetSerialPort(sp); - SetOffline(false); + conn.port = port; + conn.offline = false; pthread_create(&reader_thread, NULL, &uart_receiver, &conn); // cache Version information now: - CmdVersion(NULL); + CmdVersion(&conn, NULL); } else { - SetOffline(true); + conn.offline = true; } FILE *script_file = NULL; @@ -97,7 +102,7 @@ void main_loop(char *script_cmds_file, bool usb_present, serial_port* sp) { cmd[strlen(cmd) - 1] = 0x00; if (cmd[0] != 0x00) { - int ret = CommandReceived(cmd); + int ret = CommandReceived(&conn, cmd); add_history(cmd); if (ret == 99) { // exit or quit break; @@ -121,6 +126,8 @@ void main_loop(char *script_cmds_file, bool usb_present, serial_port* sp) { fclose(script_file); script_file = NULL; } + + pthread_mutex_destroy(&conn.recv_lock); pthread_mutex_destroy(&conn.recv_lock); } @@ -192,6 +199,7 @@ int main(int argc, char* argv[]) { bool usb_present = false; char *script_cmds_file = NULL; + bool flush_after_write = false; g_debugMode = 0; serial_port *sp = uart_open(argv[1]); @@ -214,7 +222,7 @@ int main(int argc, char* argv[]) { argv[2][4] == 'h') { printf("Output will be flushed after every print.\n"); - flushAfterWrite = 1; + flush_after_write = 1; } else script_cmds_file = argv[2]; @@ -225,19 +233,19 @@ int main(int argc, char* argv[]) { #ifdef HAVE_GUI #ifdef _WIN32 - InitGraphics(argc, argv, script_cmds_file, usb_present, sp); + InitGraphics(argc, argv, script_cmds_file, usb_present, sp, flush_after_write); MainGraphics(); #else char* display = getenv("DISPLAY"); if (display && strlen(display) > 1) { - InitGraphics(argc, argv, script_cmds_file, usb_present, sp); + InitGraphics(argc, argv, script_cmds_file, usb_present, sp, flush_after_write); MainGraphics(); } else { - main_loop(script_cmds_file, usb_present, sp); + main_loop(script_cmds_file, usb_present, sp, flush_after_write); } #endif #else diff --git a/client/proxmark3.h b/client/proxmark3.h index e2cb0c02..91e0de73 100644 --- a/client/proxmark3.h +++ b/client/proxmark3.h @@ -12,6 +12,7 @@ #ifndef PROXMARK3_H__ #define PROXMARK3_H__ +#include "uart.h" #include "usb_cmd.h" #include "uart.h" @@ -21,10 +22,9 @@ extern "C" { #endif -void SendCommand(UsbCommand *c); const char *get_my_executable_path(void); const char *get_my_executable_directory(void); -void main_loop(char *script_cmds_file, bool usb_present, serial_port* sp); +void main_loop(char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write); #ifdef __cplusplus } diff --git a/client/scripting.c b/client/scripting.c index 13cb8cdf..823f6fd6 100644 --- a/client/scripting.c +++ b/client/scripting.c @@ -14,6 +14,7 @@ #include #include #include +#include #include "proxmark3.h" #include "usb_cmd.h" #include "cmdmain.h" @@ -26,6 +27,10 @@ #include "../common/sha1.h" #include "polarssl/aes.h" #include "cmdcrc.h" + +#define GET_PM3_CONNECTION pm3_connection* conn = (pm3_connection*)L->l_G->user_context; + + /** * The following params expected: * UsbCommand c @@ -34,7 +39,7 @@ * @return */ static int l_SendCommand(lua_State *L){ - + GET_PM3_CONNECTION; /* * The SendCommand (native) expects the following structure: @@ -61,7 +66,7 @@ static int l_SendCommand(lua_State *L){ } // UsbCommand c = (*data); - SendCommand((UsbCommand* )data); + SendCommand(conn, (UsbCommand* )data); return 0; // no return values } /** @@ -72,7 +77,7 @@ static int l_SendCommand(lua_State *L){ * @return */ static int l_WaitForResponseTimeout(lua_State *L){ - + GET_PM3_CONNECTION; uint32_t cmd = 0; size_t ms_timeout = -1; @@ -100,7 +105,7 @@ static int l_WaitForResponseTimeout(lua_State *L){ UsbCommand response; - if(WaitForResponseTimeout(cmd, &response, ms_timeout)) + if(WaitForResponseTimeout(conn, cmd, &response, ms_timeout)) { //Push it as a string lua_pushlstring(L,(const char *)&response,sizeof(UsbCommand)); @@ -127,10 +132,10 @@ static int returnToLuaWithError(lua_State *L, const char* fmt, ...) } static int l_mfDarkside(lua_State *L){ - + GET_PM3_CONNECTION; uint64_t key; - int retval = mfDarkside(&key); + int retval = mfDarkside(conn, &key); //Push the retval on the stack lua_pushinteger(L, retval); @@ -148,7 +153,8 @@ static int l_mfDarkside(lua_State *L){ //static int l_PrintAndLog(lua_State *L){ return CmdHF14AMfDump(luaL_checkstring(L, 1));} static int l_clearCommandBuffer(lua_State *L){ - clearCommandBuffer(); + GET_PM3_CONNECTION; + clearCommandBuffer(conn); return 0; } /** @@ -196,7 +202,8 @@ static int l_ukbhit(lua_State *L) */ static int l_CmdConsole(lua_State *L) { - CommandReceived((char *)luaL_checkstring(L, 1)); + GET_PM3_CONNECTION; + CommandReceived(conn, (char *)luaL_checkstring(L, 1)); return 0; } @@ -472,7 +479,7 @@ int setLuaPath( lua_State* L, const char* path ) } -int set_pm3_libraries(lua_State *L) +int set_pm3_libraries(lua_State *L, pm3_connection* conn) { static const luaL_Reg libs[] = { @@ -522,5 +529,9 @@ int set_pm3_libraries(lua_State *L) strcat(libraries_path, LUA_LIBRARIES_WILDCARD); setLuaPath(L, libraries_path); + // Stuff the pm3_connection in the lua_State as "context". + // TODO: Find a better way to do this within Lua's API. + L->l_G->user_context = conn; + return 1; } diff --git a/client/scripting.h b/client/scripting.h index 1d35d78a..bd73324d 100644 --- a/client/scripting.h +++ b/client/scripting.h @@ -11,6 +11,7 @@ #define SCRIPTING_H__ #include +#include "comms.h" #define LUA_LIBRARIES_DIRECTORY "lualibs/" #define LUA_SCRIPTS_DIRECTORY "scripts/" @@ -22,6 +23,6 @@ * @param L */ -int set_pm3_libraries(lua_State *L); +int set_pm3_libraries(lua_State *L, pm3_connection* conn); #endif diff --git a/client/ui.c b/client/ui.c index 48869fd1..bd015375 100644 --- a/client/ui.c +++ b/client/ui.c @@ -18,23 +18,17 @@ #include "ui.h" -double CursorScaleFactor = 1; -int PlotGridX=0, PlotGridY=0, PlotGridXdefault= 64, PlotGridYdefault= 64, CursorCPos= 0, CursorDPos= 0; -int offline; -bool flushAfterWrite = false; //buzzy -int GridOffset = 0; -bool GridLocked = false; -bool showDemod = true; - extern pthread_mutex_t print_lock; static char *logfilename = "proxmark3.log"; +static bool flushAfterWrite = false; void PrintAndLog(char *fmt, ...) { char *saved_line; int saved_point; va_list argptr, argptr2; + // TODO: stash these elsewhere static FILE *logfile = NULL; static int logging=1; @@ -90,15 +84,10 @@ void PrintAndLog(char *fmt, ...) } va_end(argptr2); - if (flushAfterWrite == 1) //buzzy - { - fflush(NULL); - } //release lock pthread_mutex_unlock(&print_lock); } - void SetLogFilename(char *fn) { logfilename = fn; diff --git a/client/ui.h b/client/ui.h index 2986efaf..ed07e6e4 100644 --- a/client/ui.h +++ b/client/ui.h @@ -14,22 +14,18 @@ #include #include #include +#include "comms.h" // a global mutex to prevent interlaced printing from different threads pthread_mutex_t print_lock; extern uint8_t g_debugMode; void ShowGui(void); -void HideGraphWindow(void); -void ShowGraphWindow(void); -void RepaintGraphWindow(void); +void HideGraphWindow(pm3_connection* conn); +void ShowGraphWindow(pm3_connection* conn); +void RepaintGraphWindow(pm3_connection* conn); void PrintAndLog(char *fmt, ...); void SetLogFilename(char *fn); - -extern double CursorScaleFactor; -extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, CursorCPos, CursorDPos, GridOffset; -extern bool flushAfterWrite; //buzzy -extern bool GridLocked; -extern bool showDemod; +void SetFlushAfterWrite(bool flush_after_write); #endif diff --git a/common/iso15693tools.c b/common/iso15693tools.c index cf7d5341..89a2ea76 100644 --- a/common/iso15693tools.c +++ b/common/iso15693tools.c @@ -10,7 +10,11 @@ #include "proxmark3.h" #include #include -//#include "iso15693tools.h" +#include "iso15693tools.h" + +#ifdef ON_DEVICE +#include "../armsrc/printf.h" // for sprintf +#endif #define POLY 0x8408 diff --git a/common/lfdemod.c b/common/lfdemod.c index f470371a..d10d3724 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -44,16 +44,22 @@ #define LOWEST_DEFAULT_CLOCK 32 #define FSK_PSK_THRESHOLD 123 -//to allow debug print calls when used not on device +#ifdef ON_DEVICE +// We're code running on the device. + +// To allow debug print calls when used not on device void dummy(char *fmt, ...){} -#ifndef ON_DEVICE + +#define g_debugMode 0 +#define prnt dummy + +#else +// We're the proxmark client. #include "ui.h" #include "cmdparser.h" #include "cmddata.h" #define prnt PrintAndLog -#else - uint8_t g_debugMode=0; -#define prnt dummy + #endif uint8_t justNoise(uint8_t *BitStream, size_t size) { diff --git a/include/usb_cmd.h b/include/usb_cmd.h index df2923a0..c8a7ddec 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -212,6 +212,8 @@ typedef struct{ #define CMD_HF_SNIFFER 0x0800 #define CMD_UNKNOWN 0xFFFF + +// Special mode for WaitForResponse: listens for any command in response. #define CMD_ANY 0xFFFFFFFFFFFFFFFF //Mifare simulation flags diff --git a/liblua/lstate.h b/liblua/lstate.h index c8a31f5c..752ae310 100644 --- a/liblua/lstate.h +++ b/liblua/lstate.h @@ -145,6 +145,9 @@ typedef struct global_State { TString *memerrmsg; /* memory-error message */ TString *tmname[TM_N]; /* array with tag-method names */ struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ + + // Pointer to additional context storage. + void* user_context; } global_State; diff --git a/uart/uart.h b/uart/uart.h index fe75a683..43ef27a0 100644 --- a/uart/uart.h +++ b/uart/uart.h @@ -39,7 +39,7 @@ #include #include -typedef unsigned char byte_t; +#include "common.h" /* serial_port is declared as a void*, which you should cast to whatever type * makes sense to your connection method. Both the posix and win32 @@ -61,11 +61,11 @@ typedef void* serial_port; * * On errors, this method returns INVALID_SERIAL_PORT or CLAIMED_SERIAL_PORT. */ -serial_port uart_open(const char* pcPortName); +serial_port* uart_open(const char* pcPortName); /* Closes the given port. */ -void uart_close(const serial_port sp); +void uart_close(serial_port* sp); /* Reads from the given serial port for up to 30ms. * pbtRx: A pointer to a buffer for the returned data to be written to. @@ -78,21 +78,21 @@ void uart_close(const serial_port sp); * partial read may have completed into the buffer by the corresponding * implementation, so pszRxLen should be checked to see if any data was written. */ -bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen); +bool uart_receive(serial_port* sp, byte_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen); /* Sends a buffer to a given serial port. * pbtTx: A pointer to a buffer containing the data to send. * szTxLen: The amount of data to be sent. */ -bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen); +bool uart_send(serial_port* sp, const byte_t* pbtTx, const size_t szTxLen); /* Sets the current speed of the serial port, in baud. */ -bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed); +bool uart_set_speed(serial_port* sp, const uint32_t uiPortSpeed); /* Gets the current speed of the serial port, in baud. */ -uint32_t uart_get_speed(const serial_port sp); +uint32_t uart_get_speed(serial_port* sp); #endif // _PM3_UART_H_ diff --git a/uart/uart_posix.c b/uart/uart_posix.c index 45e0d3d2..9e457b11 100644 --- a/uart/uart_posix.c +++ b/uart/uart_posix.c @@ -59,7 +59,10 @@ const struct timeval timeout = { .tv_usec = 30000 // 30000 micro seconds }; -serial_port uart_open(const char* pcPortName) +// Overall timeout for receives -- 300ms +#define RECV_TOTAL_TIMEOUT_MS 300 + +serial_port *uart_open(const char* pcPortName) { serial_port_unix* sp = malloc(sizeof(serial_port_unix)); if (sp == 0) return INVALID_SERIAL_PORT; @@ -118,7 +121,7 @@ serial_port uart_open(const char* pcPortName) return sp; } -void uart_close(const serial_port sp) { +void uart_close(serial_port* sp) { serial_port_unix* spu = (serial_port_unix*)sp; tcflush(spu->fd,TCIOFLUSH); tcsetattr(spu->fd,TCSANOW,&(spu->tiOld)); @@ -133,11 +136,12 @@ void uart_close(const serial_port sp) { free(sp); } -bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen) { +bool uart_receive(serial_port* sp, byte_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen) { int res; int byteCount; fd_set rfds; struct timeval tv; + uint64_t timeout_at = msclock() + RECV_TOTAL_TIMEOUT_MS; // Reset the output count *pszRxLen = 0; @@ -187,12 +191,13 @@ bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t pszMaxRxLen, size_ return true; } - } while (byteCount); + // Keep going if we haven't hit a timeout yet + } while (msclock() < timeout_at); return true; } -bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen) { +bool uart_send(serial_port* sp, const byte_t* pbtTx, const size_t szTxLen) { int32_t res; size_t szPos = 0; fd_set rfds; @@ -226,7 +231,7 @@ bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen) return true; } -bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { +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) { @@ -270,7 +275,7 @@ bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { return (tcsetattr(spu->fd,TCSANOW,&ti) != -1); } -uint32_t uart_get_speed(const serial_port sp) { +uint32_t uart_get_speed(serial_port* sp) { struct termios ti; uint32_t uiPortSpeed; const serial_port_unix* spu = (serial_port_unix*)sp; diff --git a/uart/uart_win32.c b/uart/uart_win32.c index af521ead..615e2500 100644 --- a/uart/uart_win32.c +++ b/uart/uart_win32.c @@ -57,7 +57,7 @@ void upcase(char *p) { } } -serial_port uart_open(const char* pcPortName) { +serial_port* uart_open(const char* pcPortName) { char acPortName[255]; serial_port_windows* sp = malloc(sizeof(serial_port_windows)); @@ -102,30 +102,30 @@ serial_port uart_open(const char* pcPortName) { return sp; } -void uart_close(const serial_port sp) { +void uart_close(serial_port* sp) { CloseHandle(((serial_port_windows*)sp)->hPort); free(sp); } -bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen) { +bool uart_receive(serial_port* sp, byte_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen) { ReadFile(((serial_port_windows*)sp)->hPort,pbtRx,pszMaxRxLen,(LPDWORD)pszRxLen,NULL); return (*pszRxLen != 0); } -bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen) { +bool uart_send(serial_port* sp, const byte_t* pbtTx, const size_t szTxLen) { DWORD dwTxLen = 0; return WriteFile(((serial_port_windows*)sp)->hPort,pbtTx,szTxLen,&dwTxLen,NULL); return (dwTxLen != 0); } -bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { +bool uart_set_speed(serial_port* sp, const uint32_t uiPortSpeed) { serial_port_windows* spw; spw = (serial_port_windows*)sp; spw->dcb.BaudRate = uiPortSpeed; return SetCommState(spw->hPort, &spw->dcb); } -uint32_t uart_get_speed(const serial_port sp) { +uint32_t uart_get_speed(serial_port* sp) { const serial_port_windows* spw = (serial_port_windows*)sp; if (!GetCommState(spw->hPort, (serial_port)&spw->dcb)) { return spw->dcb.BaudRate; From b4a56dd77447362c0cf74889982157d60e0e0711 Mon Sep 17 00:00:00 2001 From: Michael Farrell Date: Sat, 8 Jul 2017 22:53:28 +1000 Subject: [PATCH 3/4] fixup QT GUI --- client/cmddata.c | 2 + client/comms.h | 1 + client/graph.h | 7 +++ client/guidummy.cpp | 6 +-- client/proxgui.cpp | 18 +++---- client/proxgui.h | 8 +-- client/proxguiqt.cpp | 117 ++++++++++++++++++++++--------------------- client/proxguiqt.h | 16 ++++-- client/proxmark3.c | 9 ++-- client/ui.h | 6 +-- 10 files changed, 106 insertions(+), 84 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 94cb093f..8fab4d0f 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -25,6 +25,8 @@ #include "loclass/cipherutils.h" // for decimating samples in getsamples #include "cmdlfem4x.h"// for em410x demod +uint8_t g_debugMode=0; + static int CmdHelp(pm3_connection* conn, const char *Cmd); //set the demod buffer with given array of binary (one bit per byte) diff --git a/client/comms.h b/client/comms.h index 01044b0d..f336acb6 100644 --- a/client/comms.h +++ b/client/comms.h @@ -6,6 +6,7 @@ #include "usb_cmd.h" #include "uart.h" +#include "util_posix.h" #ifndef CMD_BUFFER_SIZE #define CMD_BUFFER_SIZE 50 diff --git a/client/graph.h b/client/graph.h index d149959f..4c02950d 100644 --- a/client/graph.h +++ b/client/graph.h @@ -25,7 +25,14 @@ uint8_t fskClocks(pm3_connection* conn, uint8_t *fc1, uint8_t *fc2, uint8_t *rf1 //uint8_t fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose); bool graphJustNoise(int *BitStream, int size); void setGraphBuf(pm3_connection* conn, uint8_t *buff, size_t size); + +#ifdef __cplusplus +extern "C" { +#endif void save_restoreGB(pm3_connection* conn, uint8_t saveOpt); +#ifdef __cplusplus +} +#endif bool HasGraphData(); void DetectHighLowInGraph(pm3_connection* conn, int *high, int *low, bool addFuzz); diff --git a/client/guidummy.cpp b/client/guidummy.cpp index 45b28a7e..18503c09 100644 --- a/client/guidummy.cpp +++ b/client/guidummy.cpp @@ -21,8 +21,8 @@ extern "C" void ShowGraphWindow(pm3_connection* conn) } } -extern "C" void HideGraphWindow(pm3_connection* conn) {} -extern "C" void RepaintGraphWindow(pm3_connection* conn) {} -extern "C" void MainGraphics() {} +extern "C" void HideGraphWindow() {} +extern "C" void RepaintGraphWindow() {} +extern "C" void MainGraphics(pm3_connection* conn) {} extern "C" void InitGraphics(int argc, char **argv) {} extern "C" void ExitGraphics(void) {} diff --git a/client/proxgui.cpp b/client/proxgui.cpp index d99b1b50..8ddb4d82 100644 --- a/client/proxgui.cpp +++ b/client/proxgui.cpp @@ -16,11 +16,9 @@ static ProxGuiQT *gui = NULL; static WorkerThread *main_loop_thread = NULL; -WorkerThread::WorkerThread(char *script_cmds_file, bool usb_present, - serial_port* sp, bool flush_after_write) - : script_cmds_file(script_cmds_file), usb_present(usb_present), - sp(sp), flush_after_write(flush_after_write) - + +WorkerThread::WorkerThread(char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write) + : script_cmds_file(script_cmds_file), usb_present(usb_present), port(port), flush_after_write(flush_after_write) { } @@ -29,7 +27,7 @@ WorkerThread::~WorkerThread() } void WorkerThread::run() { - main_loop(script_cmds_file, usb_present, sp, flush_after_write); + main_loop(script_cmds_file, usb_present, port, flush_after_write); } extern "C" void ShowGraphWindow(void) @@ -56,16 +54,16 @@ extern "C" void RepaintGraphWindow(void) gui->RepaintGraphWindow(); } -extern "C" void MainGraphics(void) +extern "C" void MainGraphics(pm3_connection* conn) { if (!gui) return; main_loop_thread->start(); - gui->MainLoop(); + gui->MainLoop(conn); } -extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* sp, bool flush_after_write) +extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write) { #ifdef Q_WS_X11 bool useGUI = getenv("DISPLAY") != 0; @@ -76,7 +74,7 @@ extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool return; gui = new ProxGuiQT(argc, argv); - main_loop_thread = new WorkerThread(script_cmds_file, usb_present, sp, flush_after_write); + main_loop_thread = new WorkerThread(script_cmds_file, usb_present, port, flush_after_write); QObject::connect(main_loop_thread, SIGNAL(finished()), main_loop_thread, SLOT(deleteLater())); QObject::connect(main_loop_thread, SIGNAL(finished()), gui, SLOT(_Exit())); } diff --git a/client/proxgui.h b/client/proxgui.h index fe6302d3..7424fd7f 100644 --- a/client/proxgui.h +++ b/client/proxgui.h @@ -17,10 +17,10 @@ extern "C" { #include "uart.h" #include "comms.h" -void ShowGraphWindow(pm3_connection* conn); -void HideGraphWindow(pm3_connection* conn); -void RepaintGraphWindow(pm3_connection* conn); -void MainGraphics(void); +void ShowGraphWindow(void); +void HideGraphWindow(void); +void RepaintGraphWindow(void); +void MainGraphics(pm3_connection* conn); void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write); void ExitGraphics(void); diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index 506b8138..12745717 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -26,6 +26,8 @@ #include #include "proxgui.h" #include +#include "graph.h" +#include "ui.h" //#include bool g_useOverlays = false; @@ -85,7 +87,7 @@ void ProxGuiQT::_Exit(void) { delete this; } -void ProxGuiQT::MainLoop() +void ProxGuiQT::MainLoop(pm3_connection *conn) { plotapp = new QApplication(argc, argv); @@ -94,6 +96,7 @@ void ProxGuiQT::MainLoop() connect(this, SIGNAL(HideGraphWindowSignal()), this, SLOT(_HideGraphWindow())); connect(this, SIGNAL(ExitSignal()), this, SLOT(_Exit())); + this->conn = conn; plotapp->exec(); } @@ -120,19 +123,19 @@ ProxGuiQT::~ProxGuiQT(void) void ProxWidget::applyOperation() { //printf("ApplyOperation()"); - save_restoreGB(GRAPH_SAVE); - memcpy(GraphBuffer, s_Buff, sizeof(int) * GraphTraceLen); + save_restoreGB(master->conn, GRAPH_SAVE); + memcpy(master->conn->GraphBuffer, master->conn->s_Buff, sizeof(int) * master->conn->GraphTraceLen); RepaintGraphWindow(); } void ProxWidget::stickOperation() { - save_restoreGB(GRAPH_RESTORE); + save_restoreGB(master->conn, GRAPH_RESTORE); //printf("stickOperation()"); } void ProxWidget::vchange_autocorr(int v) { int ans; - ans = AutoCorrelate(GraphBuffer, s_Buff, GraphTraceLen, v, true, false); + ans = AutoCorrelate(master->conn->GraphBuffer, master->conn->s_Buff, master->conn->GraphTraceLen, v, true, false); if (g_debugMode) printf("vchange_autocorr(w:%d): %d\n", v, ans); g_useOverlays = true; RepaintGraphWindow(); @@ -141,7 +144,7 @@ void ProxWidget::vchange_askedge(int v) { int ans; //extern int AskEdgeDetect(const int *in, int *out, int len, int threshold); - ans = AskEdgeDetect(GraphBuffer, s_Buff, GraphTraceLen, v); + ans = AskEdgeDetect(master->conn->GraphBuffer, master->conn->s_Buff, master->conn->GraphTraceLen, v); if (g_debugMode) printf("vchange_askedge(w:%d)%d\n", v, ans); g_useOverlays = true; RepaintGraphWindow(); @@ -149,7 +152,7 @@ void ProxWidget::vchange_askedge(int v) void ProxWidget::vchange_dthr_up(int v) { int down = opsController->horizontalSlider_dirthr_down->value(); - directionalThreshold(GraphBuffer, s_Buff, GraphTraceLen, v, down); + directionalThreshold(master->conn->GraphBuffer, master->conn->s_Buff, master->conn->GraphTraceLen, v, down); //printf("vchange_dthr_up(%d)", v); g_useOverlays = true; RepaintGraphWindow(); @@ -158,7 +161,7 @@ void ProxWidget::vchange_dthr_down(int v) { //printf("vchange_dthr_down(%d)", v); int up = opsController->horizontalSlider_dirthr_up->value(); - directionalThreshold(GraphBuffer,s_Buff, GraphTraceLen, v, up); + directionalThreshold(master->conn->GraphBuffer,master->conn->s_Buff, master->conn->GraphTraceLen, v, up); g_useOverlays = true; RepaintGraphWindow(); } @@ -194,7 +197,7 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) // Set up the plot widget, which does the actual plotting - plot = new Plot(this); + plot = new Plot(this, master); /* QSlider* slider = new QSlider(Qt::Horizontal); slider->setFocusPolicy(Qt::StrongFocus); @@ -306,20 +309,20 @@ void Plot::setMaxAndStart(int *buffer, int len, QRect plotRect) void Plot::PlotDemod(uint8_t *buffer, size_t len, QRect plotRect, QRect annotationRect, QPainter *painter, int graphNum, int plotOffset) { - if (len == 0 || PlotGridX <= 0) return; + if (len == 0 || master->conn->PlotGridX <= 0) return; //clock_t begin = clock(); QPainterPath penPath; - int grid_delta_x = PlotGridX; - int first_delta_x = grid_delta_x; //(plotOffset > 0) ? PlotGridX : (PlotGridX +); + int grid_delta_x = master->conn->PlotGridX; + int first_delta_x = grid_delta_x; //(plotOffset > 0) ? master->conn->PlotGridX : (master->conn->PlotGridX +); if (GraphStart > plotOffset) first_delta_x -= (GraphStart-plotOffset); int DemodStart = GraphStart; if (plotOffset > GraphStart) DemodStart = plotOffset; int BitStart = 0; // round down - if (DemodStart-plotOffset > 0) BitStart = (int)(((DemodStart-plotOffset)+(PlotGridX-1))/PlotGridX)-1; - first_delta_x += BitStart * PlotGridX; + if (DemodStart-plotOffset > 0) BitStart = (int)(((DemodStart-plotOffset)+(master->conn->PlotGridX-1))/master->conn->PlotGridX)-1; + first_delta_x += BitStart * master->conn->PlotGridX; if (BitStart > (int)len) return; int delta_x = 0; int v = 0; @@ -435,26 +438,26 @@ void Plot::PlotGraph(int *buffer, int len, QRect plotRect, QRect annotationRect, void Plot::plotGridLines(QPainter* painter,QRect r) { - // set GridOffset - if (PlotGridX <= 0) return; - int offset = GridOffset; - if (GridLocked && PlotGridX) { - offset = GridOffset + PlotGridX - (GraphStart % PlotGridX); - } else if (!GridLocked && GraphStart > 0 && PlotGridX) { - offset = PlotGridX-((GraphStart - offset) % PlotGridX) + GraphStart - unlockStart; + // set master->conn->GridOffset + if (master->conn->PlotGridX <= 0) return; + int offset = master->conn->GridOffset; + if (master->conn->GridLocked && master->conn->PlotGridX) { + offset = master->conn->GridOffset + master->conn->PlotGridX - (GraphStart % master->conn->PlotGridX); + } else if (!master->conn->GridLocked && GraphStart > 0 && master->conn->PlotGridX) { + offset = master->conn->PlotGridX-((GraphStart - offset) % master->conn->PlotGridX) + GraphStart - unlockStart; } - offset %= PlotGridX; - if (offset < 0) offset += PlotGridX; + offset %= master->conn->PlotGridX; + if (offset < 0) offset += master->conn->PlotGridX; int i; - int grid_delta_x = (int) (PlotGridX * GraphPixelsPerPoint); - int grid_delta_y = PlotGridY; - if ((PlotGridX > 0) && ((PlotGridX * GraphPixelsPerPoint) > 1)) { + int grid_delta_x = (int) (master->conn->PlotGridX * GraphPixelsPerPoint); + int grid_delta_y = master->conn->PlotGridY; + if ((master->conn->PlotGridX > 0) && ((master->conn->PlotGridX * GraphPixelsPerPoint) > 1)) { for(i = (offset * GraphPixelsPerPoint); i < r.right(); i += grid_delta_x) { painter->drawLine(r.left()+i, r.top(), r.left()+i, r.bottom()); } } - if (PlotGridY > 0) { + if (master->conn->PlotGridY > 0) { for(i = 0; yCoordOf(i,r,g_absVMax) > r.top(); i += grid_delta_y) { painter->drawLine( r.left(), yCoordOf(i,r,g_absVMax), r.right(), yCoordOf(i,r,g_absVMax) ); painter->drawLine( r.left(), yCoordOf(i*-1,r,g_absVMax), r.right(), yCoordOf(i*-1,r,g_absVMax) ); @@ -478,14 +481,14 @@ void Plot::paintEvent(QPaintEvent *event) GraphStart = 0; } - if (CursorAPos > GraphTraceLen) + if (CursorAPos > master->conn->GraphTraceLen) CursorAPos= 0; - if(CursorBPos > GraphTraceLen) + if(CursorBPos > master->conn->GraphTraceLen) CursorBPos= 0; - if(CursorCPos > GraphTraceLen) - CursorCPos= 0; - if(CursorDPos > GraphTraceLen) - CursorDPos= 0; + if(master->conn->CursorCPos > master->conn->GraphTraceLen) + master->conn->CursorCPos= 0; + if(master->conn->CursorDPos > master->conn->GraphTraceLen) + master->conn->CursorDPos= 0; QRect plotRect(WIDTH_AXES, 0, width()-WIDTH_AXES, height()-HEIGHT_INFO); QRect infoRect(0, height()-HEIGHT_INFO, width(), HEIGHT_INFO); @@ -496,7 +499,7 @@ void Plot::paintEvent(QPaintEvent *event) painter.fillRect(plotRect, QColor(0, 0, 0)); //init graph variables - setMaxAndStart(GraphBuffer,GraphTraceLen,plotRect); + setMaxAndStart(master->conn->GraphBuffer,master->conn->GraphTraceLen,plotRect); // center line int zeroHeight = plotRect.top() + (plotRect.bottom() - plotRect.top()) / 2; @@ -506,14 +509,14 @@ void Plot::paintEvent(QPaintEvent *event) plotGridLines(&painter, plotRect); //Start painting graph - PlotGraph(GraphBuffer, GraphTraceLen,plotRect,infoRect,&painter,0); - if (showDemod && DemodBufferLen > 8) { - PlotDemod(DemodBuffer, DemodBufferLen,plotRect,infoRect,&painter,2,g_DemodStartIdx); + PlotGraph(master->conn->GraphBuffer, master->conn->GraphTraceLen,plotRect,infoRect,&painter,0); + if (master->conn->showDemod && master->conn->DemodBufferLen > 8) { + PlotDemod(master->conn->DemodBuffer, master->conn->DemodBufferLen,plotRect,infoRect,&painter,2,master->conn->g_DemodStartIdx); } if (g_useOverlays) { //init graph variables - setMaxAndStart(s_Buff,GraphTraceLen,plotRect); - PlotGraph(s_Buff, GraphTraceLen,plotRect,infoRect,&painter,1); + setMaxAndStart(master->conn->s_Buff,master->conn->GraphTraceLen,plotRect); + PlotGraph(master->conn->s_Buff, master->conn->GraphTraceLen,plotRect,infoRect,&painter,1); } // End graph drawing @@ -528,29 +531,31 @@ void Plot::paintEvent(QPaintEvent *event) painter.setPen(QColor(255, 0, 255)); painter.drawLine(xCoordOf(CursorBPos, plotRect),plotRect.top(),xCoordOf(CursorBPos, plotRect),plotRect.bottom()); } - if(CursorCPos > GraphStart && xCoordOf(CursorCPos, plotRect) < plotRect.right()) + if(master->conn->CursorCPos > GraphStart && xCoordOf(master->conn->CursorCPos, plotRect) < plotRect.right()) { painter.setPen(QColor(255, 153, 0)); //orange - painter.drawLine(xCoordOf(CursorCPos, plotRect),plotRect.top(),xCoordOf(CursorCPos, plotRect),plotRect.bottom()); + painter.drawLine(xCoordOf(master->conn->CursorCPos, plotRect),plotRect.top(),xCoordOf(master->conn->CursorCPos, plotRect),plotRect.bottom()); } - if(CursorDPos > GraphStart && xCoordOf(CursorDPos, plotRect) < plotRect.right()) + if(master->conn->CursorDPos > GraphStart && xCoordOf(master->conn->CursorDPos, plotRect) < plotRect.right()) { painter.setPen(QColor(0, 0, 205)); //light blue - painter.drawLine(xCoordOf(CursorDPos, plotRect),plotRect.top(),xCoordOf(CursorDPos, plotRect),plotRect.bottom()); + painter.drawLine(xCoordOf(master->conn->CursorDPos, plotRect),plotRect.top(),xCoordOf(master->conn->CursorDPos, plotRect),plotRect.bottom()); } //Draw annotations char str[200]; sprintf(str, "@%d dt=%d [%2.2f] zoom=%2.2f CursorAPos=%d CursorBPos=%d GridX=%d GridY=%d (%s) GridXoffset=%d", - GraphStart, CursorBPos - CursorAPos, (CursorBPos - CursorAPos)/CursorScaleFactor, - GraphPixelsPerPoint,CursorAPos,CursorBPos,PlotGridXdefault,PlotGridYdefault,GridLocked?"Locked":"Unlocked",GridOffset); + GraphStart, CursorBPos - CursorAPos, (CursorBPos - CursorAPos)/master->conn->CursorScaleFactor, + GraphPixelsPerPoint,CursorAPos,CursorBPos,master->conn->PlotGridXdefault,master->conn->PlotGridYdefault,master->conn->GridLocked?"Locked":"Unlocked",master->conn->GridOffset); painter.setPen(QColor(255, 255, 255)); painter.drawText(20, infoRect.bottom() - 3, str); } -Plot::Plot(QWidget *parent) : QWidget(parent), GraphStart(0), GraphPixelsPerPoint(1) +Plot::Plot(QWidget *parent, ProxGuiQT *master) : QWidget(parent), GraphStart(0), GraphPixelsPerPoint(1) { + this->master = master; + //Need to set this, otherwise we don't receive keypress events setFocusPolicy( Qt::StrongFocus); resize(600, 300); @@ -595,8 +600,8 @@ void Plot::keyPressEvent(QKeyEvent *event) int offset; if(event->modifiers() & Qt::ShiftModifier) { - if (PlotGridX) - offset= PageWidth - (PageWidth % PlotGridX); + if (master->conn->PlotGridX) + offset= PageWidth - (PageWidth % master->conn->PlotGridX); else offset= PageWidth; } else @@ -635,12 +640,12 @@ void Plot::keyPressEvent(QKeyEvent *event) break; case Qt::Key_G: - if(PlotGridX || PlotGridY) { - PlotGridX= 0; - PlotGridY= 0; + if(master->conn->PlotGridX || master->conn->PlotGridY) { + master->conn->PlotGridX= 0; + master->conn->PlotGridY= 0; } else { - PlotGridX= PlotGridXdefault; - PlotGridY= PlotGridYdefault; + master->conn->PlotGridX= master->conn->PlotGridXdefault; + master->conn->PlotGridY= master->conn->PlotGridYdefault; } break; @@ -666,9 +671,9 @@ void Plot::keyPressEvent(QKeyEvent *event) break; case Qt::Key_L: - GridLocked = !GridLocked; - if (GridLocked) - GridOffset += (GraphStart - unlockStart); + master->conn->GridLocked = !master->conn->GridLocked; + if (master->conn->GridLocked) + master->conn->GridOffset += (GraphStart - unlockStart); else unlockStart = GraphStart; break; diff --git a/client/proxguiqt.h b/client/proxguiqt.h index fe5c2973..c911ab2c 100644 --- a/client/proxguiqt.h +++ b/client/proxguiqt.h @@ -24,6 +24,9 @@ #include "uart.h" #include "ui/ui_overlays.h" #include "uart.h" +#include "comms.h" + +class ProxGuiQT; /** * @brief The actual plot, black area were we paint the graph @@ -31,6 +34,7 @@ class Plot: public QWidget { private: + ProxGuiQT *master; int GraphStart; double GraphPixelsPerPoint; int CursorAPos; @@ -44,7 +48,7 @@ private: void setMaxAndStart(int *buffer, int len, QRect plotRect); QColor getColor(int graphNum); public: - Plot(QWidget *parent = 0); + Plot(QWidget *parent = 0, ProxGuiQT *master = NULL); protected: void paintEvent(QPaintEvent *event); @@ -54,7 +58,6 @@ protected: void keyPressEvent(QKeyEvent *event); }; -class ProxGuiQT; /** * The window with plot and controls @@ -101,15 +104,18 @@ class ProxGuiQT : public QObject int argc; char **argv; void (*main_func)(void); - + public: ProxGuiQT(int argc, char **argv); ~ProxGuiQT(void); void ShowGraphWindow(void); void RepaintGraphWindow(void); void HideGraphWindow(void); - void MainLoop(void); + void MainLoop(pm3_connection *conn); void Exit(void); + // Shared for ProxWidget + pm3_connection *conn; + private slots: void _ShowGraphWindow(void); void _RepaintGraphWindow(void); @@ -132,7 +138,7 @@ public: private: char *script_cmds_file = NULL; bool usb_present; - serial_port *sp = NULL; + serial_port *port = NULL; bool flush_after_write = false; }; diff --git a/client/proxmark3.c b/client/proxmark3.c index 09472c51..f07f674f 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -56,6 +56,11 @@ void main_loop(char *script_cmds_file, bool usb_present, serial_port* port, bool conn.offline = true; } +#ifdef HAVE_GUI + // Setup GUI with reference to our connection struct. + MainGraphics(&conn); +#endif + FILE *script_file = NULL; char script_cmd_buf[256]; // iceman, needs lua script the same file_path_buffer as the rest @@ -234,14 +239,12 @@ int main(int argc, char* argv[]) { #ifdef HAVE_GUI #ifdef _WIN32 InitGraphics(argc, argv, script_cmds_file, usb_present, sp, flush_after_write); - MainGraphics(); #else char* display = getenv("DISPLAY"); if (display && strlen(display) > 1) { InitGraphics(argc, argv, script_cmds_file, usb_present, sp, flush_after_write); - MainGraphics(); } else { @@ -249,7 +252,7 @@ int main(int argc, char* argv[]) { } #endif #else - main_loop(script_cmds_file, usb_present, sp); + main_loop(script_cmds_file, usb_present, sp, flush_after_write); #endif // Clean up the port diff --git a/client/ui.h b/client/ui.h index ed07e6e4..7c3e15db 100644 --- a/client/ui.h +++ b/client/ui.h @@ -21,9 +21,9 @@ pthread_mutex_t print_lock; extern uint8_t g_debugMode; void ShowGui(void); -void HideGraphWindow(pm3_connection* conn); -void ShowGraphWindow(pm3_connection* conn); -void RepaintGraphWindow(pm3_connection* conn); +void HideGraphWindow(); +void ShowGraphWindow(); +void RepaintGraphWindow(); void PrintAndLog(char *fmt, ...); void SetLogFilename(char *fn); void SetFlushAfterWrite(bool flush_after_write); From e3fdbbc90b2acdf4f308142e1536a5fda2681624 Mon Sep 17 00:00:00 2001 From: Michael Farrell Date: Wed, 18 Oct 2017 00:14:25 +1100 Subject: [PATCH 4/4] wip rebasing libmk2 --- client/proxgui.cpp | 9 +++------ client/proxmark3.c | 35 +++++++++++++++++++++++------------ client/proxmark3.h | 1 + 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/client/proxgui.cpp b/client/proxgui.cpp index 8ddb4d82..f2e8fe4b 100644 --- a/client/proxgui.cpp +++ b/client/proxgui.cpp @@ -65,13 +65,10 @@ extern "C" void MainGraphics(pm3_connection* conn) extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write) { -#ifdef Q_WS_X11 - bool useGUI = getenv("DISPLAY") != 0; -#else - bool useGUI = true; -#endif - if (!useGUI) + if (!has_gui()) { + printf("Oops, InitGraphics called when we have no GUI!\n"); return; + } gui = new ProxGuiQT(argc, argv); main_loop_thread = new WorkerThread(script_cmds_file, usb_present, port, flush_after_write); diff --git a/client/proxmark3.c b/client/proxmark3.c index f07f674f..4d7114f1 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -27,6 +27,23 @@ #include "whereami.h" #include "comms.h" +/* Returns true if we have a display that we should set up a GUI on. + */ +bool has_gui() { +#ifdef HAVE_GUI +# ifdef Q_WS_X11 + // Check for "DISPLAY" environment variable. If present, we have a GUI + char* display = getenv("DISPLAY"); + return (display && strlen(display) > 1); +# else + // Non-X11 always has GUI, if this is built. + return true; +# endif +#else + // Built without GUI support + return false; +#endif +} void main_loop(char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write) { pm3_connection conn; @@ -57,8 +74,10 @@ void main_loop(char *script_cmds_file, bool usb_present, serial_port* port, bool } #ifdef HAVE_GUI - // Setup GUI with reference to our connection struct. - MainGraphics(&conn); + if (has_gui()) { + // Setup GUI with reference to our connection struct. + MainGraphics(&conn); + } #endif FILE *script_file = NULL; @@ -237,23 +256,15 @@ int main(int argc, char* argv[]) { pthread_mutex_init(&print_lock, NULL); #ifdef HAVE_GUI -#ifdef _WIN32 - InitGraphics(argc, argv, script_cmds_file, usb_present, sp, flush_after_write); -#else - char* display = getenv("DISPLAY"); - - if (display && strlen(display) > 1) + if (has_gui()) { InitGraphics(argc, argv, script_cmds_file, usb_present, sp, flush_after_write); } else +#endif { main_loop(script_cmds_file, usb_present, sp, flush_after_write); } -#endif -#else - main_loop(script_cmds_file, usb_present, sp, flush_after_write); -#endif // Clean up the port if (usb_present) { diff --git a/client/proxmark3.h b/client/proxmark3.h index 91e0de73..4d64f767 100644 --- a/client/proxmark3.h +++ b/client/proxmark3.h @@ -22,6 +22,7 @@ extern "C" { #endif +bool has_gui(); const char *get_my_executable_path(void); const char *get_my_executable_directory(void); void main_loop(char *script_cmds_file, bool usb_present, serial_port* port, bool flush_after_write);