malware analysis

Performing Dynamic Analysis with ANY.RUN

Performs interactive dynamic malware analysis using the ANY.RUN cloud sandbox to observe real-time execution behavior, interact with malware prompts, and capture process trees, network traffic, and system changes. Activates for requests involving interactive sandbox analysis, cloud-based malware detonation, real-time behavioral observation, or ANY.RUN usage.

any.rundynamic-analysisinteractive-analysismalwaresandbox
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • Interactive malware analysis is needed where the analyst must click dialogs, enter credentials, or navigate installer screens
  • Rapid cloud-based sandbox analysis without maintaining local sandbox infrastructure
  • Malware requires user interaction to proceed past anti-sandbox checks (document macros requiring "Enable Content")
  • Sharing analysis results with team members via public or private task URLs
  • Comparing behavior across different OS versions (Windows 7, 10, 11) available in ANY.RUN

Do not use for highly sensitive samples that cannot be uploaded to cloud services; use an on-premises sandbox like Cuckoo instead.

Prerequisites

  • ANY.RUN account (free community tier or paid subscription at https://any.run)
  • Modern web browser with WebSocket support for interactive session streaming
  • Sample file ready for upload (max 100 MB for free tier, 256 MB for paid)
  • Understanding of the sample type to select appropriate execution environment
  • VPN or secure network for accessing ANY.RUN portal during analysis sessions

Workflow

Step 1: Configure Analysis Environment

Set up the ANY.RUN task with appropriate parameters:

ANY.RUN Task Configuration:
━━━━━━━━━━━━━━━━━━━━━━━━━━
OS Selection:        Windows 10 x64 (recommended default)
                     Windows 7 x64 (for legacy malware)
                     Windows 11 x64 (for modern samples)
Execution Time:      60 seconds (default) / 120-300 for slow-acting malware
Network:             Connected (captures real C2 traffic)
                     Residential Proxy (bypasses geo-blocking)
Privacy:             Public (free tier) / Private (paid - not indexed)
MITM Proxy:          Enable for HTTPS traffic decryption
Fake Net:            Enable to simulate internet services if sample checks connectivity

API-based submission (paid tier):

# Submit file via ANY.RUN API
curl -X POST "https://api.any.run/v1/analysis" \
  -H "Authorization: API-Key $ANYRUN_API_KEY" \
  -F "file=@suspect.exe" \
  -F "env_os=windows" \
  -F "env_version=10" \
  -F "env_bitness=64" \
  -F "opt_timeout=120" \
  -F "opt_network_connect=true" \
  -F "opt_privacy_type=bylink"
 
# Check task status
curl "https://api.any.run/v1/analysis/$TASK_ID" \
  -H "Authorization: API-Key $ANYRUN_API_KEY" | jq '.data.status'

Step 2: Interact with Malware During Execution

Use the interactive session to trigger malware behavior:

Interactive Actions During Analysis:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Document Macros:   Click "Enable Content" / "Enable Editing" when prompted
2. Installer Screens: Click through installation dialogs
3. UAC Prompts:       Click "Yes" to allow elevation (observe privilege escalation)
4. Credential Harvests: Enter fake credentials to observe phishing behavior
5. Browser Redirects:  Navigate to URLs if malware opens browser windows
6. File Dialogs:       Select target files if malware presents file picker
7. Timeout Extension:  Extend analysis time if malware has delayed execution

Step 3: Analyze Process Tree

Review the complete process execution chain:

Process Tree Analysis Points:
━━━━━━━━━━━━━━━━━━━━━━━━━━━
Parent-Child Relationships:
  - WINWORD.EXE -> cmd.exe -> powershell.exe (macro execution chain)
  - explorer.exe -> suspect.exe -> svchost.exe (process injection)
 
Process Events to Note:
  - Process creation with suspicious command-line arguments
  - PowerShell with encoded commands (-enc / -encodedcommand)
  - cmd.exe executing script files (.bat, .vbs, .js)
  - Legitimate processes spawned from unusual parents
  - Process termination (self-deletion behavior)

Step 4: Review Network Activity

Examine DNS, HTTP/HTTPS, and TCP/UDP connections:

ANY.RUN Network Panel Analysis:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DNS Requests:
  - Domain resolutions with threat intelligence tags
  - Fast-flux or DGA domain patterns
  - DNS over HTTPS (DoH) detection
 
HTTP/HTTPS Traffic (with MITM enabled):
  - Full request/response bodies for HTTP
  - Decrypted HTTPS traffic showing C2 commands
  - Downloaded payloads and their content types
  - POST data containing exfiltrated information
 
Connection Map:
  - Geographic visualization of C2 server locations
  - Connection timeline showing beacon patterns
  - Suricata alerts triggered on network traffic

Step 5: Examine IOCs and Threat Intelligence

Extract indicators and map to known threats:

ANY.RUN IOC Categories:
━━━━━━━━━━━━━━━━━━━━━━
Files:       Dropped files with hashes, YARA matches, VirusTotal results
Network:     IPs, domains, URLs contacted during execution
Registry:    Keys created/modified for persistence
Processes:   Suspicious process names and command lines
Mutex:       Named mutexes created (used for single-instance checking)
Signatures:  Suricata rules triggered, behavioral signatures matched
 
MITRE ATT&CK Mapping:
  - ANY.RUN automatically maps observed behaviors to ATT&CK techniques
  - Review the ATT&CK matrix tab for technique coverage
  - Export ATT&CK Navigator layer for reporting

Step 6: Export Analysis Results

Download comprehensive reports and artifacts:

# Download report via API
curl "https://api.any.run/v1/analysis/$TASK_ID/report" \
  -H "Authorization: API-Key $ANYRUN_API_KEY" \
  -o report.json
 
# Download PCAP
curl "https://api.any.run/v1/analysis/$TASK_ID/pcap" \
  -H "Authorization: API-Key $ANYRUN_API_KEY" \
  -o capture.pcap
 
# Download dropped files
curl "https://api.any.run/v1/analysis/$TASK_ID/files" \
  -H "Authorization: API-Key $ANYRUN_API_KEY" \
  -o dropped_files.zip
 
# Available exports from ANY.RUN web interface:
# - HTML Report (shareable standalone page)
# - PCAP file (network traffic capture)
# - Process dump (memory dumps of processes)
# - Dropped files (all files created during execution)
# - MITRE ATT&CK Navigator JSON
# - IOC export (STIX/JSON/CSV format)

Key Concepts

Term Definition
Interactive Sandbox Analysis environment allowing real-time analyst interaction with the executing sample, enabling triggering of user-dependent behaviors
MITM Proxy Man-in-the-middle TLS interception in ANY.RUN that decrypts HTTPS traffic for visibility into encrypted C2 communications
Residential Proxy ANY.RUN feature routing malware traffic through residential IP addresses to bypass geo-IP and datacenter-IP evasion checks
Suricata Alerts Network IDS signatures triggered during execution, providing immediate identification of known malicious traffic patterns
Process Tree Hierarchical visualization of parent-child process relationships showing the complete execution chain from initial sample to final payloads
Behavioral Tags ANY.RUN classification labels automatically applied based on observed behavior (e.g., "trojan", "stealer", "ransomware")

Tools & Systems

  • ANY.RUN: Cloud-based interactive malware sandbox providing real-time execution monitoring, process trees, network capture, and MITRE ATT&CK mapping
  • ANY.RUN API: REST API for programmatic sample submission, status checking, and report/artifact retrieval
  • Suricata: Integrated network IDS within ANY.RUN providing signature-based detection of malicious network traffic
  • MITRE ATT&CK Navigator: Framework integration mapping observed malware behaviors to adversary techniques and tactics
  • VirusTotal Integration: Automatic hash lookup of sample and dropped files against VirusTotal detection results

Common Scenarios

Scenario: Analyzing a Macro-Enabled Document Requiring User Interaction

Context: Phishing email contains a .docm file that requires clicking "Enable Content" to trigger the macro payload. Traditional non-interactive sandboxes fail to trigger the malicious behavior.

Approach:

  1. Upload .docm to ANY.RUN with Windows 10 environment and Microsoft Office installed
  2. When Word opens and displays the security banner, click "Enable Content" interactively
  3. Observe the macro execution in the process tree (Word -> cmd.exe -> powershell.exe)
  4. Monitor network panel for PowerShell downloading second-stage payload
  5. If a UAC prompt appears, click "Yes" to allow the payload to observe full behavior chain
  6. Review Suricata alerts for known malware signatures on the downloaded payload
  7. Export IOCs (download URLs, dropped file hashes, C2 domains) for blocking

Pitfalls:

  • Forgetting to enable MITM proxy, resulting in encrypted HTTPS traffic without visibility
  • Using too short an execution timeout for malware with delayed execution or sleep timers
  • Uploading to public analysis when the sample contains sensitive organizational data
  • Not clicking through all prompts; some malware requires multiple user interactions to fully execute

Output Format

ANY.RUN ANALYSIS REPORT
=========================
Task URL:         https://app.any.run/tasks/<task_id>
Sample:           invoice_q3.docm
SHA-256:          e3b0c44298fc1c149afbf4c8996fb924...
Verdict:          MALICIOUS (Score: 95/100)
Family:           Emotet
Tags:             [trojan, banker, spam, macro]
 
PROCESS TREE
WINWORD.EXE (PID: 2184)
  └── cmd.exe (PID: 3456) "/c powershell -enc JABXAG..."
      └── powershell.exe (PID: 4012)
          └── rundll32.exe (PID: 4568) "C:\Users\...\payload.dll,Control_RunDLL"
 
NETWORK INDICATORS
DNS:    update.emotet-c2[.]com -> 185.220.101.42
HTTPS:  POST hxxps://185.220.101[.]42/wp-content/gate/ (C2 beacon)
HTTP:   GET hxxp://compromised-site[.]com/invoice.dll (payload download)
 
SURICATA ALERTS
[1:2028401] ET MALWARE Emotet CnC Beacon
[1:2028402] ET MALWARE Win32/Emotet Activity
 
MITRE ATT&CK TECHNIQUES
T1566.001  Phishing: Spearphishing Attachment
T1204.002  User Execution: Malicious File
T1059.001  Command and Scripting Interpreter: PowerShell
T1218.011  Rundll32 Execution
T1071.001  Application Layer Protocol: Web Protocols
 
DROPPED FILES
payload.dll  SHA-256: abc123... Detection: 48/72 (VirusTotal)
config.dat   SHA-256: def456... (encrypted configuration)
Source materials

References and resources

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

References 1

api-reference.md3.1 KB

API Reference: Performing Dynamic Analysis with ANY.RUN

ANY.RUN API v1

Endpoint Method Description
/v1/analysis POST Submit file or URL for analysis
/v1/analysis/{taskid} GET Get full analysis report
/v1/analysis/{taskid}/ioc GET Get extracted IOCs
/v1/analysis/{taskid}/download/{type} GET Download PCAP, screenshots, or dropped files

Submission Parameters

Parameter Type Description
file file Malware sample to analyze (multipart upload)
obj_url string URL to analyze in browser
env_os string OS: windows-7, windows-10, windows-11
env_bitness int Architecture: 32 or 64
opt_privacy_type string public, private, or bylink
opt_timeout int Analysis timeout in seconds (60-660)
opt_network_connect bool Allow internet access during analysis
opt_network_fakenet bool Use fake network services

Report Structure

Field Description
analysis.scores.verdict Overall verdict and threat level
analysis.processes[] Process tree with command lines
analysis.network.dnsRequests[] DNS queries made by sample
analysis.network.httpRequests[] HTTP requests with URLs and methods
analysis.network.connections[] TCP/UDP connections
analysis.mitre[] Mapped MITRE ATT&CK techniques
analysis.tags[] Malware family and behavior tags

Official Python SDK (anyrun-sdk)

Class / Method Description
SandboxConnector.windows(api_key) Create sandbox connector for Windows analysis (context manager)
SandboxConnector.linux(api_key) Create sandbox connector for Linux analysis (context manager)
connector.run_file_analysis(filepath) Submit local file, returns analysis_id
connector.run_url_analysis(url) Submit URL for browser analysis, returns analysis_id
connector.get_task_status(analysis_id) Generator yielding status updates until completion
connector.get_analysis_verdict(analysis_id) Returns verdict string (malicious/suspicious/clean)
connector.get_analysis_report(analysis_id) Returns full analysis report dict

Key Libraries

  • anyrun-sdk (pip install anyrun-sdk): Official ANY.RUN Python SDK with SandboxConnector
  • requests (pip install requests): HTTP client for REST API fallback
  • time (stdlib): Polling for analysis completion
  • json (stdlib): Parse and export analysis results

Configuration

Variable Description
ANYRUN_API_KEY ANY.RUN API key (from account settings)

Rate Limits

Plan Submissions/Day API Calls/Minute
Free 5 public 10
Hunter Unlimited private 60
Enterprise Unlimited 120

References

Scripts 1

agent.py10.5 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Dynamic Analysis with ANY.RUN Agent
Submits malware samples to ANY.RUN sandbox via API, monitors task execution,
and retrieves behavioral analysis results including process trees, network
indicators, and MITRE ATT&CK mappings.

Supports both the official anyrun-sdk (pip install anyrun-sdk) with
SandboxConnector and the legacy REST API via requests.
"""

import json
import os
import sys
import time
from datetime import datetime, timezone

import requests

try:
    from anyrun.connectors import SandboxConnector
    HAS_ANYRUN_SDK = True
except ImportError:
    HAS_ANYRUN_SDK = False


ANYRUN_API_BASE = "https://api.any.run/v1"


def submit_file(filepath: str, api_key: str, os_version: str = "windows-10",
                 privacy: str = "private", timeout_seconds: int = 120) -> dict:
    """Submit a file to ANY.RUN for dynamic analysis."""
    if not os.path.exists(filepath):
        return {"error": f"File not found: {filepath}"}

    headers = {"Authorization": f"API-Key {api_key}"}

    with open(filepath, "rb") as f:
        files = {"file": (os.path.basename(filepath), f)}
        data = {
            "env_os": os_version,
            "env_bitness": 64,
            "env_type": "complete",
            "opt_privacy_type": privacy,
            "opt_timeout": timeout_seconds,
            "opt_network_connect": True,
            "opt_network_fakenet": False,
            "opt_network_tor": False,
        }

        resp = requests.post(
            f"{ANYRUN_API_BASE}/analysis",
            headers=headers, files=files, data=data, timeout=60,
        )

    if resp.status_code in (200, 201):
        result = resp.json()
        return {
            "task_id": result.get("data", {}).get("taskid", ""),
            "status": "submitted",
            "task_url": f"https://app.any.run/tasks/{result.get('data', {}).get('taskid', '')}",
        }

    return {"error": f"Submission failed: {resp.status_code} - {resp.text[:200]}"}


def submit_url(url: str, api_key: str, os_version: str = "windows-10") -> dict:
    """Submit a URL to ANY.RUN for dynamic analysis."""
    headers = {"Authorization": f"API-Key {api_key}"}
    data = {
        "obj_url": url,
        "env_os": os_version,
        "env_bitness": 64,
        "opt_privacy_type": "private",
        "opt_timeout": 120,
        "opt_network_connect": True,
    }

    resp = requests.post(
        f"{ANYRUN_API_BASE}/analysis",
        headers=headers, data=data, timeout=60,
    )

    if resp.status_code in (200, 201):
        result = resp.json()
        return {
            "task_id": result.get("data", {}).get("taskid", ""),
            "status": "submitted",
        }

    return {"error": f"URL submission failed: {resp.status_code}"}


def get_task_report(task_id: str, api_key: str) -> dict:
    """Retrieve the full analysis report for a completed task."""
    headers = {"Authorization": f"API-Key {api_key}"}

    resp = requests.get(
        f"{ANYRUN_API_BASE}/analysis/{task_id}",
        headers=headers, timeout=30,
    )

    if resp.status_code != 200:
        return {"error": f"Report retrieval failed: {resp.status_code}"}

    data = resp.json().get("data", {})

    report = {
        "task_id": task_id,
        "verdict": data.get("analysis", {}).get("scores", {}).get("verdict", {}).get("verdict", "unknown"),
        "threat_level": data.get("analysis", {}).get("scores", {}).get("verdict", {}).get("threatLevelText", ""),
        "tags": data.get("analysis", {}).get("tags", []),
    }

    processes = data.get("analysis", {}).get("processes", [])
    report["processes"] = []
    for proc in processes:
        report["processes"].append({
            "pid": proc.get("pid", 0),
            "name": proc.get("fileName", ""),
            "command_line": proc.get("commandLine", "")[:200],
            "parent_pid": proc.get("parentPID", 0),
            "is_malicious": proc.get("scores", {}).get("verdict", {}).get("isMalicious", False),
        })

    network = data.get("analysis", {}).get("network", {})
    report["network"] = {
        "dns_requests": [
            {"domain": d.get("domain", ""), "ip": d.get("ip", "")}
            for d in network.get("dnsRequests", [])
        ],
        "http_requests": [
            {"url": h.get("url", ""), "method": h.get("method", ""), "status": h.get("status", 0)}
            for h in network.get("httpRequests", [])
        ],
        "connections": [
            {"ip": c.get("ip", ""), "port": c.get("port", 0), "protocol": c.get("protocol", "")}
            for c in network.get("connections", [])
        ],
    }

    mitre = data.get("analysis", {}).get("mitre", [])
    report["mitre_techniques"] = [
        {"technique_id": m.get("id", ""), "name": m.get("name", ""), "tactic": m.get("tactic", "")}
        for m in mitre
    ]

    return report


def wait_for_completion(task_id: str, api_key: str, max_wait: int = 300) -> dict:
    """Poll task status until analysis completes."""
    headers = {"Authorization": f"API-Key {api_key}"}
    start = time.time()

    while time.time() - start < max_wait:
        resp = requests.get(
            f"{ANYRUN_API_BASE}/analysis/{task_id}",
            headers=headers, timeout=30,
        )

        if resp.status_code == 200:
            status = resp.json().get("data", {}).get("analysis", {}).get("status", "")
            if status == "done":
                return {"status": "completed", "elapsed": round(time.time() - start)}
            if status == "failed":
                return {"status": "failed", "elapsed": round(time.time() - start)}

        time.sleep(15)

    return {"status": "timeout", "elapsed": max_wait}


def get_iocs_from_report(report: dict) -> dict:
    """Extract IOCs from an ANY.RUN analysis report."""
    iocs = {
        "domains": set(),
        "ips": set(),
        "urls": set(),
        "processes": [],
        "mitre_techniques": [],
    }

    for dns_req in report.get("network", {}).get("dns_requests", []):
        if dns_req.get("domain"):
            iocs["domains"].add(dns_req["domain"])
        if dns_req.get("ip"):
            iocs["ips"].add(dns_req["ip"])

    for http_req in report.get("network", {}).get("http_requests", []):
        if http_req.get("url"):
            iocs["urls"].add(http_req["url"])

    for conn in report.get("network", {}).get("connections", []):
        if conn.get("ip"):
            iocs["ips"].add(conn["ip"])

    for proc in report.get("processes", []):
        if proc.get("is_malicious"):
            iocs["processes"].append(proc["name"])

    iocs["mitre_techniques"] = report.get("mitre_techniques", [])
    iocs["domains"] = sorted(iocs["domains"])
    iocs["ips"] = sorted(iocs["ips"])
    iocs["urls"] = sorted(iocs["urls"])

    return iocs


def generate_report(submission: dict, report: dict, iocs: dict) -> str:
    """Generate dynamic analysis report."""
    lines = [
        "DYNAMIC ANALYSIS REPORT (ANY.RUN)",
        "=" * 50,
        f"Date: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}",
        f"Task ID: {report.get('task_id', submission.get('task_id', 'N/A'))}",
        f"Task URL: {submission.get('task_url', 'N/A')}",
        "",
        f"Verdict: {report.get('verdict', 'N/A')}",
        f"Threat Level: {report.get('threat_level', 'N/A')}",
        f"Tags: {', '.join(report.get('tags', []))}",
        "",
        f"PROCESSES ({len(report.get('processes', []))}):",
    ]

    for proc in report.get("processes", [])[:10]:
        mal = " [MALICIOUS]" if proc.get("is_malicious") else ""
        lines.append(f"  PID {proc['pid']}: {proc['name']}{mal}")
        if proc.get("command_line"):
            lines.append(f"    CMD: {proc['command_line'][:100]}")

    lines.extend([
        "",
        "NETWORK IOCs:",
        f"  Domains: {len(iocs.get('domains', []))}",
        f"  IPs: {len(iocs.get('ips', []))}",
        f"  URLs: {len(iocs.get('urls', []))}",
    ])

    if iocs.get("mitre_techniques"):
        lines.extend(["", "MITRE ATT&CK TECHNIQUES:"])
        for tech in iocs["mitre_techniques"][:10]:
            lines.append(f"  {tech['technique_id']} - {tech['name']} ({tech['tactic']})")

    return "\n".join(lines)


def run_with_sdk(api_key: str, target: str, is_url: bool) -> dict:
    """Use official anyrun-sdk (SandboxConnector) if available."""
    with SandboxConnector.windows(api_key) as connector:
        if is_url:
            analysis_id = connector.run_url_analysis(target)
        else:
            analysis_id = connector.run_file_analysis(target)

        print(f"[*] SDK analysis ID: {analysis_id}")
        for status in connector.get_task_status(analysis_id):
            print(f"[*] Status: {status}")

        verdict = connector.get_analysis_verdict(analysis_id)
        report = connector.get_analysis_report(analysis_id)
        return {"analysis_id": analysis_id, "verdict": verdict, "report": report}


if __name__ == "__main__":
    api_key = os.getenv("ANYRUN_API_KEY", "")
    if not api_key:
        print("[!] Set ANYRUN_API_KEY environment variable")
        sys.exit(1)

    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <file_or_url> [--url]")
        sys.exit(1)

    target = sys.argv[1]
    is_url = "--url" in sys.argv or target.startswith("http")

    # Prefer official SDK when available, fall back to REST API
    if HAS_ANYRUN_SDK:
        print("[*] Using official anyrun-sdk (SandboxConnector)")
        sdk_result = run_with_sdk(api_key, target, is_url)
        print(json.dumps(sdk_result, indent=2, default=str))
        sys.exit(0)

    print("[*] anyrun-sdk not found, using REST API fallback")

    if is_url:
        print(f"[*] Submitting URL: {target}")
        submission = submit_url(target, api_key)
    else:
        print(f"[*] Submitting file: {target}")
        submission = submit_file(target, api_key)

    if "error" in submission:
        print(f"[!] {submission['error']}")
        sys.exit(1)

    task_id = submission["task_id"]
    print(f"[*] Task ID: {task_id}")

    print("[*] Waiting for analysis to complete...")
    completion = wait_for_completion(task_id, api_key)
    print(f"[*] Status: {completion['status']} ({completion.get('elapsed', 0)}s)")

    if completion["status"] == "completed":
        report = get_task_report(task_id, api_key)
        iocs = get_iocs_from_report(report)

        output_text = generate_report(submission, report, iocs)
        print(output_text)

        output = f"anyrun_analysis_{task_id}.json"
        with open(output, "w") as f:
            json.dump({"submission": submission, "report": report, "iocs": iocs}, f, indent=2)
        print(f"\n[*] Results saved to {output}")
    else:
        print(f"[!] Analysis did not complete: {completion['status']}")
Keep exploring