Spaces:
Sleeping
Sleeping
Commit ·
cf8b7a1
0
Parent(s):
cyberdefense-openenv
Browse files- Dockerfile +10 -0
- README.md +87 -0
- cyber_env/__init__.py +8 -0
- cyber_env/__pycache__/__init__.cpython-313.pyc +0 -0
- cyber_env/__pycache__/env.cpython-313.pyc +0 -0
- cyber_env/__pycache__/schemas.cpython-313.pyc +0 -0
- cyber_env/__pycache__/simulator.cpython-313.pyc +0 -0
- cyber_env/__pycache__/tasks.cpython-313.pyc +0 -0
- cyber_env/env.py +42 -0
- cyber_env/schemas.py +67 -0
- cyber_env/simulator.py +33 -0
- cyber_env/tasks.py +116 -0
- evaluate.py +15 -0
- evaluate_agent.py +123 -0
- openenv.yaml +11 -0
- requirements.txt +11 -0
Dockerfile
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY requirements.txt .
|
| 5 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 6 |
+
|
| 7 |
+
COPY . .
|
| 8 |
+
|
| 9 |
+
# Command to run your evaluation or a simple UI
|
| 10 |
+
CMD ["python", "evaluate.py"]
|
README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CyberDefenseEnv
|
| 2 |
+
|
| 3 |
+
**CyberDefenseEnv** is a simulated Security Operations Center (SOC) environment built for the OpenEnv standard. It challenges autonomous AI agents to act as incident responders defending a simulated Linux server.
|
| 4 |
+
|
| 5 |
+
Instead of playing a toy game, the agent must monitor realistic system telemetry—such as running processes, active network connections, and system logs—to detect anomalies. The agent must then take precise, targeted actions to mitigate cyber threats (like SSH brute-forcing, cryptominers, and APT backdoors) without disrupting legitimate system operations.
|
| 6 |
+
|
| 7 |
+
This environment implements the full OpenEnv specification, utilizing strictly typed Pydantic models for reliable Agent-Environment interaction.
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## Observation Space (`state`)
|
| 12 |
+
|
| 13 |
+
When the agent calls `env.state()`, it receives a fully typed `ServerState` object representing the current snapshot of the simulated server.
|
| 14 |
+
|
| 15 |
+
### Server State Overview
|
| 16 |
+
|
| 17 |
+
| Field | Data Type | Description |
|
| 18 |
+
| :--- | :--- | :--- |
|
| 19 |
+
| **`system_load`** | `float` | Overall system CPU load percentage (0.0 to 100.0). |
|
| 20 |
+
| **`active_processes`** | `List[ProcessInfo]` | A list of all currently running processes on the server. |
|
| 21 |
+
| **`network_connections`** | `List[NetworkConnection]`| A list of all active incoming and outgoing network TCP/UDP connections. |
|
| 22 |
+
| **`recent_logs`** | `List[LogEntry]` | The last 50 lines of system logs (e.g., auth, syslog). |
|
| 23 |
+
| **`blocked_ips`** | `List[str]` | A list of IP addresses currently dropped by the server's firewall. |
|
| 24 |
+
|
| 25 |
+
### Nested Data Structures
|
| 26 |
+
To parse the state effectively, the agent relies on the following sub-components:
|
| 27 |
+
|
| 28 |
+
* **`ProcessInfo`**: Contains `pid` (int), `name` (str), `user` (str), `cpu_percent` (float), and `open_files` (List[str]).
|
| 29 |
+
* **`NetworkConnection`**: Contains `conn_id` (str), `protocol` (str), `local_port` (int), `remote_ip` (str), `remote_port` (int), `state` (str), and an optional `associated_pid` (int).
|
| 30 |
+
* **`LogEntry`**: Contains `timestamp` (str), `source` (str), `message` (str), and `severity` (str).
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Action Space (`step`)
|
| 35 |
+
|
| 36 |
+
The environment accepts a typed discriminated union of actions. The agent must pass one of the following structured JSON objects to `env.step(action)` to alter the state of the server and mitigate threats.
|
| 37 |
+
|
| 38 |
+
| Action Type (`action_type`) | Required Parameters | Description |
|
| 39 |
+
| :--- | :--- | :--- |
|
| 40 |
+
| **`kill_process`** | `pid` (int) | Forcefully terminates the process matching the provided Process ID. |
|
| 41 |
+
| **`block_ip`** | `ip_address` (str) | Adds the specified IP address to the firewall blocklist, dropping active and future connections. |
|
| 42 |
+
| **`delete_file`** | `filepath` (str) | Deletes the specified file from the system (used for removing malicious binaries or scripts). |
|
| 43 |
+
| **`restart_service`** | `service_name` (str) | Restarts a legitimate system service (e.g., 'ssh', 'apache2') to apply patches or clear in-memory hooks. |
|
| 44 |
+
| **`wait`** | `duration` (int) | Pauses the agent for a specified number of seconds to observe how the system state evolves. |
|
| 45 |
+
|
| 46 |
+
## Scenarios & Tasks
|
| 47 |
+
|
| 48 |
+
The environment includes three progressively difficult scenarios, fulfilling the OpenEnv task requirements. Each task features a custom deterministic grader that outputs a score between `0.0` and `1.0`.
|
| 49 |
+
|
| 50 |
+
1. **Task 1: SSH Brute Force (Easy)**
|
| 51 |
+
* **Threat:** A remote IP is repeatedly failing authentication attempts.
|
| 52 |
+
* **Objective:** Read the system logs, identify the malicious IP, and execute a `block_ip` action.
|
| 53 |
+
2. **Task 2: Hidden Cryptominer (Medium)**
|
| 54 |
+
* **Threat:** A process disguised as a system update is consuming 99% of the CPU and communicating with an external mining pool.
|
| 55 |
+
* **Objective:** Identify the anomaly, execute `kill_process`, and `block_ip` on the C2 server.
|
| 56 |
+
3. **Task 3: APT Backdoor (Hard)**
|
| 57 |
+
* **Threat:** An attacker has established a reverse shell via a hidden cron job script.
|
| 58 |
+
* **Objective:** The agent must dismantle the kill chain by killing the reverse shell process, blocking the attacker's IP, and executing `delete_file` to remove the persistence script.
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## Quick Start & Installation
|
| 63 |
+
|
| 64 |
+
You can run this environment locally or build the included Docker container.
|
| 65 |
+
|
| 66 |
+
### Option 1: Local Setup
|
| 67 |
+
1. Clone the repository and navigate to the directory.
|
| 68 |
+
2. Install the required dependencies:
|
| 69 |
+
```bash
|
| 70 |
+
pip install -r requirements.txt
|
| 71 |
+
3. Set your LLM API key as an environment variable (the baseline agent uses the Gemini API via OpenAI compatibility):
|
| 72 |
+
export GEMINI_API_KEY="your-api-key-here"
|
| 73 |
+
### Option 2: Docker
|
| 74 |
+
Build and run the evaluation agent inside a container:
|
| 75 |
+
docker build -t cyberdefense-env .
|
| 76 |
+
docker run -e GEMINI_API_KEY="your-api-key-here" cyberdefense-env
|
| 77 |
+
|
| 78 |
+
---
|
| 79 |
+
|
| 80 |
+
## Running the Autonomous Evaluation
|
| 81 |
+
This project includes a fully autonomous baseline agent (evaluate_agent.py) that uses a ReAct (Reasoning and Acting) loop to solve the environment dynamically.
|
| 82 |
+
|
| 83 |
+
To watch the AI act as an autonomous SOC analyst, run:
|
| 84 |
+
python evaluate_agent.py
|
| 85 |
+
|
| 86 |
+
### Expected Output:
|
| 87 |
+
The script will initialize the environment, parse the ServerState JSON to the LLM, and execute the LLM's structured JSON decisions until the threat is neutralized and a score of 1.0 is achieved.
|
cyber_env/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CyberDefenseEnv: An OpenEnv compliant SOC simulator.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from .env import CyberDefenseEnv
|
| 6 |
+
|
| 7 |
+
__version__ = "1.0.0"
|
| 8 |
+
__all__ = ["CyberDefenseEnv"]
|
cyber_env/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (330 Bytes). View file
|
|
|
cyber_env/__pycache__/env.cpython-313.pyc
ADDED
|
Binary file (3.02 kB). View file
|
|
|
cyber_env/__pycache__/schemas.cpython-313.pyc
ADDED
|
Binary file (5.3 kB). View file
|
|
|
cyber_env/__pycache__/simulator.cpython-313.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
cyber_env/__pycache__/tasks.cpython-313.pyc
ADDED
|
Binary file (3.73 kB). View file
|
|
|
cyber_env/env.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict
|
| 2 |
+
from .schemas import ServerState, AgentAction
|
| 3 |
+
from .simulator import SimulatedServer
|
| 4 |
+
from .tasks import setup_task_1, grade_task_1, setup_task_2, grade_task_2, setup_task_3, grade_task_3 # <--- Added Task 3 imports
|
| 5 |
+
|
| 6 |
+
class CyberDefenseEnv:
|
| 7 |
+
def __init__(self, task_name: str = "task_1"):
|
| 8 |
+
self.task_name = task_name
|
| 9 |
+
self.server = SimulatedServer()
|
| 10 |
+
self.reset()
|
| 11 |
+
|
| 12 |
+
def reset(self):
|
| 13 |
+
self.server = SimulatedServer()
|
| 14 |
+
if self.task_name == "task_1":
|
| 15 |
+
setup_task_1(self.server)
|
| 16 |
+
elif self.task_name == "task_2":
|
| 17 |
+
setup_task_2(self.server)
|
| 18 |
+
elif self.task_name == "task_3": # <--- Added route
|
| 19 |
+
setup_task_3(self.server)
|
| 20 |
+
|
| 21 |
+
def state(self) -> ServerState:
|
| 22 |
+
return self.server.get_state()
|
| 23 |
+
|
| 24 |
+
def step(self, action: AgentAction):
|
| 25 |
+
if action.action_type == "kill_process":
|
| 26 |
+
self.server.kill_process(action.pid)
|
| 27 |
+
elif action.action_type == "block_ip":
|
| 28 |
+
self.server.block_ip(action.ip_address)
|
| 29 |
+
elif action.action_type == "delete_file": # <--- Added action handler
|
| 30 |
+
self.server.delete_file(action.filepath)
|
| 31 |
+
|
| 32 |
+
self.server.load += 0.1
|
| 33 |
+
|
| 34 |
+
def score(self) -> float:
|
| 35 |
+
if self.task_name == "task_1":
|
| 36 |
+
return grade_task_1(self.server)
|
| 37 |
+
elif self.task_name == "task_2":
|
| 38 |
+
return grade_task_2(self.server)
|
| 39 |
+
elif self.task_name == "task_3": # <--- Added grading route
|
| 40 |
+
return grade_task_3(self.server)
|
| 41 |
+
|
| 42 |
+
return 0.0
|
cyber_env/schemas.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
|
| 4 |
+
# --- Sub-components of the System State ---
|
| 5 |
+
|
| 6 |
+
class ProcessInfo(BaseModel):
|
| 7 |
+
pid: int = Field(description="Process ID")
|
| 8 |
+
name: str = Field(description="Name of the executable")
|
| 9 |
+
user: str = Field(description="User running the process (e.g., 'root', 'www-data')")
|
| 10 |
+
cpu_percent: float = Field(description="Current CPU usage percentage")
|
| 11 |
+
open_files: List[str] = Field(default_factory=list, description="Files currently opened by this process")
|
| 12 |
+
|
| 13 |
+
class NetworkConnection(BaseModel):
|
| 14 |
+
conn_id: str = Field(description="Unique connection identifier")
|
| 15 |
+
protocol: str = Field(description="TCP or UDP")
|
| 16 |
+
local_port: int = Field(description="Local port number")
|
| 17 |
+
remote_ip: str = Field(description="IP address of the remote connection")
|
| 18 |
+
remote_port: int = Field(description="Port of the remote connection")
|
| 19 |
+
state: str = Field(description="Connection state (e.g., 'ESTABLISHED', 'LISTEN', 'TIME_WAIT')")
|
| 20 |
+
associated_pid: Optional[int] = Field(None, description="PID of the process owning this connection, if any")
|
| 21 |
+
|
| 22 |
+
class LogEntry(BaseModel):
|
| 23 |
+
timestamp: str = Field(description="Time of the event")
|
| 24 |
+
source: str = Field(description="Log source (e.g., 'auth.log', 'syslog', 'apache2')")
|
| 25 |
+
message: str = Field(description="The actual log message content")
|
| 26 |
+
severity: str = Field(description="INFO, WARNING, ERROR, or CRITICAL")
|
| 27 |
+
|
| 28 |
+
# --- The Main State Model ---
|
| 29 |
+
|
| 30 |
+
class ServerState(BaseModel):
|
| 31 |
+
"""The complete observable state of the simulated Linux server."""
|
| 32 |
+
system_load: float = Field(description="Overall system CPU load (0.0 to 100.0)")
|
| 33 |
+
active_processes: List[ProcessInfo] = Field(description="List of currently running processes")
|
| 34 |
+
network_connections: List[NetworkConnection] = Field(description="List of active network connections")
|
| 35 |
+
recent_logs: List[LogEntry] = Field(description="Last 50 lines of system logs")
|
| 36 |
+
blocked_ips: List[str] = Field(default_factory=list, description="List of currently blocked IP addresses via firewall")
|
| 37 |
+
|
| 38 |
+
from typing import Literal, Union
|
| 39 |
+
|
| 40 |
+
class KillProcessAction(BaseModel):
|
| 41 |
+
action_type: Literal["kill_process"] = "kill_process"
|
| 42 |
+
pid: int = Field(description="The PID of the process to terminate")
|
| 43 |
+
|
| 44 |
+
class BlockIPAction(BaseModel):
|
| 45 |
+
action_type: Literal["block_ip"] = "block_ip"
|
| 46 |
+
ip_address: str = Field(description="The IP address to drop at the firewall")
|
| 47 |
+
|
| 48 |
+
class DeleteFileAction(BaseModel):
|
| 49 |
+
action_type: Literal["delete_file"] = "delete_file"
|
| 50 |
+
filepath: str = Field(description="The absolute path of the file to remove")
|
| 51 |
+
|
| 52 |
+
class RestartServiceAction(BaseModel):
|
| 53 |
+
action_type: Literal["restart_service"] = "restart_service"
|
| 54 |
+
service_name: str = Field(description="Name of the service to restart (e.g., 'ssh', 'apache2')")
|
| 55 |
+
|
| 56 |
+
class WaitAction(BaseModel):
|
| 57 |
+
action_type: Literal["wait"] = "wait"
|
| 58 |
+
duration: int = Field(description="Seconds to wait before taking another action, useful for observing changes")
|
| 59 |
+
|
| 60 |
+
# The unified Action type that the OpenEnv will accept
|
| 61 |
+
AgentAction = Union[
|
| 62 |
+
KillProcessAction,
|
| 63 |
+
BlockIPAction,
|
| 64 |
+
DeleteFileAction,
|
| 65 |
+
RestartServiceAction,
|
| 66 |
+
WaitAction
|
| 67 |
+
]
|
cyber_env/simulator.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .schemas import ServerState, ProcessInfo, LogEntry, NetworkConnection
|
| 2 |
+
|
| 3 |
+
class SimulatedServer:
|
| 4 |
+
def __init__(self):
|
| 5 |
+
self.load = 10.0
|
| 6 |
+
self.processes = []
|
| 7 |
+
self.connections = []
|
| 8 |
+
self.logs = []
|
| 9 |
+
self.firewall_blocks = []
|
| 10 |
+
self.filesystem = [] # <--- NEW: Mock filesystem to track files
|
| 11 |
+
|
| 12 |
+
def get_state(self) -> ServerState:
|
| 13 |
+
return ServerState(
|
| 14 |
+
system_load=self.load,
|
| 15 |
+
active_processes=self.processes,
|
| 16 |
+
network_connections=self.connections,
|
| 17 |
+
recent_logs=self.logs[-50:],
|
| 18 |
+
blocked_ips=self.firewall_blocks
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
def kill_process(self, pid: int):
|
| 22 |
+
self.processes = [p for p in self.processes if p.pid != pid]
|
| 23 |
+
self.logs.append(LogEntry(timestamp="now", source="kernel", message=f"Killed PID {pid}", severity="INFO"))
|
| 24 |
+
|
| 25 |
+
def block_ip(self, ip: str):
|
| 26 |
+
self.firewall_blocks.append(ip)
|
| 27 |
+
self.connections = [c for c in self.connections if c.remote_ip != ip]
|
| 28 |
+
|
| 29 |
+
# --- NEW METHOD ADDED BELOW ---
|
| 30 |
+
def delete_file(self, filepath: str):
|
| 31 |
+
if filepath in self.filesystem:
|
| 32 |
+
self.filesystem.remove(filepath)
|
| 33 |
+
self.logs.append(LogEntry(timestamp="now", source="kernel", message=f"Deleted file {filepath}", severity="INFO"))
|
cyber_env/tasks.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .simulator import SimulatedServer
|
| 2 |
+
|
| 3 |
+
# --- TASK 1: EASY (SSH Brute Force) ---
|
| 4 |
+
def setup_task_1(server: SimulatedServer):
|
| 5 |
+
# Inject normal logs + malicious SSH logs
|
| 6 |
+
server.logs.append({"timestamp": "10:00", "source": "sshd", "message": "Failed password for root from 192.168.1.100", "severity": "WARNING"})
|
| 7 |
+
server.logs.append({"timestamp": "10:01", "source": "sshd", "message": "Failed password for root from 192.168.1.100", "severity": "WARNING"})
|
| 8 |
+
|
| 9 |
+
def grade_task_1(server: SimulatedServer) -> float:
|
| 10 |
+
# Did they block the bad IP?
|
| 11 |
+
if "192.168.1.100" in server.firewall_blocks:
|
| 12 |
+
return 1.0
|
| 13 |
+
return 0.0
|
| 14 |
+
|
| 15 |
+
# (Repeat for Task 2 and Task 3, writing setup and grade functions)
|
| 16 |
+
|
| 17 |
+
from .simulator import SimulatedServer
|
| 18 |
+
from .schemas import ProcessInfo, NetworkConnection
|
| 19 |
+
|
| 20 |
+
# --- TASK 2: MEDIUM (Cryptominer Eradication) ---
|
| 21 |
+
|
| 22 |
+
def setup_task_2(server: SimulatedServer):
|
| 23 |
+
# 1. Inject a malicious process eating 99% CPU
|
| 24 |
+
miner_pid = 31337
|
| 25 |
+
server.processes.append(
|
| 26 |
+
ProcessInfo(
|
| 27 |
+
pid=miner_pid,
|
| 28 |
+
name="systemd-update", # Hiding in plain sight
|
| 29 |
+
user="www-data",
|
| 30 |
+
cpu_percent=99.5,
|
| 31 |
+
open_files=["/tmp/.hidden_miner"]
|
| 32 |
+
)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# 2. Inject the command-and-control network connection
|
| 36 |
+
server.connections.append(
|
| 37 |
+
NetworkConnection(
|
| 38 |
+
conn_id="tcp_554",
|
| 39 |
+
protocol="TCP",
|
| 40 |
+
local_port=44532,
|
| 41 |
+
remote_ip="203.0.113.50",
|
| 42 |
+
remote_port=3333,
|
| 43 |
+
state="ESTABLISHED",
|
| 44 |
+
associated_pid=miner_pid
|
| 45 |
+
)
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Push system load to critical
|
| 49 |
+
server.load = 99.9
|
| 50 |
+
|
| 51 |
+
def grade_task_2(server: SimulatedServer) -> float:
|
| 52 |
+
score = 0.0
|
| 53 |
+
|
| 54 |
+
# Did they kill the process?
|
| 55 |
+
process_dead = not any(p.pid == 31337 for p in server.processes)
|
| 56 |
+
if process_dead:
|
| 57 |
+
score += 0.4
|
| 58 |
+
|
| 59 |
+
# Did they block the mining pool IP?
|
| 60 |
+
if "203.0.113.50" in server.firewall_blocks:
|
| 61 |
+
score += 0.6
|
| 62 |
+
|
| 63 |
+
return score
|
| 64 |
+
|
| 65 |
+
# --- TASK 3: HARD (APT Backdoor) ---
|
| 66 |
+
|
| 67 |
+
def setup_task_3(server: SimulatedServer):
|
| 68 |
+
# The attacker dropped a script
|
| 69 |
+
server.filesystem.append("/var/tmp/revshell.sh")
|
| 70 |
+
|
| 71 |
+
# It executes via a hidden cron job, leaving a clue in the logs
|
| 72 |
+
server.logs.append(
|
| 73 |
+
{"timestamp": "03:00", "source": "CRON", "message": "CMD (/var/tmp/revshell.sh)", "severity": "INFO"}
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# The active reverse shell process
|
| 77 |
+
apt_pid = 1337
|
| 78 |
+
server.processes.append(
|
| 79 |
+
ProcessInfo(
|
| 80 |
+
pid=apt_pid,
|
| 81 |
+
name="bash",
|
| 82 |
+
user="www-data",
|
| 83 |
+
cpu_percent=0.1, # Sneaky, low CPU
|
| 84 |
+
open_files=["/var/tmp/revshell.sh"]
|
| 85 |
+
)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# The active connection back to the attacker's machine
|
| 89 |
+
server.connections.append(
|
| 90 |
+
NetworkConnection(
|
| 91 |
+
conn_id="tcp_999",
|
| 92 |
+
protocol="TCP",
|
| 93 |
+
local_port=54321,
|
| 94 |
+
remote_ip="198.51.100.99",
|
| 95 |
+
remote_port=4444,
|
| 96 |
+
state="ESTABLISHED",
|
| 97 |
+
associated_pid=apt_pid
|
| 98 |
+
)
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def grade_task_3(server: SimulatedServer) -> float:
|
| 102 |
+
score = 0.0
|
| 103 |
+
|
| 104 |
+
# 1. Did they kill the reverse shell?
|
| 105 |
+
if not any(p.pid == 1337 for p in server.processes):
|
| 106 |
+
score += 0.3
|
| 107 |
+
|
| 108 |
+
# 2. Did they block the attacker's IP?
|
| 109 |
+
if "198.51.100.99" in server.firewall_blocks:
|
| 110 |
+
score += 0.3
|
| 111 |
+
|
| 112 |
+
# 3. Did they delete the malicious script?
|
| 113 |
+
if "/var/tmp/revshell.sh" not in server.filesystem:
|
| 114 |
+
score += 0.4
|
| 115 |
+
|
| 116 |
+
return score
|
evaluate.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from cyber_env.env import CyberDefenseEnv
|
| 2 |
+
from cyber_env.schemas import BlockIPAction
|
| 3 |
+
|
| 4 |
+
# Initialize the env
|
| 5 |
+
env = CyberDefenseEnv(task_name="task_1")
|
| 6 |
+
|
| 7 |
+
# Show initial state
|
| 8 |
+
print("Initial Logs:", env.state().recent_logs)
|
| 9 |
+
|
| 10 |
+
# Agent decides to act (Hardcoded baseline for demonstration)
|
| 11 |
+
action = BlockIPAction(ip_address="192.168.1.100")
|
| 12 |
+
env.step(action)
|
| 13 |
+
|
| 14 |
+
# Print Final Score
|
| 15 |
+
print("Final Score:", env.score()) # Should print 1.0
|
evaluate_agent.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from pydantic import ValidationError
|
| 5 |
+
|
| 6 |
+
# Import your environment and schemas
|
| 7 |
+
from cyber_env.env import CyberDefenseEnv
|
| 8 |
+
from cyber_env.schemas import (
|
| 9 |
+
KillProcessAction, BlockIPAction, DeleteFileAction,
|
| 10 |
+
RestartServiceAction, WaitAction
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
# Initialize the LLM Client using the Gemini API compatibility endpoint
|
| 14 |
+
# Replace this entire block
|
| 15 |
+
client = OpenAI(
|
| 16 |
+
api_key="AIzaSyCDT5wyz0jXUEDTSERIVoI1SftT8Pv7ReQ", # <--- Hardcoded here!
|
| 17 |
+
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# Define the models we want the LLM to know about
|
| 21 |
+
AVAILABLE_ACTIONS = {
|
| 22 |
+
"kill_process": KillProcessAction.model_json_schema(),
|
| 23 |
+
"block_ip": BlockIPAction.model_json_schema(),
|
| 24 |
+
"delete_file": DeleteFileAction.model_json_schema(),
|
| 25 |
+
"restart_service": RestartServiceAction.model_json_schema(),
|
| 26 |
+
"wait": WaitAction.model_json_schema()
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
def run_autonomous_agent(task_name: str, max_steps: int = 5):
|
| 30 |
+
print(f"\nStarting Autonomous Evaluation for {task_name.upper()}...")
|
| 31 |
+
env = CyberDefenseEnv(task_name=task_name)
|
| 32 |
+
|
| 33 |
+
# The System Prompt tells the LLM how to behave and what its constraints are
|
| 34 |
+
system_prompt = f"""
|
| 35 |
+
You are an autonomous Security Operations Center (SOC) agent.
|
| 36 |
+
Your goal is to neutralize cyber threats on a Linux server without breaking legitimate services.
|
| 37 |
+
|
| 38 |
+
You will be provided with the current ServerState in JSON format.
|
| 39 |
+
Analyze the processes, connections, and logs to identify threats.
|
| 40 |
+
|
| 41 |
+
You MUST respond with a SINGLE valid JSON object representing your chosen action.
|
| 42 |
+
Do NOT include markdown formatting, backticks, or conversational text. Just the JSON.
|
| 43 |
+
|
| 44 |
+
Here are the JSON schemas for the actions you are allowed to take:
|
| 45 |
+
{json.dumps(AVAILABLE_ACTIONS, indent=2)}
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
for step in range(max_steps):
|
| 49 |
+
print(f"\n--- Step {step + 1} ---")
|
| 50 |
+
|
| 51 |
+
# 1. Observe the State
|
| 52 |
+
current_state = env.state()
|
| 53 |
+
state_json = current_state.model_dump_json(indent=2)
|
| 54 |
+
print(f"Server Load: {current_state.system_load}% | Score: {env.score()}")
|
| 55 |
+
|
| 56 |
+
# Check for early win
|
| 57 |
+
if env.score() >= 1.0:
|
| 58 |
+
print("Threat completely neutralized! Agent wins.")
|
| 59 |
+
break
|
| 60 |
+
|
| 61 |
+
# 2. Prompt the LLM
|
| 62 |
+
print("Agent is thinking...")
|
| 63 |
+
try:
|
| 64 |
+
response = client.chat.completions.create(
|
| 65 |
+
model="gemini-2.5-flash", # Using the fast, reasoning-optimized Gemini model
|
| 66 |
+
messages=[
|
| 67 |
+
{"role": "system", "content": system_prompt},
|
| 68 |
+
{"role": "user", "content": f"CURRENT STATE:\n{state_json}\n\nWhat is your next action (output raw JSON)?"}
|
| 69 |
+
],
|
| 70 |
+
temperature=0.1 # Low temperature for logical, deterministic choices
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Extract the JSON string from the LLM's response
|
| 74 |
+
llm_output = response.choices[0].message.content.strip()
|
| 75 |
+
|
| 76 |
+
# Clean up markdown if the LLM hallucinated it despite instructions
|
| 77 |
+
if llm_output.startswith("```json"):
|
| 78 |
+
llm_output = llm_output[7:-3].strip()
|
| 79 |
+
elif llm_output.startswith("```"):
|
| 80 |
+
llm_output = llm_output[3:-3].strip()
|
| 81 |
+
|
| 82 |
+
action_dict = json.loads(llm_output)
|
| 83 |
+
print(f"Agent Decided: {json.dumps(action_dict)}")
|
| 84 |
+
|
| 85 |
+
# 3. Validate and Act
|
| 86 |
+
action_type = action_dict.get("action_type")
|
| 87 |
+
|
| 88 |
+
if action_type == "kill_process":
|
| 89 |
+
action = KillProcessAction(**action_dict)
|
| 90 |
+
elif action_type == "block_ip":
|
| 91 |
+
action = BlockIPAction(**action_dict)
|
| 92 |
+
elif action_type == "delete_file":
|
| 93 |
+
action = DeleteFileAction(**action_dict)
|
| 94 |
+
elif action_type == "restart_service":
|
| 95 |
+
action = RestartServiceAction(**action_dict)
|
| 96 |
+
elif action_type == "wait":
|
| 97 |
+
action = WaitAction(**action_dict)
|
| 98 |
+
else:
|
| 99 |
+
print(f"LLM chose an invalid action type: {action_type}")
|
| 100 |
+
env.step(WaitAction(duration=5))
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
# Execute the validated Pydantic action in the environment
|
| 104 |
+
env.step(action)
|
| 105 |
+
|
| 106 |
+
except json.JSONDecodeError:
|
| 107 |
+
print(f"Agent failed to output valid JSON. Raw output: {llm_output}")
|
| 108 |
+
env.step(WaitAction(duration=5)) # Penalty wait
|
| 109 |
+
except ValidationError as e:
|
| 110 |
+
print(f"Agent output invalid parameters for the action: {e}")
|
| 111 |
+
env.step(WaitAction(duration=5)) # Penalty wait
|
| 112 |
+
|
| 113 |
+
print(f"\nFinal Evaluation Score for {task_name}: {env.score()}")
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
print("Bypassing environment checks, using hardcoded API key...")
|
| 117 |
+
|
| 118 |
+
# Run the agent against Task 1
|
| 119 |
+
run_autonomous_agent(task_name="task_1", max_steps=3)
|
| 120 |
+
|
| 121 |
+
# Uncomment to run against the harder tasks later:
|
| 122 |
+
run_autonomous_agent(task_name="task_2", max_steps=5)
|
| 123 |
+
run_autonomous_agent(task_name="task_3", max_steps=8)
|
openenv.yaml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "CyberDefenseEnv"
|
| 2 |
+
description: "A simulated SOC environment where an agent mitigates cyber attacks."
|
| 3 |
+
version: "1.0.0"
|
| 4 |
+
entrypoint: "cyber_env.env:CyberDefenseEnv" # Format: module.file:ClassName
|
| 5 |
+
tasks:
|
| 6 |
+
- name: "task_1"
|
| 7 |
+
description: "Mitigate an SSH Brute Force attack."
|
| 8 |
+
- name: "task_2"
|
| 9 |
+
description: "Eradicate a hidden cryptominer."
|
| 10 |
+
- name: "task_3"
|
| 11 |
+
description: "Dismantle an APT backdoor."
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core Framework
|
| 2 |
+
openenv
|
| 3 |
+
|
| 4 |
+
# Data validation and typed models (Required by OpenEnv spec)
|
| 5 |
+
pydantic>=2.0.0
|
| 6 |
+
|
| 7 |
+
# Optional: If you plan to build a baseline LLM agent in evaluate.py
|
| 8 |
+
# that calls an API (like Groq, OpenAI, or Anthropic)
|
| 9 |
+
# requests
|
| 10 |
+
|
| 11 |
+
openai
|