Skip to content

Dankular/SharpVM

Repository files navigation

SharpVM

A comprehensive binary analysis and emulation framework written in C#/.NET 8.0.

Features

  • Universal Binary Analyzer - Detect crypto algorithms, obfuscation, and protection techniques in any binary
  • PE Loader - Parses Windows PE executables, extracts code sections, and resolves import tables
  • x86-64 Emulation - Full CPU emulation with register/flags/memory support via Iced library
  • NT Syscall Emulation - Real Windows syscall handling (26+ handlers) for SYSCALL instruction
  • Virtual Registry - Full read/write Windows registry emulation with defaults
  • VM Bytecode Engine - VMProtect-style stack-based VM with rolling key encryption
  • Windows API Emulation - Stubs for kernel32, user32, msvcrt, and more
  • Hybrid Execution - Forward unimplemented APIs to real Windows
  • Interactive Debugger - Breakpoints, snapshots, tracing, and state persistence
  • Protection Analysis - Arxan, VMProtect, Themida detection and VM bytecode extraction

Quick Start

# Build
dotnet build

# Analyze any binary for crypto/obfuscation
dotnet run -- --analyze suspicious.exe -v

# Execute a PE through the VM
dotnet run -- --blackbone test.exe -x

# With execution tracing
dotnet run -- --blackbone test.exe -x -t

Universal Binary Analyzer (--analyze)

The universal analyzer can detect crypto algorithms, obfuscation techniques, and protection schemes in any binary file.

# Basic analysis
dotnet run -- --analyze target.exe

# Verbose output with all details
dotnet run -- --analyze target.exe -v

# Export report to file
dotnet run -- --analyze target.exe -o report.txt

What it detects:

File Formats:

  • PE (Windows executables)
  • ELF (Linux executables)
  • Mach-O (macOS executables)
  • Raw binaries

Cryptographic Algorithms:

  • AES (S-box constants, key schedule patterns)
  • XTEA/TEA (delta constants, shift patterns)
  • RC4 (KSA/PRGA patterns)
  • MD5/SHA-1/SHA-256 (IV constants)
  • CRC32 (polynomial tables)
  • ChaCha20/Salsa20 (quarter-round patterns)
  • RSA (modular exponentiation patterns)

Protection/Obfuscation:

  • VMProtect (section names, signatures)
  • Themida/WinLicense (markers, API patterns)
  • Arxan (code guards, integrity checks)
  • Denuvo (trigger patterns)
  • UPX and other packers
  • Custom packers (entropy analysis)
  • Anti-debug techniques (IsDebuggerPresent, timing checks)
  • Control flow flattening
  • String encryption

Code Analysis:

  • Entropy per section (packed/encrypted detection)
  • Suspicious API imports (injection, keylogging)
  • VM handler tables and dispatchers
  • Bytecode region detection
  • High-entropy string detection

Example Output:

╔═══════════════════════════════════════════════════════════════╗
║           SharpVM - Universal Binary Analyzer                  ║
╚═══════════════════════════════════════════════════════════════╝

File: Launcher.exe
Size: 125,829,120 bytes
SHA-256: a1b2c3d4...

=== Analysis Summary ===
Format: PE64 (Windows x64)
Sections: 7
Findings: 23

=== Critical Findings ===
[Critical] Arxan Protection Detected
  Found Arxan code guard signatures in .text section

[High] XTEA Cipher Pattern
  Classic XTEA shift sequence at 0x1106007D
  Pattern: shl 4 / shr 5 / shr 11 (delta shift)

[High] High Entropy Section: .data2
  Entropy 7.89 suggests encryption/compression

=== Detected Protections ===
- Arxan (CodeVirtualization, 85% confidence)
- Custom Packer (CustomPacker, 80% confidence)
- String Encryption (StringEncryption, 70% confidence)

Blackbone PE Mapper (--blackbone)

Manual PE mapping with full x86-64 emulation, similar to Blackbone kernel mapper.

# Load and analyze PE
dotnet run -- --blackbone target.exe

# Interactive exploration
dotnet run -- --blackbone target.exe -i

# Execute with API emulation
dotnet run -- --blackbone target.exe -x

# Execute with tracing
dotnet run -- --blackbone target.exe -x -t

# Execute with debugger
dotnet run -- --blackbone target.exe -x -d

# Passthrough mode (real Windows APIs)
dotnet run -- --blackbone target.exe -x -p

# VM analysis for protected binaries
dotnet run -- --blackbone target.exe -x --vmanalysis analysis.txt

# Memory dump when protection completes
dotnet run -- --blackbone target.exe -x --memdump dump.bin

Options:

  • -i, --interactive - Interactive exploration mode
  • -x, --execute - Execute through VM with API emulation
  • -t, --trace - Enable instruction tracing
  • -d, --debug - Break at entry point for debugging
  • -p, --passthrough - Forward API calls to real Windows
  • --max N - Maximum instructions to execute
  • --dump <path> - Dump execution trace to file
  • --vmanalysis <path> - Enable protection VM analysis
  • --memdump <path> - Dump memory regions

Architecture

┌─────────────────┐
│   Binary File   │  (PE, ELF, raw binary)
└────────┬────────┘
         │
         v
┌─────────────────┐
│ Universal       │  File format detection
│ Analyzer        │  Crypto pattern matching
│                 │  Obfuscation detection
└────────┬────────┘
         │
         v
┌─────────────────┐
│   PE Loader     │  Parse headers, sections, imports
│   (Blackbone)   │  Manual mapping, relocations
└────────┬────────┘
         │
         v
┌─────────────────────────────────────────────────┐
│           Unified Execution Environment          │
├─────────────────────────────────────────────────┤
│ ┌─────────────────┐    ┌─────────────────────┐  │
│ │ x86-64 CPU      │    │ Unified Virtual     │  │
│ │ (Iced decoder)  │    │ Memory Manager      │  │
│ └────────┬────────┘    └──────────┬──────────┘  │
│          │                        │              │
│          v                        v              │
│ ┌─────────────────────────────────────────────┐ │
│ │         NT Syscall Dispatcher               │ │
│ │  ┌────────┐ ┌────────┐ ┌────────┐ ┌──────┐  │ │
│ │  │ Memory │ │Registry│ │ Thread │ │System│  │ │
│ │  │Syscalls│ │Syscalls│ │Syscalls│ │ Info │  │ │
│ │  └────────┘ └────────┘ └────────┘ └──────┘  │ │
│ └─────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────┤
│ ┌──────────────┐  ┌────────────┐  ┌──────────┐  │
│ │Virtual       │  │ Handle     │  │ API      │  │
│ │Registry      │  │ Manager    │  │ Emulator │  │
│ └──────────────┘  └────────────┘  └──────────┘  │
└─────────────────────────────────────────────────┘
         │
         v
┌─────────────────┐
│ VM Debugger     │  Breakpoints, snapshots
│                 │  State persistence
└─────────────────┘

Unified Syscall Emulation (Sogen Integration)

SharpVM includes a unified NT syscall emulation layer that handles SYSCALL instructions directly, providing real Windows behavior without stubs.

Implemented Syscalls (26 handlers)

Memory Operations:

  • NtAllocateVirtualMemory (0x18) - Allocate/commit memory
  • NtFreeVirtualMemory (0x1E) - Free/decommit memory
  • NtProtectVirtualMemory (0x50) - Change page protection
  • NtQueryVirtualMemory (0x23) - Query region info
  • NtReadVirtualMemory (0x3A) - Read process memory
  • NtWriteVirtualMemory (0x3B) - Write process memory

Registry Operations:

  • NtOpenKey / NtOpenKeyEx (0x12, 0x119) - Open registry key
  • NtCreateKey (0x1D) - Create registry key
  • NtQueryValueKey (0x17) - Read registry value
  • NtSetValueKey (0x60) - Write registry value
  • NtEnumerateKey (0x13) - Enumerate subkeys
  • NtEnumerateValueKey (0x14) - Enumerate values
  • NtQueryKey (0x16) - Query key info
  • NtClose (0x0F) - Close handle

Thread/Process:

  • NtSetInformationThread (0x0D) - Set thread info (HideFromDebugger, etc.)
  • NtQueryInformationThread (0x25) - Query thread state
  • NtQueryInformationProcess (0x19) - Query process info (PEB, debug status)
  • NtDelayExecution (0x34) - Sleep
  • NtYieldExecution (0x46) - Yield CPU

System Information:

  • NtQuerySystemInformation (0x36) - System info classes
  • NtQueryLicenseValue (0x118) - License/activation values
  • NtQueryDefaultLocale (0x6C) - Locale info
  • NtQueryDefaultUILanguage (0x15) - UI language

Virtual Registry

The emulator includes a full read/write virtual registry with Windows 10 defaults:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion
  ProductName = "Windows 10 Pro"
  CurrentBuildNumber = "19045"

HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
  PROCESSOR_ARCHITECTURE = "AMD64"
  NUMBER_OF_PROCESSORS = "8"

HKCU\Control Panel\International
  LocaleName = "en-US"

Usage

Syscall emulation is automatically enabled when using --blackbone -x:

# Execute with syscall emulation (automatic)
dotnet run -- --blackbone target.exe -x

# With tracing to see syscalls
dotnet run -- --blackbone target.exe -x -t

Project Structure

SharpVM/
├── src/
│   ├── Core/               # Unified emulation infrastructure
│   │   ├── Memory/         # Unified virtual memory
│   │   │   ├── IVirtualMemory.cs
│   │   │   └── UnifiedVirtualMemory.cs
│   │   ├── Syscalls/       # NT syscall emulation
│   │   │   ├── SyscallDispatcher.cs
│   │   │   ├── SyscallContext.cs
│   │   │   ├── NtStatus.cs
│   │   │   └── Handlers/   # Syscall handlers
│   │   │       ├── MemorySyscalls.cs
│   │   │       ├── RegistrySyscalls.cs
│   │   │       ├── ThreadSyscalls.cs
│   │   │       └── SystemSyscalls.cs
│   │   ├── Registry/       # Virtual registry
│   │   │   └── VirtualRegistry.cs
│   │   └── Handles/        # Kernel object handles
│   │       └── HandleManager.cs
│   ├── Analyzer/           # Universal binary analyzer
│   │   ├── Core/           # Analyzer framework
│   │   │   ├── IAnalyzerModule.cs
│   │   │   └── UniversalAnalyzer.cs
│   │   └── Modules/        # Detection modules
│   │       ├── FileFormatDetector.cs
│   │       ├── CryptoPatternDetector.cs
│   │       ├── ObfuscationDetector.cs
│   │       ├── EntropyAnalyzer.cs
│   │       ├── StringAnalyzer.cs
│   │       ├── CodePatternAnalyzer.cs
│   │       ├── ImportExportAnalyzer.cs
│   │       └── VmProtectionDetector.cs
│   ├── Blackbone/          # PE mapper and executor
│   │   ├── PE/             # PE parsing
│   │   ├── ManualMap/      # Manual mapping
│   │   ├── Memory/         # Legacy virtual memory
│   │   └── Execution/      # Execution engine
│   │       ├── VmExecutor.cs
│   │       ├── X64InstructionExecutor.cs
│   │       └── ApiEmulator.cs
│   ├── CPU/                # x86 CPU emulation
│   │   ├── X86Cpu.cs       # Main CPU emulator
│   │   ├── X86Registers.cs # Register state
│   │   └── BiosInterrupts.cs
│   ├── Debugger/           # Interactive debugger
│   │   └── VmDebugger.cs
│   ├── Loader/             # PE loading
│   │   ├── PeLoader.cs
│   │   └── X86Decoder.cs
│   ├── Runtime/            # VM runtime
│   │   ├── VmEngine.cs
│   │   ├── MemoryManager.cs
│   │   └── WinApiEmulator.cs
│   ├── Translator/         # x86 to VM bytecode
│   │   ├── IrInstruction.cs
│   │   ├── X86ToIr.cs
│   │   └── IrToVm.cs
│   ├── Tracing/            # Execution tracing
│   │   └── ExecutionTracer.cs
│   ├── Sogen/              # Sogen Windows emulator wrapper
│   │   └── Core/
│   └── Arxan/              # Arxan protection analysis
│       └── VmBytecodeDecoder.cs
├── tools/
│   └── ProtectionLoopAnalyzer/  # XTEA loop analyzer
└── demos/
    └── DemoRunner.cs

Dependencies

  • Iced - x86/x64 disassembler
  • PeNet - PE file parser
  • .NET 8.0

Supported Instructions

  • Data Movement: MOV, MOVZX, MOVSX, LEA, PUSH, POP, XCHG
  • Arithmetic: ADD, SUB, MUL, IMUL, DIV, IDIV, INC, DEC, NEG
  • Logical: AND, OR, XOR, NOT, SHL, SHR, SAR, ROL, ROR
  • Control Flow: JMP, Jcc (all conditions), CALL, RET
  • Comparison: CMP, TEST
  • String: REP MOVSB/STOSB/MOVSD

Emulated APIs

  • kernel32: GetModuleHandle, GetProcAddress, VirtualAlloc, ExitProcess, CreateFile, ReadFile, WriteFile, etc.
  • user32: MessageBox, ShellExecute
  • msvcrt: CRT initialization, memory functions
  • advapi32: ETW stubs, registry operations
  • ntdll: Nt* low-level functions

Use Cases

  1. Malware Analysis - Analyze protected malware without execution
  2. Game Protection Research - Study Arxan, Denuvo, VMProtect implementations
  3. Binary Reverse Engineering - Understand crypto and obfuscation
  4. Security Research - Detect anti-debug and anti-analysis techniques
  5. CTF Challenges - Identify crypto algorithms in challenge binaries

Command Reference

Command Description
--analyze <file> Universal binary analysis
--analyze <file> -v Verbose analysis output
--analyze <file> -o <path> Export report to file
--blackbone <exe> Load and analyze PE
--blackbone <exe> -x Execute through VM
--blackbone <exe> -x -t Execute with tracing
--blackbone <exe> -x -d Execute with debugger
--inject <exe> Legacy PE injection mode
--advanced Run algorithm demos

Example: Analyzing Protected Binary

# Analyze Rockstar Games Launcher
dotnet run -- --analyze "Launcher.exe" -v -o launcher_report.txt

# Output shows:
# - Arxan protection detected
# - XTEA encryption in protection loop
# - High entropy packed sections
# - VM handler tables at specific addresses

Example: Executing with Protection Analysis

# Execute with VM analysis enabled
dotnet run -- --blackbone "Launcher.exe" -x --vmanalysis vm_analysis.txt --max 2000000000

# This will:
# - Execute the binary through the VM
# - Track protection loop iterations
# - Identify XTEA decryption patterns
# - Extract VM bytecode when possible

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors