malware analysis

Reverse Engineering Rust Malware

Reverse engineer Rust-compiled malware using IDA Pro and Ghidra with techniques for handling non-null-terminated strings, crate dependency extraction, and Rust-specific control flow analysis.

binary-analysisghidraida-promalware-analysisreverse-engineeringrustrust-malware
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Rust has become increasingly popular for malware development due to its cross-compilation, memory safety guarantees, and the complexity it introduces for reverse engineers. Rust binaries contain the entire standard library statically linked, producing large binaries with extensive boilerplate code. Key challenges include non-null-terminated strings (Rust uses fat pointers with pointer+length), monomorphization generating duplicated generic code, complex error handling (Result/Option unwrap chains), and unfamiliar calling conventions. Decompiling Rust to C produces unhelpful output compared to C/C++ binaries. Tools like Ghidra scripts for crate extraction, and training focused on Rust-specific patterns (2024-2025) help address these challenges. Notable Rust malware includes BlackCat/ALPHV ransomware, Hive ransomware variants, and Buer Loader.

When to Use

  • When performing authorized security testing that involves reverse engineering rust malware
  • When analyzing malware samples or attack artifacts in a controlled environment
  • When conducting red team exercises or penetration testing engagements
  • When building detection capabilities based on offensive technique understanding

Prerequisites

  • IDA Pro 8.0+ or Ghidra 11.0+
  • Rust toolchain for reference compilation
  • Python 3.9+ for helper scripts
  • Understanding of Rust memory model (ownership, borrowing)
  • Familiarity with Rust string types (String, &str, CString)

Workflow

Step 1: Identify and Parse Rust Binary Metadata

#!/usr/bin/env python3
"""Analyze Rust malware binary metadata and extract crate dependencies."""
import re
import sys
import json
 
 
def identify_rust_binary(data):
    """Check if binary is Rust-compiled and extract version info."""
    indicators = {
        "rust_panic_strings": bool(re.search(rb'panicked at', data)),
        "rust_unwrap": bool(re.search(rb'called.*unwrap.*on.*None', data)),
        "core_panic": bool(re.search(rb'core::panicking', data)),
        "std_rt": bool(re.search(rb'std::rt::lang_start', data)),
        "cargo_path": bool(re.search(rb'\.cargo[/\\]registry', data)),
        "rustc_version": None,
    }
 
    version = re.search(rb'rustc\s+(\d+\.\d+\.\d+)', data)
    if version:
        indicators["rustc_version"] = version.group(1).decode()
 
    is_rust = sum(1 for v in indicators.values() if v) >= 2
    return is_rust, indicators
 
 
def extract_crates(data):
    """Extract Rust crate (dependency) names from binary strings."""
    crate_pattern = re.compile(
        rb'(?:crates\.io-[a-f0-9]+/|\.cargo/registry/src/[^/]+/)'
        rb'([\w-]+)-(\d+\.\d+\.\d+)'
    )
    crates = {}
    for match in crate_pattern.finditer(data):
        name = match.group(1).decode()
        version = match.group(2).decode()
        crates[name] = version
 
    # Also check for common malware-relevant crates
    suspicious_crates = {
        "reqwest": "HTTP client",
        "hyper": "HTTP library",
        "tokio": "Async runtime",
        "aes": "AES encryption",
        "chacha20": "ChaCha20 encryption",
        "rsa": "RSA encryption",
        "ring": "Crypto library",
        "base64": "Base64 encoding",
        "winapi": "Windows API bindings",
        "winreg": "Registry access",
        "sysinfo": "System information",
        "screenshots": "Screen capture",
        "clipboard": "Clipboard access",
        "keylogger": "Key logging",
    }
 
    capabilities = []
    for crate_name, description in suspicious_crates.items():
        if crate_name in crates:
            capabilities.append({
                "crate": crate_name,
                "version": crates[crate_name],
                "capability": description,
            })
 
    return crates, capabilities
 
 
def extract_rust_strings(data):
    """Extract strings handling Rust's non-null-terminated format."""
    # Rust strings are stored as pointer+length, but string literals
    # are often in .rodata as contiguous sequences
    strings = []
    ascii_pattern = re.compile(rb'[\x20-\x7e]{8,500}')
    for match in ascii_pattern.finditer(data):
        s = match.group().decode('ascii')
        # Filter for malware-relevant strings
        keywords = ['http', 'socket', 'encrypt', 'decrypt', 'shell',
                    'exec', 'cmd', 'upload', 'download', 'persist',
                    'registry', 'mutex', 'pipe', 'inject']
        if any(kw in s.lower() for kw in keywords):
            strings.append(s)
 
    return strings
 
 
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <rust_binary>")
        sys.exit(1)
 
    with open(sys.argv[1], 'rb') as f:
        data = f.read()
 
    is_rust, indicators = identify_rust_binary(data)
    print(f"[{'+'if is_rust else '-'}] Rust binary: {is_rust}")
    print(json.dumps(indicators, indent=2, default=str))
 
    crates, capabilities = extract_crates(data)
    print(f"\n[+] Crates ({len(crates)}):")
    for name, ver in sorted(crates.items()):
        print(f"  {name} v{ver}")
 
    if capabilities:
        print(f"\n[!] Suspicious capabilities:")
        for cap in capabilities:
            print(f"  {cap['crate']} -> {cap['capability']}")
 
    strings = extract_rust_strings(data)
    if strings:
        print(f"\n[+] Suspicious strings ({len(strings)}):")
        for s in strings[:20]:
            print(f"  {s}")

Validation Criteria

  • Binary correctly identified as Rust-compiled with version info
  • Crate dependencies extracted revealing malware capabilities
  • Rust-specific string extraction handles fat pointer format
  • Main entry point and core logic functions identified
  • Encryption, networking, and persistence code located

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.7 KB

API Reference: Reverse Engineering Rust Malware

Rust Binary Indicators

Indicator Pattern Description
Panic strings panicked at Rust panic handler messages
Unwrap failure called.*unwrap.*on.*None Option/Result unwrap
Core panic core::panicking Standard library panic
Runtime start std::rt::lang_start Rust runtime entry point
Cargo registry .cargo/registry Crate dependency paths
Rustc version rustc X.Y.Z Compiler version string

Crate Extraction Pattern

Pattern Example Match
crates.io-<hash>/<name>-<ver> crates.io-abc123/reqwest-0.11.22
.cargo/registry/src/<index>/<name>-<ver> .cargo/registry/src/index.crates.io/aes-0.8.3

Suspicious Crate Capabilities

Crate Capability Malware Use
reqwest / hyper HTTP client C2 communication
aes / chacha20 / rsa Encryption Ransomware encryption
ring Crypto primitives Key generation
winapi / winreg Windows API Persistence, injection
sysinfo System info Host enumeration
native-tls TLS Encrypted C2 channel

Python Libraries

Library Version Purpose
re stdlib Pattern matching for Rust indicators
struct stdlib PE header parsing
hashlib stdlib SHA256 sample hashing
json stdlib Report generation

References

standards.md0.3 KB

Standards Reference - reverse-engineering-rust-malware

Applicable Standards

  • MITRE ATT&CK Framework
  • NIST SP 800-83 Guide to Malware Incident Prevention
  • NIST SP 800-86 Guide to Integrating Forensic Techniques

Related MITRE ATT&CK Techniques

See SKILL.md for specific technique mappings.

workflows.md0.4 KB

Analysis Workflows - reverse-engineering-rust-malware

Primary Workflow

[Sample Collection] --> [Static Analysis] --> [Dynamic Analysis] --> [IOC Extraction]
                                                                          |
                                                                          v
                                                                 [Report Generation]

See SKILL.md for detailed step-by-step procedures.

Scripts 1

agent.py6.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for reverse engineering Rust-compiled malware.

Identifies Rust binaries, extracts crate dependencies, locates
crypto/network/persistence patterns, and maps suspicious capabilities
for malware analysis reporting.
"""

import json
import re
import struct
import sys
import hashlib
from pathlib import Path
from datetime import datetime


SUSPICIOUS_CRATES = {
    "reqwest": "HTTP client (C2 communication)",
    "hyper": "HTTP library (C2/exfiltration)",
    "tokio": "Async runtime (concurrent operations)",
    "aes": "AES encryption (ransomware/data theft)",
    "chacha20": "ChaCha20 cipher (ransomware)",
    "rsa": "RSA encryption (key exchange)",
    "ring": "Crypto library (encryption)",
    "base64": "Base64 encoding (data encoding)",
    "winapi": "Windows API (system interaction)",
    "winreg": "Registry access (persistence)",
    "sysinfo": "System enumeration",
    "screenshots": "Screen capture (spyware)",
    "clipboard": "Clipboard access (data theft)",
    "rusqlite": "SQLite access (credential theft)",
    "native-tls": "TLS connections (encrypted C2)",
}


class RustMalwareREAgent:
    """Reverse engineers Rust-compiled malware binaries."""

    def __init__(self, sample_path, output_dir="./rust_re"):
        self.sample_path = Path(sample_path)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.findings = []
        self.data = b""

    def load_sample(self):
        self.data = self.sample_path.read_bytes()
        return len(self.data)

    def identify_rust_binary(self):
        """Check if binary is Rust-compiled and extract version info."""
        indicators = {
            "panicked_at": bool(re.search(rb"panicked at", self.data)),
            "unwrap_none": bool(re.search(rb"called.*unwrap.*on.*None", self.data)),
            "core_panic": bool(re.search(rb"core::panicking", self.data)),
            "std_rt": bool(re.search(rb"std::rt::lang_start", self.data)),
            "cargo_registry": bool(re.search(rb"\.cargo[/\\]registry", self.data)),
            "rustc_version": None,
        }
        ver = re.search(rb"rustc\s+(\d+\.\d+\.\d+)", self.data)
        if ver:
            indicators["rustc_version"] = ver.group(1).decode()
        is_rust = sum(1 for v in indicators.values() if v) >= 2
        if is_rust:
            self.findings.append({
                "type": "Binary Identification",
                "detail": "Rust-compiled binary confirmed",
                "rustc_version": indicators["rustc_version"],
            })
        return is_rust, indicators

    def extract_crates(self):
        """Extract crate dependencies from binary strings."""
        pattern = re.compile(
            rb"(?:crates\.io-[a-f0-9]+/|\.cargo/registry/src/[^/]+/)"
            rb"([\w-]+)-(\d+\.\d+\.\d+)"
        )
        crates = {}
        for m in pattern.finditer(self.data):
            crates[m.group(1).decode()] = m.group(2).decode()

        capabilities = []
        for name, desc in SUSPICIOUS_CRATES.items():
            if name in crates:
                capabilities.append({
                    "crate": name,
                    "version": crates[name],
                    "capability": desc,
                })
                self.findings.append({
                    "type": "Suspicious Crate",
                    "crate": name,
                    "capability": desc,
                })
        return crates, capabilities

    def extract_suspicious_strings(self):
        """Extract malware-relevant strings from the binary."""
        keywords = [
            "http", "socket", "encrypt", "decrypt", "shell", "exec",
            "cmd", "upload", "download", "persist", "registry", "mutex",
            "pipe", "inject", "ransom", "bitcoin", "wallet", "onion",
            "tor", "password", "credential", "keylog",
        ]
        strings = []
        for m in re.finditer(rb"[\x20-\x7e]{8,500}", self.data):
            s = m.group().decode("ascii")
            if any(kw in s.lower() for kw in keywords):
                strings.append(s)
        return strings[:50]

    def detect_pe_sections(self):
        """Parse PE sections if Windows binary."""
        if self.data[:2] != b"MZ":
            return []
        try:
            pe_offset = struct.unpack_from("<I", self.data, 0x3C)[0]
            if self.data[pe_offset:pe_offset + 4] != b"PE\x00\x00":
                return []
            num_sections = struct.unpack_from("<H", self.data, pe_offset + 6)[0]
            sections = []
            sec_start = pe_offset + 24 + struct.unpack_from("<H", self.data, pe_offset + 20)[0]
            for i in range(min(num_sections, 20)):
                off = sec_start + i * 40
                name = self.data[off:off + 8].rstrip(b"\x00").decode("ascii", errors="ignore")
                vsize = struct.unpack_from("<I", self.data, off + 8)[0]
                rsize = struct.unpack_from("<I", self.data, off + 16)[0]
                sections.append({"name": name, "virtual_size": vsize, "raw_size": rsize})
            return sections
        except (struct.error, IndexError):
            return []

    def generate_report(self):
        size = self.load_sample()
        sha256 = hashlib.sha256(self.data).hexdigest()
        is_rust, rust_indicators = self.identify_rust_binary()
        crates, capabilities = self.extract_crates()
        strings = self.extract_suspicious_strings()
        sections = self.detect_pe_sections()

        report = {
            "sample": str(self.sample_path),
            "sha256": sha256,
            "file_size": size,
            "report_date": datetime.utcnow().isoformat(),
            "is_rust_binary": is_rust,
            "rust_indicators": rust_indicators,
            "crates_found": len(crates),
            "crates": crates,
            "suspicious_capabilities": capabilities,
            "suspicious_strings_count": len(strings),
            "suspicious_strings": strings[:20],
            "pe_sections": sections,
            "findings": self.findings,
        }
        out = self.output_dir / "rust_re_report.json"
        with open(out, "w") as f:
            json.dump(report, f, indent=2, default=str)
        print(json.dumps(report, indent=2, default=str))
        return report


def main():
    if len(sys.argv) < 2:
        print("Usage: agent.py <rust_binary_path>")
        sys.exit(1)
    agent = RustMalwareREAgent(sys.argv[1])
    agent.generate_report()


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 0.4 KB
Keep exploring