# API Reference: Velociraptor Incident Response Collection

## Libraries Used

| Library | Purpose |
|---------|---------|
| `pyvelociraptor` | Official Python bindings for Velociraptor gRPC API |
| `grpc` | gRPC transport for API communication |
| `json` | Parse VQL query results |
| `yaml` | Read Velociraptor API config files |

## Installation

```bash
pip install pyvelociraptor grpcio pyyaml
```

## Authentication

Velociraptor uses mTLS with an API config file generated by the server:

```python
import pyvelociraptor
import json
import os

# Generate API config on the Velociraptor server:
# velociraptor config api_client --name analyst > api_client.yaml

config_path = os.environ.get("VELOCIRAPTOR_API_CONFIG", "api_client.yaml")
```

## gRPC API — Query Method

The primary API method is `Query()`, which executes VQL (Velociraptor Query Language) statements:

```python
import pyvelociraptor
import json

def run_vql(config_path, query):
    config = pyvelociraptor.LoadConfigFile(config_path)
    grpc_channel = pyvelociraptor.grpc_channel(config)
    stub = pyvelociraptor.api_pb2_grpc.APIStub(grpc_channel)

    request = pyvelociraptor.api_pb2.VQLCollectorArgs(
        max_wait=10,
        max_row=1000,
        Query=[pyvelociraptor.api_pb2.VQLRequest(
            VQL=query,
        )],
    )

    results = []
    for response in stub.Query(request):
        if response.Response:
            rows = json.loads(response.Response)
            results.extend(rows)
    return results
```

## Common VQL Queries

### List Connected Clients
```python
clients = run_vql(config_path, """
    SELECT client_id, os_info.hostname as hostname,
           os_info.system as os, last_seen_at
    FROM clients()
    WHERE last_seen_at > now() - 3600
""")
```

### Collect Artifacts from an Endpoint
```python
# Start a collection (hunt) on a specific client
collection = run_vql(config_path, """
    SELECT collect_client(
        client_id='C.abc123def456',
        artifacts=['Windows.KapeFiles.Targets'],
        parameters=dict(Device='C:', VSSAnalysis='Y')
    ) FROM scope()
""")
flow_id = collection[0]["collect_client"]["flow_id"]
```

### Monitor Collection Status
```python
status = run_vql(config_path, f"""
    SELECT * FROM flows(client_id='C.abc123def456')
    WHERE session_id = '{flow_id}'
""")
# Fields: state, create_time, total_collected_rows, total_uploaded_bytes
```

### Retrieve Flow Results
```python
results = run_vql(config_path, f"""
    SELECT * FROM flow_results(
        client_id='C.abc123def456',
        flow_id='{flow_id}',
        artifact='Windows.KapeFiles.Targets'
    )
""")
```

### Hunt Across All Clients
```python
hunt = run_vql(config_path, """
    SELECT hunt(
        description='Search for suspicious scheduled tasks',
        artifacts=['Windows.System.TaskScheduler'],
        parameters=dict()
    ) FROM scope()
""")
hunt_id = hunt[0]["hunt"]["hunt_id"]
```

### Search for IOCs Across Fleet
```python
ioc_results = run_vql(config_path, """
    SELECT * FROM hunt_results(hunt_id='H.abc123')
    WHERE OSPath =~ 'mimikatz|lazagne|rubeus'
""")
```

## Key VQL Functions

| Function | Purpose |
|----------|---------|
| `clients()` | List all enrolled clients |
| `collect_client()` | Start artifact collection on endpoint |
| `flows()` | List collection flows for a client |
| `flow_results()` | Get results from a completed flow |
| `hunt()` | Create a new hunt across clients |
| `hunt_results()` | Get results from a hunt |
| `artifact_definitions()` | List available artifacts |
| `source()` | Read server-side event log data |
| `upload()` | Upload files from endpoint to server |

## Built-in Artifact Categories

| Category | Examples |
|----------|----------|
| Windows Triage | `Windows.KapeFiles.Targets`, `Windows.EventLogs.Evtx` |
| Process Forensics | `Windows.System.Pslist`, `Generic.System.Pstree` |
| Persistence | `Windows.Persistence.PermanentWMIEvents`, `Windows.System.TaskScheduler` |
| Network | `Windows.Network.Netstat`, `Windows.Network.ArpCache` |
| Memory | `Windows.Detection.Yara.Process`, `Windows.System.VAD` |
| Linux | `Linux.Sys.Users`, `Linux.Search.FileFinder` |
| macOS | `MacOS.System.Users`, `MacOS.Applications.Chrome.History` |

## Output Format

```json
{
  "client_id": "C.abc123def456",
  "hostname": "WORKSTATION-01",
  "os": "windows",
  "flow_id": "F.xyz789",
  "state": "FINISHED",
  "artifacts_collected": ["Windows.KapeFiles.Targets"],
  "total_collected_rows": 1542,
  "total_uploaded_bytes": 52428800,
  "create_time": "2025-01-15T10:30:00Z"
}
```
