Repository navigation
Expand file tree
/
Copy pathScanner.cpp
More file actions
315 lines (260 loc) · 11.9 KB
/
Copy pathScanner.cpp
File metadata and controls
315 lines (260 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#include "Scanner.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <map>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
using namespace std;
Scanner::Scanner() {
scanStart = 0;
scanEnd = 0;
}
// --- PE PARSER HELPERS / AUXILIARES DO PARSER PE ---
// Reads a 32-bit unsigned integer in Little-Endian format from the buffer
// Lê um inteiro sem sinal de 32 bits (Little-Endian) diretamente do buffer
uint32_t Scanner::readU32(size_t offset) {
if (offset + 4 > targetBuffer.size()) return 0;
return targetBuffer[offset] | (targetBuffer[offset + 1] << 8) |
(targetBuffer[offset + 2] << 16) | (targetBuffer[offset + 3] << 24);
}
// Reads a 16-bit unsigned integer in Little-Endian format from the buffer
// Lê um inteiro sem sinal de 16 bits (Little-Endian) diretamente do buffer
uint16_t Scanner::readU16(size_t offset) {
if (offset + 2 > targetBuffer.size()) return 0;
return targetBuffer[offset] | (targetBuffer[offset + 1] << 8);
}
// Parses the Portable Executable (PE) headers and maps its sections
// Faz o parsing dos cabeçalhos do arquivo PE e mapeia suas seções
bool Scanner::parsePE() {
if (targetBuffer.size() < 64) return false;
// Verifies the DOS MZ header signature (0x5A4D)
// Verifica a assinatura MZ do cabeçalho DOS
if (targetBuffer[0] != 0x4D || targetBuffer[1] != 0x5A) return false;
uint32_t peOffset = readU32(0x3C);
if (peOffset + 24 > targetBuffer.size()) return false;
// Verifies the NT PE header signature (PE\0\0)
// Verifica a assinatura PE dos cabeçalhos NT
if (targetBuffer[peOffset] != 'P' || targetBuffer[peOffset + 1] != 'E' ||
targetBuffer[peOffset + 2] != 0 || targetBuffer[peOffset + 3] != 0) return false;
cout << "[+] Valid Windows PE File detected. Mapping all sections..." << endl;
uint16_t numSections = readU16(peOffset + 6);
uint16_t optHeaderSize = readU16(peOffset + 20);
uint32_t sectionOffset = peOffset + 24 + optHeaderSize;
foundSections.clear();
// Maps the main PE header as the first virtual section
// Mapeia o cabeçalho principal como a primeira seção virtual
foundSections.push_back({ "HEADER", 0, peOffset + 24 });
for (int i = 0; i < numSections; ++i) {
if (sectionOffset + 40 > targetBuffer.size()) break;
string secName = "";
for (int j = 0; j < 8; ++j) {
char c = targetBuffer[sectionOffset + j];
if (c == 0) break;
secName += c;
}
uint32_t rawSize = readU32(sectionOffset + 16);
uint32_t rawPointer = readU32(sectionOffset + 20);
// Ensures the section has a valid physical size and offset on disk
// Garante que a seção possui um tamanho e ponteiro físico válidos no disco
if (rawSize > 0 && rawPointer > 0) {
foundSections.push_back({ secName, rawPointer, rawPointer + rawSize });
cout << " [>] Section: " << left << setw(8) << secName
<< " | Offset: 0x" << hex << uppercase << rawPointer
<< " | Size: " << dec << rawSize << " bytes" << endl;
}
sectionOffset += 40;
}
return true;
}
// --- SCANNER MODES (STATIC & DYNAMIC) / MODOS DE ESCANEAMENTO ---
// Attaches to a live process and dumps its memory for dynamic analysis
// Anexa a um processo em execução e extrai sua memória para análise dinâmica
bool Scanner::scanProcess(DWORD pid, std::string outputFile) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (!hProcess) {
cerr << "[-] Failed to open process. Error: " << GetLastError() << endl;
return false;
}
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) {
MODULEINFO modInfo;
if (GetModuleInformation(hProcess, hMod, &modInfo, sizeof(modInfo))) {
size_t bufferSize = modInfo.SizeOfImage;
targetBuffer.resize(bufferSize);
SIZE_T bytesRead;
if (ReadProcessMemory(hProcess, modInfo.lpBaseOfDll, targetBuffer.data(), bufferSize, &bytesRead)) {
cout << "[+] Successfully read " << bytesRead << " bytes from live RAM (PID: " << pid << ")" << endl;
// Treats the entire loaded memory dump as a single continuous block
// Trata todo o dump carregado em memória RAM como um bloco contínuo único
foundSections.clear();
SectionRange fullImage = { "RAM_IMG", 0, (uint32_t)bufferSize };
foundSections.push_back(fullImage);
this->run(outputFile);
}
}
}
CloseHandle(hProcess);
return true;
}
// Loads a static target file from disk into the local buffer
// Carrega um arquivo alvo estático do disco diretamente para o buffer
bool Scanner::loadTarget(const string& filename) {
ifstream file(filename, ios::binary | ios::ate);
if (!file.is_open()) return false;
streamsize size = file.tellg();
file.seekg(0, ios::beg);
targetBuffer.resize(size);
if (file.read(reinterpret_cast<char*>(targetBuffer.data()), size)) {
// If it's not a valid PE file, treats it as raw binary data
// Se não for um executável PE válido, mapeia como arquivo binário bruto (Raw Data)
if (!parsePE()) {
foundSections.clear();
SectionRange fullFile = { "RAW_DATA", 0, (uint32_t)targetBuffer.size() };
foundSections.push_back(fullFile);
}
return true;
}
return false;
}
// --- CORE ENGINE LOGIC / LÓGICA CENTRAL DA ENGINE ---
// Compiles a string-based hex pattern (e.g., "FF ?? 00") into byte structures
// Compila uma assinatura hexadecimal em string para estruturas de bytes com suporte a curingas
vector<SigByte> Scanner::compilePattern(const string& hexStr) {
vector<SigByte> result;
stringstream ss(hexStr);
string byteStr;
while (ss >> byteStr) {
SigByte b;
if (byteStr == "??" || byteStr == "?") {
b.isWildcard = true;
b.value = 0x00;
} else {
b.isWildcard = false;
b.value = static_cast<uint8_t>(stoi(byteStr, nullptr, 16));
}
result.push_back(b);
}
return result;
}
// Parses the wordlist file and builds the signature database
// Analisa o arquivo de wordlist e constrói o banco de assinaturas estruturado
bool Scanner::loadSignatures(const string& filename) {
ifstream file(filename);
string line;
if (!file.is_open()) return false;
signatures.clear();
while (getline(file, line)) {
if (line.empty() || line[0] == '#') continue;
size_t firstPipe = line.find('|');
size_t secondPipe = line.find('|', firstPipe + 1);
if (firstPipe != string::npos && secondPipe != string::npos) {
Signature sig;
sig.category = line.substr(0, firstPipe);
sig.originalPattern = line.substr(firstPipe + 1, secondPipe - firstPipe - 1);
sig.description = line.substr(secondPipe + 1);
sig.compiledPattern = compilePattern(sig.originalPattern);
signatures.push_back(sig);
}
}
return true;
}
// Bootstraps the scanner by loading both the rules and the target data
// Inicializa o scanner carregando as regras (assinaturas) e os dados do alvo
bool Scanner::init(const string& sigFile, const string& targetFile) {
if (!loadSignatures(sigFile)) {
cerr << "[-] Error: Could not load signatures." << endl;
return false;
}
cout << "[+] Loaded " << signatures.size() << " signatures from wordlist." << endl;
if (!loadTarget(targetFile)) {
cerr << "[-] Error: Could not load target." << endl;
return false;
}
return true;
}
// Executes the pattern matching algorithm across the loaded memory buffer
// Executa o algoritmo de busca de padrões varrendo todo o buffer carregado
void Scanner::run(const string& outputFile) {
cout << "[*] Starting Global Deep Scan (0x0 to 0x" << hex << uppercase << targetBuffer.size() << ")..." << endl;
if (targetBuffer.empty() || signatures.empty()) {
cout << "[-] No data to scan. Exiting." << endl;
return;
}
int totalMatches = 0;
map<string, vector<MatchRecord>> categorizedResults;
// Deep scan loop: evaluates every byte sequence against the signature database
// Loop de escaneamento profundo: avalia as sequências de bytes contra o banco de assinaturas
for (size_t i = 0; i < targetBuffer.size(); ++i) {
for (const auto& sig : signatures) {
bool match = true;
size_t sigSize = sig.compiledPattern.size();
if (i + sigSize > targetBuffer.size()) continue;
for (size_t j = 0; j < sigSize; ++j) {
if (!sig.compiledPattern[j].isWildcard &&
targetBuffer[i + j] != sig.compiledPattern[j].value) {
match = false;
break;
}
}
if (match) {
totalMatches++;
// Resolves the physical or virtual section where the match occurred
// Resolve a seção física ou virtual onde a assinatura foi encontrada
string location = "OVERLAY/UNKNOWN";
for (const auto& sec : foundSections) {
if (i >= sec.start && i < sec.end) {
location = sec.name;
break;
}
}
MatchRecord record = { i, sig.originalPattern, sig.description + " [In: " + location + "]" };
categorizedResults[sig.category].push_back(record);
}
}
}
// --- DISPLAY RESULTS / EXIBIÇÃO DE RESULTADOS ---
cout << "\n=========================================" << endl;
cout << " SCAN RESULTS " << endl;
cout << "=========================================" << endl;
if (categorizedResults.empty()) {
cout << "[+] Binary looks clean. No signatures found." << endl;
} else {
for (const auto& categoryPair : categorizedResults) {
const string& categoryName = categoryPair.first;
const vector<MatchRecord>& matches = categoryPair.second;
cout << "\n" << categoryName << " - Found " << matches.size() << " match(es):" << endl;
cout << "-----------------------------------------" << endl;
// Smart display limit to prevent terminal flooding
// Limite inteligente de exibição para não poluir o terminal
size_t displayLimit = (matches.size() > 10) ? 5 : matches.size();
for (size_t i = 0; i < displayLimit; ++i) {
cout << " [+] Offset: 0x" << uppercase << hex << setfill('0') << setw(8) << matches[i].offset << dec
<< " | " << matches[i].description << endl;
}
if (matches.size() > 10) {
cout << " ... and " << (matches.size() - displayLimit) << " more hidden to prevent terminal flood." << endl;
}
}
}
cout << "\n[*] Scan complete. Total matches across all categories: " << totalMatches << endl;
// Exports the full scanning report to disk if a filename was provided
// Exporta o relatório completo de escaneamento para o disco se um arquivo for especificado
if (!outputFile.empty()) {
ofstream outFile(outputFile);
if (outFile.is_open()) {
outFile << "SIGHUNTER DEEP SCAN REPORT\n==========================\n\n";
for (const auto& cp : categorizedResults) {
outFile << "[" << cp.first << "]\n";
for (const auto& m : cp.second) {
outFile << "0x" << hex << uppercase << m.offset << " | " << m.description << "\n";
}
outFile << "\n";
}
outFile.close();
cout << "[+] Full report exported to: " << outputFile << endl;
}
}
}