Getting started overview

This guide provides a structured approach to initiating interaction with CAPEsandbox, an open-source dynamic malware analysis system. The process involves setting up a local or remote CAPE instance, configuring its components, obtaining API access credentials, and executing a foundational API request. CAPE, a fork of Cuckoo Sandbox, emphasizes configurability for diverse threat analysis scenarios (CAPEsandbox homepage). Understanding its architecture, which includes an analysis manager, guest agents, and reporting modules, facilitates effective deployment and utilization.

Before proceeding, ensure you have a suitable environment for installation. CAPE typically runs on Linux-based systems and requires virtualization software (e.g., VirtualBox, KVM) to isolate analysis environments. Familiarity with command-line operations and Python is beneficial for installation and API interaction.

The initial setup phases are critical for establishing a functional analysis environment. This includes installing dependencies, configuring network settings for virtual machines, and preparing the CAPE web interface and API service. The API enables programmatic submission of samples, retrieval of analysis results, and management of tasks, supporting integration into automated security workflows (CAPEsandbox API usage documentation).

The following table summarizes the key steps:

Step What to do Where
1. Review Prerequisites Check hardware, OS, and software requirements. CAPEsandbox installation documentation
2. Install CAPE Install CAPE and its dependencies. CAPEsandbox installation documentation
3. Configure Virtual Machines Set up guest VMs for analysis. CAPEsandbox guest setup documentation
4. Configure CAPE Adjust CAPE settings (networking, modules). conf/ directory within CAPE installation
5. Start CAPE Services Launch the web interface and API. Command line (e.g., ./cape.py web & ./cape.py api &)
6. Obtain API Key Locate or generate the API key. conf/api.conf or CAPE web UI (if configured)
7. Make First Request Submit a sample using the API. Python script or curl command

Create an account and get keys

As CAPEsandbox is open-source software, there is no centralized account creation process analogous to cloud-based API services. Instead, you install and configure the software on your own infrastructure. API access is controlled locally through a configuration file.

  1. Install CAPE: Follow the official CAPEsandbox installation guide. This typically involves cloning the repository, installing Python dependencies, and setting up the necessary database and virtualization components. A standard installation includes steps for setting up the main CAPE daemon, the web interface, and the API service.

  2. API Key Location: Once CAPE is installed, the API key is defined in the CAPE configuration files. Navigate to your CAPE installation directory and locate the conf/api.conf file. Within this file, you will find a section similar to this:

    [api]
    enabled = yes
    key = YOUR_API_KEY_HERE
    

    The key parameter contains the API token that clients will use to authenticate requests. For security reasons, it is recommended to change the default key to a strong, unique value. Save the file after making any changes.

  3. Start the API Service: To enable API access, ensure the CAPE API service is running. From your CAPE installation directory, execute the command:

    ./cape.py api
    

    This command starts the API server, typically listening on http://127.0.0.1:8000 by default, though this can be configured in conf/api.conf. The API key you configured will be required in the Authorization header for all authenticated requests.

It is important to secure your CAPE instance, especially if exposing the API externally. Consider implementing network firewalls, VPNs, or API gateways (e.g., Kong API Gateway) to restrict access to the API endpoint and protect your analysis environment from unauthorized submissions or data exfiltration.

Your first request

With CAPE installed, configured, and its API service running, you can now submit your first sample for analysis. This example uses Python, as it is the primary language for CAPE's SDKs and a common choice for interacting with its API.

Prerequisites

  • Python installed (version 3.6 or higher recommended).
  • The requests library for Python: pip install requests.
  • A CAPE instance running with the API service active.
  • Your API key from conf/api.conf.
  • A benign sample file for testing (e.g., a simple text file, test.txt, containing "hello world").

Python example: Submitting a file

Create a Python file (e.g., submit_sample.py) with the following content. Replace YOUR_API_KEY with your actual CAPE API key and adjust CAPE_API_URL if your API service is running on a different address or port.

import requests
import os

CAPE_API_URL = "http://127.0.0.1:8000/tasks/create/file"
API_KEY = "YOUR_API_KEY"
SAMPLE_PATH = "test.txt" # Path to your sample file

def submit_file_for_analysis(api_url, api_key, file_path):
    headers = {
        "Authorization": f"Bearer {api_key}"
    }

    if not os.path.exists(file_path):
        print(f"Error: File not found at {file_path}")
        return None

    with open(file_path, "rb") as sample_file:
        files = {"file": (os.path.basename(file_path), sample_file)}
        try:
            response = requests.post(api_url, headers=headers, files=files)
            response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
            return response.json()
        except requests.exceptions.HTTPError as http_err:
            print(f"HTTP error occurred: {http_err} - {response.text}")
        except requests.exceptions.ConnectionError as conn_err:
            print(f"Connection error occurred: {conn_err}")
        except requests.exceptions.Timeout as timeout_err:
            print(f"Timeout error occurred: {timeout_err}")
        except requests.exceptions.RequestException as req_err:
            print(f"An unexpected error occurred: {req_err}")
    return None

if __name__ == "__main__":
    # Create a dummy test file if it doesn't exist
    if not os.path.exists(SAMPLE_PATH):
        with open(SAMPLE_PATH, "w") as f:
            f.write("This is a test file for CAPE sandbox analysis.")
        print(f"Created dummy file: {SAMPLE_PATH}")

    print(f"Submitting {SAMPLE_PATH} to CAPE for analysis...")
    result = submit_file_for_analysis(CAPE_API_URL, API_KEY, SAMPLE_PATH)

    if result:
        print("Analysis submission successful!")
        print(f"Task ID: {result.get('task_id')}")
        print(f"Status: {result.get('status')}")
        print("Further details can be viewed in the CAPE web interface or fetched via API.")
    else:
        print("Failed to submit sample.")

Running the script

  1. Save the code as submit_sample.py.
  2. Ensure test.txt exists in the same directory, or modify SAMPLE_PATH to point to your desired test file.
  3. Run the script from your terminal: python submit_sample.py.

Upon successful execution, the script will output a task ID and status, indicating that CAPE has accepted the file for analysis. You can then monitor the analysis progress through the CAPE web interface or query the API for results using the returned task_id.

Common next steps

After successfully submitting your first sample, consider these common next steps to leverage CAPEsandbox's full capabilities:

  • Retrieve Analysis Results: Use the CAPE API to fetch the detailed analysis report for your submitted task. The API endpoint for retrieving results is typically /tasks/report/{task_id}. Reports include dynamic analysis data, network activity, dropped files, and behavioral indicators (CAPEsandbox API report documentation).

  • Explore the Web Interface: Access the CAPE web interface (usually at http://127.0.0.1:8000 by default) to visually inspect analysis reports, manage tasks, and configure various CAPE settings. The web interface offers a richer view of the data than raw API responses.

  • Customize Analysis Options: CAPE offers extensive customization for analysis. Explore options like specifying the guest operating system, injecting arguments into the analyzed process, or enabling specific analysis modules (e.g., network sniffing, memory dumps) (CAPEsandbox submission options). These can be passed as parameters during API submission.

  • Integrate with Other Tools: Due to its API-driven nature, CAPE can be integrated into broader security ecosystems. Consider connecting it with Security Information and Event Management (SIEM) systems, threat intelligence platforms, or incident response playbooks using tools like Tray.io's CAPESandbox connector for automation.

  • Update and Maintain: Regularly update your CAPE instance and its components (operating systems, virtualization software, Python packages) to ensure you have the latest features, bug fixes, and security patches. Consult the CAPEsandbox upgrading documentation.

  • Contribute to the Community: As an open-source project, CAPE benefits from community contributions. Consider reporting bugs, suggesting features, or contributing code to the project's GitHub repository.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps:

  • API Service Not Running: Ensure the CAPE API service is active. Run ./cape.py api from your CAPE installation directory. Check the terminal output for any errors or messages indicating the server started successfully.

  • Incorrect API Key: Double-check that the API_KEY in your script exactly matches the key value in your conf/api.conf file. Any mismatch, including extra spaces, will result in authentication failures (typically a 401 Unauthorized error).

  • Incorrect API URL: Verify that CAPE_API_URL in your script points to the correct IP address and port where your CAPE API is listening. The default is http://127.0.0.1:8000. If CAPE is on a remote server, ensure the IP address is accessible and firewalls are configured correctly.

  • Network Connectivity Issues: If CAPE is running on a different machine or a virtual machine, ensure there is network connectivity between your client and the CAPE API endpoint. Use ping or curl from your client machine to test connectivity to the CAPE server's IP and port.

  • File Path Errors: Confirm that the SAMPLE_PATH in your script correctly points to an existing file. Relative paths should be relative to where you run the Python script. The error message "Error: File not found" specifically indicates this problem.

  • Dependencies Not Installed: Ensure the Python requests library is installed (pip install requests). Missing libraries will result in Python ModuleNotFoundError.

  • CAPE Logs: Check the CAPE log files for detailed error messages. Logs are typically found in the log/ directory within your CAPE installation. The API server's console output also provides valuable debugging information.

  • Firewall Blocking: If you are exposing CAPE's API to the network, ensure that any host-based firewalls (e.g., ufw on Linux) or network firewalls are configured to allow incoming connections on the CAPE API port (default 8000).

  • Virtual Machine Issues: Although not directly related to the API call, if CAPE's underlying virtual machines are not properly configured or running, task submissions might succeed but analysis will fail later. Check the status of your guest VMs and their network configuration as described in the CAPEsandbox guest setup documentation.