diff --git a/3rdPartyLibs/capstone/include/capstone/capstone.h b/3rdPartyLibs/capstone/include/capstone/capstone.h new file mode 100644 index 00000000..d7d9653e --- /dev/null +++ b/3rdPartyLibs/capstone/include/capstone/capstone.h @@ -0,0 +1,1019 @@ +#ifndef CAPSTONE_ENGINE_H +#define CAPSTONE_ENGINE_H + +/* Capstone Disassembly Engine */ +/* By Nguyen Anh Quynh , 2013-2016 */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#if defined(CAPSTONE_HAS_OSXKERNEL) +#include +#else +#include +#include +#include +#endif + +#include "cs_operand.h" +#include "platform.h" + +#ifdef _MSC_VER +#pragma warning(disable : 4201) +#pragma warning(disable : 4100) +#define CAPSTONE_API __cdecl +#ifdef CAPSTONE_SHARED +#define CAPSTONE_EXPORT __declspec(dllexport) +#else // defined(CAPSTONE_STATIC) +#define CAPSTONE_EXPORT +#endif +#else +#define CAPSTONE_API +#if (defined(__GNUC__) || defined(__IBMC__)) && !defined(CAPSTONE_STATIC) +#define CAPSTONE_EXPORT __attribute__((visibility("default"))) +#else // defined(CAPSTONE_STATIC) +#define CAPSTONE_EXPORT +#endif +#endif + +#if (defined(__GNUC__) || defined(__IBMC__)) +#define CAPSTONE_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define CAPSTONE_DEPRECATED __declspec(deprecated) +#else +#pragma message( \ + "WARNING: You need to implement CAPSTONE_DEPRECATED for this compiler") +#define CAPSTONE_DEPRECATED +#endif + +// Capstone API version +#define CS_API_MAJOR 6 +#define CS_API_MINOR 0 + +// Version for bleeding edge code of the Github's "next" branch. +// Use this if you want the absolutely latest development code. +// This version number will be bumped up whenever we have a new major change. +#define CS_NEXT_VERSION 7 + +// Capstone package version +#define CS_VERSION_MAJOR CS_API_MAJOR +#define CS_VERSION_MINOR CS_API_MINOR +#define CS_VERSION_EXTRA 0 + +/// Macro to create combined version which can be compared to +/// result of cs_version() API. +#define CS_MAKE_VERSION(major, minor) ((major << 8) + minor) + +/// Maximum size of an instruction mnemonic string. +#define CS_MNEMONIC_SIZE 32 + +// Handle using with all API +typedef uintptr_t csh; + +/// Architecture type +typedef enum cs_arch { + CS_ARCH_ARM = 0, ///< ARM architecture (including Thumb, Thumb-2) +#ifdef CAPSTONE_AARCH64_COMPAT_HEADER + CS_ARCH_ARM64 = 1, ///< ARM64 +#else + CS_ARCH_AARCH64 = 1, ///< AArch64 +#endif +#ifdef CAPSTONE_SYSTEMZ_COMPAT_HEADER + CS_ARCH_SYSZ = 2, ///< SystemZ architecture +#else + CS_ARCH_SYSTEMZ = 2, ///< SystemZ architecture +#endif + CS_ARCH_MIPS, ///< Mips architecture + CS_ARCH_X86, ///< X86 architecture (including x86 & x86-64) + CS_ARCH_PPC, ///< PowerPC architecture + CS_ARCH_SPARC, ///< Sparc architecture + CS_ARCH_XCORE, ///< XCore architecture + CS_ARCH_M68K, ///< 68K architecture + CS_ARCH_TMS320C64X, ///< TMS320C64x architecture + CS_ARCH_M680X, ///< 680X architecture + CS_ARCH_EVM, ///< Ethereum architecture + CS_ARCH_MOS65XX, ///< MOS65XX architecture (including MOS6502) + CS_ARCH_WASM, ///< WebAssembly architecture + CS_ARCH_BPF, ///< Berkeley Packet Filter architecture (including eBPF) + CS_ARCH_RISCV, ///< RISCV architecture + CS_ARCH_SH, ///< SH architecture + CS_ARCH_TRICORE, ///< TriCore architecture + CS_ARCH_ALPHA, ///< Alpha architecture + CS_ARCH_HPPA, ///< HPPA architecture + CS_ARCH_LOONGARCH, ///< LoongArch architecture + CS_ARCH_XTENSA, ///< Xtensa architecture + CS_ARCH_ARC, ///< ARC architecture + CS_ARCH_MAX, + CS_ARCH_ALL = 0xFFFF, // All architectures - for cs_support() +} cs_arch; + +// Support value to verify diet mode of the engine. +// If cs_support(CS_SUPPORT_DIET) return True, the engine was compiled +// in diet mode. +#define CS_SUPPORT_DIET (CS_ARCH_ALL + 1) + +// Support value to verify X86 reduce mode of the engine. +// If cs_support(CS_SUPPORT_X86_REDUCE) return True, the engine was compiled +// in X86 reduce mode. +#define CS_SUPPORT_X86_REDUCE (CS_ARCH_ALL + 2) + +/// The mode bits of the AArch64 ISA (not vendor specific). +#define CS_MODE_AARCH64_ISA_BITS 0x00fffff8 +#define CS_MODE_VENDOR_AARCH64_BIT0 30 + +/// Mode type +typedef enum cs_mode { + CS_MODE_LITTLE_ENDIAN = 0, ///< little-endian mode (default mode) + CS_MODE_ARM = 0, ///< 32-bit ARM + CS_MODE_16 = 1 << 1, ///< 16-bit mode (X86) + CS_MODE_32 = 1 << 2, ///< 32-bit mode (X86) + CS_MODE_64 = 1 << 3, ///< 64-bit mode (X86, PPC) + // ARM + CS_MODE_THUMB = 1 << 4, ///< ARM's Thumb mode, including Thumb-2 + CS_MODE_MCLASS = 1 << 5, ///< ARM's Cortex-M series + CS_MODE_V8 = 1 << 6, ///< ARMv8 A32 encodings for ARM + // AArch64 + CS_MODE_APPLE_PROPRIETARY = + 1 + << CS_MODE_VENDOR_AARCH64_BIT0, ///< Enable Apple proprietary AArch64 instructions like AMX, MUL53, and others. + // SPARC + CS_MODE_V9 = 1 << 4, ///< SparcV9 mode (Sparc) + // PPC + CS_MODE_QPX = 1 << 4, ///< Quad Processing eXtensions mode (PPC) + CS_MODE_SPE = 1 << 5, ///< Signal Processing Engine mode (PPC) + CS_MODE_BOOKE = 1 << 6, ///< Book-E mode (PPC) + CS_MODE_PS = 1 << 7, ///< Paired-singles mode (PPC) + CS_MODE_AIX_OS = 1 << 8, ///< PowerPC AIX-OS + CS_MODE_PWR7 = 1 << 9, ///< Power 7 + CS_MODE_PWR8 = 1 << 10, ///< Power 8 + CS_MODE_PWR9 = 1 << 11, ///< Power 9 + CS_MODE_PWR10 = 1 << 12, ///< Power 10 + CS_MODE_PPC_ISA_FUTURE = 1 << 13, ///< Power ISA Future + CS_MODE_MODERN_AIX_AS = 1 + << 14, ///< PowerPC AIX-OS with modern assembly + CS_MODE_MSYNC = + 1 + << 15, ///< PowerPC Has only the msync instruction instead of sync. Implies BOOKE + CS_MODE_M68K_000 = 1 << 1, ///< M68K 68000 mode + CS_MODE_M68K_010 = 1 << 2, ///< M68K 68010 mode + CS_MODE_M68K_020 = 1 << 3, ///< M68K 68020 mode + CS_MODE_M68K_030 = 1 << 4, ///< M68K 68030 mode + CS_MODE_M68K_040 = 1 << 5, ///< M68K 68040 mode + CS_MODE_M68K_060 = 1 << 6, ///< M68K 68060 mode + CS_MODE_BIG_ENDIAN = 1U << 31, ///< big-endian mode + CS_MODE_MIPS16 = CS_MODE_16, ///< Generic mips16 + CS_MODE_MIPS32 = CS_MODE_32, ///< Generic mips32 + CS_MODE_MIPS64 = CS_MODE_64, ///< Generic mips64 + CS_MODE_MICRO = 1 << 4, ///< microMips + CS_MODE_MIPS1 = 1 << 5, ///< Mips I ISA Support + CS_MODE_MIPS2 = 1 << 6, ///< Mips II ISA Support + CS_MODE_MIPS32R2 = 1 << 7, ///< Mips32r2 ISA Support + CS_MODE_MIPS32R3 = 1 << 8, ///< Mips32r3 ISA Support + CS_MODE_MIPS32R5 = 1 << 9, ///< Mips32r5 ISA Support + CS_MODE_MIPS32R6 = 1 << 10, ///< Mips32r6 ISA Support + CS_MODE_MIPS3 = 1 << 11, ///< MIPS III ISA Support + CS_MODE_MIPS4 = 1 << 12, ///< MIPS IV ISA Support + CS_MODE_MIPS5 = 1 << 13, ///< MIPS V ISA Support + CS_MODE_MIPS64R2 = 1 << 14, ///< Mips64r2 ISA Support + CS_MODE_MIPS64R3 = 1 << 15, ///< Mips64r3 ISA Support + CS_MODE_MIPS64R5 = 1 << 16, ///< Mips64r5 ISA Support + CS_MODE_MIPS64R6 = 1 << 17, ///< Mips64r6 ISA Support + CS_MODE_OCTEON = 1 << 18, ///< Octeon cnMIPS Support + CS_MODE_OCTEONP = 1 << 19, ///< Octeon+ cnMIPS Support + CS_MODE_NANOMIPS = 1 << 20, ///< Generic nanomips + CS_MODE_NMS1 = ((1 << 21) | CS_MODE_NANOMIPS), ///< nanoMips NMS1 + CS_MODE_I7200 = ((1 << 22) | CS_MODE_NANOMIPS), ///< nanoMips I7200 + CS_MODE_MIPS_NOFLOAT = 1 << 23, ///< Disable floating points ops + CS_MODE_MIPS_PTR64 = 1 << 24, ///< Mips pointers are 64-bit + CS_MODE_MICRO32R3 = + (CS_MODE_MICRO | CS_MODE_MIPS32R3), ///< microMips32r3 + CS_MODE_MICRO32R6 = + (CS_MODE_MICRO | CS_MODE_MIPS32R6), ///< microMips32r6 + CS_MODE_M680X_6301 = 1 << 1, ///< M680X Hitachi 6301,6303 mode + CS_MODE_M680X_6309 = 1 << 2, ///< M680X Hitachi 6309 mode + CS_MODE_M680X_6800 = 1 << 3, ///< M680X Motorola 6800,6802 mode + CS_MODE_M680X_6801 = 1 << 4, ///< M680X Motorola 6801,6803 mode + CS_MODE_M680X_6805 = 1 << 5, ///< M680X Motorola/Freescale 6805 mode + CS_MODE_M680X_6808 = 1 + << 6, ///< M680X Motorola/Freescale/NXP 68HC08 mode + CS_MODE_M680X_6809 = 1 << 7, ///< M680X Motorola 6809 mode + CS_MODE_M680X_6811 = 1 + << 8, ///< M680X Motorola/Freescale/NXP 68HC11 mode + CS_MODE_M680X_CPU12 = 1 << 9, ///< M680X Motorola/Freescale/NXP CPU12 + ///< used on M68HC12/HCS12 + CS_MODE_M680X_HCS08 = 1 << 10, ///< M680X Freescale/NXP HCS08 mode + CS_MODE_BPF_CLASSIC = 0, ///< Classic BPF mode (default) + CS_MODE_BPF_EXTENDED = 1 << 0, ///< Extended BPF mode + CS_MODE_RISCV32 = 1 << 0, ///< RISCV RV32G + CS_MODE_RISCV64 = 1 << 1, ///< RISCV RV64G + CS_MODE_RISCVC = 1 << 2, ///< RISCV compressed instructure mode + CS_MODE_MOS65XX_6502 = 1 << 1, ///< MOS65XXX MOS 6502 + CS_MODE_MOS65XX_65C02 = 1 << 2, ///< MOS65XXX WDC 65c02 + CS_MODE_MOS65XX_W65C02 = 1 << 3, ///< MOS65XXX WDC W65c02 + CS_MODE_MOS65XX_65816 = 1 << 4, ///< MOS65XXX WDC 65816, 8-bit m/x + CS_MODE_MOS65XX_65816_LONG_M = + (1 << 5), ///< MOS65XXX WDC 65816, 16-bit m, 8-bit x + CS_MODE_MOS65XX_65816_LONG_X = + (1 << 6), ///< MOS65XXX WDC 65816, 8-bit m, 16-bit x + CS_MODE_MOS65XX_65816_LONG_MX = CS_MODE_MOS65XX_65816_LONG_M | + CS_MODE_MOS65XX_65816_LONG_X, + CS_MODE_SH2 = 1 << 1, ///< SH2 + CS_MODE_SH2A = 1 << 2, ///< SH2A + CS_MODE_SH3 = 1 << 3, ///< SH3 + CS_MODE_SH4 = 1 << 4, ///< SH4 + CS_MODE_SH4A = 1 << 5, ///< SH4A + CS_MODE_SHFPU = 1 << 6, ///< w/ FPU + CS_MODE_SHDSP = 1 << 7, ///< w/ DSP + CS_MODE_TRICORE_110 = 1 << 1, ///< Tricore 1.1 + CS_MODE_TRICORE_120 = 1 << 2, ///< Tricore 1.2 + CS_MODE_TRICORE_130 = 1 << 3, ///< Tricore 1.3 + CS_MODE_TRICORE_131 = 1 << 4, ///< Tricore 1.3.1 + CS_MODE_TRICORE_160 = 1 << 5, ///< Tricore 1.6 + CS_MODE_TRICORE_161 = 1 << 6, ///< Tricore 1.6.1 + CS_MODE_TRICORE_162 = 1 << 7, ///< Tricore 1.6.2 + CS_MODE_TRICORE_180 = 1 << 8, ///< Tricore 1.8.0 + CS_MODE_HPPA_11 = 1 << 1, ///< HPPA 1.1 + CS_MODE_HPPA_20 = 1 << 2, ///< HPPA 2.0 + CS_MODE_HPPA_20W = CS_MODE_HPPA_20 | (1 << 3), ///< HPPA 2.0 wide + CS_MODE_LOONGARCH32 = 1 << 0, ///< LoongArch32 + CS_MODE_LOONGARCH64 = 1 << 1, ///< LoongArch64 + CS_MODE_SYSTEMZ_ARCH8 = + 1 << 1, ///< Enables features of the ARCH8 processor + CS_MODE_SYSTEMZ_ARCH9 = + 1 << 2, ///< Enables features of the ARCH9 processor + CS_MODE_SYSTEMZ_ARCH10 = + 1 << 3, ///< Enables features of the ARCH10 processor + CS_MODE_SYSTEMZ_ARCH11 = + 1 << 4, ///< Enables features of the ARCH11 processor + CS_MODE_SYSTEMZ_ARCH12 = + 1 << 5, ///< Enables features of the ARCH12 processor + CS_MODE_SYSTEMZ_ARCH13 = + 1 << 6, ///< Enables features of the ARCH13 processor + CS_MODE_SYSTEMZ_ARCH14 = + 1 << 7, ///< Enables features of the ARCH14 processor + CS_MODE_SYSTEMZ_Z10 = 1 << 8, ///< Enables features of the Z10 processor + CS_MODE_SYSTEMZ_Z196 = 1 + << 9, ///< Enables features of the Z196 processor + CS_MODE_SYSTEMZ_ZEC12 = + 1 << 10, ///< Enables features of the ZEC12 processor + CS_MODE_SYSTEMZ_Z13 = 1 + << 11, ///< Enables features of the Z13 processor + CS_MODE_SYSTEMZ_Z14 = 1 + << 12, ///< Enables features of the Z14 processor + CS_MODE_SYSTEMZ_Z15 = 1 + << 13, ///< Enables features of the Z15 processor + CS_MODE_SYSTEMZ_Z16 = 1 + << 14, ///< Enables features of the Z16 processor + CS_MODE_SYSTEMZ_GENERIC = + 1 << 15, ///< Enables features of the generic processor + CS_MODE_XTENSA_ESP32 = 1 << 1, ///< Xtensa ESP32 + CS_MODE_XTENSA_ESP32S2 = 1 << 2, ///< Xtensa ESP32S2 + CS_MODE_XTENSA_ESP8266 = 1 << 3, ///< Xtensa ESP328266 +} cs_mode; + +typedef void *(CAPSTONE_API *cs_malloc_t)(size_t size); +typedef void *(CAPSTONE_API *cs_calloc_t)(size_t nmemb, size_t size); +typedef void *(CAPSTONE_API *cs_realloc_t)(void *ptr, size_t size); +typedef void(CAPSTONE_API *cs_free_t)(void *ptr); +typedef int(CAPSTONE_API *cs_vsnprintf_t)(char *str, size_t size, + const char *format, va_list ap); + +/// User-defined dynamic memory related functions: malloc/calloc/realloc/free/vsnprintf() +/// By default, Capstone uses system's malloc(), calloc(), realloc(), free() & vsnprintf(). +typedef struct cs_opt_mem { + cs_malloc_t malloc; + cs_calloc_t calloc; + cs_realloc_t realloc; + cs_free_t free; + cs_vsnprintf_t vsnprintf; +} cs_opt_mem; + +/// Customize mnemonic for instructions with alternative name. +/// To reset existing customized instruction to its default mnemonic, +/// call cs_option(CS_OPT_MNEMONIC) again with the same @id and NULL value +/// for @mnemonic. +typedef struct cs_opt_mnem { + /// ID of instruction to be customized. + unsigned int id; + /// Customized instruction mnemonic. + const char *mnemonic; +} cs_opt_mnem; + +/// Runtime option for the disassembled engine +typedef enum cs_opt_type { + CS_OPT_INVALID = 0, ///< No option specified + CS_OPT_SYNTAX, ///< Assembly output syntax + CS_OPT_DETAIL, ///< Break down instruction structure into details + CS_OPT_MODE, ///< Change engine's mode at run-time + CS_OPT_MEM, ///< User-defined dynamic memory related functions + CS_OPT_SKIPDATA, ///< Skip data when disassembling. Then engine is in SKIPDATA mode. + CS_OPT_SKIPDATA_SETUP, ///< Setup user-defined function for SKIPDATA option + CS_OPT_MNEMONIC, ///< Customize instruction mnemonic + CS_OPT_UNSIGNED, ///< print immediate operands in unsigned form + CS_OPT_ONLY_OFFSET_BRANCH, ///< ARM, PPC, AArch64: Don't add the branch immediate value to the PC. + CS_OPT_LITBASE, ///< Xtensa, set the LITBASE value. LITBASE is set to 0 by default. +} cs_opt_type; + +/// Runtime option value (associated with option type above) +typedef enum cs_opt_value { + CS_OPT_OFF = + 0, ///< Turn OFF an option - default for CS_OPT_DETAIL, CS_OPT_SKIPDATA, CS_OPT_UNSIGNED. + CS_OPT_ON = + 1 << 0, ///< Turn ON an option (CS_OPT_DETAIL, CS_OPT_SKIPDATA). + CS_OPT_SYNTAX_DEFAULT = 1 << 1, ///< Default asm syntax (CS_OPT_SYNTAX). + CS_OPT_SYNTAX_INTEL = + 1 + << 2, ///< X86 Intel asm syntax - default on X86 (CS_OPT_SYNTAX). + CS_OPT_SYNTAX_ATT = 1 << 3, ///< X86 ATT asm syntax (CS_OPT_SYNTAX). + CS_OPT_SYNTAX_NOREGNAME = + 1 + << 4, ///< Prints register name with only number (CS_OPT_SYNTAX) + CS_OPT_SYNTAX_MASM = 1 << 5, ///< X86 Intel Masm syntax (CS_OPT_SYNTAX). + CS_OPT_SYNTAX_MOTOROLA = 1 << 6, ///< MOS65XX use $ as hex prefix + CS_OPT_SYNTAX_CS_REG_ALIAS = + 1 + << 7, ///< Prints common register alias which are not defined in LLVM (ARM: r9 = sb etc.) + CS_OPT_SYNTAX_PERCENT = + 1 << 8, ///< Prints the % in front of PPC registers. + CS_OPT_SYNTAX_NO_DOLLAR = + 1 + << 9, ///< Does not print the $ in front of Mips, LoongArch registers. + CS_OPT_DETAIL_REAL = + 1 + << 1, ///< If enabled, always sets the real instruction detail. Even if the instruction is an alias. +} cs_opt_value; + +/// An option +typedef struct { + cs_opt_type type; ///< The option type + cs_opt_value val; ///< The option value to set. +} cs_opt; + +/// Common instruction groups - to be consistent across all architectures. +typedef enum cs_group_type { + CS_GRP_INVALID = 0, ///< uninitialized/invalid group. + CS_GRP_JUMP, ///< all jump instructions (conditional+direct+indirect jumps) + CS_GRP_CALL, ///< all call instructions + CS_GRP_RET, ///< all return instructions + CS_GRP_INT, ///< all interrupt instructions (int+syscall) + CS_GRP_IRET, ///< all interrupt return instructions + CS_GRP_PRIVILEGE, ///< all privileged instructions + CS_GRP_BRANCH_RELATIVE, ///< all relative branching instructions +} cs_group_type; + +/** + User-defined callback function for SKIPDATA option. + See tests/test_skipdata.c for sample code demonstrating this API. + + @code: the input buffer containing code to be disassembled. + This is the same buffer passed to cs_disasm(). + @code_size: size (in bytes) of the above @code buffer. + @offset: the position of the currently-examining byte in the input + buffer @code mentioned above. + @user_data: user-data passed to cs_option() via @user_data field in + cs_opt_skipdata struct below. + + @return: return number of bytes to skip, or 0 to immediately stop disassembling. +*/ +typedef size_t(CAPSTONE_API *cs_skipdata_cb_t)(const uint8_t *code, + size_t code_size, size_t offset, + void *user_data); + +/// User-customized setup for SKIPDATA option +typedef struct cs_opt_skipdata { + /// Capstone considers data to skip as special "instructions". + /// User can specify the string for this instruction's "mnemonic" here. + /// By default (if @mnemonic is NULL), Capstone use ".byte". + const char *mnemonic; + + /// User-defined callback function to be called when Capstone hits data. + /// If the returned value from this callback is positive (>0), Capstone + /// will skip exactly that number of bytes & continue. Otherwise, if + /// the callback returns 0, Capstone stops disassembling and returns + /// immediately from cs_disasm() + /// NOTE: if this callback pointer is NULL, Capstone would skip a number + /// of bytes depending on architectures, as following: + /// Arm: 2 bytes (Thumb mode) or 4 bytes. + /// AArch64: 4 bytes. + /// Mips: 4 bytes. + /// M680x: 1 byte. + /// PowerPC: 4 bytes. + /// Sparc: 4 bytes. + /// SystemZ: 2 bytes. + /// X86: 1 bytes. + /// XCore: 2 bytes. + /// EVM: 1 bytes. + /// RISCV: 4 bytes. + /// WASM: 1 bytes. + /// MOS65XX: 1 bytes. + /// BPF: 8 bytes. + /// TriCore: 2 bytes. + /// LoongArch: 4 bytes. + /// ARC: 2 bytes. + cs_skipdata_cb_t callback; // default value is NULL + + /// User-defined data to be passed to @callback function pointer. + void *user_data; +} cs_opt_skipdata; + +#include "arm.h" +#ifdef CAPSTONE_AARCH64_COMPAT_HEADER +#include "arm64.h" +#else +#include "aarch64.h" +#endif +#include "m68k.h" +#include "mips.h" +#include "ppc.h" +#include "sparc.h" +#include "systemz.h" +#include "x86.h" +#include "xcore.h" +#include "tms320c64x.h" +#include "m680x.h" +#include "evm.h" +#include "riscv.h" +#include "wasm.h" +#include "mos65xx.h" +#include "bpf.h" +#include "sh.h" +#include "tricore.h" +#include "alpha.h" +#include "hppa.h" +#include "loongarch.h" +#include "xtensa.h" +#include "arc.h" + +#define MAX_IMPL_W_REGS 47 +#define MAX_IMPL_R_REGS 20 +#define MAX_NUM_GROUPS 16 + +/// NOTE: All information in cs_detail is only available when CS_OPT_DETAIL = CS_OPT_ON +/// Initialized as memset(., 0, offsetof(cs_detail, ARCH)+sizeof(cs_ARCH)) +/// by ARCH_getInstruction in arch/ARCH/ARCHDisassembler.c +/// if cs_detail changes, in particular if a field is added after the union, +/// then update arch/ARCH/ARCHDisassembler.c accordingly +typedef struct cs_detail { + uint16_t regs_read + [MAX_IMPL_R_REGS]; ///< list of implicit registers read by this insn + uint8_t regs_read_count; ///< number of implicit registers read by this insn + + uint16_t regs_write + [MAX_IMPL_W_REGS]; ///< list of implicit registers modified by this insn + uint8_t regs_write_count; ///< number of implicit registers modified by this insn + + uint8_t groups[MAX_NUM_GROUPS]; ///< list of group this instruction belong to + uint8_t groups_count; ///< number of groups this insn belongs to + + bool writeback; ///< Instruction has writeback operands. + + /// Architecture-specific instruction info + union { + cs_x86 x86; ///< X86 architecture, including 16-bit, 32-bit & 64-bit mode +#ifdef CAPSTONE_AARCH64_COMPAT_HEADER + cs_arm64 arm64; +#else + cs_aarch64 aarch64; ///< AArch6464 architecture (aka ARM64) +#endif + +#ifdef CAPSTONE_SYSTEMZ_COMPAT_HEADER + cs_sysz sysz; ///< SystemZ architecture +#else + cs_systemz systemz; ///< SystemZ architecture (aka SysZ) +#endif + cs_arm arm; ///< ARM architecture (including Thumb/Thumb2) + cs_m68k m68k; ///< M68K architecture + cs_mips mips; ///< MIPS architecture + cs_ppc ppc; ///< PowerPC architecture + cs_sparc sparc; ///< Sparc architecture + cs_xcore xcore; ///< XCore architecture + cs_tms320c64x tms320c64x; ///< TMS320C64x architecture + cs_m680x m680x; ///< M680X architecture + cs_evm evm; ///< Ethereum architecture + cs_mos65xx mos65xx; ///< MOS65XX architecture (including MOS6502) + cs_wasm wasm; ///< Web Assembly architecture + cs_bpf bpf; ///< Berkeley Packet Filter architecture (including eBPF) + cs_riscv riscv; ///< RISCV architecture + cs_sh sh; ///< SH architecture + cs_tricore tricore; ///< TriCore architecture + cs_alpha alpha; ///< Alpha architecture + cs_hppa hppa; ///< HPPA architecture + cs_loongarch loongarch; ///< LoongArch architecture + cs_xtensa xtensa; ///< Xtensa architecture + cs_arc arc; ///< ARC architecture + }; +} cs_detail; + +/// Detail information of disassembled instruction +typedef struct cs_insn { + /// Instruction ID (basically a numeric ID for the instruction mnemonic) + /// Find the instruction id in the '[ARCH]_insn' enum in the header file + /// of corresponding architecture, such as 'arm_insn' in arm.h for ARM, + /// 'x86_insn' in x86.h for X86, etc... + /// This information is available even when CS_OPT_DETAIL = CS_OPT_OFF + /// NOTE: in Skipdata mode, "data" instruction has 0 for this id field. + unsigned int id; + + /// If this instruction is an alias instruction, this member is set with + /// the alias ID. + /// Otherwise to _INS_INVALID. + /// -- Only supported by auto-sync archs -- + uint64_t alias_id; + + /// Address (EIP) of this instruction + /// This information is available even when CS_OPT_DETAIL = CS_OPT_OFF + uint64_t address; + + /// Size of this instruction + /// This information is available even when CS_OPT_DETAIL = CS_OPT_OFF + uint16_t size; + + /// Machine bytes of this instruction, with number of bytes indicated by @size above + /// This information is available even when CS_OPT_DETAIL = CS_OPT_OFF + uint8_t bytes[24]; + + /// Ascii text of instruction mnemonic + /// This information is available even when CS_OPT_DETAIL = CS_OPT_OFF + char mnemonic[CS_MNEMONIC_SIZE]; + + /// Ascii text of instruction operands + /// This information is available even when CS_OPT_DETAIL = CS_OPT_OFF + char op_str[160]; + + /// True: This instruction is an alias. + /// False: Otherwise. + /// -- Only supported by auto-sync archs -- + bool is_alias; + + /// True: The operands are the ones of the alias instructions. + /// False: The detail operands are from the real instruction. + bool usesAliasDetails; + + /// True: The bytes disassemble to a valid instruction, but it is illegal by ISA definitions. + /// For example the instruction uses a register which is not allowed or it appears in + /// an invalid context. + /// + /// False: The instruction decoded correctly and is valid. + bool illegal; + + /// Pointer to cs_detail. + /// NOTE: detail pointer is only valid when both requirements below are met: + /// (1) CS_OP_DETAIL = CS_OPT_ON + /// (2) Engine is not in Skipdata mode (CS_OP_SKIPDATA option set to CS_OPT_ON) + /// + /// NOTE 2: when in Skipdata mode, or when detail mode is OFF, even if this pointer + /// is not NULL, its content is still irrelevant. + cs_detail *detail; +} cs_insn; + +/// Calculate the offset of a disassembled instruction in its buffer, given its position +/// in its array of disassembled insn +/// NOTE: this macro works with position (>=1), not index +#define CS_INSN_OFFSET(insns, post) (insns[post - 1].address - insns[0].address) + +/// All type of errors encountered by Capstone API. +/// These are values returned by cs_errno() +typedef enum cs_err { + CS_ERR_OK = 0, ///< No error: everything was fine + CS_ERR_MEM, ///< Out-Of-Memory error: cs_open(), cs_disasm(), cs_disasm_iter() + CS_ERR_ARCH, ///< Unsupported architecture: cs_open() + CS_ERR_HANDLE, ///< Invalid handle: cs_op_count(), cs_op_index() + CS_ERR_CSH, ///< Invalid csh argument: cs_close(), cs_errno(), cs_option() + CS_ERR_MODE, ///< Invalid/unsupported mode: cs_open() + CS_ERR_OPTION, ///< Invalid/unsupported option: cs_option() + CS_ERR_DETAIL, ///< Information is unavailable because detail option is OFF + CS_ERR_MEMSETUP, ///< Dynamic memory management uninitialized (see CS_OPT_MEM) + CS_ERR_VERSION, ///< Unsupported version (bindings) + CS_ERR_DIET, ///< Access irrelevant data in "diet" engine + CS_ERR_SKIPDATA, ///< Access irrelevant data for "data" instruction in SKIPDATA mode + CS_ERR_X86_ATT, ///< X86 AT&T syntax is unsupported (opt-out at compile time) + CS_ERR_X86_INTEL, ///< X86 Intel syntax is unsupported (opt-out at compile time) + CS_ERR_X86_MASM, ///< X86 Masm syntax is unsupported (opt-out at compile time) +} cs_err; + +/** + Return combined API version & major and minor version numbers. + + @major: major number of API version + @minor: minor number of API version + + @return hexical number as (major << 8 | minor), which encodes both + major & minor versions. + NOTE: This returned value can be compared with version number made + with macro CS_MAKE_VERSION + + For example, second API version would return 1 in @major, and 1 in @minor + The return value would be 0x0101 + + NOTE: if you only care about returned value, but not major and minor values, + set both @major & @minor arguments to NULL. +*/ +CAPSTONE_EXPORT +unsigned int CAPSTONE_API cs_version(int *major, int *minor); + +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_arm(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_aarch64(void); +#ifdef CAPSTONE_AARCH64_COMPAT_HEADER +#define cs_arch_register_aarch64 cs_arch_register_arm64 +#endif +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_mips(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_x86(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_powerpc(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_sparc(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_systemz(void); +#ifdef CAPSTONE_SYSTEMZ_COMPAT_HEADER +#define cs_arch_register_sysz cs_arch_register_systemz +#endif +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_xcore(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_m68k(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_tms320c64x(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_m680x(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_evm(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_mos65xx(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_wasm(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_bpf(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_riscv(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_sh(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_tricore(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_alpha(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_loongarch(void); +CAPSTONE_EXPORT +void CAPSTONE_API cs_arch_register_arc(void); + +/** + This API can be used to either ask for archs supported by this library, + or check to see if the library was compile with 'diet' option (or called + in 'diet' mode). + + To check if a particular arch is supported by this library, set @query to + arch mode (CS_ARCH_* value). + To verify if this library supports all the archs, use CS_ARCH_ALL. + + To check if this library is in 'diet' mode, set @query to CS_SUPPORT_DIET. + + @return True if this library supports the given arch, or in 'diet' mode. +*/ +CAPSTONE_EXPORT +bool CAPSTONE_API cs_support(int query); + +/** + Initialize CS handle: this must be done before any usage of CS. + + @arch: architecture type (CS_ARCH_*) + @mode: hardware mode. This is combined of CS_MODE_* + @handle: pointer to handle, which will be updated at return time + + @return CS_ERR_OK on success, or other value on failure (refer to cs_err enum + for detailed error). +*/ +CAPSTONE_EXPORT +cs_err CAPSTONE_API cs_open(cs_arch arch, cs_mode mode, csh *handle); + +/** + Close CS handle: MUST do to release the handle when it is not used anymore. + NOTE: this must be only called when there is no longer usage of Capstone, + not even access to cs_insn array. The reason is the this API releases some + cached memory, thus access to any Capstone API after cs_close() might crash + your application. + + In fact,this API invalidate @handle by ZERO out its value (i.e *handle = 0). + + @handle: pointer to a handle returned by cs_open() + + @return CS_ERR_OK on success, or other value on failure (refer to cs_err enum + for detailed error). +*/ +CAPSTONE_EXPORT +cs_err CAPSTONE_API cs_close(csh *handle); + +/** + Set option for disassembling engine at runtime + + @handle: handle returned by cs_open() + @type: type of option to be set + @value: option value corresponding with @type + + @return: CS_ERR_OK on success, or other value on failure. + Refer to cs_err enum for detailed error. + + NOTE: in the case of CS_OPT_MEM, handle's value can be anything, + so that cs_option(handle, CS_OPT_MEM, value) can (i.e must) be called + even before cs_open() +*/ +CAPSTONE_EXPORT +cs_err CAPSTONE_API cs_option(csh handle, cs_opt_type type, uintptr_t value); + +/** + Report the last error number when some API function fail. + Like glibc's errno, cs_errno might not retain its old value once accessed. + + @handle: handle returned by cs_open() + + @return: error code of cs_err enum type (CS_ERR_*, see above) +*/ +CAPSTONE_EXPORT +cs_err CAPSTONE_API cs_errno(csh handle); + +/** + Return a string describing given error code. + + @code: error code (see CS_ERR_* above) + + @return: returns a pointer to a string that describes the error code + passed in the argument @code +*/ +CAPSTONE_EXPORT +const char *CAPSTONE_API cs_strerror(cs_err code); + +/** + Disassemble binary code, given the code buffer, size, address and number + of instructions to be decoded. + This API dynamically allocate memory to contain disassembled instruction. + Resulting instructions will be put into @*insn + + NOTE 1: this API will automatically determine memory needed to contain + output disassembled instructions in @insn. + + NOTE 2: caller must free the allocated memory itself to avoid memory leaking. + + NOTE 3: for system with scarce memory to be dynamically allocated such as + OS kernel or firmware, the API cs_disasm_iter() might be a better choice than + cs_disasm(). The reason is that with cs_disasm(), based on limited available + memory, we have to calculate in advance how many instructions to be disassembled, + which complicates things. This is especially troublesome for the case @count=0, + when cs_disasm() runs uncontrollably (until either end of input buffer, or + when it encounters an invalid instruction). + + @handle: handle returned by cs_open() + @code: buffer containing raw binary code to be disassembled. + @code_size: size of the above code buffer. + @address: address of the first instruction in given raw code buffer. + @insn: array of instructions filled in by this API. + NOTE: @insn will be allocated by this function, and should be freed + with cs_free() API. + @count: number of instructions to be disassembled, or 0 to get all of them + + @return: the number of successfully disassembled instructions, + or 0 if this function failed to disassemble the given code + + On failure, call cs_errno() for error code. +*/ +CAPSTONE_EXPORT +size_t CAPSTONE_API cs_disasm(csh handle, const uint8_t *code, size_t code_size, + uint64_t address, size_t count, cs_insn **insn); + +/** + Free memory allocated by cs_malloc() or cs_disasm() (argument @insn) + + @insn: pointer returned by @insn argument in cs_disasm() or cs_malloc() + @count: number of cs_insn structures returned by cs_disasm(), or 1 + to free memory allocated by cs_malloc(). +*/ +CAPSTONE_EXPORT +void CAPSTONE_API cs_free(cs_insn *insn, size_t count); + +/** + Allocate memory for 1 instruction to be used by cs_disasm_iter(). + + @handle: handle returned by cs_open() + + NOTE: when no longer in use, you can reclaim the memory allocated for + this instruction with cs_free(insn, 1) +*/ +CAPSTONE_EXPORT +cs_insn *CAPSTONE_API cs_malloc(csh handle); + +/** + Fast API to disassemble binary code, given the code buffer, size, address + and number of instructions to be decoded. + This API puts the resulting instruction into a given cache in @insn. + See tests/test_iter.c for sample code demonstrating this API. + + NOTE 1: this API will update @code, @size & @address to point to the next + instruction in the input buffer. Therefore, it is convenient to use + cs_disasm_iter() inside a loop to quickly iterate all the instructions. + While decoding one instruction at a time can also be achieved with + cs_disasm(count=1), some benchmarks shown that cs_disasm_iter() can be 30% + faster on random input. + + NOTE 2: the cache in @insn can be created with cs_malloc() API. + + NOTE 3: for system with scarce memory to be dynamically allocated such as + OS kernel or firmware, this API is recommended over cs_disasm(), which + allocates memory based on the number of instructions to be disassembled. + The reason is that with cs_disasm(), based on limited available memory, + we have to calculate in advance how many instructions to be disassembled, + which complicates things. This is especially troublesome for the case + @count=0, when cs_disasm() runs uncontrollably (until either end of input + buffer, or when it encounters an invalid instruction). + + @handle: handle returned by cs_open() + @code: buffer containing raw binary code to be disassembled + @size: size of above code + @address: address of the first insn in given raw code buffer + @insn: pointer to instruction to be filled in by this API. + + @return: true if this API successfully decode 1 instruction, + or false otherwise. + + On failure, call cs_errno() for error code. +*/ +CAPSTONE_EXPORT +bool CAPSTONE_API cs_disasm_iter(csh handle, const uint8_t **code, size_t *size, + uint64_t *address, cs_insn *insn); + +/** + Return friendly name of register in a string. + Find the instruction id from header file of corresponding architecture (arm.h for ARM, + x86.h for X86, ...) + + WARN: when in 'diet' mode, this API is irrelevant because engine does not + store register name. + + @handle: handle returned by cs_open() + @reg_id: register id + + @return: string name of the register, or NULL if @reg_id is invalid. +*/ +CAPSTONE_EXPORT +const char *CAPSTONE_API cs_reg_name(csh handle, unsigned int reg_id); + +/** + Return friendly name of an instruction in a string. + Find the instruction id from header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + + WARN: when in 'diet' mode, this API is irrelevant because the engine does not + store instruction name. + + @handle: handle returned by cs_open() + @insn_id: instruction id + + @return: string name of the instruction, or NULL if @insn_id is invalid. +*/ +CAPSTONE_EXPORT +const char *CAPSTONE_API cs_insn_name(csh handle, unsigned int insn_id); + +/** + Return friendly name of a group id (that an instruction can belong to) + Find the group id from header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + + WARN: when in 'diet' mode, this API is irrelevant because the engine does not + store group name. + + @handle: handle returned by cs_open() + @group_id: group id + + @return: string name of the group, or NULL if @group_id is invalid. +*/ +CAPSTONE_EXPORT +const char *CAPSTONE_API cs_group_name(csh handle, unsigned int group_id); + +/** + Check if a disassembled instruction belong to a particular group. + Find the group id from header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + Internally, this simply verifies if @group_id matches any member of insn->groups array. + + NOTE: this API is only valid when detail option is ON (which is OFF by default). + + WARN: when in 'diet' mode, this API is irrelevant because the engine does not + update @groups array. + + @handle: handle returned by cs_open() + @insn: disassembled instruction structure received from cs_disasm() or cs_disasm_iter() + @group_id: group that you want to check if this instruction belong to. + + @return: true if this instruction indeed belongs to the given group, or false otherwise. +*/ +CAPSTONE_EXPORT +bool CAPSTONE_API cs_insn_group(csh handle, const cs_insn *insn, + unsigned int group_id); + +/** + Check if a disassembled instruction IMPLICITLY used a particular register. + Find the register id from header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + Internally, this simply verifies if @reg_id matches any member of insn->regs_read array. + + NOTE: this API is only valid when detail option is ON (which is OFF by default) + + WARN: when in 'diet' mode, this API is irrelevant because the engine does not + update @regs_read array. + + @insn: disassembled instruction structure received from cs_disasm() or cs_disasm_iter() + @reg_id: register that you want to check if this instruction used it. + + @return: true if this instruction indeed implicitly used the given register, or false otherwise. +*/ +CAPSTONE_EXPORT +bool CAPSTONE_API cs_reg_read(csh handle, const cs_insn *insn, + unsigned int reg_id); + +/** + Check if a disassembled instruction IMPLICITLY modified a particular register. + Find the register id from header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + Internally, this simply verifies if @reg_id matches any member of insn->regs_write array. + + NOTE: this API is only valid when detail option is ON (which is OFF by default) + + WARN: when in 'diet' mode, this API is irrelevant because the engine does not + update @regs_write array. + + @insn: disassembled instruction structure received from cs_disasm() or cs_disasm_iter() + @reg_id: register that you want to check if this instruction modified it. + + @return: true if this instruction indeed implicitly modified the given register, or false otherwise. +*/ +CAPSTONE_EXPORT +bool CAPSTONE_API cs_reg_write(csh handle, const cs_insn *insn, + unsigned int reg_id); + +/** + Count the number of operands of a given type. + Find the operand type in header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + + NOTE: this API is only valid when detail option is ON (which is OFF by default) + + @handle: handle returned by cs_open() + @insn: disassembled instruction structure received from cs_disasm() or cs_disasm_iter() + @op_type: Operand type to be found. + + @return: number of operands of given type @op_type in instruction @insn, + or -1 on failure. +*/ +CAPSTONE_EXPORT +int CAPSTONE_API cs_op_count(csh handle, const cs_insn *insn, + unsigned int op_type); + +/** + Retrieve the position of operand of given type in .operands[] array. + Later, the operand can be accessed using the returned position. + Find the operand type in header file of corresponding architecture (arm.h for ARM, x86.h for X86, ...) + + NOTE: this API is only valid when detail option is ON (which is OFF by default) + + @handle: handle returned by cs_open() + @insn: disassembled instruction structure received from cs_disasm() or cs_disasm_iter() + @op_type: Operand type to be found. + @position: position of the operand to be found. This must be in the range + [1, cs_op_count(handle, insn, op_type)] + + @return: index of operand of given type @op_type in .operands[] array + in instruction @insn, or -1 on failure. +*/ +CAPSTONE_EXPORT +int CAPSTONE_API cs_op_index(csh handle, const cs_insn *insn, + unsigned int op_type, unsigned int position); + +/// Type of array to keep the list of registers +typedef uint16_t cs_regs[64]; + +/** + Retrieve all the registers accessed by an instruction, either explicitly or + implicitly. + + WARN: when in 'diet' mode, this API is irrelevant because engine does not + store registers. + + @handle: handle returned by cs_open() + @insn: disassembled instruction structure returned from cs_disasm() or cs_disasm_iter() + @regs_read: on return, this array contains all registers read by instruction. + @regs_read_count: number of registers kept inside @regs_read array. + @regs_write: on return, this array contains all registers written by instruction. + @regs_write_count: number of registers kept inside @regs_write array. + + @return CS_ERR_OK on success, or other value on failure (refer to cs_err enum + for detailed error). +*/ +CAPSTONE_EXPORT +cs_err CAPSTONE_API cs_regs_access(csh handle, const cs_insn *insn, + cs_regs regs_read, uint8_t *regs_read_count, + cs_regs regs_write, + uint8_t *regs_write_count); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdPartyLibs/capstone/lib/capstone.lib b/3rdPartyLibs/capstone/lib/capstone.lib new file mode 100644 index 00000000..62152920 Binary files /dev/null and b/3rdPartyLibs/capstone/lib/capstone.lib differ diff --git a/3rdPartyLibs/output/output.txt b/3rdPartyLibs/output/output.txt new file mode 100644 index 00000000..300d06cd --- /dev/null +++ b/3rdPartyLibs/output/output.txt @@ -0,0 +1,5 @@ +warning: rule "Detect_IMUL_Instruction" in D:\MASTER\reverse\RepoTest\REVERSE_ENGINEERING-PROJECT\3rdPartyLibs\rules\Detect_Imul.yara(10): string "$imul_triple_with_byte" may slow down scanning +Detect_IMUL_Instruction [] [description="Detecteaza instructiuni IMUL (x86)"] D:\MASTER\reverse\RepoTest\REVERSE_ENGINEERING-PROJECT\3rdPartyLibs\viruses\p12 +0x46b:$imul_standard_2ops: 0F AF 45 F8 +0x475:$imul_standard_2ops: 0F AF 4D F8 +0x479:$imul_triple_with_byte: 6B D1 03 diff --git a/3rdPartyLibs/results/results_2026-01-30_16-59-27.txt b/3rdPartyLibs/results/results_2026-01-30_16-59-27.txt new file mode 100644 index 00000000..6aa7286b --- /dev/null +++ b/3rdPartyLibs/results/results_2026-01-30_16-59-27.txt @@ -0,0 +1,87 @@ +=== SCANNING RESULTS === + +Summary: + Total Matches: 1 + Status: INFECTED + +------------------------------------------------------------- +Scanning with rule: Detect_Imul.yara + [WARNING] warning: rule "Detect_IMUL_Instruction" in + D:\reverse\project\REVERSE_ENGINEERING-PROJECT\3rdPartyLibs\rules\Detect_Imul.yara(10): + string "$imul_triple_with_byte" may slow down scanning + [MATCH] Rule: Detect_IMUL_Instruction + 0x46b:$imul_standard_2ops: 0F AF 45 F8 + At: + Hex Dump: + File offset: 0x46B + Section: .text + 0x0000042b CC CC CC CC CC 55 8B EC 5D C3 CC CC CC CC CC CC .....U..]....... + 0x0000043b CC CC CC CC CC 55 8B EC 83 EC 4C 53 56 57 B9 A2 .....U....LSVW.. + 0x0000044b 50 40 00 E8 B7 FF FF FF C7 45 FC 02 00 00 00 C7 P@.......E...... + 0x0000045b 45 F8 02 00 00 00 C7 45 F4 02 00 00 00 8B 45 FC E......E......E. + 0x0000046b 0F AF 45 F8 83 C0 02 8B 4D FC 0F AF 4D F8 6B D1 ..E.....M...M.k. + 0x0000047b 03 3B C2 7D 14 8B 45 F4 83 E8 01 83 F8 05 7D 07 .;.}..E.......}. + 0x0000048b C7 45 F4 08 00 00 00 EB 1E 8B 45 F4 03 45 FC 03 .E........E..E.. + 0x0000049b 45 F8 83 F8 03 75 09 C7 45 F4 14 00 00 00 EB 07 E....u..E....... + Disassembly: + 0x0000046b imul eax, dword ptr [rbp - 8] + 0x0000046f add eax, 2 + 0x00000472 mov ecx, dword ptr [rbp - 4] + 0x00000475 imul ecx, dword ptr [rbp - 8] + 0x00000479 imul edx, ecx, 3 + 0x0000047c cmp eax, edx + 0x0000047e jge 0x494 + 0x00000480 mov eax, dword ptr [rbp - 0xc] + 0x00000483 sub eax, 1 + 0x00000486 cmp eax, 5 + 0x00000489 jge 0x492 + 0x475:$imul_standard_2ops: 0F AF 4D F8 + At: + Hex Dump: + File offset: 0x475 + Section: .text + 0x00000435 CC CC CC CC CC CC CC CC CC CC CC 55 8B EC 83 EC ...........U.... + 0x00000445 4C 53 56 57 B9 A2 50 40 00 E8 B7 FF FF FF C7 45 LSVW..P@.......E + 0x00000455 FC 02 00 00 00 C7 45 F8 02 00 00 00 C7 45 F4 02 ......E......E.. + 0x00000465 00 00 00 8B 45 FC 0F AF 45 F8 83 C0 02 8B 4D FC ....E...E.....M. + 0x00000475 0F AF 4D F8 6B D1 03 3B C2 7D 14 8B 45 F4 83 E8 ..M.k..;.}..E... + 0x00000485 01 83 F8 05 7D 07 C7 45 F4 08 00 00 00 EB 1E 8B ....}..E........ + 0x00000495 45 F4 03 45 FC 03 45 F8 83 F8 03 75 09 C7 45 F4 E..E..E....u..E. + 0x000004a5 14 00 00 00 EB 07 C7 45 F4 1E 00 00 00 8B 45 F4 .......E......E. + Disassembly: + 0x00000475 imul ecx, dword ptr [rbp - 8] + 0x00000479 imul edx, ecx, 3 + 0x0000047c cmp eax, edx + 0x0000047e jge 0x494 + 0x00000480 mov eax, dword ptr [rbp - 0xc] + 0x00000483 sub eax, 1 + 0x00000486 cmp eax, 5 + 0x00000489 jge 0x492 + 0x0000048b mov dword ptr [rbp - 0xc], 8 + 0x00000492 jmp 0x4b2 + 0x479:$imul_triple_with_byte: 6B D1 03 + At: + Hex Dump: + File offset: 0x479 + Section: .text + 0x00000439 CC CC CC CC CC CC CC 55 8B EC 83 EC 4C 53 56 57 .......U....LSVW + 0x00000449 B9 A2 50 40 00 E8 B7 FF FF FF C7 45 FC 02 00 00 ..P@.......E.... + 0x00000459 00 C7 45 F8 02 00 00 00 C7 45 F4 02 00 00 00 8B ..E......E...... + 0x00000469 45 FC 0F AF 45 F8 83 C0 02 8B 4D FC 0F AF 4D F8 E...E.....M...M. + 0x00000479 6B D1 03 3B C2 7D 14 8B 45 F4 83 E8 01 83 F8 05 k..;.}..E....... + 0x00000489 7D 07 C7 45 F4 08 00 00 00 EB 1E 8B 45 F4 03 45 }..E........E..E + 0x00000499 FC 03 45 F8 83 F8 03 75 09 C7 45 F4 14 00 00 00 ..E....u..E..... + 0x000004a9 EB 07 C7 45 F4 1E 00 00 00 8B 45 F4 83 C0 02 89 ...E......E..... + Disassembly: + 0x00000479 imul edx, ecx, 3 + 0x0000047c cmp eax, edx + 0x0000047e jge 0x494 + 0x00000480 mov eax, dword ptr [rbp - 0xc] + 0x00000483 sub eax, 1 + 0x00000486 cmp eax, 5 + 0x00000489 jge 0x492 + 0x0000048b mov dword ptr [rbp - 0xc], 8 + 0x00000492 jmp 0x4b2 + 0x00000494 mov eax, dword ptr [rbp - 0xc] + +=== SCAN COMPLETE === diff --git a/3rdPartyLibs/rules/Detect_Imul.yara b/3rdPartyLibs/rules/Detect_Imul.yara new file mode 100644 index 00000000..2c9acfb5 --- /dev/null +++ b/3rdPartyLibs/rules/Detect_Imul.yara @@ -0,0 +1,18 @@ +import "pe" + +rule Detect_IMUL_Instruction +{ + meta: + description = "Detecteaza instructiuni IMUL (x86)" + + strings: + $imul_standard_2ops = { 0F AF ?? ?? } // imul reg, [mem] + $imul_triple_with_byte = { 6B (C? | D? | E? | F?) ?? } // imul reg, reg, imm8 + + condition: + pe.is_pe and any of them in ( + pe.sections[pe.section_index(".text")].raw_data_offset .. + pe.sections[pe.section_index(".text")].raw_data_offset + + pe.sections[pe.section_index(".text")].raw_data_size + ) +} \ No newline at end of file diff --git a/3rdPartyLibs/rules/Hardcoded_Bytes.yara b/3rdPartyLibs/rules/Hardcoded_Bytes.yara new file mode 100644 index 00000000..5f468083 --- /dev/null +++ b/3rdPartyLibs/rules/Hardcoded_Bytes.yara @@ -0,0 +1,11 @@ +rule Hardcoded_Bytes { + meta: + description = "Detects hardcoded byte pattern " + severity = "high" + + strings: + $xor = { 1F 0A 1F 0A } + + condition: + $xor +} \ No newline at end of file diff --git a/3rdPartyLibs/rules/helloworld - Copy.yara b/3rdPartyLibs/rules/helloworld - Copy.yara new file mode 100644 index 00000000..4a6ccb26 --- /dev/null +++ b/3rdPartyLibs/rules/helloworld - Copy.yara @@ -0,0 +1,13 @@ +rule hello_world_str { + + meta: + description = "A simple proof-of-concept to show YARA rules" + author = "Carcea Razvan" + + strings: + $hello = "Hello World!" + + condition: + $hello + +} \ No newline at end of file diff --git a/3rdPartyLibs/rules/helloworld.yara b/3rdPartyLibs/rules/helloworld.yara new file mode 100644 index 00000000..9caa2b06 --- /dev/null +++ b/3rdPartyLibs/rules/helloworld.yara @@ -0,0 +1,32 @@ +rule hello_str : test demo poc{ + + meta: + description = "A simple proof-of-concept to show YARA rules" + author = "Carcea Razvan" + severity = "low" + + + strings: + $hello = "Hello" + $world = "World" + + condition: + $hello or $world + +} + +rule world_str : malware demo{ + + meta: + description = "Demo" + author = "Carcea Diana" + severity = "high" + + + strings: + $world = "World" + + condition: + $world + +} \ No newline at end of file diff --git a/3rdPartyLibs/rules/p1_find_integer_2.yara b/3rdPartyLibs/rules/p1_find_integer_2.yara new file mode 100644 index 00000000..23fbbedc --- /dev/null +++ b/3rdPartyLibs/rules/p1_find_integer_2.yara @@ -0,0 +1,12 @@ +rule find_integer_2 { + meta: + description = "Matches x86 opcode sequence for mov dword ptr [ebp-?], 2" + + strings: + $mov_i_2 = { C7 45 ?? 02 00 00 00 } + + condition: + $mov_i_2 + +} + \ No newline at end of file diff --git a/3rdPartyLibs/rules/simple_beacon.yara b/3rdPartyLibs/rules/simple_beacon.yara new file mode 100644 index 00000000..be959f17 --- /dev/null +++ b/3rdPartyLibs/rules/simple_beacon.yara @@ -0,0 +1,11 @@ +rule C2_Beacon { + meta: + description = "Identifies indicators of simple HTTP-based C2 beaconing" + + strings: + $url = /http(s)?:\/\/.*\/api/ + $beacon = "beacon" + + condition: + $url and $beacon +} diff --git a/3rdPartyLibs/rules/suspicious_admin.yara b/3rdPartyLibs/rules/suspicious_admin.yara new file mode 100644 index 00000000..7f9f1a50 --- /dev/null +++ b/3rdPartyLibs/rules/suspicious_admin.yara @@ -0,0 +1,16 @@ +rule admin_tool { + + meta: + description = "Detects suspicious admin-like command execution" + author = "Carcea Razvan" + + strings: + $cmd1 = "whoami" + $cmd2 = "ipconfig" + $cmd3 = "net user" + $log = "output.log" + + condition: + 2 of ($cmd*) and $log + +} \ No newline at end of file diff --git a/3rdPartyLibs/viruses/TestYara.exe b/3rdPartyLibs/viruses/TestYara.exe new file mode 100644 index 00000000..d290ffb9 Binary files /dev/null and b/3rdPartyLibs/viruses/TestYara.exe differ diff --git a/3rdPartyLibs/viruses/encoded_string.exe b/3rdPartyLibs/viruses/encoded_string.exe new file mode 100644 index 00000000..24e85d7f Binary files /dev/null and b/3rdPartyLibs/viruses/encoded_string.exe differ diff --git a/3rdPartyLibs/viruses/example_program.exe b/3rdPartyLibs/viruses/example_program.exe new file mode 100644 index 00000000..de8f3274 Binary files /dev/null and b/3rdPartyLibs/viruses/example_program.exe differ diff --git a/3rdPartyLibs/viruses/hello_world.exe b/3rdPartyLibs/viruses/hello_world.exe new file mode 100644 index 00000000..fd60a023 Binary files /dev/null and b/3rdPartyLibs/viruses/hello_world.exe differ diff --git a/3rdPartyLibs/viruses/p1 b/3rdPartyLibs/viruses/p1 new file mode 100644 index 00000000..f1aa2d29 Binary files /dev/null and b/3rdPartyLibs/viruses/p1 differ diff --git a/3rdPartyLibs/viruses/p12 b/3rdPartyLibs/viruses/p12 new file mode 100644 index 00000000..ba1fb6f2 Binary files /dev/null and b/3rdPartyLibs/viruses/p12 differ diff --git a/3rdPartyLibs/viruses/simple_beacon.exe b/3rdPartyLibs/viruses/simple_beacon.exe new file mode 100644 index 00000000..d4b2ae0e Binary files /dev/null and b/3rdPartyLibs/viruses/simple_beacon.exe differ diff --git a/3rdPartyLibs/viruses/suspicious_admin.exe b/3rdPartyLibs/viruses/suspicious_admin.exe new file mode 100644 index 00000000..d1172508 Binary files /dev/null and b/3rdPartyLibs/viruses/suspicious_admin.exe differ diff --git a/3rdPartyLibs/yara-win64/yara64.exe b/3rdPartyLibs/yara-win64/yara64.exe new file mode 100644 index 00000000..1fd6b1a2 Binary files /dev/null and b/3rdPartyLibs/yara-win64/yara64.exe differ diff --git a/3rdPartyLibs/yara-win64/yarac64.exe b/3rdPartyLibs/yara-win64/yarac64.exe new file mode 100644 index 00000000..4a1c3f55 Binary files /dev/null and b/3rdPartyLibs/yara-win64/yarac64.exe differ diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d81b618..0adfa8cd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,6 +23,15 @@ endif() project(${CURRENT_PROJECT_NAME} VERSION 1.0 DESCRIPTION "GView - GenericViewer" LANGUAGES C CXX) +# --- Capstone static library --- +add_library(Capstone STATIC IMPORTED) + +# Path către lib-ul static +set_target_properties(Capstone PROPERTIES + IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/3rdPartyLibs/capstone/lib/capstone.lib" + INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/3rdPartyLibs/capstone/include" +) + include(CheckIPOSupported) check_ipo_supported(RESULT supported OUTPUT error) @@ -156,6 +165,9 @@ add_subdirectory(3rdPartyLibs/LLVMDemangle) add_subdirectory(AppCUI) add_subdirectory(GViewCore) +target_link_libraries(GViewCore PRIVATE Capstone) + + if(NOT DEFINED CMAKE_TESTING_ENABLED) add_subdirectory(GView) endif() diff --git a/GViewCore/CMakeLists.txt b/GViewCore/CMakeLists.txt index e6080aab..fb595aad 100644 --- a/GViewCore/CMakeLists.txt +++ b/GViewCore/CMakeLists.txt @@ -115,6 +115,7 @@ include_directories(src/View/DissasmViewer) include_directories(src/View/TextViewer) include_directories(src/View/ContainerViewer) include_directories(src/View/LexicalViewer) +include_directories(src/View/YaraViewer) add_subdirectory(src) diff --git a/GViewCore/include/GView.cpp b/GViewCore/include/GView.cpp new file mode 100644 index 00000000..e69de29b diff --git a/GViewCore/include/GView.hpp b/GViewCore/include/GView.hpp index 23cb10ae..4e9cb39c 100644 --- a/GViewCore/include/GView.hpp +++ b/GViewCore/include/GView.hpp @@ -1194,6 +1194,18 @@ namespace View }; }; // namespace ImageViewer + namespace YaraViewer + { + + struct CORE_EXPORT Settings { + void* data; + + Settings(); + void SetAnalysisLevel(int analysisLevel); + + }; + }; // namespace YaraViewer + namespace ContainerViewer { struct CORE_EXPORT EnumerateInterface { @@ -1679,7 +1691,7 @@ namespace View Settings(); }; - }; // namespace DissasmViewer + }; // namespace DissasmViewer struct CORE_EXPORT WindowInterface { virtual Reference GetObject() = 0; @@ -1691,6 +1703,8 @@ namespace View virtual bool CreateViewer(TextViewer::Settings& settings) = 0; virtual bool CreateViewer(ContainerViewer::Settings& settings) = 0; virtual bool CreateViewer(LexicalViewer::Settings& settings) = 0; + virtual bool CreateViewer(YaraViewer::Settings& settings) = 0; + virtual Reference GetCurrentView() = 0; virtual uint32 GetViewsCount() = 0; virtual Reference GetViewByIndex(uint32 index) = 0; diff --git a/GViewCore/src/App/FileWindow.cpp b/GViewCore/src/App/FileWindow.cpp index 68df11c6..58fa9bc3 100644 --- a/GViewCore/src/App/FileWindow.cpp +++ b/GViewCore/src/App/FileWindow.cpp @@ -6,6 +6,7 @@ #include "TextViewer.hpp" #include "ContainerViewer.hpp" #include "LexicalViewer.hpp" +#include "YaraViewer.hpp" using namespace GView::App; using namespace GView::App::InstanceCommands; @@ -158,6 +159,11 @@ bool FileWindow::CreateViewer(GView::View::LexicalViewer::Settings& settings) .IsValid(); } +bool FileWindow::CreateViewer(GView::View::YaraViewer::Settings& settings) +{ + return this->view->CreateChildControl(Reference(this->obj.get()), &settings).IsValid(); +} + Reference FileWindow::GetCurrentView() { return view->GetCurrentTab().ToObjectRef(); diff --git a/GViewCore/src/View/CMakeLists.txt b/GViewCore/src/View/CMakeLists.txt index c2902e50..f608c238 100644 --- a/GViewCore/src/View/CMakeLists.txt +++ b/GViewCore/src/View/CMakeLists.txt @@ -6,4 +6,5 @@ add_subdirectory(GridViewer) add_subdirectory(DissasmViewer) add_subdirectory(TextViewer) add_subdirectory(ContainerViewer) -add_subdirectory(LexicalViewer) \ No newline at end of file +add_subdirectory(LexicalViewer) +add_subdirectory(YaraViewer) \ No newline at end of file diff --git a/GViewCore/src/View/YaraViewer/CMakeLists.txt b/GViewCore/src/View/YaraViewer/CMakeLists.txt new file mode 100644 index 00000000..4a777a32 --- /dev/null +++ b/GViewCore/src/View/YaraViewer/CMakeLists.txt @@ -0,0 +1 @@ +target_sources(GViewCore PRIVATE YaraViewer.hpp Config.cpp GoToDialog.cpp Instance.cpp Settings.cpp) \ No newline at end of file diff --git a/GViewCore/src/View/YaraViewer/Config.cpp b/GViewCore/src/View/YaraViewer/Config.cpp new file mode 100644 index 00000000..52126718 --- /dev/null +++ b/GViewCore/src/View/YaraViewer/Config.cpp @@ -0,0 +1,24 @@ +#include "YaraViewer.hpp" + +using namespace GView::View::YaraViewer; +using namespace AppCUI::Input; + +void Config::Update(IniSection sect) +{ + //sect.UpdateValue("Key.WrapMethod", Key::F2, true); +} +void Config::Initialize() +{ + //auto ini = AppCUI::Application::GetAppSettings(); + //if (ini) + //{ + // auto sect = ini->GetSection("View.Text"); + // this->Keys.WordWrap = sect.GetValue("Key.WrapMethod").ToKey(Key::F2); + //} + //else + //{ + // this->Keys.WordWrap = Key::F2; + //} + + this->Loaded = true; +} diff --git a/GViewCore/src/View/YaraViewer/GoToDialog.cpp b/GViewCore/src/View/YaraViewer/GoToDialog.cpp new file mode 100644 index 00000000..d61b0ffe --- /dev/null +++ b/GViewCore/src/View/YaraViewer/GoToDialog.cpp @@ -0,0 +1,5 @@ +#include "YaraViewer.hpp" + +using namespace GView::View::YaraViewer; +using namespace AppCUI::Input; + diff --git a/GViewCore/src/View/YaraViewer/Instance.cpp b/GViewCore/src/View/YaraViewer/Instance.cpp new file mode 100644 index 00000000..fcaabc2a --- /dev/null +++ b/GViewCore/src/View/YaraViewer/Instance.cpp @@ -0,0 +1,1808 @@ +#include "YaraViewer.hpp" +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "capstone/capstone.h" + +#undef MessageBox + +using namespace GView::View::YaraViewer; +using namespace AppCUI::Input; +namespace fs = std::filesystem; + +Config Instance::config; + +constexpr int startingX = 5; + + +// Constructor +Instance::Instance(Reference _obj, Settings* _settings) + : ViewControl("Yara View", UserControlFlags::ShowVerticalScrollBar | UserControlFlags::ScrollBarOutsideControl), settings(nullptr) +{ + this->obj = _obj; + + this->cursorRow = 0; + this->cursorCol = 0; + this->startViewLine = 0; + this->leftViewCol = 0; + + this->selectionActive = false; + this->selectionAnchorRow = 0; + this->selectionAnchorCol = 0; + + // settings + if ((_settings) && (_settings->data)) + { + // move settings data pointer + this->settings.reset((SettingsData*) _settings->data); + _settings->data = nullptr; + } + else + { + // default setup + this->settings.reset(new SettingsData()); + } + + if (config.Loaded == false) + config.Initialize(); + + layout.visibleLines = 1; + layout.maxCharactersPerLine = 10; +} + + +// --- Metode ViewControl (Interfața Standard) --- +bool Instance::GetPropertyValue(uint32 propertyID, PropertyValue& value){ NOT_IMPLEMENTED(false) } +bool Instance::SetPropertyValue(uint32 propertyID, const PropertyValue& value, String& error){ NOT_IMPLEMENTED(false) } +void Instance::SetCustomPropertyValue(uint32 propertyID){} //NOT IMPLEMENTED +bool Instance::IsPropertyValueReadOnly(uint32 propertyID){ NOT_IMPLEMENTED(false) } +const vector Instance::GetPropertiesList(){ return {}; } + +bool Instance::GoTo(uint64 offset){ NOT_IMPLEMENTED(false) } +bool Instance::Select(uint64 offset, uint64 size) { NOT_IMPLEMENTED(false) } + + +// --- Dialoguri --- +bool Instance::ShowGoToDialog(){ NOT_IMPLEMENTED(false) } +bool Instance::ShowCopyDialog(){ NOT_IMPLEMENTED(false) } +bool Instance::ShowFindDialog() +{ + // 1. Inițializare dialog și preluare input utilizator + FindDialog dlg; + if (dlg.Show() != Dialogs::Result::Ok) + return true; + + std::string text = dlg.resultText; + if (text.empty()) + return true; + + // 2. Salvare stare și refresh UI (activează butonul 'Find Next' și forțează focus) + this->lastSearchText = text; + this->isButtonFindPressed = true; + this->SetFocus(); + + // 3. Pregătire căutare Case-Insensitive (convertim inputul la lowercase) + std::string textToFindLower = text; + std::transform(textToFindLower.begin(), textToFindLower.end(), textToFindLower.begin(), ::tolower); + + uint32 totalLines = (uint32) yaraLines.size(); + if (totalLines == 0) + return true; + + // 4. Începem căutarea de la începutul fișierului + uint32 startIdx = 0; + + for (uint32 i = 0; i < totalLines; i++) { + // Implementare wrap-around (când ajunge la final, o ia de la capăt) + uint32 currentIdx = (startIdx + i) % totalLines; + + const auto& line = yaraLines[currentIdx]; + + // 5. Verificare potrivire pe linia curentă (tot lowercase) + std::string lineLower = line.text; + std::transform(lineLower.begin(), lineLower.end(), lineLower.begin(), ::tolower); + + size_t foundPos = lineLower.find(textToFindLower); + + if (foundPos != std::string::npos) { + + // A. Dacă linia găsită este ascunsă (pliată), căutăm header-ul părinte și îl expandăm + if (!line.isVisible) { + for (int k = (int) currentIdx - 1; k >= 0; k--) { + if (yaraLines[k].type == LineType::FileHeader) { + if (!yaraLines[k].isExpanded) { + ToggleFold(k); + } + break;// Am găsit header-ul, ne oprim + } + } + } + + // B. Mapăm indexul real la cel vizual și evidențiem rezultatul (Highlight Galben) + for (size_t v = 0; v < visibleIndices.size(); v++) { + if (visibleIndices[v] == currentIdx) { + SelectMatch((uint32) v, foundPos, (uint32) textToFindLower.length()); + return true; + } + } + } + } + + // 6. Nicio potrivire găsită după scanarea completă + AppCUI::Dialogs::MessageBox::ShowError("Not Found", "Text '" + text + "' not found!"); + return true; +} + + +// --- Desenare & UI --- +void Instance::PaintCursorInformation(AppCUI::Graphics::Renderer& renderer, uint32 width, uint32 height) +{ + // 1. Validare spațiu (nu desenăm dacă zona este invizibilă) + if (height == 0) + return; + + ColorPair cfgColor = { Color::White, Color::Transparent }; + + // 2. Pregătire text informativ + LocalString<128> info; + info.Format("Ln: %u | Col: %u", this->cursorRow + 1, this->cursorCol + 1); + + // 3. Randare efectivă + renderer.Clear(' ', cfgColor); + renderer.WriteSingleLineText(1, 0, info.GetText(), cfgColor); +} +void Instance::Paint(Graphics::Renderer& renderer) +{ + // 1. Definiții Paletă de Culori + ColorPair textNormal = ColorPair{ Color::White, Color::Transparent }; + ColorPair textCursor = ColorPair{ Color::Black, Color::White }; + ColorPair arrowColor = ColorPair{ Color::Gray, Color::Transparent }; + ColorPair marginColor = ColorPair{ Color::Gray, Color::Transparent }; + ColorPair textSelection = ColorPair{ Color::Black, Color::Silver }; + ColorPair warningColor = ColorPair{ Color::Olive, Color::Transparent }; + + ColorPair ruleBlockColor = ColorPair{ Color::Green, Color::Transparent }; + ColorPair checkboxColor = ColorPair{ Color::Red, Color::Transparent }; // pt [x] + ColorPair headerColor = ColorPair{ Color::Yellow, Color::Transparent }; // pt nume fisier + ColorPair infoColor = ColorPair{ Color::Red, Color::Transparent }; + ColorPair matchColor = ColorPair{ Color::Teal, Color::Transparent }; + ColorPair foldColor = ColorPair{ Color::Aqua, Color::Transparent }; + + // 2. Dimensiuni Viewport & Layout + uint32 rows = this->GetHeight(); + uint32 width = this->GetWidth(); + const int LEFT_MARGIN = 4; + + // 3. Coordonate Selecție + uint32 selStartRow = this->cursorRow; + uint32 selStartCol = this->cursorCol; + uint32 selEndRow = this->selectionAnchorRow; + uint32 selEndCol = this->selectionAnchorCol; + + GetRulesFiles(); // Lazy loading date + + // Asigurăm popularea cache-ului de linii vizibile + if (visibleIndices.empty() && !yaraLines.empty()) + UpdateVisibleIndices(); + + if (this->selectionActive) { + // Swap dacă selecția a fost făcută de jos în sus sau dreapta->stânga + if (selStartRow > selEndRow || (selStartRow == selEndRow && selStartCol > selEndCol)) { + std::swap(selStartRow, selEndRow); + std::swap(selStartCol, selEndCol); + } + } + + // ======================================================================== + // MAIN RENDER LOOP (Iterăm prin rândurile vizibile pe ecran) + // ======================================================================== + + for (uint32 tr = 0; tr < rows; tr++) { + + // A. Mapare: Index Ecran (tr) -> Index Date + uint32 visualIndex = this->startViewLine + tr; + if (visualIndex >= visibleIndices.size()) + break; // Am terminat de desenat liniile disponibile + + size_t realIndex = visibleIndices[visualIndex]; + const LineInfo& info = yaraLines[realIndex]; + std::string displayText = info.text; + + // B. Decoratori Text (Prefixe/Sufixe vizuale) + int checkboxStart = -1; + int checkboxEnd = -1; + int arrowStart = -1; + + // --- ADAUGĂM VIZUAL SĂGEATA DE EXPANDARE --- + if (info.type == LineType::FileHeader) { + // Prefix: Checkbox [ ] + std::string prefix = info.isChecked ? "[x] " : "[ ] "; + displayText = prefix + displayText; + + checkboxStart = 0; + checkboxEnd = 4; + + // Suffix: Săgeata de Fold > sau v + std::string arrow = info.isExpanded ? " v" : " >"; + arrowStart = (int) displayText.length(); + displayText += arrow; + } else if (info.indentLevel > 0) { + displayText.insert(0, " "); + } + + // C. Logică Dual-Color pentru OffsetHeader ("File offset: 0x...") + int splitColorIndex = -1; + if (info.type == LineType::OffsetHeader) { + size_t pos = displayText.find("0x"); + if (pos != std::string::npos) { + splitColorIndex = (int) pos; + } + } + + // D. Desenare Elemente Margine (Gutter) + renderer.WriteSpecialCharacter(LEFT_MARGIN - 1, tr, SpecialChars::BoxVerticalSingleLine, marginColor); + + // Indicator linia curentă "->" + if (visualIndex == this->cursorRow) { + renderer.WriteSingleLineText(1, tr, "->", arrowColor); + } + + // ==================================================================== + // CHARACTER RENDER LOOP (Desenare conținut text caracter cu caracter) + // ==================================================================== + + if (displayText.length() > this->leftViewCol) { + // Tăiem partea din stânga dacă avem scroll orizontal + std::string_view view = displayText; + view = view.substr(this->leftViewCol); + + for (uint32 i = 0; i < view.length(); i++) { + // Nu desenăm în afara ferestrei + if (LEFT_MARGIN + i >= width) + break; + + uint32 absCol = this->leftViewCol + i; + ColorPair currentColor = textNormal; // Default + + // ------------------------------------------------------------ + // LAYER 1: Culoarea de bază (Syntax Highlighting) + // ------------------------------------------------------------ + if (info.type == LineType::OffsetHeader) { + // Split: Alb până la "0x", Verde după + if (splitColorIndex != -1 && absCol >= splitColorIndex) { + currentColor = ruleBlockColor; + } else { + currentColor = textNormal; + } + } else if (info.type == LineType::Warning) { + currentColor = warningColor; + } else if (info.type == LineType::RuleContent) + currentColor = ruleBlockColor; + else if (info.type == LineType::Info) + currentColor = infoColor; + else if (info.type == LineType::Match) + currentColor = matchColor; + else if (info.type == LineType::FileHeader) { + // Culori specifice Header (Checkbox vs Text vs Arrow) + if (absCol >= checkboxStart && absCol < checkboxEnd) + currentColor = checkboxColor; + else if (arrowStart != -1 && absCol >= arrowStart) + currentColor = foldColor; + else + currentColor = headerColor; + } + + // ------------------------------------------------------------ + // LAYER 2: Highlight Căutare (Override peste bază) + // ------------------------------------------------------------ + if (this->searchActive && realIndex == this->searchResultRealIndex) { + if (absCol >= this->searchResultStartCol && absCol < (this->searchResultStartCol + this->searchResultLen)) { + currentColor = ColorPair{ Color::Black, Color::Yellow }; + } + } + + // ------------------------------------------------------------ + // LAYER 3: Selecție Utilizator (Override peste Search) + // ------------------------------------------------------------ + if (this->selectionActive) { + bool isSelected = false; + // Logica de selecție multi-line + if (visualIndex > selStartRow && visualIndex < selEndRow) { + isSelected = true; // Linie complet interioară + } else if (visualIndex == selStartRow && visualIndex == selEndRow) { + // Selecție pe o singură linie + if (absCol >= selStartCol && absCol < selEndCol) + isSelected = true; + } else if (visualIndex == selStartRow) { + // Prima linie a selecției + if (absCol >= selStartCol) + isSelected = true; + } else if (visualIndex == selEndRow) { + // Ultima linie a selecției + if (absCol < selEndCol) + isSelected = true; + } + + if (isSelected) { + currentColor = textSelection; + } + } + + // ------------------------------------------------------------ + // LAYER 4: Cursor + // ------------------------------------------------------------ + if (visualIndex == this->cursorRow && absCol == this->cursorCol) { + currentColor = textCursor; + } + // Desenare efectivă caracter + renderer.WriteCharacter(LEFT_MARGIN + i, tr, view[i], currentColor); + } + + // E. Fill Background (pentru linii colorate complet, ex: RuleContent) + if (info.type == LineType::RuleContent) { + int startFill = LEFT_MARGIN + (int) view.length(); + for (int k = startFill; k < (int) width; k++) { + bool isCursorHere = (visualIndex == this->cursorRow && (this->leftViewCol + (k - LEFT_MARGIN)) == this->cursorCol); + renderer.WriteCharacter(k, tr, ' ', isCursorHere ? textCursor : ruleBlockColor); + } + } + } + + // F. Desenare Cursor dacă este la finalul liniei (după text) + if (visualIndex == this->cursorRow && this->cursorCol == displayText.length()) { + if (this->cursorCol >= this->leftViewCol) { + int screenX = (int) (this->cursorCol - this->leftViewCol) + LEFT_MARGIN; + if (screenX < (int) width) { + renderer.WriteCharacter(screenX, tr, ' ', textCursor); + } + } + } + } +} +void Instance::OnAfterResize(int newWidth, int newHeight) +{ + layout.visibleLines = GetHeight(); + if (layout.visibleLines > 0) + layout.visibleLines--; + layout.maxCharactersPerLine = GetWidth() - startingX /*left*/ - startingX /*right*/; +} +void Instance::AddMatchToUI(const std::string& ruleName, const std::string& tags, const std::string& author, const std::string& severity, const std::vector& strings, const std::string& filePath) +{ + yaraLines.push_back({ " [MATCH] Rule: " + ruleName, LineType::Match }); + if (!tags.empty()) + yaraLines.push_back({ " Tags: " + tags, LineType::Normal }); + if (!author.empty()) + yaraLines.push_back({ " Author: " + author, LineType::Normal }); + if (!severity.empty()) + yaraLines.push_back({ " Severity: " + severity, LineType::Normal }); + + for (const auto& s : strings) { + yaraLines.push_back({ " " + s, LineType::RuleContent }); + yaraLines.push_back({ " At:", LineType::Normal }); + + // Hex Context + auto ctx = ExtractHexContextFromYaraMatch(s, filePath); + for (auto& ctxPair : ctx) { + LineInfo infoLine; + + std::string prefix = " "; + + if (ctxPair.first.find("0x") == 0) { + prefix += " "; + } + infoLine.text = prefix + ctxPair.first; + infoLine.type = ctxPair.second; + yaraLines.push_back(infoLine); + } + + // Disassembly + auto disasmLines = ExtractDisassemblyFromYaraMatch(s, filePath); + for (auto& disPair : disasmLines) { + LineInfo infoLine; + if (disPair.first.find("Disassembly:") != std::string::npos) { + infoLine.text = " " + disPair.first; + } else { + infoLine.text = " " + disPair.first; + } + + infoLine.type = disPair.second; + yaraLines.push_back(infoLine); + } + } + yaraLines.push_back({ "", LineType::Normal }); +} + + +// --- Serializare Setări --- +std::string_view Instance::GetCategoryNameForSerialization() const { return "YaraViewer"; } +bool Instance::AddCategoryBeforePropertyNameWhenSerializing() const { return true; } + + +// --- Input Handling --- +bool Instance::OnUpdateCommandBar(Application::CommandBar& commandBar) +{ + if (!yaraExecuted) { + commandBar.SetCommand(Commands::YaraRunCommand.Key, Commands::YaraRunCommand.Caption, Commands::YaraRunCommand.CommandId); + } + commandBar.SetCommand(Commands::ViewRulesCommand.Key, Commands::ViewRulesCommand.Caption, Commands::ViewRulesCommand.CommandId); + commandBar.SetCommand(Commands::EditRulesCommand.Key, Commands::EditRulesCommand.Caption, Commands::EditRulesCommand.CommandId); + if (!yaraExecuted) { + commandBar.SetCommand(Commands::SelectAllCommand.Key, "Select All", Commands::SelectAllCommand.CommandId); + commandBar.SetCommand(Commands::DeselectAllCommand.Key, "Deselect All", Commands::DeselectAllCommand.CommandId); + } + commandBar.SetCommand(Commands::FindTextCommand.Key, "Find Text", Commands::FindTextCommand.CommandId); + + if (isButtonFindPressed) { + commandBar.SetCommand(Commands::FindNextCommand.Key, "Find Next", Commands::FindNextCommand.CommandId); + } + if (yaraExecuted) { + commandBar.SetCommand(Commands::SaveReportCommand.Key, "Save Report", Commands::SaveReportCommand.CommandId); + } + return false; +} +bool Instance::UpdateKeys(KeyboardControlsInterface* interfaceParam) +{ + interfaceParam->RegisterKey(&Commands::YaraRunCommand); + interfaceParam->RegisterKey(&Commands::ViewRulesCommand); + interfaceParam->RegisterKey(&Commands::EditRulesCommand); + interfaceParam->RegisterKey(&Commands::SelectAllCommand); + interfaceParam->RegisterKey(&Commands::DeselectAllCommand); + interfaceParam->RegisterKey(&Commands::FindTextCommand); + interfaceParam->RegisterKey(&Commands::FindNextCommand); + interfaceParam->RegisterKey(&Commands::SaveReportCommand); + + return true; +} +bool Instance::OnEvent(Reference, Event eventType, int ID) +{ + // Procesăm doar evenimentele de tip Comandă (Butoane, Taste, Meniu) + if (eventType != Event::Command) + return false; + + // --- COMMAND DISPATCHER --- + + if (ID == Commands::YaraRunCommand.CommandId) { // Run Yara + auto result = AppCUI::Dialogs::MessageBox::ShowOkCancel("Run Yara", "Are you sure?"); + + if (result == Dialogs::Result::Ok) { + yaraExecuted = false; + RunYara(); + } + + } else if (ID == Commands::ViewRulesCommand.CommandId) { //View Rules + yaraGetRulesFiles = false; + yaraExecuted = false; + GetRulesFiles(); + + } else if (ID == Commands::EditRulesCommand.CommandId) { // Edit Rules + yaraGetRulesFiles = false; + GetRulesFiles(); + + fs::path currentPath = fs::current_path(); + fs::path rootPath = currentPath.parent_path().parent_path(); + fs::path yaraRules = rootPath / "3rdPartyLibs" / "rules"; + + if (!fs::exists(yaraRules)) { + fs::create_directories(yaraRules); + } + + // Deschidem folderul + ShellExecuteA(NULL, "explore", yaraRules.string().c_str(), NULL, NULL, SW_SHOWNORMAL); + + auto result = AppCUI::Dialogs::MessageBox::ShowOkCancel( + "Edit Rules", "Rules folder opened.\n\nYou can Add, Edit or Delete .yara files now.\n\nClick [OK] when you are done to refresh the list."); + + // Refresh automat la OK + if (result == Dialogs::Result::Ok) { + yaraGetRulesFiles = false; + GetRulesFiles(); + } + } else if (ID == Commands::SelectAllCommand.CommandId) { // Select All + SelectAllRules(); + return true; + } else if (ID == Commands::DeselectAllCommand.CommandId) { // Deselect All + DeselectAllRules(); + return true; + } else if (ID == Commands::FindNextCommand.CommandId) { // Find Next + FindNext(); + return true; + } else if (ID == Commands::SaveReportCommand.CommandId) { // Save Report + ExportResults(); + return true; + } else if (ID == Commands::FindTextCommand.CommandId) { // Find Text + ShowFindDialog(); + return true; + } + + return false; +} +bool Instance::OnKeyEvent(AppCUI::Input::Key keyCode, char16 charCode) +{ + if (keyCode == (Key::Ctrl | Key::C)) { + CopySelectionToClipboard(); + return true; + } + + if (visibleIndices.empty()) + return false; + + auto GetCurrentLine = [&]() -> LineInfo& { + size_t realIdx = visibleIndices[cursorRow]; + return yaraLines[realIdx]; + }; + + if (keyCode == Key::Space) { + if (cursorRow < visibleIndices.size()) { + auto& line = GetCurrentLine(); + if (line.type == LineType::FileHeader) { + line.isChecked = !line.isChecked; + } + } + return true; + } + + if (keyCode == Key::Enter) { + if (cursorRow < visibleIndices.size()) { + size_t realIdx = visibleIndices[cursorRow]; + if (yaraLines[realIdx].type == LineType::FileHeader) { + ToggleFold(realIdx); + } + } + return true; + } + + if (keyCode == Key::Escape) { + this->selectionActive = false; + this->searchActive = false; + this->isButtonFindPressed = false; + this->SetFocus(); + this->lastSearchText.clear(); + return true; + } + + // Navigare și Scroll + uint32 pageHeight = this->GetHeight(); // Câte linii încap pe ecran + + switch (keyCode) { + case Key::Right: { + auto& line = GetCurrentLine(); + if (cursorCol < line.text.length()) { + cursorCol++; + } + // Trecem la linia următoare doar dacă există în lista VIZIBILĂ + else if (cursorRow + 1 < visibleIndices.size()) { + cursorRow++; + cursorCol = 0; + + // Check Scroll Jos la wrap-around + if (cursorRow >= startViewLine + pageHeight) + startViewLine++; + } + } + MoveTo(); + return true; + + case Key::Left: + if (cursorCol > 0) + cursorCol--; + else if (cursorRow > 0) { + cursorRow--; + // Luăm lungimea liniei ANTERIOARE vizibile + size_t prevRealIdx = visibleIndices[cursorRow]; + cursorCol = (uint32) yaraLines[prevRealIdx].text.length(); + + // Check Scroll Sus la wrap-around + if (cursorRow < startViewLine) + startViewLine = cursorRow; + } + MoveTo(); + return true; + + case Key::Down: + if (cursorRow + 1 < visibleIndices.size()) { + cursorRow++; + + // Ajustare coloană (să nu fim în afara textului noii linii) + auto& line = GetCurrentLine(); + if (cursorCol > line.text.length()) + cursorCol = (uint32) line.text.length(); + + // Dacă cursorul coboară sub partea de jos a ecranului, tragem imaginea în jos + if (cursorRow >= startViewLine + pageHeight) { + startViewLine++; + } + } + MoveTo(); // Actualizează poziția cursorului + return true; + + case Key::Up: + if (cursorRow > 0) { + cursorRow--; + + // Ajustare coloană + auto& line = GetCurrentLine(); + if (cursorCol > line.text.length()) + cursorCol = (uint32) line.text.length(); + + // Dacă cursorul urcă deasupra primei linii vizibile, tragem imaginea în sus + if (cursorRow < startViewLine) { + startViewLine = cursorRow; + } + } + MoveTo(); + return true; + + // Page Up / Page Down pentru navigare rapidă + case Key::PageDown: + if (cursorRow + pageHeight < visibleIndices.size()) { + cursorRow += pageHeight; + startViewLine += pageHeight; // Scroll pagină întreagă + } else { + cursorRow = (uint32) visibleIndices.size() - 1; + if (visibleIndices.size() > pageHeight) + startViewLine = (uint32) visibleIndices.size() - pageHeight; + } + MoveTo(); + return true; + + case Key::PageUp: + if (cursorRow > pageHeight) { + cursorRow -= pageHeight; + if (startViewLine > pageHeight) + startViewLine -= pageHeight; + else + startViewLine = 0; + } else { + cursorRow = 0; + startViewLine = 0; + } + MoveTo(); + return true; + } + + return false; +} + + +// --- Mouse Handling --- +bool Instance::OnMouseWheel(int x, int y, AppCUI::Input::MouseWheel direction, AppCUI::Input::Key key) +{ + //Tratam evenimentul de scroll ca și o apăsare de tastă + switch (direction) { + case MouseWheel::Up: + return OnKeyEvent(Key::Up, false); + + case MouseWheel::Down: + return OnKeyEvent(Key::Down, false); + + case MouseWheel::Left: + return OnKeyEvent(Key::Left, false); + + case MouseWheel::Right: + return OnKeyEvent(Key::Right, false); + } + + return false; +} +bool Instance::OnMouseDrag(int x, int y, AppCUI::Input::MouseButton button, AppCUI::Input::Key keyCode) +{ + if ((button & MouseButton::Left) == MouseButton::None) + return false; + if (yaraLines.empty()) + return false; + + // Actualizăm poziția cursorului în timp ce tragem + ComputeMouseCoords(x, y, this->startViewLine, this->leftViewCol, this->yaraLines, this->cursorRow, this->cursorCol); + + // Activăm selecția dacă poziția s-a schimbat + if (this->cursorRow != this->selectionAnchorRow || this->cursorCol != this->selectionAnchorCol) { + this->selectionActive = true; + } + MoveTo(); // Auto-scroll dacă tragem mouse-ul în afara zonei vizibile + return true; +} +void Instance::OnMousePressed(int x, int y, AppCUI::Input::MouseButton button, AppCUI::Input::Key keyCode) +{ + if ((button & MouseButton::Left) == MouseButton::None) + return; + if (visibleIndices.empty() || yaraLines.empty()) + return; + + // 1. Calculăm rândul vizual + uint32 clickVisualRow = this->startViewLine + y; + if (clickVisualRow >= visibleIndices.size()) + return; + + // 2. Calculăm coordonatele exacte (Rând și Coloană) + ComputeMouseCoords(x, y, this->startViewLine, this->leftViewCol, this->yaraLines, this->cursorRow, this->cursorCol); + + // 3. Resetăm ancora selecției (Începem o nouă selecție) + this->selectionAnchorRow = this->cursorRow; + this->selectionAnchorCol = this->cursorCol; + this->selectionActive = false; + + // 4. Logica pentru Header (Checkbox / Fold) + size_t realIndex = visibleIndices[clickVisualRow]; + LineInfo& line = yaraLines[realIndex]; + + int relX = (x - 4) + this->leftViewCol; // Ajustare pentru margine + + if (line.type == LineType::FileHeader) { + // Verificăm click pe zona Checkbox "[ ]" + if (relX >= 0 && relX <= 2) { + line.isChecked = !line.isChecked; + return; + } + + // Verificăm click pe zona Săgeată ">" + int arrowStart = 4 + (int) line.text.length(); + if (relX >= arrowStart && relX <= arrowStart + 1) { + ToggleFold(realIndex); + return; + } + } + + MoveTo(); +} +void Instance::ComputeMouseCoords(int x, int y, uint32 startViewLine, uint32 leftViewCol, const std::vector& lines, uint32& outRow, uint32& outCol) +{ + const int LEFT_MARGIN = 4; + + // 1. Calculăm Rândul Vizual + uint32 r = startViewLine + y; + + // Validăm limitele vizuale + if (visibleIndices.empty()) { + r = 0; + } else if (r >= visibleIndices.size()) { + r = (uint32) visibleIndices.size() - 1; + } + outRow = r; + + // 2. Calculăm Coloana Vizuală + int val = (int) leftViewCol + (x - LEFT_MARGIN); + if (val < 0) + val = 0; + uint32 c = (uint32) val; + + // 3. Limităm coloana la lungimea textului de pe ecran + if (!visibleIndices.empty()) { + size_t realIndex = visibleIndices[outRow]; // Mapăm vizual -> real + const auto& line = lines[realIndex]; + + size_t displayLen = line.text.length(); + + // Ajustăm lungimea pentru elementele vizuale (prefixe) + if (line.type == LineType::FileHeader) { + displayLen += 6; // "[ ] " + " >" + } else if (line.indentLevel > 0) { + displayLen += 4; // indentare + } + + if (c > displayLen) + c = (uint32) displayLen; + } else { + c = 0; + } + + outCol = c; +} +void Instance::MoveTo() +{ + // Asigură că poziția cursorului este vizibilă (Logică de Auto-Scroll) + + uint32 height = this->GetHeight(); + uint32 width = this->GetWidth(); + const int LEFT_MARGIN = 4; + uint32 totalVisible = (uint32) visibleIndices.size(); + uint32 textWidth = (width > LEFT_MARGIN) ? (width - LEFT_MARGIN) : 1; + + // 1. SCROLL VERTICAL (Rânduri) + if (this->cursorRow < this->startViewLine) { + this->startViewLine = this->cursorRow; + } else if (this->cursorRow >= this->startViewLine + height) { + this->startViewLine = this->cursorRow - height + 1; + } + + if (this->startViewLine > totalVisible) + this->startViewLine = 0; + + // 2. SCROLL ORIZONTAL (Coloane) + if (this->cursorCol < this->leftViewCol) { + this->leftViewCol = this->cursorCol; + } else if (this->cursorCol >= this->leftViewCol + textWidth) { + this->leftViewCol = this->cursorCol - textWidth + 1; + } +} + + +// Selection & Folding +void Instance::ToggleSelection() +{ + // Comută starea 'Bifat' pentru liniile de tip Header (Checkbox) + if (this->cursorRow < yaraLines.size()) { + if (yaraLines[this->cursorRow].type == LineType::FileHeader) { + yaraLines[this->cursorRow].isChecked = !yaraLines[this->cursorRow].isChecked; + } + } +} +void Instance::SelectAllRules() +{ + // Bifează toate liniile de tip Header (Checkbox) + bool changesMade = false; + for (auto& line : yaraLines) { + if (line.type == LineType::FileHeader) { + if (!line.isChecked) { + line.isChecked = true; + changesMade = true; + } + } + } +} +void Instance::DeselectAllRules() +{ + // Debifează toate liniile de tip Header (Checkbox) + bool changesMade = false; + for (auto& line : yaraLines) { + if (line.type == LineType::FileHeader) { + if (line.isChecked) { + line.isChecked = false; + changesMade = true; + } + } + } +} +void Instance::UpdateVisibleIndices() +{ + // Reconstruiește harta vizuală (index cache) ignorând liniile ascunse + visibleIndices.clear(); + for (size_t i = 0; i < yaraLines.size(); i++) { + if (yaraLines[i].isVisible) { + visibleIndices.push_back(i); + } + } +} +void Instance::ToggleFold(size_t index) +{ + if (index >= yaraLines.size()) + return; + + // Logică de expandare/pliere pentru secțiunile Header + if (yaraLines[index].type == LineType::FileHeader) { + + // Inversăm starea curentă + bool newState = !yaraLines[index].isExpanded; + yaraLines[index].isExpanded = newState; + + // Iterăm în jos + for (size_t i = index + 1; i < yaraLines.size(); i++) { + if (yaraLines[i].type == LineType::FileHeader) { + break; // Am ajuns la următorul header, oprim + } + + // Modificăm vizibilitatea doar pentru liniile de conținut (RuleContent) + if (yaraLines[i].type == LineType::RuleContent) { + yaraLines[i].isVisible = newState; + } + } + // Actualizăm maparea viewport-ului + UpdateVisibleIndices(); + } +} +void Instance::CopySelectionToClipboard() +{ + // Variabila în care vom construi textul + std::string textToCopy; + + // Construirea textui de copiat + { + if (!this->selectionActive || this->yaraLines.empty()) + return; + + uint32 r1 = this->cursorRow; + uint32 c1 = this->cursorCol; + uint32 r2 = this->selectionAnchorRow; + uint32 c2 = this->selectionAnchorCol; + + if (r1 > r2 || (r1 == r2 && c1 > c2)) { + std::swap(r1, r2); + std::swap(c1, c2); + } + + // Iterăm prin liniile selectate + for (uint32 r = r1; r <= r2; r++) { + if (r >= this->yaraLines.size()) + break; + + const std::string& line = this->yaraLines[r].text; + + uint32 start = (r == r1) ? c1 : 0; + uint32 end = (r == r2) ? c2 : (uint32) line.length(); + + if (start > line.length()) + start = (uint32) line.length(); + if (end > line.length()) + end = (uint32) line.length(); + + if (end > start) { + textToCopy += line.substr(start, end - start); + } + + // Adăugăm NewLine dacă nu suntem la ultima linie + if (r < r2) { + textToCopy += "\r\n"; // Format standard Windows + } + } + } + + // Trimitem datele în Clipboard-ul sistemului de operare + if (!textToCopy.empty()) { + AppCUI::OS::Clipboard::SetText(textToCopy); + } +} + + +// Search Helpers +void Instance::SelectMatch(uint32 visualRow, size_t startRawCol, uint32 length) +{ + // 1. Identificăm linia REALĂ din maparea vizuală + size_t realIndex = visibleIndices[visualRow]; + const auto& line = yaraLines[realIndex]; + + // 2. Ajustăm coloana vizuală (compensăm indentarea sau prefixele) + size_t visualCol = startRawCol; + if (line.type == LineType::FileHeader) + visualCol += 4; // "[ ] " + else if (line.indentLevel > 0) + visualCol += 4; // " " + + // 3. Activăm Highlight-ul Căutării + this->searchActive = true; + this->searchResultRealIndex = realIndex; // Salvăm indexul real pentru persistență la scroll/fold + this->searchResultStartCol = (uint32) visualCol; + this->searchResultLen = length; + + // 4. Mutăm cursorul la finalul termenului găsit + this->cursorRow = visualRow; + this->cursorCol = (uint32) (visualCol + length); + + // Dezactivăm selecția veche pentru a evidenția doar rezultatul curent + this->selectionActive = false; + + MoveTo(); // Asigurăm vizibilitatea cursorului +} +bool Instance::FindNext() +{ + if (lastSearchText.empty()) + return false; + if (visibleIndices.empty() || yaraLines.empty()) + return false; + + // 1. Pregătire text (lowercase) + std::string textToFindLower = lastSearchText; + std::transform(textToFindLower.begin(), textToFindLower.end(), textToFindLower.begin(), ::tolower); + + uint32 totalLines = (uint32) yaraLines.size(); + + // Identificăm indexul REAL al liniei unde se află cursorul + uint32 currentRealIndex = 0; + if (this->cursorRow < visibleIndices.size()) { + currentRealIndex = (uint32) visibleIndices[this->cursorRow]; + } + + // --- FAZA 1: Căutăm pe restul liniei curente (de la cursor spre dreapta) --- + { + const auto& line = yaraLines[currentRealIndex]; + std::string lineLower = line.text; + std::transform(lineLower.begin(), lineLower.end(), lineLower.begin(), ::tolower); + + // Calculăm offset-ul + int searchStartOffset = this->cursorCol; + if (line.type == LineType::FileHeader) + searchStartOffset -= 4; // "[ ] " + else if (line.indentLevel > 0) + searchStartOffset -= 4; // " " + + if (searchStartOffset < 0) + searchStartOffset = 0; + + // Căutare efectivă + size_t foundPos = lineLower.find(textToFindLower, searchStartOffset); + + if (foundPos != std::string::npos) { + // Dacă am găsit, evidențiem folosind rândul vizual curent + SelectMatch(this->cursorRow, foundPos, (uint32) textToFindLower.length()); + return true; + } + } + + // --- FAZA 2: Căutăm pe restul liniilor (Scanare completă cu Wrap-Around) --- + for (uint32 i = 1; i <= totalLines; i++) { + uint32 nextRealIdx = (currentRealIndex + i) % totalLines; // Wrap-around la început + + const auto& line = yaraLines[nextRealIdx]; + std::string lineLower = line.text; + std::transform(lineLower.begin(), lineLower.end(), lineLower.begin(), ::tolower); + + size_t foundPos = lineLower.find(textToFindLower); // Căutăm de la începutul liniei + + if (foundPos != std::string::npos) { + // A. Expandăm automat secțiunea dacă linia găsită este ascunsă + if (!line.isVisible) { + for (int k = (int) nextRealIdx - 1; k >= 0; k--) { + if (yaraLines[k].type == LineType::FileHeader) { + if (!yaraLines[k].isExpanded) + ToggleFold(k); + break; // Am găsit părintele, ne oprim + } + } + } + + // B. Recalculăm indexul VIZUAL (poate s-a schimbat după ToggleFold) + for (size_t v = 0; v < visibleIndices.size(); v++) { + if (visibleIndices[v] == nextRealIdx) { + SelectMatch((uint32) v, foundPos, (uint32) textToFindLower.length()); + return true; + } + } + } + } + + // Niciun rezultat găsit după o tură completă + AppCUI::Dialogs::MessageBox::ShowNotification("Info", "No more occurrences found."); + return false; +} + + +// --- Internal Logic Methods --- +void Instance::RunYara() +{ + // --------------------------------------------------------- + // 1. SELECTIE REGULI + // --------------------------------------------------------- + std::vector selectedRules; + for (const auto& line : yaraLines) { + if (line.type == LineType::FileHeader && line.isChecked) { + selectedRules.push_back(line.filePath); + } + } + + if (selectedRules.empty()) { + AppCUI::Dialogs::MessageBox::ShowError("Error", "No rules selected!"); + return; + } + + // --------------------------------------------------------- + // 2. SETUP PATH-URI + // --------------------------------------------------------- + fs::path currentPath = fs::current_path(); + fs::path rootPath = currentPath.parent_path().parent_path(); + fs::path yaraExe = rootPath / "3rdPartyLibs" / "yara-win64" / "yara64.exe"; + fs::path outputFile = rootPath / "3rdPartyLibs" / "output" / "output.txt"; + fs::path currentFile = this->obj->GetPath(); + + fs::path outputDir = outputFile.parent_path(); + if (!fs::exists(outputDir)) + fs::create_directories(outputDir); + + if (!fs::exists(yaraExe)) { + AppCUI::Dialogs::MessageBox::ShowError("Error", "Yara exe not found!"); + return; + } + + // --------------------------------------------------------- + // 3. RESETARE INTERFATA + // --------------------------------------------------------- + this->cursorRow = 0; + this->cursorCol = 0; + this->startViewLine = 0; + this->leftViewCol = 0; + this->selectionActive = false; + this->selectionAnchorRow = 0; + this->selectionAnchorCol = 0; + + yaraLines.clear(); + + // Header temporar (va fi completat la final cu Summary) + yaraLines.push_back({ "=== SCANNING RESULTS ===", LineType::Normal }); + yaraLines.push_back({ "", LineType::Normal }); + yaraLines.push_back({ "scanning...", LineType::Normal }); // Placeholder pt Summary + + int globalMatchCount = 0; + + // --------------------------------------------------------- + // 4. EXECUTIE PER REGULA + // --------------------------------------------------------- + for (const auto& rulePath : selectedRules) { + std::string ruleName = rulePath.filename().string(); + + // Separator vizual între reguli + yaraLines.push_back({ "-------------------------------------------------------------", LineType::Normal }); + yaraLines.push_back({ "Scanning with rule: " + ruleName, LineType::Info }); + + // Comanda YARA + std::string cmdArgs = "/C \"\"" + yaraExe.string() + + "\" -g -m -s -r " + "\"" + + rulePath.string() + + "\" " + "\"" + + currentFile.string() + + "\" " + "> \"" + + outputFile.string() + "\" 2>&1\""; + + SHELLEXECUTEINFOA shExecInfo{}; + shExecInfo.cbSize = sizeof(SHELLEXECUTEINFOA); + shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; // pentru a astepta procesul + shExecInfo.hwnd = nullptr; + shExecInfo.lpVerb = "open"; // rulare / deschide + shExecInfo.lpFile = "cmd.exe"; // ce se ruleaza + shExecInfo.lpParameters = cmdArgs.c_str(); // parametrii + shExecInfo.nShow = SW_HIDE; // fara afisare cmd + + if (ShellExecuteExA(&shExecInfo)) { + WaitForSingleObject(shExecInfo.hProcess, INFINITE); + CloseHandle(shExecInfo.hProcess); + + // --------------------------------------------------------- + // 5. PARSARE REZULTATE (Logica ta veche) + // --------------------------------------------------------- + std::ifstream in(outputFile); + if (!in.is_open()) { + yaraLines.push_back({ " [ERROR] Cannot open output file.", LineType::Normal }); + continue; + } + + std::string line; + std::vector matchedStrings; + std::string currentRule, currentTags, currentAuthor, currentSeverity; + + bool foundAnyInFile = false; + bool hasErrors = false; + + while (std::getline(in, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) + line.pop_back(); + if (line.empty()) + continue; + + foundAnyInFile = true; + + if (line.find("error:") != std::string::npos || line.find("syntax error") != std::string::npos) { + hasErrors = true; + std::string prefix = " [SYNTAX ERROR] "; + + size_t posIn = line.find(" in "); + size_t posColon = line.find("): "); + + if (posIn != std::string::npos && posColon != std::string::npos) { + + std::string partContext = line.substr(0, posIn + 3); + yaraLines.push_back({ prefix + partContext, LineType::Info }); + + size_t pathStart = posIn + 4; + size_t pathLength = (posColon + 2) - pathStart; + std::string partPath = line.substr(pathStart, pathLength); + + yaraLines.push_back({ " " + partPath, LineType::Info }); + + std::string partMsg = line.substr(posColon + 3); + yaraLines.push_back({ " " + partMsg, LineType::Info }); + + } else { + + std::string fullError = prefix + line; + const size_t MAX_LEN = 100; + + if (fullError.length() <= MAX_LEN) { + yaraLines.push_back({ fullError, LineType::Info }); + } else { + size_t currentPos = 0; + bool isFirstLine = true; + while (currentPos < fullError.length()) { + size_t chunkLen = (std::min)(MAX_LEN, fullError.length() - currentPos); + std::string part = fullError.substr(currentPos, chunkLen); + + if (isFirstLine) { + yaraLines.push_back({ part, LineType::Info }); + isFirstLine = false; + } else { + yaraLines.push_back({ " " + part, LineType::Info }); + } + currentPos += chunkLen; + } + } + } + continue; + } + + if (line.find("warning:") != std::string::npos) { + std::string prefix = " [WARNING] "; + + size_t posIn = line.find(" in "); // Separă regula de cale + size_t posColon = line.find("): "); // Separă calea de mesaj + + if (posIn != std::string::npos && posColon != std::string::npos) { + + std::string partContext = line.substr(0, posIn + 3); + yaraLines.push_back({ prefix + partContext, LineType::Warning }); + + size_t pathStart = posIn + 4; + size_t pathLength = (posColon + 2) - pathStart; + std::string partPath = line.substr(pathStart, pathLength); + + yaraLines.push_back({ " " + partPath, LineType::Warning }); + + std::string partMsg = line.substr(posColon + 3); + + const size_t MAX_MSG_LEN = 90; + if (partMsg.length() <= MAX_MSG_LEN) { + yaraLines.push_back({ " " + partMsg, LineType::Warning }); + } else { + size_t currentPos = 0; + while (currentPos < partMsg.length()) { + size_t chunkLen = (std::min)(MAX_MSG_LEN, partMsg.length() - currentPos); + std::string chunk = partMsg.substr(currentPos, chunkLen); + yaraLines.push_back({ " " + chunk, LineType::Warning }); + currentPos += chunkLen; + } + } + + } else { + std::string fullWarn = prefix + line; + const size_t MAX_LEN = 100; + + size_t currentPos = 0; + bool isFirstLine = true; + while (currentPos < fullWarn.length()) { + size_t chunkLen = (std::min)(MAX_LEN, fullWarn.length() - currentPos); + std::string part = fullWarn.substr(currentPos, chunkLen); + + if (isFirstLine) { + yaraLines.push_back({ part, LineType::Warning }); + isFirstLine = false; + } else { + yaraLines.push_back({ " " + part, LineType::Warning }); + } + currentPos += chunkLen; + } + } + continue; + } + + + if (line.find(currentFile.string()) != std::string::npos && line.find('[') != std::string::npos && line.find(']') != std::string::npos) { + + if (!currentRule.empty()) { + globalMatchCount++; + // APELĂM FUNCȚIA HELPER + AddMatchToUI(currentRule, currentTags, currentAuthor, currentSeverity, matchedStrings, currentFile.string()); + } + + + // === RESETARE PENTRU REGULA NOUĂ === + matchedStrings.clear(); + currentAuthor.clear(); + currentSeverity.clear(); + currentTags.clear(); + + // === PARSARE HEADER NOU === + // 1. Rule Name + size_t spacePos = line.find(' '); + currentRule = line.substr(0, spacePos); + + // 2. Tags + size_t firstBracketStart = line.find('['); + size_t firstBracketEnd = line.find(']'); + if (firstBracketStart != std::string::npos && firstBracketEnd != std::string::npos) + currentTags = line.substr(firstBracketStart + 1, firstBracketEnd - firstBracketStart - 1); + + // 3. Meta (Author, Severity) + size_t metaStart = line.find('[', firstBracketEnd + 1); + size_t metaEnd = line.find(']', metaStart); + if (metaStart != std::string::npos && metaEnd != std::string::npos) { + std::string metaStr = line.substr(metaStart + 1, metaEnd - metaStart - 1); + + auto extractMeta = [&](const std::string& key) -> std::string { + size_t keyPos = metaStr.find(key + "=\""); + if (keyPos != std::string::npos) { + size_t start = keyPos + key.length() + 2; + size_t end = metaStr.find("\"", start); + if (end != std::string::npos) + return metaStr.substr(start, end - start); + } + return ""; + }; + + currentAuthor = extractMeta("author"); + currentSeverity = extractMeta("severity"); + } + } else { + // Este o linie cu un string ($s1: ...) + matchedStrings.push_back(line); + } + } + in.close(); + + // === DUMP ULTIMA REGULĂ DIN FIȘIER === + if (!currentRule.empty()) { + globalMatchCount++; + AddMatchToUI(currentRule, currentTags, currentAuthor, currentSeverity, matchedStrings, currentFile.string()); + } else if (!foundAnyInFile) { + yaraLines.push_back({ " [CLEAN] No matches for this rule.", LineType::Normal }); + } else if (!hasErrors && currentRule.empty()) { + // S-a scris ceva in fisier, dar nu am detectat "error:" si nici nu am parsat o regula. + // Poate fi Clean sau un output necunoscut. + yaraLines.push_back({ " [CLEAN] No matches for this rule.", LineType::Normal }); + } + } else { + yaraLines.push_back({ " [ERROR] Execution failed.", LineType::Normal }); + } + } + + // --------------------------------------------------------- + // 6. SUMAR FINAL (Inserat la început) + // --------------------------------------------------------- + // Modificăm liniile rezervate la început + yaraLines[2].text = "Summary:"; + yaraLines.insert(yaraLines.begin() + 3, { " Total Matches: " + std::to_string(globalMatchCount), LineType::Normal }); + yaraLines.insert(yaraLines.begin() + 4, { globalMatchCount > 0 ? " Status: INFECTED" : " Status: CLEAN", LineType::Normal }); + yaraLines.insert(yaraLines.begin() + 5, { "", LineType::Normal }); + + yaraLines.push_back({ "=== SCAN COMPLETE ===", LineType::Normal }); + + yaraExecuted = true; + yaraGetRulesFiles = true; // Previne reîncărcarea automată + UpdateVisibleIndices(); +} +std::string Instance::GetSectionFromOffset(const std::string& exePath, uint64_t offset) +{ + // // Deschidem fișierul EXE în modul binar + std::ifstream file(exePath, std::ios::binary); + if (!file) + return "UNKNOWN"; + + // 1️ DOS Header (MZ) + IMAGE_DOS_HEADER dos{}; + file.read(reinterpret_cast(&dos), sizeof(dos)); + // Verificăm semnătura "MZ" + if (dos.e_magic != IMAGE_DOS_SIGNATURE) + return "NOT_A_PE"; + + // 2️ Ne mutăm la offset-ul NT Headers (dat de DOS) + file.seekg(dos.e_lfanew, std::ios::beg); + DWORD signature = 0; + file.read(reinterpret_cast(&signature), sizeof(signature)); + if (signature != IMAGE_NT_SIGNATURE) + return "NOT_A_PE"; + + + // Citim File Header + // Header-ul care conține numărul de secțiuni etc. + IMAGE_FILE_HEADER fileHeader{}; + file.read(reinterpret_cast(&fileHeader), sizeof(fileHeader)); + + // 3️ Detect 32-bit vs 64-bit + IMAGE_OPTIONAL_HEADER32 optional32{}; + IMAGE_OPTIONAL_HEADER64 optional64{}; + bool is64 = false; + WORD magic; + file.read(reinterpret_cast(&magic), sizeof(magic)); + file.seekg(-static_cast(sizeof(magic)), std::ios::cur); + + if (magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + file.read(reinterpret_cast(&optional32), sizeof(optional32)); + is64 = false; + + } else if (magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) { + file.read(reinterpret_cast(&optional64), sizeof(optional64)); + is64 = true; + + } else { + return "UNKNOWN"; + } + + // 4️ Secțiuni + std::vector sections(fileHeader.NumberOfSections); + + // iteram peste toate secțiunile + for (int i = 0; i < fileHeader.NumberOfSections; i++) { + file.read(reinterpret_cast(§ions[i]), sizeof(IMAGE_SECTION_HEADER)); + } + + // 5️ Căutăm secțiunea pentru offset + for (const auto& sec : sections) { + DWORD start = sec.PointerToRawData; + DWORD end = start + sec.SizeOfRawData; + if (offset >= start && offset < end) { + + // Returnează numele secțiunii + return std::string(reinterpret_cast(sec.Name), strnlen(reinterpret_cast(sec.Name), 8)); + } + } + + return "UNKNOWN"; +} +void Instance::GetRulesFiles() +{ + if (yaraGetRulesFiles) + return; + + // --------------------------------------------------------- + // RESETARE INTERFATA + // --------------------------------------------------------- + this->cursorRow = 0; + this->cursorCol = 0; + this->startViewLine = 0; + this->leftViewCol = 0; + this->selectionActive = false; + this->selectionAnchorRow = 0; + this->selectionAnchorCol = 0; + + yaraLines.clear(); + + fs::path currentPath = fs::current_path(); + fs::path rootPath = currentPath.parent_path().parent_path(); + fs::path yaraRules = rootPath / "3rdPartyLibs" / "rules"; + + if (!fs::exists(yaraRules) || !fs::is_directory(yaraRules)) + return; + + // Header info + yaraLines.push_back({ "=== YARA RULES SELECTION ===", LineType::Normal }); + yaraLines.push_back({ "", LineType::Normal }); + yaraLines.push_back({ "Controls:", LineType::Normal }); + yaraLines.push_back({ " [Space] or [Click] : Toggle selection", LineType::Normal }); + yaraLines.push_back({ " [Enter] : Expand/Collapse content", LineType::Normal }); + yaraLines.push_back({ " [Ctrl + A] : Select All", LineType::Normal }); + yaraLines.push_back({ " [Ctrl + D] : Deselect All", LineType::Normal }); + yaraLines.push_back({ " [F6] Run | [F7] View Rules | [F8] Edit", LineType::Normal }); + + // --- 2. DELIMITARE --- + yaraLines.push_back({ "_________________________________________", LineType::Normal }); + yaraLines.push_back({ "", LineType::Normal }); + + // --- 3. TITLU LISTĂ --- + yaraLines.push_back({ "Rules list:", LineType::Info }); // Folosesc Info ca să fie galben (opțional) sau Normal + yaraLines.push_back({ "", LineType::Normal }); + + for (auto& entry : fs::directory_iterator(yaraRules)) { + if (entry.is_regular_file()) { + std::string filename = entry.path().filename().string(); + + // Adăugăm HEADER-ul fișierului (care va avea checkbox) + LineInfo header; + header.text = filename; + header.type = LineType::FileHeader; + header.isChecked = false; + header.filePath = entry.path(); + header.isExpanded = false; // <--- START PLIAT + header.isVisible = true; + yaraLines.push_back(header); + + std::ifstream in(entry.path()); + if (in.is_open()) { + std::string line; + while (std::getline(in, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) + line.pop_back(); + + // CONȚINUT (Invizibil la start) + LineInfo content; + content.text = line; + content.type = LineType::RuleContent; + content.isVisible = false; // <--- ASCUNS PÂNĂ DAI ENTER + content.indentLevel = 1; + yaraLines.push_back(content); + } + } + yaraLines.push_back({ "", LineType::Normal }); + } + } + UpdateVisibleIndices(); + yaraGetRulesFiles = true; +} +void Instance::ExportResults() +{ + // 1. Verificăm dacă avem ce salva + if (yaraLines.empty()) { + AppCUI::Dialogs::MessageBox::ShowError("Error", "No scan results to save!"); + return; + } + + // 2. Dialog de confirmare salvare + auto response = AppCUI::Dialogs::MessageBox::ShowOkCancel("Save Report", "Do you want to save the scan results to a text file?"); + + if (response != Dialogs::Result::Ok) { + return; // Dacă userul dă Cancel sau X, ieșim și nu salvăm nimic. + } + + // 3. Generăm numele bazat pe Timestamp (Dată + Oră) + auto now = std::chrono::system_clock::now(); + auto in_time_t = std::chrono::system_clock::to_time_t(now); + + std::stringstream ss; + ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d_%H-%M-%S"); + std::string fileName = "results_" + ss.str() + ".txt"; + + // 4. Configurare cale output (root/3rdPartyLibs/results/) și creare folder + fs::path currentPath = fs::current_path(); + fs::path rootPath = currentPath.parent_path().parent_path(); + fs::path resultsDir = rootPath / "3rdPartyLibs" / "results"; + + if (!fs::exists(resultsDir)) { + fs::create_directories(resultsDir); + } + + fs::path fullPath = resultsDir / fileName; + + // 5. Scrierea efectivă + std::ofstream out(fullPath); + if (!out.is_open()) { + AppCUI::Dialogs::MessageBox::ShowError("Error", "Could not create file!"); + return; + } + + for (const auto& line : yaraLines) { + // Păstrăm indentarea + for (int i = 0; i < line.indentLevel; i++) + out << "\t"; + + // Păstrăm checkbox-ul vizual + if (line.type == LineType::FileHeader) { + out << (line.isChecked ? "[x] " : "[ ] "); + } + + out << line.text << "\n"; + } + out.close(); + + // 6. Notificare finală și deschidere folder + AppCUI::Dialogs::MessageBox::ShowNotification("Saved", "Report saved successfully!\nOpening folder..."); + ShellExecuteA(NULL, "explore", resultsDir.string().c_str(), NULL, NULL, SW_SHOWNORMAL); +} + + +std::vector> Instance::ExtractHexContextFromYaraMatch( + const std::string& yaraLine, const std::string& exePath, size_t contextSize) +{ + + + std::vector> output; + + // 1. Extragem offset-ul (0x....) + size_t pos = yaraLine.find(':'); + if (pos == std::string::npos) + return output; + + std::string offsetStr = yaraLine.substr(0, pos); + uint64_t offset = 0; + try { + // convertire în număr baza 16 + offset = std::stoull(offsetStr, nullptr, 16); + } catch (...) { + output.push_back({ "EROARE: Offset invalid în linia YARA.", LineType::Normal }); + return output; + } + + // 2. Deschidem fișierul EXE in mod binar + std::ifstream file(exePath, std::ios::binary); + if (!file.is_open()) { + output.push_back({ "EROARE: Nu pot deschide fișierul.", LineType::Normal }); + return output; + } + + // 3. Calculăm zona de citire + uint64_t startOffset = (offset > contextSize) ? offset - contextSize : 0; + size_t readSize = contextSize * 2; + + // mutam offsetul de citire la pozitia startOffset fata de începutul fisierului + file.seekg(startOffset, std::ios::beg); + + // citim zona de interes în buffer + std::vector buffer(readSize); + file.read(reinterpret_cast(buffer.data()), buffer.size()); + + //cati bytes s-au citit efectiv (poate fi mai puțin la sfarsitul fisierului) + size_t bytesRead = file.gcount(); + + // 4. Format HEX + ASCII + size_t lineSize = 16; + for (size_t i = 0; i < bytesRead; i += lineSize) { + std::ostringstream line; + std::ostringstream ascii; + + // Construim conținutul liniei (Hex + ASCII) + for (size_t j = 0; j < lineSize; j++) { + if (i + j < bytesRead) { + + // luam byte-ul + uint8_t b = buffer[i + j]; + + // std::setw(2) - afișăm exact 2 caractere pentru fiecare byte + // std::setfill('0') - dacă byte-ul are doar un caracter (A), îl completam cu 0 (0A) + // std::hex - afișăm în hexazecimal + // std::uppercase - litere mari (A-F) + // static_cast(b) - byte-ul convertit la int ca să nu fie interpretat ca caracter + line << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << static_cast(b) << ' '; + + //std::isprint(b) - verificare dacă byte-ul este caracter imprimabil (A-Z, 0-9, simboluri) + ascii << (std::isprint(b) ? static_cast(b) : '.'); + } else { + line << " "; + } + } + + // Construim linia completă + std::ostringstream fullLine; + uint64_t currentLineAddr = startOffset + i; + + fullLine << "0x" << std::setw(8) << std::setfill('0') << std::hex << currentLineAddr << " " << line.str() << " " << ascii.str(); + + + // implicit linia este albă (Normala) + GView::View::YaraViewer::LineType currentType = GView::View::YaraViewer::LineType::Normal; + + // Verificăm dacă offset-ul căutat (cel din Yara match) se află pe această linie + // Offset-ul trebuie să fie >= începutul liniei ȘI < începutul liniei următoare + if (offset >= currentLineAddr && offset < (currentLineAddr + lineSize)) { + currentType = GView::View::YaraViewer::LineType::RuleContent; // RuleContent este VERDE în Paint() + } + + // Adăugăm linia cu tipul calculat + output.push_back({ fullLine.str(), currentType }); + } + + // 5. Header-ul cu offset (verde) + std::ostringstream header; + header << "File offset: 0x" << std::hex << std::uppercase << offset; + + std::ostringstream section; + std::string sectionName = GetSectionFromOffset(exePath, offset); + section << "Section: " << sectionName; + + // --- INSERĂM LINIILE COLORATE --- + + // Titlu (Alb) + + // Offset (Verde - folosind LineType::Info) + output.insert(output.begin(), { header.str(), LineType::OffsetHeader }); + // Secțiune (Alb) + output.insert(output.begin() + 1, { section.str(), LineType::Normal }); + + output.insert(output.begin() + 2, { "Hex Dump:", LineType::Normal }); + + return output; +} + + +std::vector> Instance::ExtractDisassemblyFromYaraMatch( + const std::string& yaraLine, const std::string& exePath, size_t contextSize) // total bytes pentru disassembly +{ + // Returnăm perechi (Text, LineType) + std::vector> output; + + // 1. Extragem offset-ul din linia YARA + size_t pos = yaraLine.find(':'); + if (pos == std::string::npos) + return output; + + std::string offsetStr = yaraLine.substr(0, pos); + uint64_t offset = 0; + try { + // convertire în număr baza 16 + offset = std::stoull(offsetStr, nullptr, 16); + } catch (...) { + output.push_back({ "EROARE: Offset invalid", LineType::Normal }); + return output; + } + + // Sectiune valida = ".text" + std::string section = GetSectionFromOffset(exePath, offset); + if (section != ".text") { + output.push_back({ "Disassembly: (skipped – non-executable section)", LineType::Normal }); + return output; + } + + // 2. Deschidem fișierul in mod binar + std::ifstream file(exePath, std::ios::binary); + if (!file.is_open()) { + output.push_back({ "EROARE: Nu pot deschide fișierul", LineType::Normal }); + return output; + } + + // 3. Citim buffer de la offset + + // mutam offsetul de citire la pozitia startOffset fata de începutul fisierului + file.seekg(offset, std::ios::beg); + + // citim zona de interes în buffer + std::vector buffer(contextSize); + file.read(reinterpret_cast(buffer.data()), buffer.size()); + + // cati bytes s-au citit efectiv (poate fi mai puțin la sfarsitul fisierului) + size_t bytesRead = file.gcount(); + + // ajustează mărimea vectorului exact la câți bytes am citit + buffer.resize(bytesRead); + + if (buffer.empty()) { + output.push_back({ "EROARE: Nu am bytes pentru disassembly", LineType::Normal }); + return output; + } + + // 4. Capstone disassembly + + // handle sesiunee curentă + csh handle; + + // inițializare Capstone pentru arhitectura x86 64-bit + // CS_ARCH_X86 - arhitectura procesorului + // CS_MODE_64 - modul 64-bit + // Returnează CS_ERR_OK dacă inițializarea e reușită + if (cs_open(CS_ARCH_X86, CS_MODE_64, &handle) != CS_ERR_OK) { + output.push_back({ "EROARE: Capstone init failed", LineType::Normal }); + return output; + } + + // CS_OPT_DETAIL, CS_OPT_OFF + // nu vrem detalii suplimentare (precum registre folosite, flags etc.), doar instrucțiunea simplă. + cs_option(handle, CS_OPT_DETAIL, CS_OPT_OFF); + + // pointer la structurile care vor conține instrucțiunile dezasamblate + cs_insn* insn; + + + // Dezasamblăm bufferul, considerând că începe la adresa 'offset' + // count - numărul de instrucțiuni dezasamblate + size_t count = cs_disasm( + handle, + buffer.data(), // pointer la bytes + buffer.size(), // câți bytes citim + offset, // adresă de start (pentru afișare în output) + 0, // număr maxim de instrucțiuni (0 = toate) + &insn // pointer unde se scriu instrucțiunile + ); + + if (count > 0) { + output.push_back({ "Disassembly:", LineType::Normal }); + + // Iterăm prin instrucțiuni + for (size_t i = 0; i < count; i++) { + + // insn[i]: + // address - adresa instrucțiunii în fișier + // mnemonic - instrucțiunea (mov, add, jmp etc.) + // op_str - operanzii (eax, ebx, etc.) + + + std::ostringstream line; + line << "0x" << std::setw(8) << std::setfill('0') << std::hex << insn[i].address << " " << insn[i].mnemonic << " " << insn[i].op_str; + + GView::View::YaraViewer::LineType lineType = GView::View::YaraViewer::LineType::Normal; + + // dacă adresa instrucțiunii este exact offset-ul căutat -> VERDE (RuleContent) + if (insn[i].address == offset) { + lineType = GView::View::YaraViewer::LineType::RuleContent; + } + + output.push_back({ line.str(), lineType }); + } + } else { + output.push_back({ "EROARE: Nu s-a putut disassembly", LineType::Normal }); + } + + // Curățare + cs_free(insn, count); + cs_close(&handle); + + return output; +} diff --git a/GViewCore/src/View/YaraViewer/Settings.cpp b/GViewCore/src/View/YaraViewer/Settings.cpp new file mode 100644 index 00000000..3f4c474c --- /dev/null +++ b/GViewCore/src/View/YaraViewer/Settings.cpp @@ -0,0 +1,18 @@ +#include "YaraViewer.hpp" + +using namespace GView::View::YaraViewer; +using namespace AppCUI::Input; + +#define DATA ((SettingsData*) data) + +SettingsData::SettingsData() +{ +} +Settings::Settings() +{ + this->data = new SettingsData(); +} +void Settings::SetAnalysisLevel(int analysisLevelParam) +{ + DATA->analysisLevel = analysisLevelParam; +} \ No newline at end of file diff --git a/GViewCore/src/View/YaraViewer/YaraViewer.hpp b/GViewCore/src/View/YaraViewer/YaraViewer.hpp new file mode 100644 index 00000000..de56bc41 --- /dev/null +++ b/GViewCore/src/View/YaraViewer/YaraViewer.hpp @@ -0,0 +1,219 @@ +#pragma once + +#include "Internal.hpp" + + +namespace GView::View::YaraViewer +{ + using namespace AppCUI; + using namespace GView::Utils; + + namespace Commands + { + constexpr int CMD_YARA_RUN = 0x01; + constexpr int CMD_VIEW_RULES = 0x02; + constexpr int CMD_EDIT_RULES = 0x03; + constexpr int CMD_SELECT_ALL = 0x04; + constexpr int CMD_DESELECT_ALL = 0x05; + constexpr int CMD_FIND_TEXT = 0x06; + constexpr int CMD_FIND_NEXT = 0x07; + constexpr int CMD_SAVE_REPORT = 0x08; + + static KeyboardControl YaraRunCommand = { Input::Key::F6, "Yara Run", "YaraRunCommand explanation", CMD_YARA_RUN }; + static KeyboardControl ViewRulesCommand = { Input::Key::F7, "View Rules", "View all the rules from folder rules", CMD_VIEW_RULES }; + static KeyboardControl EditRulesCommand = { Input::Key::F8, "Edit Rules", "Open rules folder to manage files", CMD_EDIT_RULES }; + static KeyboardControl SelectAllCommand = { Input::Key::Ctrl | Input::Key::A, "Select All", "Select all available rules", CMD_SELECT_ALL }; + static KeyboardControl DeselectAllCommand = { Input::Key::Ctrl | Input::Key::D, "Deselect All", "Deselect all rules", CMD_DESELECT_ALL }; + static KeyboardControl FindTextCommand = { Input::Key::Ctrl | Input::Key::F, "Find", "Search for text", CMD_FIND_TEXT }; + static KeyboardControl FindNextCommand = { Input::Key::F3, "Find Next", "Go to next occurrence", CMD_FIND_NEXT }; + static KeyboardControl SaveReportCommand = { Input::Key::Ctrl | Input::Key::S, "Save Report", "Save results to text file", CMD_SAVE_REPORT }; + } // namespace Commands + + struct SettingsData + { + int analysisLevel; + SettingsData(); + }; + + struct Config + { + bool Loaded; + + static void Update(IniSection sect); + void Initialize(); + }; + + struct Layout + { + uint32 visibleLines; + uint32 maxCharactersPerLine; + }; + + enum class LineType { + Normal, + FileHeader, // Conține checkbox [ ] sau [x] și numele fișierului + RuleContent, // Conținutul regulii (poate fi colorat diferit) + Info, // Mesaje informative + Match, // Linii care indică o potrivire (MATCH) + OffsetHeader,// Header pentru offset-uri și context hex/disasm + Warning // Mesaje de avertizare (galben) + }; + + struct LineInfo { + std::string text; + LineType type; + bool isChecked = false; // Pentru FileHeader + std::filesystem::path filePath; + bool isExpanded = true; // Dacă conținutul de sub header e vizibil + int indentLevel = 0; // Nivel indentare (0 = root, 1 = interior) + int parentIndex = -1; // Indexul părintelui (pentru folding) + bool isVisible = true; // Dacă linia trebuie desenată + }; + + class Instance : public View::ViewControl + { + + Pointer settings; + Reference obj; + static Config config; + Layout layout; + + // State Flags + bool yaraExecuted = false; + bool yaraGetRulesFiles = false; + bool isButtonFindPressed = false; + + // Data Storage + std::vector yaraLines; + std::vector visibleIndices; + std::string lastSearchText; + + // Search & Highlight Logic + bool searchActive = false; + size_t searchResultRealIndex = 0; + uint32 searchResultStartCol = 0; + uint32 searchResultLen = 0; + + public: + + // Viewport & Cursor + uint32 startViewLine; + uint32 leftViewCol; + uint32 cursorRow; + uint32 cursorCol; + + // Selection (Mouse/Keyboard) + bool selectionActive; + uint32 selectionAnchorRow; + uint32 selectionAnchorCol; + + // Constructor + Instance(Reference _obj, Settings* _settings); + + // --- Metode ViewControl (Interfața Standard) --- + bool GetPropertyValue(uint32 propertyID, PropertyValue& value) override; + bool SetPropertyValue(uint32 propertyID, const PropertyValue& value, String& error) override; + void SetCustomPropertyValue(uint32 propertyID) override; + bool IsPropertyValueReadOnly(uint32 propertyID) override; + const vector GetPropertiesList() override; + + bool GoTo(uint64 offset) override; + bool Select(uint64 offset, uint64 size) override; + + // --- Dialoguri --- + bool ShowGoToDialog() override; + bool ShowFindDialog() override; + bool ShowCopyDialog() override; + + // --- Desenare & UI --- + void PaintCursorInformation(AppCUI::Graphics::Renderer& renderer, uint32 width, uint32 height) override; + void Paint(Graphics::Renderer& renderer) override; + void OnAfterResize(int newWidth, int newHeight) override; + void AddMatchToUI(const std::string& ruleName, const std::string& tags, const std::string& author, const std::string& severity, const std::vector& matchedStrings, const std::string& filePath); + + // --- Serializare Setări --- + std::string_view GetCategoryNameForSerialization() const override; + bool AddCategoryBeforePropertyNameWhenSerializing() const override; + + // --- Input Handling --- + bool OnUpdateCommandBar(Application::CommandBar& commandBar) override; + bool UpdateKeys(KeyboardControlsInterface* interfaceParam) override; + bool OnEvent(Reference, Event eventType, int ID) override; + bool OnKeyEvent(AppCUI::Input::Key keyCode, char16 characterCode) override; + + // --- Mouse Handling --- + bool OnMouseWheel(int x, int y, AppCUI::Input::MouseWheel direction, AppCUI::Input::Key key) override; + bool OnMouseDrag(int x, int y, Input::MouseButton button, Input::Key keyCode) override; + void OnMousePressed(int x, int y, Input::MouseButton button, Input::Key keyCode) override; + void ComputeMouseCoords(int x, int y, uint32 startViewLine, uint32 leftViewCol, const std::vector& lines, uint32& outRow, uint32& outCol); + void MoveTo(); + + // Selection & Folding + void ToggleSelection(); + void SelectAllRules(); + void DeselectAllRules(); + void UpdateVisibleIndices(); + void ToggleFold(size_t index); + void CopySelectionToClipboard(); + + // Search Helpers + void SelectMatch(uint32 row, size_t startRawCol, uint32 length); + bool FindNext(); + + // --- Internal Logic Methods --- + void RunYara(); + void GetRulesFiles(); + void ExportResults(); + + // Hex Processing + std::vector> ExtractHexContextFromYaraMatch( + const std::string& yaraLine, const std::string& exePath, size_t contextSize = 64); + + // Disassembly + std::vector> ExtractDisassemblyFromYaraMatch( + const std::string& yaraLine, const std::string& exePath, size_t contextSize = 32); + + std::string GetSectionFromOffset(const std::string& exePath, uint64_t offset); + }; + + class FindDialog : public AppCUI::Controls::Window + { + Reference input; + + public: + std::string resultText; + + FindDialog() : Window("Find Text", "d:c,w:60,h:8", WindowFlags::ProcessReturn) + { + // Eticheta + AppCUI::Controls::Factory::Label::Create(this, "Search for:", "x:1,y:1,w:56"); + + // Câmpul de text + input = AppCUI::Controls::Factory::TextField::Create(this, "", "x:1,y:2,w:56"); + input->SetHotKey('S'); // Alt+S sare aici + input->SetFocus(); + + // Butoanele + AppCUI::Controls::Factory::Button::Create(this, "&Find", "l:16,b:0,w:13", 100); + AppCUI::Controls::Factory::Button::Create(this, "&Cancel", "l:31,b:0,w:13", 101); + } + + bool OnEvent(Reference sender, Event eventType, int controlID) override + { + if (eventType == Event::ButtonClicked || eventType == Event::WindowAccept) { + if ((eventType == Event::ButtonClicked && controlID == 100) || eventType == Event::WindowAccept) { + resultText = std::string(input->GetText()); + Exit(Dialogs::Result::Ok); + return true; + } + if (controlID == 101) + { + Exit(Dialogs::Result::Cancel); + return true; + } + } + return Window::OnEvent(sender, eventType, controlID); + } + }; + +}; // namespace GView \ No newline at end of file diff --git a/GViewCore/src/include/Internal.hpp b/GViewCore/src/include/Internal.hpp index 3f55bfba..3bb7b23e 100644 --- a/GViewCore/src/include/Internal.hpp +++ b/GViewCore/src/include/Internal.hpp @@ -772,6 +772,8 @@ namespace App bool CreateViewer(View::TextViewer::Settings& settings) override; bool CreateViewer(View::ContainerViewer::Settings& settings) override; bool CreateViewer(View::LexicalViewer::Settings& settings) override; + bool CreateViewer(View::YaraViewer::Settings& settings) override; + CommonInterfaces::QueryInterface* GetQueryInterface() override; Reference GetSelectionZoneInterfaceFromViewerCreation(View::BufferViewer::Settings& settings) override; diff --git a/Types/PE/src/pe.cpp b/Types/PE/src/pe.cpp index 17c3a8fa..fe95ee80 100644 --- a/Types/PE/src/pe.cpp +++ b/Types/PE/src/pe.cpp @@ -198,6 +198,10 @@ PLUGIN_EXPORT bool PopulateWindow(Reference win) auto pe = win->GetObject()->GetContentType(); pe->Update(); + GView::View::YaraViewer::Settings settings; + settings.SetAnalysisLevel(3); + win->CreateViewer(settings); + #ifdef DISSASM_DEV CreateDissasmView(win, pe); CreateBufferView(win, pe);