# CAPEv2 Agent Architecture and Host Communication Protocol

> Explore the CAPEv2 agent architecture and its host communication protocol. Learn how this Python HTTP microservice uses IP pinning and JSON for secure data exchange and state management.

- Repository: [Kevin O'Reilly/capev2](https://github.com/kevoreilly/capev2)
- Tags: architecture
- Published: 2026-03-05

---

**The CAPEv2 agent is a pure-Python HTTP microservice that uses `MiniHTTPServer` and `MiniHTTPRequestHandler` to expose a REST-like API, facilitating secure host communication through IP pinning and JSON-based data exchange while maintaining analysis state in a global dictionary.**

The **CAPEv2 agent** serves as the critical bridge between malware analysis guests and the CAPE sandbox controller in the `kevoreilly/capev2` repository. Implemented as a self-contained HTTP server without external web framework dependencies, this component enables file transfers, command execution, and status reporting across both Windows and Linux environments. Understanding the **architectural structure** of the CAPEv2 agent reveals how it maintains security through IP pinning while providing a minimal attack surface for analyzed samples.

## Core Components in agent/agent.py

The CAPEv2 agent's architecture consists of three tightly coupled components defined in [`agent/agent.py`](https://github.com/kevoreilly/capev2/blob/main/agent/agent.py): a threaded HTTP server, a request normalizer, and endpoint handlers.

### MiniHTTPServer and Global State Management

The **`MiniHTTPServer`** class (lines 166-179) serves as the application's backbone. It extends `socketserver.ThreadingMixIn` to handle concurrent connections and binds to `0.0.0.0:8000` by default, configurable via command-line arguments in the `__main__` block (lines 806-818). This server maintains the routing table and hosts the global **`state`** dictionary (defined at lines 100-107), which tracks `status`, `description`, `async_subprocess` handles, and active `mutexes` across requests.

### Request Handling and Normalization

The **`MiniHTTPRequestHandler`** class (extending `http.server.SimpleHTTPRequestHandler`) processes incoming traffic. Its `do_POST` method (lines 21-41) parses multipart form data and file uploads, constructing a global **`request`** object that includes the client's IP address and normalized form fields. This handler supports GET, POST, and DELETE methods, forwarding sanitized requests to `self.httpd.handle(self)` for routing to specific endpoints.

### Route Functions and API Endpoints

Individual capabilities are exposed through Python functions decorated with `@app.route`. Key endpoints include **`/status`** (lines 445-452) for health checks and **`/execute`** (lines 651-665) for command injection. These handlers communicate results using `jsonify()` for JSON responses or `send_file()` for binary streams, ensuring consistent data formats between the agent and CAPE controller.

## Host Communication Flow and Security

Communication between the CAPE controller and the agent follows a strict request-response protocol with security enforced at the network layer.

### IP Pinning and Access Control

Before issuing commands, the controller must call the **`/pinning`** endpoint (implemented at lines 887-894). This handler records `request.client_ip` into `state["client_ip"]`, and subsequent requests validate against this stored address. If the source IP differs, the agent rejects the request, preventing malicious processes or network neighbors from hijacking the analysis session.

### Asynchronous Process Management

For long-running operations, the agent spawns background processes using **`spawn()`** (lines 221-227). The function stores subprocess handles in `state["async_subprocess"]`, allowing the `/status` endpoint to poll completion states without blocking the HTTP server. This architecture enables the controller to execute lengthy analysis scripts while maintaining API responsiveness.

### Data Exchange Formats

The agent accepts multipart form data for file uploads and command arguments, then returns structured JSON. For example, the `/execute` endpoint returns Base64-encoded stdout in its response, while `/store` confirms file writes with success messages. Binary file retrieval uses the `send_file` helper to stream content directly to the controller.

## Practical API Examples

The following `curl` commands demonstrate the actual communication protocol used by the CAPE controller.

Pinning the agent to the controller IP:

```bash
curl -X POST http://<guest_ip>:8000/pinning

```

Expected response:

```json
{
  "message": "Successfully pinned Agent",
  "client_ip": "192.168.56.101"
}

```

Querying analysis status:

```bash
curl http://<guest_ip>:8000/status

```

Response:

```json
{
  "message": "Analysis status",
  "status": "init",
  "description": ""
}

```

Executing system commands:

```bash
curl -X POST \
     -F "command=date" \
     http://<guest_ip>:8000/execute

```

Uploading files to the guest:

```bash
curl -X POST \
     -F "filepath=/tmp/uploaded.bin" \
     -F "file=@local_file.bin" \
     http://<guest_ip>:8000/store

```

Retrieving files with optional Base64 encoding:

```bash
curl -X POST \
     -F "filepath=/tmp/uploaded.bin" \
     -F "encoding=base64" \
     http://<guest_ip>:8000/retrieve --output retrieved.bin.b64

```

## Summary

- The **CAPEv2 agent** architecture relies on `MiniHTTPServer` for connection handling, `MiniHTTPRequestHandler` for request parsing, and decorated route functions for endpoint logic, all implemented in [`agent/agent.py`](https://github.com/kevoreilly/capev2/blob/main/agent/agent.py).
- **Host communication** occurs via HTTP with JSON responses or binary streams, using a global **`state`** dictionary to persist analysis data, mutexes, and subprocess handles between requests.
- Security is enforced through **IP pinning** at the `/pinning` endpoint, which locks the agent to the CAPE controller's address after initial contact.
- The agent supports **asynchronous operations** through background subprocess management, allowing long-running analysis tasks without blocking the REST API.

## Frequently Asked Questions

### What prevents unauthorized hosts from controlling the CAPEv2 agent?

The agent implements IP pinning through the `/pinning` endpoint. When first called, it stores the client's IP in `state["client_ip"]` (lines 887-894 in [`agent/agent.py`](https://github.com/kevoreilly/capev2/blob/main/agent/agent.py)) and rejects subsequent requests from any other source address, effectively binding the agent to a single controller.

### Which Python classes handle the HTTP server functionality?

The architecture uses **`MiniHTTPServer`** (lines 166-179) for threaded socket handling and routing table management, and **`MiniHTTPRequestHandler`** (with its `do_POST` method at lines 21-41) for parsing HTTP requests and constructing the global `request` object used by endpoint handlers.

### How does the agent manage state across multiple API calls?

A global **`state`** dictionary defined at lines 100-107 maintains `status`, `description`, `async_subprocess` handles, and `mutexes`. Route handlers read from and write to this dictionary, enabling persistence of analysis context and background process tracking between discrete HTTP requests.

### Where is the main entry point for starting the CAPEv2 agent?

The agent starts via the `__main__` block in [`agent/agent.py`](https://github.com/kevoreilly/capev2/blob/main/agent/agent.py) (lines 806-818), which parses command-line arguments for host and port binding (defaulting to `0.0.0.0:8000`) and initializes the `MiniHTTPServer` to begin listening for controller connections.