Metadata-Version: 2.4
Name: bx2trace
Version: 1.1.0
Summary: bx2trace - High-performance Stealth Behavioral Analysis Framework for Windows
Author-email: FBX2 <fareedataf4@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/fareed1-ataf/BX2debug
Project-URL: Repository, https://github.com/fareed1-ataf/BX2debug.git
Project-URL: Bug Tracker, https://github.com/fareed1-ataf/BX2debug/issues
Keywords: malware,analysis,dynamic,sandbox,hooking,forensics,security,windows,reverse-engineering,threat-intelligence,debugging,api-monitor
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Win32 (MS Windows)
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Information Technology
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Debuggers
Classifier: Topic :: System :: Monitoring
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: Microsoft :: Windows :: Windows 10
Classifier: Operating System :: Microsoft :: Windows :: Windows 11
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: yara-python>=4.5.0
Dynamic: license-file

<div align="center">
  <h1>bx2trace</h1>
  <p><strong>High-Performance Stealth Behavioral Analysis Framework for Windows</strong></p>
  <p>
    <a href="https://github.com/fareed1-ataf/BX2debug/issues"><img alt="Issues" src="https://img.shields.io/github/issues/fareed1-ataf/BX2debug?color=blue&style=flat-square" /></a>
    <a href="https://github.com/fareed1-ataf/BX2debug/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/fareed1-ataf/BX2debug?color=blue&style=flat-square" /></a>
    <a href="https://www.python.org/"><img alt="Python" src="https://img.shields.io/badge/Python-3.11+-blue.svg?style=flat-square&logo=python" /></a>
    <img alt="Platform" src="https://img.shields.io/badge/Platform-Windows%2010%2F11-blue.svg?style=flat-square&logo=windows" />
  </p>
</div>

---

## Table of Contents
- [What is bx2trace?](#what-is-bx2trace)
- [Key Capabilities](#key-capabilities)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [API Reference](#api-reference)
- [Built-in Detectors](#built-in-detectors)
- [Writing Custom Detectors](#writing-custom-detectors)
- [Architecture](#architecture)
- [Changelog](#changelog)
- [License](#license)

---

## What is bx2trace?

`bx2trace` is a **pure-Python Windows behavioral analysis library** that uses the native Windows Debug API to monitor any executable at the API call level — without modifying the target binary, injecting DLLs, or requiring a kernel driver.

It is the engine powering **BX2Debug**, a full malware analysis and reporting suite.

**Who is it for?**
- Malware Analysts who need programmatic access to runtime behavior
- Security Researchers building custom sandbox environments
- CTF players and Reverse Engineers who want a scriptable alternative to tools like x64dbg or Process Monitor

---

## Key Capabilities

| Capability | Details |
|---|---|
| **API Hooking** | Plants INT3 breakpoints at API entry points; captures register arguments (RCX/RDX/R8/R9) |
| **Memory Scanning** | Background thread scans RWX memory regions for injected shellcode and extracts strings |
| **Entropy Analysis** | Per-page Shannon entropy calculation to detect packed/encrypted regions |
| **String Extraction** | Extracts both ASCII and UTF-16LE strings; classifies into URLs, IPs, Paths, Commands |
| **Network Monitoring** | Intercepts WSASend, connect, DNS queries; reconstructs TLS context |
| **Crypto Detection** | Hooks CryptImportKey, BCryptEncrypt, BCryptDecrypt; infers key type from blob size |
| **Anti-Debug Detection** | Catches IsDebuggerPresent, NtQueryInformationProcess, CheckRemoteDebuggerPresent |
| **Process Injection Detection** | Tracks VirtualAllocEx + WriteProcessMemory + CreateRemoteThread chains |
| **Registry Persistence Detection** | Monitors MITRE ATT&CK T1547 registry run keys |
| **Stealth Mode** | Patches PEB.BeingDebugged and NtGlobalFlag to hide from anti-debug checks |

---

## Installation

```bash
pip install bx2trace
```

> **Requirements:** Windows 10/11, Python 3.11+, 64-bit Python interpreter, Administrator privileges (required for Debug API access).

---

## Quick Start

```python
from bx2trace import TraceSession, EngineConfig, TraceMode

# Configure the analysis
config = EngineConfig(
    target_path=r"C:\path\to\suspicious.exe",
    mode=TraceMode.FULL_TRACE,
    enable_stealth=True,   # Hide debugger presence from anti-debug checks
)

# Run the analysis session
session = TraceSession(config)
session.engine.load_defaults()  # Load all built-in detectors
session.start()

try:
    while session.is_alive:
        event = session.get_event(timeout=0.1)
        if event is None:
            continue

        # Every event is a structured TraceEvent object
        print(f"[{event.category.name}] {event.action} | PID={event.pid}")

        # Run through the detector pipeline
        alerts = session.engine.process(event)
        for alert in alerts:
            print(f"  ALERT [{alert.severity.name}]: {alert.action}")
            print(f"  Details: {alert.payload}")

finally:
    session.join()
    print("Analysis complete.")
```

---

## API Reference

### `EngineConfig`

```python
EngineConfig(
    target_path: str,          # Path to the executable to analyze
    cmd_args: str = "",        # Command-line arguments for the target
    mode: TraceMode = TraceMode.FULL_TRACE,
    enable_stealth: bool = True,
)
```

### `TraceSession`

```python
session = TraceSession(config)
session.start()           # Launch target and begin monitoring
session.get_event()       # Returns next TraceEvent or None (non-blocking)
session.is_alive          # True while the target process is running
session.join()            # Wait for clean shutdown
```

### `TraceEvent`

Every event in the system is a `TraceEvent` with these fields:

| Field | Type | Description |
|---|---|---|
| `category` | `EventCategory` | HIGH-LEVEL category: NETWORK, FILE, REGISTRY, CRYPTO, PROCESS, ANTI_DEBUG, etc. |
| `action` | `str` | Specific action: DNS_LOOKUP, DATA_SENT, VALUE_SET, KEY_IMPORTED, etc. |
| `pid` | `int` | Process ID that triggered the event |
| `severity` | `Severity` | INFO, SUSPICIOUS, HIGH, CRITICAL |
| `payload` | `dict` | All decoded, structured arguments for the event |

---

## Built-in Detectors

Load all detectors at once:

```python
session.engine.load_defaults()
```

Or register individually:

```python
from bx2trace import C2BeaconDetector, ProcessHollowingDetector, RegistryPersistenceDetector

session.engine.register(C2BeaconDetector())
session.engine.register(ProcessHollowingDetector())
session.engine.register(RegistryPersistenceDetector())
```

| Detector | Fires When | Severity |
|---|---|---|
| `C2BeaconDetector` | Same IP:Port contacted 3+ times within 60 seconds | CRITICAL |
| `ProcessHollowingDetector` | VirtualAllocEx + WriteProcessMemory + CreateRemoteThread on same PID | CRITICAL |
| `RegistryPersistenceDetector` | Write to Run/RunOnce keys (T1547) | CRITICAL/HIGH |

---

## Writing Custom Detectors

Extend `BaseDetector` to add any custom detection logic:

```python
from bx2trace import BaseDetector, TraceEvent, EventCategory, Severity
from typing import List

class MyCustomDetector(BaseDetector):
    name = "my_custom_detector"

    def handles(self, event: TraceEvent) -> bool:
        # Only process NETWORK events
        return event.category == EventCategory.NETWORK

    def process(self, event: TraceEvent) -> List[TraceEvent]:
        # Your detection logic here
        hostname = event.payload.get("details", {}).get("hostname")
        if hostname and "malicious" in hostname:
            return [TraceEvent(
                category=EventCategory.NETWORK,
                action="SUSPICIOUS_DOMAIN",
                pid=event.pid,
                severity=Severity.CRITICAL,
                payload={"hostname": hostname, "message": "Known malicious domain contacted"},
            )]
        return []

# Register it
session.engine.register(MyCustomDetector())
```

---

## Architecture

```
Target Process (suspicious.exe)
        |
        | Windows Debug API (WaitForDebugEvent)
        v
   DebugThread (core/debug_thread.py)
        |         |
        |         | Background Thread
        |         v
        |  MemoryScannerThread (core/memory_scanner.py)
        |         |
        v         v
    event_queue (queue.Queue[TraceEvent])
        |
        v
  DetectorEngine (core/detector_engine.py)
        |
        +---> C2BeaconDetector
        +---> ProcessHollowingDetector
        +---> RegistryPersistenceDetector
        +---> [Your Custom Detectors]
        |
        v
  Consumer (your application / BX2Debug reporter)
```

---

## Changelog

### v1.1.0 (2026-10-06)
- **FIX:** All Python source files now have explicit UTF-8 encoding declarations — resolves import failures on non-English Windows systems
- **FIX:** `_read_wstring()` and `_read_astring()` now return `None` instead of `"DecodeError"` on memory read failures
- **FIX:** Corrected project URLs in `pyproject.toml` to point to the correct GitHub repository
- **IMPROVE:** Added full PyPI classifiers and keywords for discoverability
- **IMPROVE:** Added `Bug Tracker` URL to project metadata

### v1.0.0 (Initial Release)
- Core debug loop with API hooking via INT3 breakpoints
- Memory scanner with Shannon entropy analysis
- Modular detector pipeline with `DetectorEngine`
- Built-in detectors: C2 Beacon, Process Hollowing, Registry Persistence
- Stealth mode (PEB patching)

---

## License

MIT License. See `LICENSE` for full text.
