intellicrack.bridges.sandbox_bridge

Sandbox bridge for isolated binary execution environments.

This module provides a tool bridge that wraps the SandboxManager to expose sandbox operations to the AI orchestrator.

json_safe(value)[source]

Recursively convert a value to a JSON-serialisable form.

Converts datetime instances to UTC ISO-8601 strings, Path instances to POSIX strings, and recurses into dict/list. All other types are returned unchanged.

Parameters:

value (object) – The value to convert.

Returns:

A JSON-serialisable representation of value.

Return type:

object

dataclass_to_dict(obj)[source]

Convert a dataclass instance to a JSON-serialisable dictionary.

Uses dataclasses.asdict for the conversion and then applies json_safe() to convert datetime and Path values to strings. A json.dumps round-trip is verified before returning.

Parameters:

obj (object) – A dataclass instance to convert.

Returns:

JSON-safe dictionary representation of obj.

Return type:

dict[str, Any]

Raises:

ToolError – If the object is not a dataclass or the result is not JSON-serialisable.

class SandboxBridge[source]

Bases: ToolBridgeBase

Bridge for sandbox operations.

Provides an AI-accessible interface to the SandboxManager for creating isolated execution environments and running binaries. Instances own a lazy slot for the shared SandboxManager singleton and record the advertised BridgeCapabilities describing the dynamic-analysis features this bridge can provide.

__init__()[source]

Initialize the SandboxBridge instance.

Return type:

None

property manager: SandboxManager | None

The underlying SandboxManager instance, if initialized.

Returns:

Active manager, or None if the bridge has not yet allocated one (or has been shut down).

Return type:

SandboxManager | None

property manager_destroyed: bool

Whether the manager has been shut down.

Returns:

True if shutdown() has been called and the manager has not been recreated, False otherwise.

Return type:

bool

attach_manager(manager)[source]

Install an externally constructed SandboxManager.

Used by callers that need to wrap an existing SandboxBase/SandboxManager instance behind the bridge without spinning up a fresh manager via ensure_manager(). Re-arming a previously shut-down bridge is also supported and clears the destroyed flag so subsequent operations succeed.

Parameters:

manager (SandboxManager) – Pre-existing manager to install on this bridge.

Return type:

None

register_existing_sandbox(sandbox, sandbox_type)[source]

Register an already-constructed sandbox with the bridge manager.

Wraps the supplied sandbox in a SandboxInstance (using the manager’s normal instance bookkeeping) and adds it to the manager owned by this bridge. If no manager has been constructed yet, a fresh one is created. Returns the new instance ID so callers can drive subsequent bridge operations.

Parameters:
  • sandbox (object) – Pre-constructed SandboxBase (or compatible duck-typed object) to register.

  • sandbox_type (Literal['windows', 'qemu']) – Type tag ("windows" or "qemu") used by bridge dispatch logic to gate type-specific operations such as snapshots and screenshots.

Returns:

ID of the registered SandboxInstance.

Return type:

str

property name: ToolName

The tool’s name.

Returns:

ToolName.SANDBOX.

Return type:

ToolName

property tool_definition: ToolDefinition

Tool definition for LLM function calling.

Returns:

ToolDefinition with all sandbox functions.

Return type:

ToolDefinition

async initialize(tool_path=None)[source]

Initialize the sandbox bridge.

Parameters:

tool_path (Path | None) – Not used for sandbox (ignored).

Return type:

None

async shutdown()[source]

Shutdown the sandbox bridge and cleanup resources.

Return type:

None

async is_available()[source]

Check if sandbox functionality is available.

Returns:

True if at least one sandbox type is available.

Return type:

bool

ensure_manager()[source]

Ensure manager is initialized and has not been shut down.

Returns:

The SandboxManager instance.

Return type:

SandboxManager

Raises:

ToolError – If the manager was previously shut down via shutdown().

async create(sandbox_type='windows', timeout_seconds=300, *, network_enabled=False, block_telemetry=True, memory_limit_mb=2048, qemu_config=None, clipboard_enabled=False, audio_enabled=False, video_enabled=False, printer_enabled=False, shared_folders=None, startup_commands=None, environment_variables=None)[source]

Create a new sandbox instance.

Rejects unknown sandbox_type values explicitly instead of silently coercing them to "qemu". The previous behaviour hid typos ("Qemu", "window", "vm") and caused the orchestrator to spin up the wrong sandbox flavour; validating up-front surfaces the mistake to the caller immediately.

qemu_config carries the QEMU-specific settings the generic SandboxConfig cannot express - most importantly the qcow2 disk image. Without it a "qemu" sandbox has no bootable disk and can never start, so callers creating a QEMU sandbox must supply one.

Parameters:
  • sandbox_type (str) – Type of sandbox ("windows" or "qemu").

  • timeout_seconds (int) – Execution timeout in seconds.

  • network_enabled (bool) – Whether to enable network access.

  • block_telemetry (bool) – Whether the guest’s own operating-system telemetry is silenced inside the guest at start. Defaults to on, matching the dialog, so a caller that says nothing gets a capture in which outbound traffic belongs to the sample.

  • memory_limit_mb (int) – Memory limit in megabytes.

  • qemu_config (QEMUConfig | None) – QEMU backend configuration forwarded to the manager. Ignored for the "windows" sandbox type.

  • clipboard_enabled (bool) – Whether the host clipboard is shared with the sandbox. Windows Sandbox only; no effect on QEMU.

  • audio_enabled (bool) – Whether the host’s audio input is redirected into the sandbox. Windows Sandbox only; no effect on QEMU.

  • video_enabled (bool) – Whether the sandbox is given a virtualized GPU. Windows Sandbox only; no effect on QEMU.

  • printer_enabled (bool) – Whether host printers are shared with the sandbox. Windows Sandbox only; no effect on QEMU.

  • shared_folders (list[dict[str, object]] | None) – Additional host folders to share with the sandbox, beyond its private work share. Each mapping carries host_path (required), guest_path (optional, defaults to C:\Shared\<host folder name>), and read_only (optional, defaults to False). Windows Sandbox honors read_only=False; on QEMU every shared folder is staged read-only regardless of this flag.

  • startup_commands (list[str] | None) – Additional cmd.exe command lines to run inside the guest after the dispatcher/monitor fleet starts. Windows Sandbox only; no effect on QEMU.

  • environment_variables (dict[str, str] | None) – Environment variables to set inside the guest before startup_commands run. Windows Sandbox only; no effect on QEMU.

Returns:

Dictionary with instance_id and status.

Return type:

dict[str, Any]

Raises:

ToolError – If sandbox_type is not one of the supported values or if creation fails inside the manager.

async destroy(instance_id)[source]

Destroy a sandbox instance.

Parameters:

instance_id (str) – ID of the instance to destroy.

Returns:

Success confirmation.

Return type:

dict[str, Any]

Raises:

ToolError – If destruction fails.

async restart(instance_id, timeout_seconds=300, *, network_enabled=False, block_telemetry=True, memory_limit_mb=2048, qemu_config=None, clipboard_enabled=False, audio_enabled=False, video_enabled=False, printer_enabled=False, shared_folders=None, startup_commands=None, environment_variables=None)[source]

Restart a sandbox instance as a single managed operation.

Delegates to SandboxManager.restart(), so the teardown and the recreate share the manager’s failure semantics instead of being chained by the caller: the original instance is gone in every outcome, and no replacement is registered when the recreate fails.

qemu_config carries the QEMU-specific settings the generic SandboxConfig cannot express - most importantly the qcow2 disk image. A QEMU instance restarted without it has no bootable disk and can never start again, so callers restarting a QEMU sandbox must supply one.

Parameters:
  • instance_id (str) – ID of the instance to restart.

  • timeout_seconds (int) – Execution timeout in seconds for the replacement.

  • network_enabled (bool) – Whether the replacement may access the network.

  • block_telemetry (bool) – Whether the replacement silences the guest’s own operating-system telemetry inside the guest at start.

  • memory_limit_mb (int) – Memory limit in megabytes for the replacement.

  • qemu_config (QEMUConfig | None) – QEMU backend configuration forwarded to the manager. Ignored for the "windows" sandbox type.

  • clipboard_enabled (bool) – Whether the replacement shares the host clipboard with the sandbox. Windows Sandbox only; no effect on QEMU.

  • audio_enabled (bool) – Whether the replacement redirects the host’s audio input into the sandbox. Windows Sandbox only; no effect on QEMU.

  • video_enabled (bool) – Whether the replacement is given a virtualized GPU. Windows Sandbox only; no effect on QEMU.

  • printer_enabled (bool) – Whether the replacement shares host printers with the sandbox. Windows Sandbox only; no effect on QEMU.

  • shared_folders (list[dict[str, object]] | None) – Additional host folders to share with the replacement, beyond its private work share. Each mapping carries host_path (required), guest_path (optional, defaults to C:\Shared\<host folder name>), and read_only (optional, defaults to False). Windows Sandbox honors read_only=False; on QEMU every shared folder is staged read-only regardless of this flag.

  • startup_commands (list[str] | None) – Additional cmd.exe command lines to run inside the replacement’s guest after the dispatcher/monitor fleet starts. Windows Sandbox only; no effect on QEMU.

  • environment_variables (dict[str, str] | None) – Environment variables to set inside the replacement’s guest before startup_commands run. Windows Sandbox only; no effect on QEMU.

Returns:

Dictionary with the new instance_id, the previous_instance_id that was torn down, and the replacement’s type, status, and creation timestamp.

Return type:

dict[str, Any]

Raises:

ToolError – If the instance is unknown or the replacement could not be created.

async run_binary(binary_path, args=None, sandbox_type='windows', time_limit=None, companions=None, *, monitor=True, qemu_config=None, reuse_instance=False, instance_id=None)[source]

Execute a binary in a sandbox with monitoring.

Validates sandbox_type up-front and refuses to launch the target under a coerced fallback when the caller supplies an unknown flavour. The previous silent coercion mapped any non-"windows" string to "qemu", which made sandbox_type="Qemu" (capitalised) or future sandbox flavours silently behave as QEMU.

Both qemu_config and reuse_instance are forwarded to the manager, which has always accepted them. Without the first, a QEMU run reaches the backend with no disk image and cannot start at all; without the second, a caller that already has a running sandbox gets a second virtual machine booted beside it rather than its binary run in the one it is looking at.

instance_id is stronger than reuse_instance and is what a caller needs to compare two runs. reuse_instance cannot express which sandbox to use - it takes whichever idle one of that type comes first - so with two sandboxes running, two successive calls both land on the same instance and diff() has only one report to work from.

Parameters:
  • binary_path (str) – Path to the binary to execute.

  • args (list[str] | None) – Optional command line arguments.

  • sandbox_type (str) – Type of sandbox to use ("windows" or "qemu").

  • time_limit (int | None) – Optional timeout override in seconds.

  • companions (list[str] | None) – Paths to files or directories the target needs beside it, each placed in the sandbox under its own name. A target staged without one of these still launches and still exits 0 while doing nothing.

  • monitor (bool) – Whether to monitor behavior.

  • qemu_config (QEMUConfig | None) – QEMU-specific configuration, required for the "qemu" type to reach a bootable disk image.

  • reuse_instance (bool) – Whether to run in an existing idle sandbox of the same type instead of creating one.

  • instance_id (str | None) – Identifier of the existing sandbox to run in. Takes precedence over reuse_instance.

Returns:

ExecutionReport as dictionary.

Return type:

dict[str, Any]

Raises:

ToolError – If sandbox_type is not one of the supported values, the binary does not exist, or execution fails.

async execute(instance_id, command, time_limit=None, working_directory=None)[source]

Execute a command in an existing sandbox.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • command (str) – Command to execute.

  • time_limit (int | None) – Optional command timeout in seconds.

  • working_directory (str | None) – Optional working directory.

Returns:

Dictionary with exit_code, stdout, stderr.

Return type:

dict[str, Any]

Raises:

ToolError – If execution fails.

async copy_to(instance_id, source, dest)[source]

Copy a file into a sandbox.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • source (str) – Local source file path.

  • dest (str) – Destination path inside sandbox.

Returns:

Success confirmation.

Return type:

dict[str, Any]

Raises:

ToolError – If copy fails.

async copy_from(instance_id, source, dest)[source]

Copy a file from a sandbox.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • source (str) – Source path inside sandbox.

  • dest (str) – Local destination file path.

Returns:

Success confirmation.

Return type:

dict[str, Any]

Raises:

ToolError – If copy fails.

async status()[source]

Get sandbox manager status.

Returns:

Status dictionary with available types and instance info.

Return type:

dict[str, Any]

async list()[source]

List all active sandbox instances.

Returns:

List of instance information dictionaries.

Return type:

list[dict[str, Any]]

async snapshot_create(instance_id, name)[source]

Create a snapshot of a QEMU sandbox.

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • name (str) – Name for the snapshot.

Returns:

Dictionary with snapshot_id.

Return type:

dict[str, Any]

Raises:

ToolError – If snapshot fails or not supported.

async snapshot_restore(instance_id, snapshot_id)[source]

Restore a QEMU sandbox to a snapshot.

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • snapshot_id (str) – ID of the snapshot to restore.

Returns:

Success confirmation.

Return type:

dict[str, Any]

Raises:

ToolError – If restore fails or not supported.

async snapshot_list(instance_id)[source]

List available snapshots for a QEMU sandbox.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

Dictionary with list of snapshot names.

Return type:

dict[str, Any]

Raises:

ToolError – If listing fails or not supported.

async snapshot_delete(instance_id, name)[source]

Delete a snapshot from a QEMU sandbox.

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • name (str) – Name of the snapshot to delete.

Returns:

Success confirmation.

Return type:

dict[str, Any]

Raises:

ToolError – If deletion fails or not supported.

async stop(instance_id)[source]

Pause execution of a running QEMU sandbox VM.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

Command response dictionary.

Return type:

dict[str, Any]

Raises:

ToolError – If pause fails, QMP is not connected, or the instance is not a QEMU sandbox.

async cont(instance_id)[source]

Resume execution of a paused QEMU sandbox VM.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

Command response dictionary.

Return type:

dict[str, Any]

Raises:

ToolError – If resume fails, QMP is not connected, or the instance is not a QEMU sandbox.

async get_pending_messages(instance_id)[source]

Get pending messages from the QEMU guest agent.

Raises ToolError when the guest agent is not connected instead of returning an empty list, so callers can distinguish “no messages waiting” (empty messages list, success) from “agent channel is dead” (error). Previously both paths returned {"messages": [], "count": 0}, which masked agent-channel faults behind a benign-looking empty response and left GUI / orchestrator consumers with no way to surface the root cause.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

Dictionary with list of pending messages.

Return type:

dict[str, Any]

Raises:

ToolError – If the instance is unknown, is not a QEMU sandbox, has no connected guest agent, or the retrieval call itself fails.

async pcap_start(instance_id)[source]

Start packet capture on a QEMU sandbox instance.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

Dictionary with capture_id.

Return type:

dict[str, Any]

Raises:

ToolError – If capture cannot be started or sandbox is not QEMU.

async pcap_stop(instance_id, capture_id, output_path=None)[source]

Stop packet capture and retrieve the PCAP file.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • capture_id (str) – Capture ID from pcap_start.

  • output_path (str | None) – Optional local path to save the PCAP file.

Returns:

Dictionary with pcap file path.

Return type:

dict[str, Any]

Raises:

ToolError – If capture cannot be stopped.

async stop_pcap(instance_id)[source]

Stop any active PCAP capture for the given sandbox instance.

Cleanup-friendly variant of pcap_stop() used by UI teardown paths that do not retain the original capture_id value. If no capture is active for the instance, the call is a no-op and returns stopped=False.

Parameters:

instance_id (str) – ID of the sandbox instance whose PCAP capture should be stopped.

Returns:

Dictionary describing the outcome. Contains instance_id (str) and stopped (bool); when a capture was active, also capture_id (str) and pcap_path (str) of the saved file.

Return type:

dict[str, Any]

Raises:

ToolError – If a capture was active and stopping it failed.

set_vnc_password(instance_id, password)[source]

Register the VNC password configured for a sandbox instance.

QEMU VNC passwords are negotiated at launch (via the QMP change vnc password command) and are not persisted by the underlying QEMU process in a way the bridge can recover later. Callers that configure VNC authentication on a QEMU sandbox MUST register the password through this method so that UI consumers can retrieve it via get_vnc_password() when auto-connecting an embedded viewer.

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • password (str) – Plaintext VNC password to associate with the instance. Pass an empty string to indicate the VNC display is configured without authentication.

Return type:

None

get_vnc_password(instance_id)[source]

Return the VNC password registered for a sandbox instance.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

The plaintext VNC password previously registered via set_vnc_password(), or None if no password has been registered for this instance.

Return type:

str | None

async screenshot(instance_id, output_path=None)[source]

Capture a screenshot of the QEMU sandbox display.

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • output_path (str | None) – Optional local path to save the screenshot.

Returns:

Dictionary with screenshot file path.

Return type:

dict[str, Any]

Raises:

ToolError – If screenshot cannot be captured or sandbox is not QEMU.

async anti_evasion(instance_id, profile='default')[source]

Apply anti-evasion hardening to a QEMU sandbox instance.

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • profile (str) – Anti-evasion profile name.

Returns:

Dictionary describing applied techniques.

Return type:

dict[str, Any]

Raises:

ToolError – If anti-evasion cannot be applied or sandbox is not QEMU.

async memory_dump(instance_id, output_path=None, target_pid=None)[source]

Dump guest memory from a sandbox instance.

QEMU sandboxes dump the whole VM via the dump-guest-memory QMP command and ignore target_pid. Windows Sandbox runs MiniDumpWriteDump inside the guest against the process identified by target_pid; target_pid is required for Windows Sandbox because passing GetCurrentProcess() would (incorrectly) dump the PowerShell host instead of the analysis target (audit7 F-0021).

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • output_path (str | None) – Optional local path to save the memory dump.

  • target_pid (int | None) – Guest-side PID of the process to dump. Required for Windows Sandbox instances; ignored for QEMU.

Returns:

Dictionary with memory dump file path.

Return type:

dict[str, Any]

Raises:

ToolError – If memory dump fails or required arguments are missing.

async list_guest_processes(instance_id)[source]

List processes currently running inside a Windows Sandbox guest.

Lets a caller discover a valid target_pid before calling memory_dump() against a Windows Sandbox instance, which rejects a missing or non-positive target_pid outright.

Parameters:

instance_id (str) – ID of the Windows Sandbox instance.

Returns:

Dictionary with instance_id and a processes list of {"pid", "name", "path"} records.

Return type:

dict[str, Any]

Raises:

ToolError – If the instance is not found, is not a Windows Sandbox, or the guest process listing fails.

async extract_dropped_files(instance_id, output_path=None)[source]

Extract files created during sandbox execution (QEMU only).

Parameters:
  • instance_id (str) – ID of the QEMU sandbox instance.

  • output_path (str | None) – Optional local path to save the ZIP archive.

Returns:

Dictionary with ZIP archive path.

Return type:

dict[str, Any]

Raises:

ToolError – If extraction fails or sandbox is not QEMU.

async yara_scan(instance_id, rules_path=None, scan_target='files')[source]

Run YARA rules against sandbox artifacts.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • rules_path (str | None) – Path to YARA rules file.

  • scan_target (str) – What to scan (‘files’ or ‘memory’).

Returns:

Dictionary with YARA match results.

Return type:

dict[str, Any]

Raises:

ToolError – If scan_target is invalid or scan fails.

async extract_iocs(instance_id)[source]

Extract IOCs from the last execution report.

Parameters:

instance_id (str) – ID of the sandbox instance.

Returns:

Dictionary with list of IOC entries.

Return type:

dict[str, Any]

Raises:

ToolError – If extraction fails or no report available.

async timeline(instance_id, categories=None)[source]

Generate an event timeline from the last execution report.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • categories (list[str] | None) – Optional list of categories to include.

Returns:

Dictionary with list of timeline events.

Return type:

dict[str, Any]

Raises:

ToolError – If timeline generation fails or no report available.

async detect_behaviors(instance_id, custom_rules_path=None)[source]

Match behavioral signatures against the last execution report.

If custom_rules_path is provided it must point to an existing YAML file whose top-level value is a list of rule dictionaries. A missing file or invalid YAML raises ToolError immediately; the underlying match_behaviors call is not made.

Parameters:
  • instance_id (str) – ID of the sandbox instance.

  • custom_rules_path (str | None) – Optional path to custom YAML rules file.

Returns:

Dictionary with list of behavior matches.

Return type:

dict[str, Any]

Raises:

ToolError – If the rules path is given but not found, the file is not valid YAML, the YAML top-level is not a list, detection fails, or no report is available.

async detect_c2(instance_id)[source]

Detect C2 communication patterns in the last execution report.

Parameters:

instance_id (str) – ID of the sandbox instance.

Returns:

Dictionary with list of C2 pattern detections.

Return type:

dict[str, Any]

Raises:

ToolError – If detection fails or no report available.

async diff(instance_id_a, instance_id_b)[source]

Compare two sandbox execution reports.

Parameters:
  • instance_id_a (str) – ID of the first sandbox instance.

  • instance_id_b (str) – ID of the second sandbox instance.

Returns:

Dictionary with per-field comparison results.

Return type:

dict[str, Any]

Raises:

ToolError – If comparison fails or reports unavailable.

async get_vnc_port(instance_id)[source]

Get the VNC port for a QEMU sandbox instance.

Only QEMU sandboxes expose a VNC port. Calling this on a non-QEMU instance raises ToolError. A QEMU instance whose VNC port has not been allocated yet also raises ToolError rather than returning None, since callers that query this method are specifically trying to connect a viewer and a None return is not actionable.

Parameters:

instance_id (str) – ID of the QEMU sandbox instance.

Returns:

The VNC port number.

Return type:

int

Raises:

ToolError – If the instance is not registered, is not a QEMU sandbox, or has no VNC port allocated.