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
datetimeinstances to UTC ISO-8601 strings,Pathinstances to POSIX strings, and recurses intodict/list. All other types are returned unchanged.
- dataclass_to_dict(obj)[source]
Convert a dataclass instance to a JSON-serialisable dictionary.
Uses
dataclasses.asdictfor the conversion and then appliesjson_safe()to convertdatetimeandPathvalues to strings. Ajson.dumpsround-trip is verified before returning.
- class SandboxBridge[source]
Bases:
ToolBridgeBaseBridge for sandbox operations.
Provides an AI-accessible interface to the
SandboxManagerfor creating isolated execution environments and running binaries. Instances own a lazy slot for the sharedSandboxManagersingleton and record the advertisedBridgeCapabilitiesdescribing the dynamic-analysis features this bridge can provide.- property manager: SandboxManager | None
The underlying
SandboxManagerinstance, if initialized.- Returns:
Active manager, or
Noneif 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:
Trueifshutdown()has been called and the manager has not been recreated,Falseotherwise.- Return type:
- attach_manager(manager)[source]
Install an externally constructed
SandboxManager.Used by callers that need to wrap an existing
SandboxBase/SandboxManagerinstance behind the bridge without spinning up a fresh manager viaensure_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:
- Returns:
ID of the registered
SandboxInstance.- Return type:
- property tool_definition: ToolDefinition
Tool definition for LLM function calling.
- Returns:
ToolDefinition with all sandbox functions.
- Return type:
- async initialize(tool_path=None)[source]
Initialize the sandbox bridge.
- Parameters:
tool_path (Path | None) – Not used for sandbox (ignored).
- 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:
- ensure_manager()[source]
Ensure manager is initialized and has not been shut down.
- Returns:
The SandboxManager instance.
- Return type:
- 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_typevalues 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_configcarries the QEMU-specific settings the genericSandboxConfigcannot 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 toC:\Shared\<host folder name>), andread_only(optional, defaults to False). Windows Sandbox honorsread_only=False; on QEMU every shared folder is staged read-only regardless of this flag.startup_commands (list[str] | None) – Additional
cmd.execommand 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_commandsrun. Windows Sandbox only; no effect on QEMU.
- Returns:
Dictionary with instance_id and status.
- Return type:
- Raises:
ToolError – If
sandbox_typeis not one of the supported values or if creation fails inside the manager.
- 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_configcarries the QEMU-specific settings the genericSandboxConfigcannot 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 toC:\Shared\<host folder name>), andread_only(optional, defaults to False). Windows Sandbox honorsread_only=False; on QEMU every shared folder is staged read-only regardless of this flag.startup_commands (list[str] | None) – Additional
cmd.execommand 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_commandsrun. Windows Sandbox only; no effect on QEMU.
- Returns:
Dictionary with the new
instance_id, theprevious_instance_idthat was torn down, and the replacement’s type, status, and creation timestamp.- Return type:
- 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_typeup-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 madesandbox_type="Qemu"(capitalised) or future sandbox flavours silently behave as QEMU.Both
qemu_configandreuse_instanceare 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_idis stronger thanreuse_instanceand is what a caller needs to compare two runs.reuse_instancecannot 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 anddiff()has only one report to work from.- Parameters:
binary_path (str) – Path to the binary to execute.
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
0while 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:
- Raises:
ToolError – If
sandbox_typeis 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:
- Returns:
Dictionary with exit_code, stdout, stderr.
- Return type:
- Raises:
ToolError – If execution fails.
- async get_pending_messages(instance_id)[source]
Get pending messages from the QEMU guest agent.
Raises
ToolErrorwhen the guest agent is not connected instead of returning an empty list, so callers can distinguish “no messages waiting” (emptymessageslist, 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.
- async pcap_stop(instance_id, capture_id, output_path=None)[source]
Stop packet capture and retrieve the PCAP file.
- 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 originalcapture_idvalue. If no capture is active for the instance, the call is a no-op and returnsstopped=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) andstopped(bool); when a capture was active, alsocapture_id(str) andpcap_path(str) of the saved file.- Return type:
- 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 passwordcommand) 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 viaget_vnc_password()when auto-connecting an embedded viewer.
- 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(), orNoneif 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.
- async anti_evasion(instance_id, profile='default')[source]
Apply anti-evasion hardening to a QEMU sandbox instance.
- 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-memoryQMP command and ignoretarget_pid. Windows Sandbox runsMiniDumpWriteDumpinside the guest against the process identified bytarget_pid;target_pidis required for Windows Sandbox because passingGetCurrentProcess()would (incorrectly) dump the PowerShell host instead of the analysis target (audit7 F-0021).- Parameters:
- Returns:
Dictionary with memory dump file path.
- Return type:
- 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_pidbefore callingmemory_dump()against a Windows Sandbox instance, which rejects a missing or non-positivetarget_pidoutright.
- async extract_dropped_files(instance_id, output_path=None)[source]
Extract files created during sandbox execution (QEMU only).
- async yara_scan(instance_id, rules_path=None, scan_target='files')[source]
Run YARA rules against sandbox artifacts.
- Parameters:
- Returns:
Dictionary with YARA match results.
- Return type:
- Raises:
ToolError – If scan_target is invalid or scan fails.
- async timeline(instance_id, categories=None)[source]
Generate an event timeline from the last execution report.
- async detect_behaviors(instance_id, custom_rules_path=None)[source]
Match behavioral signatures against the last execution report.
If
custom_rules_pathis 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 raisesToolErrorimmediately; the underlyingmatch_behaviorscall is not made.- Parameters:
- Returns:
Dictionary with list of behavior matches.
- Return type:
- 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.
- 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 raisesToolErrorrather than returningNone, since callers that query this method are specifically trying to connect a viewer and aNonereturn is not actionable.