Skip to content

A Hardware Hacking Tool with Web-Based CLI That Speaks Every Protocol

add flash analyze, flash strings, flash search for spi

Geo1caa0b737afc
diff --git a/platformio.ini b/platformio.ini
index d3fdff14..87c70d8e 100644
--- a/platformio.ini
+++ b/platformio.ini
@@ -26,6 +26,7 @@ build_flags =
-D CONFIG_TINYUSB_HID_ENABLED=1
-D ARDUINO_USB_MODE=1
-D ARDUINO_USB_CDC_ON_BOOT=1
+
-DDEVICE_CARDPUTER
; --- Pin in use ---
@@ -103,10 +104,10 @@ build_flags =
-DI2C_FREQ=100000
; --- SPI ---
- -DSPI_CS_PIN=33
- -DSPI_CLK_PIN=0
- -DSPI_MISO_PIN=25
- -DSPI_MOSI_PIN=26
+ -DSPI_CS_PIN=0
+ -DSPI_CLK_PIN=25
+ -DSPI_MISO_PIN=32
+ -DSPI_MOSI_PIN=33
; --- Infrared ---
-DIR_TX_PIN=19
diff --git a/src/Controllers/SpiController.cpp b/src/Controllers/SpiController.cpp
index 56353a2d..9e43adca 100644
--- a/src/Controllers/SpiController.cpp
+++ b/src/Controllers/SpiController.cpp
@@ -2,8 +2,15 @@
SpiController::SpiController(ITerminalView& terminalView, IInput& terminalInput,
SpiService& spiService, SdService& sdService, ArgTransformer& argTransformer,
- UserInputManager& userInputManager)
- : terminalView(terminalView), terminalInput(terminalInput), spiService(spiService), sdService(sdService), argTransformer(argTransformer), userInputManager(userInputManager) {}
+ UserInputManager& userInputManager, BinaryAnalyzeManager& binaryAnalyzeManager)
+ : terminalView(terminalView),
+ terminalInput(terminalInput),
+ spiService(spiService),
+ sdService(sdService),
+ argTransformer(argTransformer),
+ userInputManager(userInputManager),
+ binaryAnalyzeManager(binaryAnalyzeManager)
+{}
/*
Entry point for command
@@ -25,16 +32,20 @@ void SpiController::handleCommand(const TerminalCommand& cmd) {
else if (cmd.getRoot() == "flash") {
if (cmd.getSubcommand() == "probe") {
handleFlashProbe();
+ } else if (cmd.getSubcommand() == "analyze") {
+ handleFlashAnalyze(cmd);
+ } else if (cmd.getSubcommand() == "strings") {
+ handleFlashStrings(cmd);
+ } else if (cmd.getSubcommand() == "search") {
+ handleFlashSearch(cmd);
} else if (cmd.getSubcommand() == "read") {
handleFlashRead(cmd);
} else if (cmd.getSubcommand() == "write") {
handleFlashWrite(cmd);
- } else if (cmd.getRoot() == "sdcard") {
- handleSdCard();
} else if (cmd.getSubcommand() == "erase") {
handleFlashErase(cmd);
} else {
- terminalView.println("Unknown SPI flash command. Use: probe, read, write, erase");
+ terminalView.println("Unknown SPI flash command. Use: probe, analyze, strings, read, write, erase");
}
}
@@ -115,13 +126,265 @@ void SpiController::handleFlashProbe() {
terminalView.println("");
}
+/*
+Flash Analyze
+*/
+void SpiController::handleFlashAnalyze(const TerminalCommand& cmd) {
+ if (!checkFlashPresent()) return;
+
+ // Start address if any
+ uint32_t start = 0;
+ std::vector<std::string> args = argTransformer.splitArgs(cmd.getArgs());
+ if (!args.empty()) start = argTransformer.parseHexOrDec32(args[0]);
+
+ terminalView.println("\nSPI Flash Analyze: SPI Flash from 0x" + argTransformer.toHex(start, 6) + "... Press [ENTER] to stop.");
+
+ // Get flash size
+ uint8_t id[3];
+ spiService.readFlashIdRaw(id);
+ const FlashChipInfo* chip = findFlashInfo(id[0], id[1], id[2]);
+ uint32_t flashSize = chip ? chip->capacityBytes : spiService.calculateFlashCapacity(id[2]);
+
+ // Analyze
+ BinaryAnalyzeManager::AnalysisResult result = binaryAnalyzeManager.analyze(start, flashSize);
+
+ // Calculate Summary
+ float printablePct = 100.0f * result.printableTotal / result.totalBytes;
+ float nullsPct = 100.0f * result.nullsTotal / result.totalBytes;
+ float ffPct = 100.0f * result.ffTotal / result.totalBytes;
+ uint32_t dataBytes = result.totalBytes - (result.nullsTotal + result.ffTotal);
+ float dataPct = 100.0f * dataBytes / result.totalBytes;
+ float normalizedEntropy = result.avgEntropy / 8.0f;
+ std::string bar = "[";
+ int barLength = 20;
+ int filled = std::round(normalizedEntropy * barLength);
+ for (int i = 0; i < barLength; ++i)
+ bar += (i < filled) ? '#' : '.';
+ bar += "]";
+
+ // Entropy infos
+ std::string interpretation;
+ if (normalizedEntropy >= 0.95f)
+ interpretation = "→ likely encrypted/compressed";
+ else if (normalizedEntropy >= 0.85f)
+ interpretation = "→ mostly compressed";
+ else if (normalizedEntropy >= 0.65f)
+ interpretation = "→ mixed content";
+ else if (normalizedEntropy >= 0.4f)
+ interpretation = "→ partially structured";
+ else if (normalizedEntropy >= 0.2f)
+ interpretation = "→ contains padding";
+ else
+ interpretation = "→ likely empty";
+
+ // Display Summary
+ terminalView.println("");
+ terminalView.println("\nSPI Flash Analysis Summary:");
+ terminalView.println(" Blocks analyzed : " + std::to_string(result.blocks));
+ terminalView.println(" Total bytes : " + std::to_string(result.totalBytes));
+ terminalView.println(" Avg entropy (0-1) : " + argTransformer.formatFloat(normalizedEntropy, 2) + " " + bar + " " + interpretation);
+ terminalView.println(" Printable ASCII : " + std::to_string(result.printableTotal) + " (" + argTransformer.formatFloat(printablePct, 1) + "%)");
+ terminalView.println(" Null bytes (0x00) : " + std::to_string(result.nullsTotal) + " (" + argTransformer.formatFloat(nullsPct, 1) + "%)");
+ terminalView.println(" FF bytes (0xFF) : " + std::to_string(result.ffTotal) + " (" + argTransformer.formatFloat(ffPct, 1) + "%)");
+ terminalView.println(" Likely useful data : " + std::to_string(dataBytes) + " (" + argTransformer.formatFloat(dataPct, 1) + "%)");
+
+ // Secrets
+ if (!result.foundSecrets.empty()) {
+ terminalView.println("\n Detected sensitive patterns:");
+ for (const auto& entry : result.foundSecrets) {
+ terminalView.println(" " + entry);
+ }
+ }
+
+ // Files
+ if (!result.foundFiles.empty()) {
+ terminalView.println("\n Detected file signatures:");
+ for (const auto& entry : result.foundFiles) {
+ terminalView.println(" " + entry);
+ }
+ } else {
+ terminalView.println("\n No known file signatures found.");
+ }
+
+ terminalView.println("\n SPI Flash Analyze: Done.\n");
+}
+
+/*
+Flash Strings
+*/
+void SpiController::handleFlashStrings(const TerminalCommand& cmd) {
+ // Check chip presence
+ if (!checkFlashPresent()) return;
+
+ terminalView.println("\nSPI Flash: Extracting strings... Press [ENTER] to stop.\n");
+
+ // Validate and parse args
+ std::vector<std::string> args = argTransformer.splitArgs(cmd.getArgs());
+ uint8_t minStringLen = 7; // default
+ if (!args.empty() && argTransformer.isValidNumber(args[0])) {
+ minStringLen = argTransformer.parseHexOrDec(args[0]);
+ if (minStringLen < 1) minStringLen = 1;
+ if (minStringLen > 255) minStringLen = 255;
+ }
+
+ const uint32_t blockSize = 512;
+ uint8_t buffer[blockSize];
+ std::string currentStr;
+ uint32_t currentAddr = 0;
+ uint32_t stringStartAddr = 0;
+ bool inString = false;
+
+ // Get flash size
+ uint8_t id[3];
+ spiService.readFlashIdRaw(id);
+ const FlashChipInfo* chip = findFlashInfo(id[0], id[1], id[2]);
+ uint32_t flashSize = chip ? chip->capacityBytes : spiService.calculateFlashCapacity(id[2]);
+
+ // Read flash in chuncks
+ for (uint32_t addr = 0; addr < flashSize; addr += blockSize) {
+ spiService.readFlashData(addr, buffer, blockSize);
+
+ // Read blocks
+ for (uint32_t i = 0; i < blockSize; ++i) {
+ uint8_t b = buffer[i];
+ uint32_t absoluteAddr = addr + i;
+
+ if (b >= 32 && b <= 126) { // printable ASCII
+ if (!inString) {
+ inString = true;
+ stringStartAddr = absoluteAddr;
+ }
+ currentStr += static_cast<char>(b);
+ } else {
+ if (inString && currentStr.length() >= minStringLen) {
+ terminalView.println(
+ "0x" + argTransformer.toHex(stringStartAddr, 6) + ": " + currentStr
+ );
+ }
+ currentStr.clear();
+ inString = false;
+ }
+
+ // Quit if user presses ENTER
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("\nSPI Flash: Extraction cancelled by user.");
+ return;
+ }
+ }
+ }
+
+ // if remaining string
+ if (inString && currentStr.length() >= minStringLen) {
+ terminalView.println(
+ "0x" + argTransformer.toHex(stringStartAddr, 6) + ": " + currentStr
+ );
+ }
+
+ terminalView.println("\nSPI Flash: String extraction complete.\n");
+}
+
+/*
+Flash Search
+*/
+void SpiController::handleFlashSearch(const TerminalCommand& cmd) {
+ // Check chip presence
+ if (!checkFlashPresent()) return;
+
+ // Checks args
+ std::vector<std::string> args = argTransformer.splitArgs(cmd.getArgs());
+ if (args.empty() || args[0].empty()) {
+ terminalView.println("Usage: flash search <string> [start_address]");
+ return;
+ }
+
+ // Parse
+ std::string needle = args[0];
+ std::vector<uint8_t> pattern(needle.begin(), needle.end());
+ uint32_t startAddr = 0;
+ if (args.size() >= 2 && argTransformer.isValidNumber(args[1])) {
+ startAddr = argTransformer.parseHexOrDec32(args[1]);
+ }
+
+ terminalView.println("\nSearching for \"" + needle + "\" in SPI flash from 0x" + argTransformer.toHex(startAddr, 6) + "... Press [ENTER] to stop.\n");
+
+ const uint32_t blockSize = 512;
+ const uint32_t contextSize = 16; // characters before and after
+ uint8_t buffer[blockSize + 32];
+
+ // Get flash size
+ uint8_t id[3];
+ spiService.readFlashIdRaw(id);
+ const FlashChipInfo* chip = findFlashInfo(id[0], id[1], id[2]);
+ uint32_t flashSize = chip ? chip->capacityBytes : spiService.calculateFlashCapacity(id[2]);
+
+ // Read flash in chunks
+ for (uint32_t addr = startAddr; addr < flashSize; addr += blockSize - pattern.size()) {
+ spiService.readFlashData(addr, buffer, blockSize + pattern.size() - 1);
+
+ // Read block
+ for (uint32_t i = 0; i <= blockSize; ++i) {
+ if (i + pattern.size() > blockSize + pattern.size() - 1) break;
+
+ bool match = true;
+ for (size_t j = 0; j < pattern.size(); ++j) {
+ if (buffer[i + j] != pattern[j]) {
+ match = false;
+ break;
+ }
+ }
+
+ // Found a matching string
+ if (match) {
+ uint32_t matchAddr = addr + i;
+ std::string context;
+
+ // Before the pattern
+ for (int j = (int)i - (int)contextSize; j < (int)i; ++j) {
+ if (j >= 0) {
+ char c = (char)buffer[j];
+ context += (isprint(c) ? c : '.');
+ }
+ }
+
+ // Pattern
+ context += "[";
+ for (size_t j = 0; j < pattern.size(); ++j) {
+ char c = (char)buffer[i + j];
+ context += (isprint(c) ? c : '.');
+ }
+ context += "]";
+
+ // After the pattern
+ for (uint32_t j = i + pattern.size(); j < i + pattern.size() + contextSize && j < blockSize + pattern.size(); ++j) {
+ char c = (char)buffer[j];
+ context += (isprint(c) ? c : '.');
+ }
+
+ terminalView.println("0x" + argTransformer.toHex(matchAddr, 6) + ": " + context);
+ }
+
+ // Allow user to interrupt
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("\nSPI Flash Search: Cancelled by user.\n");
+ return;
+ }
+ }
+ }
+
+ terminalView.println("\nSearch complete.");
+}
+
/*
Flash Read
*/
void SpiController::handleFlashRead(const TerminalCommand& cmd) {
+ // Check chip presence
+ if (!checkFlashPresent()) return;
+
// Args (addr, length)
std::vector<std::string> args = argTransformer.splitArgs(cmd.getArgs());
-
if (args.size() < 2) {
terminalView.println("Usage: flash read <address> <length>");
return;
@@ -141,16 +404,6 @@ void SpiController::handleFlashRead(const TerminalCommand& cmd) {
return;
}
- // Detect flash
- uint8_t id[3];
- spiService.readFlashIdRaw(id);
- if ((id[0] == 0xFF && id[1] == 0xFF && id[2] == 0xFF) ||
- (id[0] == 0x00 && id[1] == 0x00 && id[2] == 0x00)) {
- terminalView.println("No SPI flash detected (bus error or missing chip).\n");
- return;
- }
-
-
// Read flash in chunks
terminalView.println("SPI Flash Read: In progress... Press [ENTER] to stop");
terminalView.println("");
@@ -228,6 +481,9 @@ void SpiController::readFlashInChunks(uint32_t address, uint32_t length) {
Flash Write
*/
void SpiController::handleFlashWrite(const TerminalCommand& cmd) {
+ // Check chip presence
+ if (!checkFlashPresent()) return;
+
// Confirm
if (!userInputManager.readYesNo("SPI Flash Write: Confirm write operation?", false)) {
terminalView.println("SPI Flash Write: Cancelled.\n");
@@ -291,23 +547,18 @@ void SpiController::handleFlashWrite(const TerminalCommand& cmd) {
Flash Erase
*/
void SpiController::handleFlashErase(const TerminalCommand& cmd) {
+ // Check chip presence
+ if (!checkFlashPresent()) return;
+
terminalView.println("");
-
if (!userInputManager.readYesNo("SPI Flash Erase: Erase entire flash memory?", false)) {
terminalView.println("SPI Flash Erase: Cancelled.\n");
return;
}
- // Check chip presence
+ // Get infos about the chip
uint8_t id[3];
spiService.readFlashIdRaw(id);
- if ((id[0] == 0xFF && id[1] == 0xFF && id[2] == 0xFF) ||
- (id[0] == 0x00 && id[1] == 0x00 && id[2] == 0x00)) {
- terminalView.println("No SPI flash detected. Aborting.\n");
- return;
- }
-
- // Get infos about the chip
const FlashChipInfo* chip = findFlashInfo(id[0], id[1], id[2]);
uint32_t freq = state.getSpiFrequency();
const uint32_t sectorSize = 4096; // standard
@@ -338,6 +589,24 @@ void SpiController::handleFlashErase(const TerminalCommand& cmd) {
terminalView.println("\r\nSPI Flash Erase: Complete.\n");
}
+/*
+Check Chip
+*/
+bool SpiController::checkFlashPresent() {
+ uint8_t id[3];
+ spiService.readFlashIdRaw(id);
+
+ bool invalid = (id[0] == 0xFF && id[1] == 0xFF && id[2] == 0xFF) ||
+ (id[0] == 0x00 && id[1] == 0x00 && id[2] == 0x00);
+
+ if (invalid) {
+ terminalView.println("No SPI flash detected (bus error or missing chip).\n");
+ return false;
+ }
+
+ return true;
+}
+
/*
Slave
*/
@@ -381,7 +650,7 @@ void SpiController::handleSlave() {
}
spiService.stopSlave(sclk, miso, mosi, cs);
- spiService.configure(mosi, miso, sclk, cs, state.getI2cFrequency()); // Reconfigure master
+ spiService.configure(mosi, miso, sclk, cs, state.getSpiFrequency()); // Reconfigure master
terminalView.println("SPI Slave: Cancelled by user.");
}
@@ -436,6 +705,9 @@ void SpiController::handleHelp() {
terminalView.println(" sdcard");
terminalView.println(" slave");
terminalView.println(" flash probe");
+ terminalView.println(" flash analyze [start address]");
+ terminalView.println(" flash strings [length]");
+ terminalView.println(" flash search <text>");
terminalView.println(" flash read <addr> <len>");
terminalView.println(" flash write <addr> <data>");
terminalView.println(" flash erase");
diff --git a/src/Controllers/SpiController.h b/src/Controllers/SpiController.h
index 48e23e1c..9f3268a2 100644
--- a/src/Controllers/SpiController.h
+++ b/src/Controllers/SpiController.h
@@ -11,13 +11,14 @@
#include "Models/ByteCode.h"
#include "Transformers/ArgTransformer.h"
#include "Managers/UserInputManager.h"
+#include "Managers/BinaryAnalyzeManager.h"
#include "States/GlobalState.h"
#include "Data/FlashDatabase.h"
class SpiController {
public:
// Constructor
- SpiController(ITerminalView& terminalView, IInput& terminalInput, SpiService& spiService, SdService& sdService, ArgTransformer& argTransformer, UserInputManager& userInputManager);
+ SpiController(ITerminalView& terminalView, IInput& terminalInput, SpiService& spiService, SdService& sdService, ArgTransformer& argTransformer, UserInputManager& userInputManager, BinaryAnalyzeManager& binaryAnalyzeManager);
// Entry point for handle raw user command
void handleCommand(const TerminalCommand& cmd);
@@ -35,6 +36,7 @@ private:
SdService& sdService;
ArgTransformer& argTransformer;
UserInputManager& userInputManager;
+ BinaryAnalyzeManager& binaryAnalyzeManager;
GlobalState& state = GlobalState::getInstance();
bool configured = false;
@@ -44,6 +46,15 @@ private:
// Probe flash chip and identify it
void handleFlashProbe();
+ // Analyze flash content
+ void handleFlashAnalyze(const TerminalCommand& cmd);
+
+ // Extract strings from the flash content
+ void handleFlashStrings(const TerminalCommand& cmd);
+
+ // Search pattern into the flash content
+ void handleFlashSearch(const TerminalCommand& cmd);
+
// Read data from flash memory
void handleFlashRead(const TerminalCommand& cmd);
void readFlashInChunks(uint32_t address, uint32_t length);
@@ -54,6 +65,9 @@ private:
// Erase flash memory
void handleFlashErase(const TerminalCommand& cmd);
+ // Check before any flash action
+ bool checkFlashPresent();
+
// SD operations
void handleSdCard();
@@ -66,4 +80,5 @@ private:
// Available commands
void handleHelp();
+
};
diff --git a/src/Controllers/UsbCardputerController.cpp b/src/Controllers/UsbCardputerController.cpp
index facad231..47a1544e 100644
--- a/src/Controllers/UsbCardputerController.cpp
+++ b/src/Controllers/UsbCardputerController.cpp
@@ -28,7 +28,7 @@ void UsbCardputerController::handleCommand(const TerminalCommand& cmd) {
else if (cmd.getRoot() == "gamepad") {
handleGamepad(cmd);
- }
+ }
else if (cmd.getRoot() == "reset") {
handleReset();
diff --git a/src/Controllers/UtilityController.cpp b/src/Controllers/UtilityController.cpp
index 4ac669d6..739c98c4 100644
--- a/src/Controllers/UtilityController.cpp
+++ b/src/Controllers/UtilityController.cpp
@@ -233,6 +233,9 @@ void UtilityController::handleHelp() {
terminalView.println(" sdcard - SD operations");
terminalView.println(" slave - Emulate SPI slave");
terminalView.println(" flash probe - Identify chip");
+ terminalView.println(" flash analyze [addr] - Identify content");
+ terminalView.println(" flash strings [len] - Extract strings");
+ terminalView.println(" flash search <str> - Search strings");
terminalView.println(" flash read <ad> <ln> - Read content");
terminalView.println(" flash write <ad> <d> - Write to flash");
terminalView.println(" flash erase - Erase flash");
diff --git a/src/Managers/BinaryAnalyzeManager.cpp b/src/Managers/BinaryAnalyzeManager.cpp
new file mode 100644
index 00000000..9fcc9119
--- /dev/null
+++ b/src/Managers/BinaryAnalyzeManager.cpp
@@ -0,0 +1,186 @@
+#include "BinaryAnalyzeManager.h"
+#include <cmath>
+#include <cstring>
+#include <sstream>
+#include <iomanip>
+
+BinaryAnalyzeManager::BinaryAnalyzeManager(SpiService& spi, ITerminalView& view, IInput& input)
+ : spiService(spi), terminalView(view), terminalInput(input) {}
+
+const char* BinaryAnalyzeManager::detectSensitivePattern(const uint8_t* buf, size_t size) {
+ static const char* patterns[] = {
+ "-----BEGIN RSA PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----", "-----BEGIN CERTIFICATE-----",
+ "ssh-rsa", "ssh-ed25519", "password=", "pwd=", "pass:", "login:", "user:", "admin",
+ "http://", "https://", "ftp://", "CONFIG_", "ENV_", "PATH=", "HOME=", "DEVICE="
+ };
+ static const char* labels[] = {
+ "RSA Private Key", "Private Key", "Certificate", "SSH RSA Key", "SSH Ed25519 Key",
+ "Password", "Password", "Password", "Login", "Username", "Admin string",
+ "URL", "URL", "FTP URL", "Config Variable", "Environment Variable",
+ "Path Variable", "Home Variable", "Device Variable"
+ };
+ static const size_t patternCount = sizeof(patterns) / sizeof(patterns[0]);
+
+ for (size_t i = 0; i < patternCount; ++i) {
+ size_t len = strlen(patterns[i]);
+ for (size_t j = 0; j + len <= size; ++j) {
+ bool match = true;
+ for (size_t k = 0; k < len; ++k) {
+ char c1 = std::tolower((unsigned char)buf[j + k]);
+ char c2 = std::tolower((unsigned char)patterns[i][k]);
+ if (c1 != c2) {
+ match = false;
+ break;
+ }
+ }
+ if (match) return labels[i];
+ }
+ }
+ return nullptr;
+}
+
+const char* BinaryAnalyzeManager::detectFileSignature(const uint8_t* buf, size_t size) {
+ for (size_t sig = 0; sig < knownSignaturesCount; ++sig) {
+ const auto& s = knownSignatures[sig];
+ if (size < s.length) continue;
+ for (size_t i = 0; i + s.length <= std::min(size_t(64), size); ++i) {
+ if (buf[i] != s.pattern[0]) continue;
+ if (memcmp(buf + i, s.pattern, s.length) == 0) return s.name;
+ }
+ }
+ return nullptr;
+}
+
+BinaryBlockStats BinaryAnalyzeManager::analyzeBlock(const uint8_t* buffer, size_t size) {
+ uint32_t printable = 0, nulls = 0, ff = 0, counts[256] = {0};
+ float entropy = 0;
+ for (size_t i = 0; i < size; ++i) {
+ uint8_t b = buffer[i];
+ counts[b]++;
+ if (b >= 32 && b <= 126) printable++;
+ if (b == 0x00) nulls++;
+ if (b == 0xFF) ff++;
+ }
+ for (int i = 0; i < 256; ++i) {
+ if (counts[i]) {
+ float p = (float)counts[i] / size;
+ entropy -= p * log2(p);
+ }
+ }
+ return {entropy, printable, nulls, ff, detectFileSignature(buffer, size)};
+}
+
+BinaryAnalyzeManager::AnalysisResult BinaryAnalyzeManager::analyze(uint32_t start, uint32_t flashSize, uint32_t blockSize) {
+ const uint32_t overlap = 32;
+ uint8_t buffer[blockSize + overlap];
+
+ uint32_t printableTotal = 0, nullsTotal = 0, ffTotal = 0, blocks = 0;
+ float entropySum = 0;
+ std::vector<std::string> foundFiles, foundSecrets;
+ uint32_t totalBlocks = (flashSize - start) / blockSize;
+ uint32_t dotInterval = std::max(totalBlocks / 30, 1u);
+
+ terminalView.print("In progress");
+
+ for (uint32_t addr = start; addr < flashSize; addr += blockSize, ++blocks) {
+ uint32_t readAddr = (addr >= overlap) ? (addr - overlap) : 0;
+ uint32_t readSize = (addr >= overlap) ? (blockSize + overlap) : (blockSize + addr);
+ spiService.readFlashData(readAddr, buffer, readSize);
+
+ const uint8_t* blockData = buffer + (addr >= overlap ? overlap : 0);
+
+ BinaryBlockStats stats = analyzeBlock(blockData, blockSize);
+ entropySum += stats.entropy;
+ printableTotal += stats.printable;
+ nullsTotal += stats.nulls;
+ ffTotal += stats.ff;
+
+ if (stats.signature) {
+ std::stringstream ss;
+ ss << "0x" << std::hex << std::uppercase << std::setw(6) << std::setfill('0') << addr;
+ ss << " → " << stats.signature;
+ foundFiles.push_back(ss.str());
+ }
+
+ const char* sensitive = detectSensitivePattern(buffer, readSize);
+ if (sensitive) {
+ std::stringstream ss;
+ ss << "0x" << std::hex << std::uppercase << std::setw(6) << std::setfill('0') << addr;
+ ss << " → Possible " << sensitive;
+ foundSecrets.push_back(ss.str());
+ }
+
+ if (blocks % dotInterval == 0) {
+ terminalView.print(".");
+ }
+
+ char c = terminalInput.readChar();
+ if (c == '\r' || c == '\n') {
+ terminalView.println("\n[PARTIAL ANALYSIS] Stopped by User.\n");
+ break;
+ };
+ }
+
+ float avgEntropy = (blocks > 0) ? (entropySum / blocks) : 0;
+ return {avgEntropy, blocks * blockSize, blocks, printableTotal, nullsTotal, ffTotal, foundFiles, foundSecrets};
+}
+
+std::vector<std::string> BinaryAnalyzeManager::extractPrintableStrings(const uint8_t* buf, size_t size, size_t minLen) {
+ std::vector<std::string> strings;
+ std::string current;
+ for (size_t i = 0; i < size; ++i) {
+ char c = buf[i];
+ if (c >= 32 && c <= 126) {
+ current += c;
+ } else {
+ if (current.length() >= minLen) {
+ strings.push_back(current);
+ }
+ current.clear();
+ }
+ }
+ if (current.length() >= minLen) strings.push_back(current);
+ return strings;
+}
+
+const FileSignature BinaryAnalyzeManager::knownSignatures[] = {
+ // Executables / Boot
+ { "ELF Executable", (const uint8_t*)"\x7F""ELF", 4 },
+ { "U-Boot uImage", (const uint8_t*)"\x27\x05\x19\x56", 4 },
+
+ // Archives / Compression
+ { "GZIP Archive", (const uint8_t*)"\x1F\x8B", 2 },
+ { "ZIP Archive", (const uint8_t*)"\x50\x4B\x03\x04", 4 },
+ { "7z Archive", (const uint8_t*)"\x37\x7A\xBC\xAF\x27\x1C", 6 },
+ { "XZ Compressed", (const uint8_t*)"\xFD\x37\x7A\x58\x5A\x00", 6 },
+ { "LZMA compressed", (const uint8_t*)"\x5D\x00\x00", 3 },
+ { "LZ4 Frame", (const uint8_t*)"\x04\x22\x4D\x18", 4 },
+
+ // File systems
+ { "SquashFS", (const uint8_t*)"hsqs", 4 },
+ { "CRAMFS", (const uint8_t*)"\x45\x3D\xCD\x28", 4 },
+ { "JFFS2", (const uint8_t*)"\x85\x19\x03\x20", 4 },
+ { "UBI/UBIFS", (const uint8_t*)"\x55\x42\x49\x23", 4 },
+ { "Ext2/3/4 Superblock", (const uint8_t*)"\x53\xEF", 2 }, // offset 0x438 en réalité
+
+ // Images
+ { "PNG Image", (const uint8_t*)"\x89PNG", 4 },
+ { "JPEG Image", (const uint8_t*)"\xFF\xD8\xFF", 3 },
+ { "GIF Image", (const uint8_t*)"GIF8", 4 },
+ { "BMP Image", (const uint8_t*)"BM", 2 },
+
+ // Documents
+ { "PDF Document", (const uint8_t*)"%PDF-", 5 },
+ { "RTF Document", (const uint8_t*)"{\\rtf", 5 },
+ { "SQLite 3 DB", (const uint8_t*)"SQLite format 3", 16 },
+
+ // Audio / Video
+ { "MP3 (ID3)", (const uint8_t*)"ID3", 3 },
+ { "WAV Audio", (const uint8_t*)"RIFF", 4 }, // + "WAVE" after 8 bytes
+ { "AVI Video", (const uint8_t*)"RIFF", 4 }, // + "AVI " after 8 bytes
+
+ // Divers
+ { "TAR Archive (ustar)", (const uint8_t*)"ustar", 5 },
+ { "RAFFS", (const uint8_t*)"\x52\x41\x46\x46\x53", 5 },
+};
+const size_t BinaryAnalyzeManager::knownSignaturesCount = sizeof(BinaryAnalyzeManager::knownSignatures) / sizeof(FileSignature);
diff --git a/src/Managers/BinaryAnalyzeManager.h b/src/Managers/BinaryAnalyzeManager.h
new file mode 100644
index 00000000..c6825e00
--- /dev/null
+++ b/src/Managers/BinaryAnalyzeManager.h
@@ -0,0 +1,52 @@
+#pragma once
+
+#include <vector>
+#include <string>
+#include <Services/SpiService.h>
+#include "Interfaces/IInput.h"
+#include "Interfaces/ITerminalView.h"
+
+struct BinaryBlockStats {
+ float entropy;
+ uint32_t printable;
+ uint32_t nulls;
+ uint32_t ff;
+ const char* signature;
+};
+
+struct FileSignature {
+ const char* name;
+ const uint8_t* pattern;
+ size_t length;
+};
+
+class BinaryAnalyzeManager {
+public:
+ struct AnalysisResult {
+ float avgEntropy;
+ uint32_t totalBytes;
+ uint32_t blocks;
+ uint32_t printableTotal;
+ uint32_t nullsTotal;
+ uint32_t ffTotal;
+ std::vector<std::string> foundFiles;
+ std::vector<std::string> foundSecrets;
+ };
+
+ BinaryAnalyzeManager(SpiService& spi, ITerminalView& view, IInput& input);
+
+ AnalysisResult analyze(uint32_t start, uint32_t flashSize, uint32_t blockSize = 512);
+
+private:
+ SpiService& spiService;
+ IInput& terminalInput;
+ ITerminalView& terminalView;
+
+ BinaryBlockStats analyzeBlock(const uint8_t* buffer, size_t size);
+ const char* detectFileSignature(const uint8_t* buf, size_t size);
+ const char* detectSensitivePattern(const uint8_t* buf, size_t size);
+ std::vector<std::string> extractPrintableStrings(const uint8_t* buf, size_t size, size_t minLen = 8);
+ static const FileSignature knownSignatures[];
+ static const size_t knownSignaturesCount;
+};
+
diff --git a/src/Providers/DependencyProvider.cpp b/src/Providers/DependencyProvider.cpp
index db768878..9848cc8b 100644
--- a/src/Providers/DependencyProvider.cpp
+++ b/src/Providers/DependencyProvider.cpp
@@ -25,6 +25,7 @@ DependencyProvider::DependencyProvider(ITerminalView& terminalView, IDeviceView&
argTransformer(),
webRequestTransformer(),
commandHistoryManager(),
+ binaryAnalyzeManager(spiService, terminalView, terminalInput),
userInputManager(terminalView, terminalInput, argTransformer),
horizontalSelector(deviceView, deviceInput),
terminalTypeConfigurator(horizontalSelector),
@@ -34,7 +35,7 @@ DependencyProvider::DependencyProvider(ITerminalView& terminalView, IDeviceView&
infraredController(terminalView, terminalInput, infraredService, argTransformer, userInputManager),
utilityController(terminalView, terminalInput, pinService, userInputManager),
hdUartController(terminalView, terminalInput, deviceInput, hdUartService, uartService, argTransformer, userInputManager),
- spiController(terminalView, terminalInput, spiService, sdService, argTransformer, userInputManager),
+ spiController(terminalView, terminalInput, spiService, sdService, argTransformer, userInputManager, binaryAnalyzeManager),
jtagController(terminalView, terminalInput),
twoWireController(terminalView, terminalInput),
threeWireController(terminalView, terminalInput),
@@ -92,6 +93,7 @@ WebRequestTransformer& DependencyProvider::getWebRequestTransformer() {return we
// Managers
CommandHistoryManager& DependencyProvider::getCommandHistoryManager() { return commandHistoryManager ;}
UserInputManager& DependencyProvider::getUserInputManager() { return userInputManager; }
+BinaryAnalyzeManager& DependencyProvider::getFlashAnalyzeManager() { return binaryAnalyzeManager; }
// Selectors
HorizontalSelector& DependencyProvider::getHorizontalSelector() { return horizontalSelector ;}
diff --git a/src/Providers/DependencyProvider.h b/src/Providers/DependencyProvider.h
index bcaebba0..173d4f3c 100644
--- a/src/Providers/DependencyProvider.h
+++ b/src/Providers/DependencyProvider.h
@@ -44,10 +44,10 @@ and injecting shared instances of core components
#include "Transformers/ArgTransformer.h"
#include "Transformers/WebRequestTransformer.h"
#include "Managers/CommandHistoryManager.h"
+#include "Managers/BinaryAnalyzeManager.h"
#include "Managers/UserInputManager.h"
#include "Config/TerminalTypeConfigurator.h"
-
class DependencyProvider {
public:
DependencyProvider(ITerminalView& terminalView, IDeviceView& deviceView,
@@ -104,6 +104,7 @@ public:
// Managers
CommandHistoryManager& getCommandHistoryManager();
UserInputManager& getUserInputManager();
+ BinaryAnalyzeManager& getFlashAnalyzeManager();
// Selectors
HorizontalSelector& getHorizontalSelector();
@@ -162,6 +163,7 @@ private:
// Managers
CommandHistoryManager commandHistoryManager;
UserInputManager userInputManager;
+ BinaryAnalyzeManager binaryAnalyzeManager;
// Selectors
HorizontalSelector horizontalSelector;
diff --git a/src/Services/SpiService.cpp b/src/Services/SpiService.cpp
index 79ae7c8a..c77e5359 100644
--- a/src/Services/SpiService.cpp
+++ b/src/Services/SpiService.cpp
@@ -1,6 +1,8 @@
#include "Services/SpiService.h"
+
#include <ESP32SPISlave.h>
+
void SpiService::configure(uint8_t mosi, uint8_t miso, uint8_t sclk, uint8_t cs, uint32_t frequency) {
csPin = cs;
spiFrequency = frequency;
@@ -295,4 +297,4 @@ std::vector<std::vector<uint8_t>> SpiService::getSlaveData() {
std::vector<std::vector<uint8_t>> data(slaveBuffer.begin(), slaveBuffer.end());
slaveBuffer.clear();
return data;
-}
+}
\ No newline at end of file
diff --git a/src/Services/UsbCardputerService.cpp b/src/Services/UsbCardputerService.cpp
index 136a1330..b9bccb0d 100644
--- a/src/Services/UsbCardputerService.cpp
+++ b/src/Services/UsbCardputerService.cpp
@@ -168,6 +168,9 @@ bool UsbCardputerService::isMouseActive() const {
return mouseActive;
}
+bool UsbCardputerService::isGamepadActive() const {
+ return gamepadActive;
+}
int32_t UsbCardputerService::storageReadCallback(uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) {
const uint32_t secSize = SD.sectorSize();
@@ -244,9 +247,4 @@ void UsbCardputerService::reset() {
}
}
-bool UsbCardputerService::isGamepadActive() const {
- return gamepadActive;
-}
-
-
#endif
\ No newline at end of file
diff --git a/src/Transformers/ArgTransformer.cpp b/src/Transformers/ArgTransformer.cpp
index a2e14598..a0d20ecf 100644
--- a/src/Transformers/ArgTransformer.cpp
+++ b/src/Transformers/ArgTransformer.cpp
@@ -238,4 +238,10 @@ std::string ArgTransformer::toHex(uint32_t value, int width) {
std::stringstream ss;
ss << std::hex << std::uppercase << std::setfill('0') << std::setw(width) << value;
return ss.str();
+}
+
+std::string ArgTransformer::formatFloat(double value, int decimals) {
+ char buf[32];
+ snprintf(buf, sizeof(buf), ("%." + std::to_string(decimals) + "f").c_str(), value);
+ return std::string(buf);
}
\ No newline at end of file
diff --git a/src/Transformers/ArgTransformer.h b/src/Transformers/ArgTransformer.h
index e1abaa9b..57cd6b3b 100644
--- a/src/Transformers/ArgTransformer.h
+++ b/src/Transformers/ArgTransformer.h
@@ -27,4 +27,5 @@ public:
int8_t toClampedInt8(const std::string& input);
bool isValidSignedNumber(const std::string& input);
std::string toHex(uint32_t value, int width = 2);
+ std::string formatFloat(double value, int decimals);
};