

Topic: Amazon says hackers' AI agents found and exploited 0-day with minimal human input
Focus: Building defensive AI agents for vulnerability detection, log analysis, and automated threat response
| Service | Purpose | Required Tier |
|---|---|---|
| GitHub | Code hosting, GitHub Advanced Security (CodeQL) | Free / Enterprise |
| AWS / GCP / Azure | Cloud infrastructure for scanning workloads | Free tier + |
| OpenAI / Anthropic / Local LLM | LLM inference for AI agents | API credits |
| Docker Hub / GHCR | Container registry for agent images | Free |
| Snyk / Semgrep / Trivy | SAST/SCA scanning engines | Free tier |
| Elasticsearch / OpenSearch | Log aggregation & analysis | Self-hosted or Cloud |
| PagerDuty / Opsgenie | Alerting & on-call | Free tier |
# Minimum versions
python >= 3.11
node >= 20.x
docker >= 24.x
kubectl >= 1.28 (for K8s deployment)
# Install core tools
brew install \
python@3.11 node@20 docker \
kubectl helm terraform \
semgrep trivy grype syft \
jq yq httpie
# Python package manager
pip install --upgrade pip uv poetry
# Node package manager
corepack enable
corepack prepare pnpm@latest --activate
mkdir -p icarax-ai-security/{agents,scanners,api,config,tests,infra}
cd icarax-ai-security
# Create virtual environment
python -m venv .venv
source .venv/bin/activate
# Install dependencies with uv (faster than pip)
uv pip install \
langchain langgraph langchain-openai langchain-anthropic \
pydantic pydantic-settings python-dotenv \
fastapi uvicorn[standard] httpx \
elasticsearch opensearch-py \
prometheus-client structlog \
pytest pytest-asyncio pytest-cov \
bandit safety pip-audit \
ruff mypy pre-commit
# Install security scanners
uv pip install semgrep trivy grype syft
# Initialize project
pnpm init -y
# Install dependencies
pnpm add \
@langchain/langgraph @langchain/openai @langchain/anthropic \
fastify @fastify/helmet @fastify/cors @fastify/rate-limit \
zod pino pino-pretty \
@elastic/elasticsearch @opensearch-project/opensearch \
prom-client \
dotenv
# Dev dependencies
pnpm add -D \
typescript tsx @types/node \
vitest @vitest/coverage-v8 \
eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser \
prettier husky lint-staged
pyproject.toml (Python)
[project]
name = "icarax-ai-security"
version = "0.1.0"
description = "AI-driven security research agents for ICARAX"
requires-python = ">=3.11"
dependencies = [
"langchain>=0.1.0",
"langgraph>=0.0.30",
"langchain-openai>=0.0.5",
"langchain-anthropic>=0.1.0",
"pydantic>=2.5",
"pydantic-settings>=2.1",
"python-dotenv>=1.0",
"fastapi>=0.104",
"uvicorn[standard]>=0.24",
"httpx>=0.25",
"elasticsearch>=8.11",
"opensearch-py>=2.4",
"prometheus-client>=0.19",
"structlog>=24.1",
]
[tool.ruff]
line-length = 100
target-version = "py311"
select = ["E", "F", "I", "UP", "B", "C4", "SIM", "T20", "W", "ARG", "PTH", "ERA", "PL", "TRY"]
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
package.json (TypeScript)
{
"name": "icarax-ai-security",
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "vitest run --coverage",
"lint": "eslint src --ext .ts",
"format": "prettier --write \"src/**/*.ts\""
},
"dependencies": {
"@langchain/langgraph": "^0.0.30",
"@langchain/openai": "^0.0.14",
"@langchain/anthropic": "^0.1.0",
"fastify": "^4.27",
"@fastify/helmet": "^11.1",
"@fastify/cors": "^9.0",
"@fastify/rate-limit": "^9.1",
"zod": "^3.22",
"pino": "^9.0",
"pino-pretty": "^11.0",
"@elastic/elasticsearch": "^8.11",
"@opensearch-project/opensearch": "^2.4",
"prom-client": "^15.1",
"dotenv": "^16.4"
},
"devDependencies": {
"typescript": "^5.4",
"tsx": "^4.7",
"@types/node": "^20.12",
"vitest": "^1.4",
"@vitest/coverage-v8": "^1.4",
"eslint": "^8.57",
"@typescript-eslint/eslint-plugin": "^7.0",
"@typescript-eslint/parser": "^7.0",
"prettier": "^3.2",
"husky": "^9.0",
"lint-staged": "^15.2"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
config/schemas.py (Python)
"""Shared Pydantic schemas for AI security agents."""
from __future__ import annotations
from datetime import datetime
from enum import Enum
from typing import Any, Optional
from pydantic import BaseModel, Field, HttpUrl
from uuid import UUID, uuid4
class Severity(str, Enum):
"""Vulnerability severity levels (CVSS-aligned)."""
CRITICAL = "critical"
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
INFO = "info"
class VulnerabilityType(str, Enum):
"""Classification of vulnerability types."""
RCE = "remote_code_execution"
SQLI = "sql_injection"
XSS = "cross_site_scripting"
SSRF = "server_side_request_forgery"
AUTH_BYPASS = "authentication_bypass"
PRIV_ESCALATION = "privilege_escalation"
DATA_EXPOSURE = "data_exposure"
LOGIC_FLAW = "business_logic_flaw"
SUPPLY_CHAIN = "supply_chain"
ZERO_DAY = "zero_day"
class ScanTarget(BaseModel):
"""Target for security scanning."""
id: UUID = Field(default_factory=uuid4)
name: str
type: str # "web", "api", "container", "k8s", "code", "dependency"
url: Optional[HttpUrl] = None
path: Optional[str] = None
metadata: dict[str, Any] = Field(default_factory=dict)
class Finding(BaseModel):
"""Security finding from AI agent analysis."""
id: UUID = Field(default_factory=uuid4)
target_id: UUID
title: str
description: str
severity: Severity
vuln_type: VulnerabilityType
cve_ids: list[str] = Field(default_factory=list)
cwe_ids: list[str] = Field(default_factory=list)
cvss_score: Optional[float] = None
cvss_vector: Optional[str] = None
evidence: dict[str, Any] = Field(default_factory=dict)
remediation: Optional[str] = None
references: list[str] = Field(default_factory=list)
discovered_at: datetime = Field(default_factory=datetime.utcnow)
discovered_by: str # agent name
confidence: float = Field(ge=0.0, le=1.0, default=0.8)
false_positive: bool = False
status: str = "open" # open, triaged, fixed, wont_fix
class AgentState(BaseModel):
"""State passed between agent nodes in LangGraph."""
target: ScanTarget
findings: list[Finding] = Field(default_factory=list)
logs: list[dict] = Field(default_factory=list)
errors: list[str] = Field(default_factory=list)
metadata: dict[str, Any] = Field(default_factory=dict)
current_step: str = "initialized"
iteration: int = 0
max_iterations: int = 10
# TypeScript equivalent in config/schemas.ts
config/schemas.ts (TypeScript)
// Shared Zod schemas for type safety across TS/Python
import { z } from "zod";
export const SeverityEnum = z.enum(["critical", "high", "medium", "low", "info"]);
export type Severity = z.infer<typeof SeverityEnum>;
export const VulnTypeEnum = z.enum([
"remote_code_execution",
"sql_injection",
"cross_site_scripting",
"server_side_request_forgery",
"authentication_bypass",
"privilege_escalation",
"data_exposure",
"business_logic_flaw",
"supply_chain",
"zero_day"
]);
export type VulnerabilityType = z.infer<typeof VulnTypeEnum>;
export const ScanTargetSchema = z.object({
id: z.string().uuid(),
name: z.string(),
type: z.enum(["web", "api", "container", "k8s", "code", "dependency"]),
url: z.string().url().optional(),
path: z.string().optional(),
metadata: z.record(z.unknown()).default({}),
});
export type ScanTarget = z.infer<typeof ScanTargetSchema>;
export const FindingSchema = z.object({
id: z.string().uuid(),
targetId: z.string().uuid(),
title: z.string(),
description: z.string(),
severity: SeverityEnum,
vulnType: VulnTypeEnum,
cveIds: z.array(z.string()).default([]),
cweIds: z.array(z.string()).default([]),
cvssScore: z.number().min(0).max(10).optional(),
cvssVector: z.string().optional(),
evidence: z.record(z.unknown()).default({}),
remediation: z.string().optional(),
references: z.array(z.string().url()).default([]),
discoveredAt: z.string().datetime(),
discoveredBy: z.string(),
confidence: z.number().min(0).max(1).default(0.8),
falsePositive: z.boolean().default(false),
status: z.enum(["open", "triaged", "fixed", "wont_fix"]).default("open"),
});
export type Finding = z.infer<typeof FindingSchema>;
export const AgentStateSchema = z.object({
target: ScanTargetSchema,
findings: z.array(FindingSchema).default([]),
logs: z.array(z.record(z.unknown())).default([]),
errors: z.array(z.string()).default([]),
metadata: z.record(z.unknown()).default({}),
currentStep: z.string().default("initialized"),
iteration: z.number().int().default(0),
maxIterations: z.number().int().default(10),
});
export type AgentState = z.infer<typeof AgentStateSchema>;
agents/base_agent.py
"""Base agent class for all security AI agents."""
from __future__ import annotations
import asyncio
import json
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Any, AsyncGenerator
from uuid import uuid4
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph, END
from pydantic import BaseModel, Field
from config.schemas import AgentState, Finding, ScanTarget, Severity, VulnerabilityType
logger = logging.getLogger(__name__)
class BaseSecurityAgent(ABC):
"""Abstract base class for security analysis agents."""
name: str = "base_agent"
description: str = "Base security analysis agent"
version: str = "1.0.0"
def __init__(
self,
llm: BaseChatModel,
config: dict[str, Any] | None = None,
):
self.llm = llm
self.config = config or {}
self.graph = self._build_graph()
@abstractmethod
def _build_graph(self) -> StateGraph:
"""Build the LangGraph state machine for this agent."""
pass
@abstractmethod
async def analyze(self, state: AgentState) -> AgentState:
"""Main analysis logic - implemented by subclasses."""
pass
async def run(self, target: ScanTarget, max_iterations: int = 10) -> AgentState:
"""Execute the agent on a scan target."""
initial_state = AgentState(
target=target,
max_iterations=max_iterations,
metadata={
"agent": self.name,
"version": self.version,
"started_at": datetime.utcnow().isoformat(),
}
)
logger.info(f"[{self.name}] Starting analysis for target: {target.name}")
try:
# Run the graph
config = RunnableConfig(
configurable={"thread_id": str(uuid4())},
recursion_limit=max_iterations + 5,
)
final_state = await self.graph.ainvoke(initial_state, config=config)
return AgentState(**final_state)
except Exception as e:
logger.exception(f"[{self.name}] Analysis failed: {e}")
initial_state.errors.append(f"Agent execution failed: {str(e)}")
return initial_state
def _create_finding(
self,
target_id: str,
title: str,
description: str,
severity: Severity,
vuln_type: VulnerabilityType,
evidence: dict[str, Any],
confidence: float = 0.8,
remediation: str | None = None,
cve_ids: list[str] | None = None,
cwe_ids: list[str] | None = None,
) -> Finding:
"""Helper to create a standardized finding."""
return Finding(
target_id=target_id,
title=title,
description=description,
severity=severity,
vuln_type=vuln_type,
evidence=evidence,
confidence=confidence,
remediation=remediation,
cve_ids=cve_ids or [],
cwe_ids=cwe_ids or [],
discovered_by=self.name,
)
def _log_step(self, state: AgentState, step: str, details: dict | None = None) -> None:
"""Log agent step for audit trail."""
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"agent": self.name,
"step": step,
"iteration": state.iteration,
"details": details or {},
}
state.logs.append(log_entry)
logger.debug(f"[{self.name}] {step}: {details}")
class LLMAgentMixin:
"""Mixin providing common LLM interaction patterns."""
async def _llm_structured_output(
self,
system_prompt: str,
user_prompt: str,
output_schema: type[BaseModel],
temperature: float = 0.1,
) -> BaseModel:
"""Get structured output from LLM with schema validation."""
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_prompt),
]
# Use structured output if supported
if hasattr(self.llm, "with_structured_output"):
structured_llm = self.llm.with_structured_output(output_schema)
return await structured_llm.ainvoke(messages)
# Fallback: parse JSON from response
response = await self.llm.ainvoke(messages, temperature=temperature)
try:
return output_schema.model_validate_json(response.content)
except Exception as e:
logger.warning(f"Failed to parse structured output: {e}")
# Try to extract JSON from markdown code blocks
content = response.content
if "```json" in content:
content = content.split("```json")[1].split("```")[0]
elif "```" in content:
content = content.split("```")[1].split("```")[0]
return output_schema.model_validate_json(content)
async def _llm_reasoning(
self,
system_prompt: str,
user_prompt: str,
temperature: float = 0.3,
) -> str:
"""Get free-form reasoning from LLM."""
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_prompt),
]
response = await self.llm.ainvoke(messages, temperature=temperature)
return response.content
agents/vuln_scanner_agent.py
"""AI agent for automated vulnerability scanning and analysis."""
from __future__ import annotations
import asyncio
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Any
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph, END
from pydantic import BaseModel, Field
from agents.base_agent import BaseSecurityAgent, LLMAgentMixin
from config.schemas import (
AgentState, Finding, ScanTarget, Severity, VulnerabilityType
)
class ScanResult(BaseModel):
"""Structured output for scan analysis."""
vulnerabilities: list[dict[str, Any]] = Field(default_factory=list)
summary: str = ""
risk_score: float = Field(ge=0.0, le=10.0, default=0.0)
class VulnScannerAgent(BaseSecurityAgent, LLMAgentMixin):
"""Agent that runs security scanners and analyzes results with AI."""
name = "vuln_scanner"
description = "Runs SAST/SCA/container scans and analyzes findings with AI"
version = "1.0.0"
SCANNERS = {
"code": ["semgrep", "bandit"],
"dependency": ["pip-audit", "safety", "npm audit"],
"container": ["trivy", "grype"],
"k8s": ["kube-hunter", "kubeaudit"],
}
def _build_graph(self) -> StateGraph:
"""Build the vulnerability scanning workflow."""
workflow = StateGraph(AgentState)
# Nodes
workflow.add_node("prepare_target", self._prepare_target)
workflow.add_node("run_scanners", self._run_scanners)
workflow.add_node("analyze_results", self._analyze_results)
workflow.add_node("enrich_findings", self._enrich_findings)
workflow.add_node("deduplicate", self._deduplicate_findings)
workflow.add_node("finalize", self._finalize)
# Edges
workflow.set_entry_point("prepare_target")
workflow.add_edge("prepare_target", "run_scanners")
workflow.add_edge("run_scanners", "analyze_results")
workflow.add_edge("analyze_results", "enrich_findings")
workflow.add_edge("enrich_findings", "deduplicate")
workflow.add_edge("deduplicate", "finalize")
workflow.add_edge("finalize", END)
return workflow.compile()
async def _prepare_target(self, state: AgentState) -> AgentState:
"""Prepare target for scanning based on type."""
state.current_step = "prepare_target"
state.iteration += 1
self._log_step(state, "prepare_target", {"target_type": state.target.type})
target = state.target
# Validate target has required info
if target.type in ("web", "api") and not target.url:
state.errors.append(f"Target {target.name} requires URL for web/api scanning")
return state
if target.type in ("code", "container") and not target.path:
state.errors.append(f"Target {target.name} requires path for code/container scanning")
return state
# Set up scanner config based on target type
state.metadata["scanners"] = self.SCANNERS.get(target.type, ["semgrep"])
state.metadata["scan_path"] = target.path or str(target.url)
return state
async def _run_scanners(self, state: AgentState) -> AgentState:
"""Execute configured security scanners."""
state.current_step = "run_scanners"
self._log_step(state, "run_scanners", {"scanners": state.metadata.get("scanners", [])})
scan_path = state.metadata.get("scan_path")
if not scan_path:
state.errors.append("No scan path configured")
return state
results = {}
scanners = state.metadata.get("scanners", ["semgrep"])
for scanner in scanners:
try:
result = await self._run_scanner(scanner, scan_path, state.target.type)
results[scanner] = result
self._log_step(state, f"scanner_{scanner}", {"findings": len(result.get("vulns", []))})
except Exception as e:
state.errors.append(f"Scanner {scanner} failed: {str(e)}")
logger.exception(f"Scanner {scanner} error")
state.metadata["scan_results"] = results
return state
async def _run_scanner(self, scanner: str, path: str, target_type: str) -> dict:
"""Run a specific scanner and return parsed results."""
cmd_map = {
"semgrep": ["semgrep", "scan", "--json", "--config=auto", path],
"bandit": ["bandit", "-r", "-f", "json", path],
"pip-audit": ["pip-audit", "--format=json", path] if Path(path).name == "requirements.txt" else ["pip-audit", "--format=json"],
"safety": ["safety", "check", "--json", "-r", path] if Path(path).name == "requirements.txt" else ["safety", "check", "--json"],
"npm audit": ["npm", "audit", "--json"],
"trivy": ["trivy", "fs", "--format", "json", "--scanners", "vuln,secret,misconfig", path],
"grype": ["grype", "-o", "json", f"dir:{path}"],
"kube-hunter": ["kube-hunter", "--remote", "--report", "json"],
"kubeaudit": ["kubeaudit", "all", "-f", "json"],
}
cmd = cmd_map.get(scanner)
if not cmd:
return {"vulns": [], "error": f"Unknown scanner: {scanner}"}
try:
# Run with timeout
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=300)
if proc.returncode not in (0, 1): # 1 often means findings found
return {"vulns": [], "error": stderr.decode()}
return self._parse_scanner_output(scanner, stdout.decode())
except asyncio.TimeoutError:
return {"vulns": [], "error": f"Scanner {scanner} timed out"}
except FileNotFoundError:
return {"vulns": [], "error": f"Scanner {scanner} not installed"}
except Exception as e:
return {"vulns": [], "error": str(e)}
def _parse_scanner_output(self, scanner: str, output: str) -> dict:
"""Parse scanner JSON output into normalized format."""
try:
data = json.loads(output)
except json.JSONDecodeError:
return {"vulns": [], "error": "Invalid JSON output"}
vulns = []
if scanner == "semgrep":
for result in data.get("results", []):
vulns.append({
"scanner": "semgrep",
"rule_id": result.get("check_id"),
"message": result.get("extra", {}).get("message", ""),
"severity": result.get("extra", {}).get("severity", "medium").lower(),
"file": result.get("path"),
"line": result.get("start", {}).get("line"),
"code": result.get("extra", {}).get("lines", ""),
"metadata": result.get("extra", {}).get("metadata", {}),
})
elif scanner == "bandit":
for result in data.get("results", []):
vulns.append({
"scanner": "bandit",
"rule_id": result.get("test_id"),
"message": result.get("issue_text", ""),
"severity": result.get("issue_severity", "medium").lower(),
"file": result.get("filename"),
"line": result.get("line_number"),
"code": result.get("code", ""),
"confidence": result.get("issue_confidence", "medium").lower(),
})
elif scanner in ("trivy", "grype"):
for result in data.get("Results", data.get("matches", [])):
for vuln in result.get("Vulnerabilities", result.get("vulnerabilities", [])):
vulns.append({
"scanner": scanner,
"vuln_id": vuln.get("VulnerabilityID", vuln.get("id")),
"package": vuln.get("PkgName", vuln.get("artifact", {}).get("name")),
"version": vuln.get("InstalledVersion", vuln.get("artifact", {}).get("version")),
"severity": vuln.get("Severity", vuln.get("severity", "medium")).lower(),
"title": vuln.get("Title", vuln.get("description", "")),
"description": vuln.get("Description", ""),
"references": vuln.get("References", vuln.get("urls", [])),
})
elif scanner in ("pip-audit", "safety"):
for vuln in data.get("vulnerabilities", data):
vulns.append({
"scanner": scanner,
"package": vuln.get("package", vuln.get("name")),
"version": vuln.get("installed_version", vuln.get("version")),
"vuln_id": vuln.get("vulnerability_id", vuln.get("id")),
"severity": "high", # These tools don't always provide severity
"description": vuln.get("description", ""),
})
return {"vulns": vulns, "raw": data}
async def _analyze_results(self, state: AgentState) -> AgentState:
"""Use LLM to analyze and prioritize scan results."""
state.current_step = "analyze_results"
self._log_step(state, "analyze_results")
scan_results = state.metadata.get("scan_results", {})
all_vulns = []
for scanner, result in scan_results.items():
for vuln in result.get("vulns", []):
vuln["_scanner"] = scanner
all_vulns.append(vuln)
if not all_vulns:
state.metadata["analysis"] = "No vulnerabilities found by scanners"
return state
# Prepare context for LLM
vuln_summary = json.dumps(all_vulns[:50], indent=2) # Limit context
system_prompt = """You are a senior application security engineer. Analyze the scanner findings and:
1. Identify true positives vs false positives
2. Assess real-world exploitability
3. Prioritize by business risk
4. Suggest specific remediation steps
5. Identify potential 0-day patterns (unusual code patterns, novel bypasses)
Output structured JSON with: vulnerabilities (list), summary, risk_score (0-10)."""
user_prompt = f"""
Target: {state.target.name} (type: {state.target.type})
Scanner Results:
{vuln_summary}
Provide analysis as JSON matching the ScanResult schema.
"""
try:
analysis = await self._llm_structured_output(
system_prompt, user_prompt, ScanResult, temperature=0.1
)
state.metadata["analysis"] = analysis.model_dump()
# Convert to Finding objects
for vuln_data in analysis.vulnerabilities:
finding = self._create_finding_from_analysis(vuln_data, state.target.id)
state.findings.append(finding)
except Exception as e:
state.errors.append(f"LLM analysis failed: {str(e)}")
logger.exception("LLM analysis error")
return state
def _create_finding_from_analysis(self, vuln_data: dict, target_id: UUID) -> Finding:
"""Convert LLM analysis to Finding object."""
severity_map = {
"critical": Severity.CRITICAL,
"high": Severity.HIGH,
"medium": Severity.MEDIUM,
"low": Severity.LOW,
"info": Severity.INFO,
}
type_map = {
"rce": VulnerabilityType.RCE,
"remote code execution": VulnerabilityType.RCE,
"sqli": VulnerabilityType.SQLI,
"sql injection": VulnerabilityType.SQLI,
"xss": VulnerabilityType.XSS,
"cross site scripting": VulnerabilityType.XSS,
"ssrf": VulnerabilityType.SSRF,
"auth bypass": VulnerabilityType.AUTH_BYPASS,
"privilege escalation": VulnerabilityType.PRIV_ESCALATION,
"data exposure": VulnerabilityType.DATA_EXPOSURE,
"logic flaw": VulnerabilityType.LOGIC_FLAW,
"supply chain": VulnerabilityType.SUPPLY_CHAIN,
"zero day": VulnerabilityType.ZERO_DAY,
}
vuln_type_str = vuln_data.get("type", "").lower()
vuln_type = type_map.get(vuln_type_str, VulnerabilityType.LOGIC_FLAW)
severity_str = vuln_data.get("severity", "medium").lower()
severity = severity_map.get(severity_str, Severity.MEDIUM)
return self._create_finding(
target_id=str(target_id),
title=vuln_data.get("title", "AI-Identified Vulnerability"),
description=vuln_data.get("description", ""),
severity=severity,
vuln_type=vuln_type,
evidence=vuln_data,
confidence=vuln_data.get("confidence", 0.75),
remediation=vuln_data.get("remediation"),
cve_ids=vuln_data.get("cve_ids", []),
cwe_ids=vuln_data.get("cwe_ids", []),
)
async def _enrich_findings(self, state: AgentState) -> AgentState:
"""Enrich findings with additional context (CVE lookup, exploit availability, etc.)."""
state.current_step = "enrich_findings"
self._log_step(state, "enrich_findings", {"finding_count": len(state.findings)})
for finding in state.findings:
# Add exploit availability check (would integrate with EPSS, Exploit-DB, etc.)
finding.evidence["enrichment"] = {
"epss_score": None, # Would query FIRST.org EPSS API
"exploit_available": False, # Would check Exploit-DB, Metasploit
"patch_available": True, # Would check vendor advisories
"threat_intel": [],
}
return state
async def _deduplicate_findings(self, state: AgentState) -> AgentState:
"""Deduplicate findings across scanners and AI analysis."""
state.current_step = "deduplicate"
# Simple deduplication by (file, line, rule_id) or (package, vuln_id)
seen = set()
unique_findings = []
for finding in state.findings:
evidence = finding.evidence
key = None
if "file" in evidence and "line" in evidence:
key = (evidence.get("file"), evidence.get("line"), evidence.get("rule_id"))
elif "package" in evidence and "vuln_id" in evidence:
key = (evidence.get("package"), evidence.get("vuln_id"))
else:
key = (finding.title, finding.vuln_type)
if key not in seen:
seen.add(key)
unique_findings.append(finding)
else:
# Merge evidence
for existing in unique
---
## Next Steps
1. **Get API Access** - Sign up at the official website
2. **Try the Examples** - Run the code snippets above
3. **Read the Docs** - Check official documentation
4. **Join Communities** - Discord, Reddit, GitHub discussions
5. **Experiment** - Build something cool!
## Further Reading
- [TechCrunch AI](https://techcrunch.com/category/artificial-intelligence/)
- [The Verge](https://www.theverge.com/technology)
- [Wired AI](https://www.wired.com/tag/artificial-intelligence/)
- [Medium AI](https://medium.com/topic/artificial-intelligence)
**Source:** [Ars Technica AI](https://arstechnica.com/security/2026/11/amazon-says-hackers-ai-agents-found-and-exploited-0-day-with-little-human-input/)
---
*Follow ICARAX for more AI insights and tutorials.*
