AGENT SKILL

malware-analysis-reversing

Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static/dynamic binary analysis, memory forensics, and YARA detection rule authoring.

License 许可
MIT
最近更新
2026-10-17
Stars
★ 8
Forks
1

01 前言 Front Matter

name
malware-analysis-reversing
metadata
{ "category": "Cybersecurity and Penetration Testing" }
description
Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static/dynamic binary analysis, memory forensics, and YARA detection rule authoring.
compatibility
Ghidra, IDA Pro, Volatility 3, YARA, REMnux, pefile / Volatility Python API

03 SKILL.md 正文

Malware Analysis & Reverse Engineering Architecture

Overview

This skill provides technical standards and defensive methodologies for malware analysis and reverse engineering. It covers isolated sandbox setup, static binary inspection (PE/ELF headers, imported functions, packed section detection), dynamic behavior monitoring, memory dump forensics, and authoring YARA rules for threat detection and incident response.


1. Malware Analysis Principles & Safety Protocols

  1. Strict Air-Gapped / Isolated Sandbox: Always perform malware execution and dynamic monitoring inside isolated virtual machines (REMnux, FLARE VM) with network isolation (INetSim / FakeNet-NG) to prevent lateral movement or C2 callbacks to live networks.
  2. Layered Analysis Methodology:
    • Static Triage: File hashing (MD5, SHA256, ssdeep), PE/ELF header analysis, string extraction, and packer detection (PEiD / Detect It Easy).
    • Dynamic Triage: API monitoring, registry/filesystem access tracking (ProcMon), network packet capturing (Wireshark).
    • Code-Level Disassembly / Decompilation: Reverse engineering control flow and functions using Ghidra or IDA Pro.
    • Memory Forensics: Extracting decrypted payloads or process injection artifacts from volatile memory dumps via Volatility 3.
  3. Automated Indicator Extraction (IOCs): Extract high-confidence Indicators of Compromise (IP addresses, domain names, file hashes, registry run keys, mutexes) for SIEM ingest.
  4. Defensive YARA Rule Generation: Write precise YARA detection rules targeting unique string signatures and byte patterns while minimizing false positives.

2. Reverse Engineering & Analysis Pipeline

[ Suspicious Binary Sample ]
       │
       ├──▶ [ 1. Static Analysis ] ──(Hashes, PE Headers, Import Table, Strings)
       │
       ├──▶ [ 2. Dynamic Sandbox ] ──(Process Trees, File/Registry Mutations, PCAP)
       │
       ├──▶ [ 3. Code Reversing ] ───(Ghidra Decompiler, Disassembly Control Flow)
       │
       └──▶ [ 4. Memory Forensics ] ─(Volatility 3 Dump, Extracted Payloads)
               │
               ▼
[ Threat Intelligence & YARA Detection Rules ]
Analysis Stage Primary Tooling Key Artifacts / Outputs
Static Triage pefile, Detect It Easy, ssdeep Imphash, Subsystem, Entropy, Export/Import Tables
Dynamic Sandbox Cuckoo Sandbox, CAPEv2, ProcMon Registry modifications, spawned sub-processes
Network Triage Wireshark, FakeNet-NG, Suricata C2 IPs, HTTP User-Agents, DNS queries
Code Reverse Eng. Ghidra, IDA Pro, x64dbg Decompiled C code, algorithmic logic, encryption routines
Memory Forensics Volatility 3, Rekall Injected DLLs, unpacked memory executable code

3. Anti-Patterns & Common Errors in Malware Analysis

  • Anti-Pattern: Executing Samples on Host Workstations Outside Isolated Sandboxes
    • Risk: Host OS infection, ransomware encryption, or unauthorized network propagation.
    • Remediation: Always execute samples exclusively within snapshot-revertible VM environments with host-only networking.
  • Anti-Pattern: Over-Reliance on Filename or Static File Hashing Alone
    • Risk: Attackers bypass static hash checks effortlessly through polymorphic re-compilation.
    • Remediation: Rely on fuzzy hashing (ssdeep), Import Hashing (imphash), and functional byte-pattern YARA rules.
  • Anti-Pattern: Neglecting Packed / Obfuscated Sections
    • Risk: Analyzing only the stub/packer code while missing the actual malicious payload logic.
    • Remediation: Measure section entropy (values > 7.0 indicate packing/compression) and un-pack binary in memory before disassembly.

4. Production Python & YARA Code Snippets

A. Python Static PE Header Inspector & Entropy Calculator (pe_analyzer.py)

#!/usr/bin/env python3
"""
Production Static PE Binary Analyzer using pefile
Extracts Hashes, Imphash, Section Entropy, and Suspicious API Imports.
"""

import hashlib
import math
import sys
import pefile

def calculate_entropy(data: bytes) -> float:
    """Calculates Shannon Entropy of a byte buffer (0.0 to 8.0)."""
    if not data:
        return 0.0
    entropy = 0.0
    length = len(data)
    occ = [0] * 256
    for b in data:
        occ[b] += 1
    for count in occ:
        if count > 0:
            p = count / length
            entropy -= p * math.log2(p)
    return round(entropy, 4)

def analyze_pe_binary(file_path: str):
    with open(file_path, "rb") as f:
        content = f.read()

    md5_hash = hashlib.md5(content).hexdigest()
    sha256_hash = hashlib.sha256(content).hexdigest()

    print(f"File: {file_path}")
    print(f"MD5: {md5_hash}")
    print(f"SHA256: {sha256_hash}")

    try:
        pe = pefile.PE(data=content)
        print(f"Imphash: {pe.get_imphash()}")
        print(f"Target Subsystem: {pe.OPTIONAL_HEADER.Subsystem}")
        print("\n--- Sections Entropy ---")
        for section in pe.sections:
            name = section.Name.decode('utf-8', errors='ignore').strip('\x00')
            entropy = calculate_entropy(section.get_data())
            is_packed = " [POSSIBLE PACKER/ENCRYPTED]" if entropy > 7.0 else ""
            print(f"  {name:10s} | VirtualSize: {section.Misc_VirtualSize:8d} | Entropy: {entropy:.4f}{is_packed}")

        print("\n--- Imported DLLs & Functions ---")
        if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
            for entry in pe.DIRECTORY_ENTRY_IMPORT:
                dll_name = entry.dll.decode('utf-8', errors='ignore')
                print(f"  DLL: {dll_name}")
                for imp in entry.imports:
                    if imp.name:
                        func_name = imp.name.decode('utf-8', errors='ignore')
                        print(f"    - {func_name}")

    except pefile.PEFormatError:
        print("[ERROR] Target file is not a valid PE binary.")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python pe_analyzer.py <binary_path>")
        sys.exit(1)
    analyze_pe_binary(sys.argv[1])

B. Production YARA Detection Rule (sample_malware_detector.yar)

rule Detect_Suspicious_PE_Loader {
    meta:
        description = "Detects packed executable with suspicious API imports and high entropy sections"
        author = "Threat Intelligence Team"
        date = "2026-08-06"
        severity = "High"

    strings:
        // Unique code bytes pattern (e.g., custom XOR decryption loop)
        $xor_loop = { 8A 04 0E 34 ?? 88 04 0E 41 3B C2 7C F2 }

        // Suspicious strings
        $str1 = "VirtualAllocEx" ascii wide
        $str2 = "WriteProcessMemory" ascii wide
        $str3 = "CreateRemoteThread" ascii wide
        $str4 = "IsDebuggerPresent" ascii wide

    condition:
        // Must be a Windows PE binary
        uint16(0) == 0x5A4D and
        
        // Match specific XOR byte loop OR at least 3 suspicious process injection strings
        ( $xor_loop or 3 of ($str*) ) and

        // PE File size threshold under 10MB
        filesize < 10MB
}

04 同仓库更多 Skills

hamzabellouch
hamzabellouch/agent-skills

security-audit

Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).

★ 8
hamzabellouch
hamzabellouch/agent-skills

application-security-pentesting

Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST/DAST pipeline integration, secure code review, threat modeling, and defensive security posture.

★ 8
hamzabellouch
hamzabellouch/agent-skills

oauth2-oidc-security-flows

Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.

★ 8
hamzabellouch
hamzabellouch/agent-skills

jwt-session-management-hardening

Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256/EdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.

★ 8
hamzabellouch
hamzabellouch/agent-skills

soc2-compliance-automation

Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI/CD security gates.

★ 8
hamzabellouch
hamzabellouch/agent-skills

gdpr-ccpa-data-privacy

Engineering patterns for GDPR, CCPA/CPRA, and global data privacy compliance. Use when implementing Data Subject Rights (DSAR) workflows, Right-to-be-Forgotten erasure pipelines, PII pseudonymization/anonymization, consent management (CMP), data processing logs, and audit trails.

★ 8