bchoudha commited on
Commit
c64a2b1
Β·
verified Β·
1 Parent(s): 6168cb2

Upload folder using huggingface_hub

Browse files
Files changed (9) hide show
  1. Csskill.md +66 -0
  2. README.md +196 -7
  3. app.py +442 -0
  4. claude.md +227 -0
  5. cs.env +7 -0
  6. cybersecurityAgents.py +1218 -0
  7. generate_graph_image.py +131 -0
  8. langgraph_pipeline.png +0 -0
  9. requirements.txt +40 -0
Csskill.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Skills & Technology Breakdown
2
+
3
+ ## Core Technologies Used
4
+
5
+ | Technology | Skill Area | Usage |
6
+ |---|---|---|
7
+ | Python 3.10+ | Backend development | Core language for all components |
8
+ | LangGraph | AI orchestration | Multi-agent state machine pipeline (nodes + conditional edges) |
9
+ | LangChain (langchain-openai) | LLM client | ChatOpenAI + @tool definitions |
10
+ | LangSmith | Observability | Auto-traces LLM calls, tool invocations, node transitions |
11
+ | Ollama | Local LLM runtime | Serves gpt-oss:120b-cloud at localhost:11434/v1 |
12
+ | HuggingFace | ML embeddings | Local sentence-transformer models (no API key) |
13
+ | LlamaIndex | RAG framework | Document indexing, retrieval, query engine |
14
+ | ChromaDB | Vector database | Persistent local vector store with cosine similarity |
15
+ | Gradio | Web UI | Interactive browser-based interface |
16
+ | python-dotenv | Config management | Secure API key loading from cs.env |
17
+
18
+ ## Architecture Skills
19
+
20
+ | Skill | Application |
21
+ |---|---|
22
+ | Multi-agent systems | 6 specialized agents orchestrated via LangGraph state machine |
23
+ | RAG (Retrieval Augmented Generation) | Knowledge base retrieval before LLM analysis |
24
+ | LangChain @tool decorator | 3 utility tools (query_knowledge_base, lookup_cve, check_compliance_control) callable inside agent nodes |
25
+ | Vector embeddings | HuggingFace local embeddings β†’ ChromaDB persistence |
26
+ | State machine design | Sequential agent pipeline with shared typed state |
27
+ | Conditional edges | Code Fixer iterative loop (max 3x) |
28
+ | Singleton patterns | Pipeline pre-initialization for Gradio performance |
29
+ | Persistence management | ChromaDB check-before-init to avoid re-indexing |
30
+
31
+ ## Cybersecurity Domain Skills
32
+
33
+ | Domain | Implementation |
34
+ |---|---|
35
+ | Log analysis | SSH brute force, SQL injection, port scan detection |
36
+ | Threat intelligence | CVE mapping, MITRE ATT&CK TTPs, threat actor identification |
37
+ | Vulnerability assessment | OWASP Top 10, CWE mapping, risk scoring |
38
+ | Incident response | NIST SP 800-61 playbook, 3-phase timeline |
39
+ | Compliance auditing | NIST CSF 2.0, ISO 27001:2022, SOC 2 Type II gap analysis |
40
+ | Docker security | Container misconfiguration detection |
41
+
42
+ ## UI/UX Skills (Gradio)
43
+
44
+ | Feature | Implementation |
45
+ |---|---|
46
+ | Authentication | In-app login: page visible to all, Run Analysis disabled until login, login bar hides after auth |
47
+ | Rate limiting | 30s cooldown between analysis requests |
48
+ | Input validation | Max 10,000 character limit on input |
49
+ | Network security | Localhost-only binding, share=False |
50
+ | Concurrency control | max_threads=2 prevents resource exhaustion |
51
+ | Tabbed interface | Report, Findings, Threat Intel, Vulnerabilities, Compliance, Trace |
52
+ | Status indicators | Green βœ… checkboxes for each initialized component |
53
+ | Persistence awareness | UI shows whether vector store loaded from disk or freshly indexed |
54
+ | Scenario selector | Dropdown with 6 agent scenarios + custom input |
55
+ | Singleton pipeline | One-time initialization, fast subsequent requests |
56
+
57
+ ## Key Design Decisions
58
+
59
+ 1. **cs.env for secrets** β€” API keys stored externally, loaded via python-dotenv
60
+ 2. **Vector store persistence check** β€” `check_vector_store_exists()` runs before heavy initialization; skips re-indexing if ChromaDB already has data
61
+ 3. **Gradio status panel** β€” Real-time green checkboxes show initialization state to the user
62
+ 4. **Singleton pattern** β€” LLM, embeddings, KB, and graph initialized once per session, not per request
63
+ 5. **Hybrid Tool architecture** β€” Pipeline uses deterministic node flow, but agents internally call `@tool` utilities (query_knowledge_base, lookup_cve, check_compliance_control) for enrichment
64
+ 6. **Ollama local LLM** β€” Uses OpenAI-compatible endpoint at localhost:11434/v1 with gpt-oss:120b-cloud
65
+ 7. **Iterative Code Fixer** β€” Conditional edge loops up to 3x until code is fully fixed
66
+ 8. **LangSmith tracing** β€” Auto-enabled when LANGSMITH_TRACING=true in cs.env; traces all LLM calls, @tool invocations, and node transitions to LangSmith dashboard
README.md CHANGED
@@ -1,13 +1,202 @@
1
  ---
2
  title: BamsamHackathon
3
- emoji: πŸ’»
4
- colorFrom: gray
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.18.0
8
- python_version: '3.13'
9
- app_file: app.py
10
- pinned: false
11
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
1
  ---
2
  title: BamsamHackathon
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 6.18.0
 
 
 
6
  ---
7
+ ╔══════════════════════════════════════════════════════════════════════╗
8
+ β•‘ CyberSecurity Multi-Agent System β•‘
9
+ β•‘ LangGraph Β· Ollama Β· HuggingFace Β· LlamaIndex Β· ChromaDB Β· @tool β•‘
10
+ β•‘ Gradio Web UI β•‘
11
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
12
+
13
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
14
+ STACK OVERVIEW
15
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
16
+
17
+ Component Role
18
+ ───────────────── ─────────────────────────────────────────────────
19
+ LangGraph Orchestrates agents as a compiled state machine
20
+ Ollama Local LLM runtime (gpt-oss:120b-cloud)
21
+ LangChain @tool Utility tools callable inside agent nodes
22
+ HuggingFace Local sentence-transformer embeddings (no API key)
23
+ LlamaIndex RAG framework β€” document indexing + retrieval
24
+ ChromaDB Persistent vector store (local disk)
25
+ Gradio Interactive web UI for analysis & visualization
26
+
27
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
28
+ QUICK START
29
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
30
+
31
+ 1. Install dependencies:
32
+ pip install -r requirements.txt
33
+
34
+ 2. Set your credentials in cs.env:
35
+ OPENROUTER_API_KEY=sk-or-... (if using OpenRouter)
36
+ GRADIO_USER=admin
37
+ GRADIO_PASSWORD=CyberSec@2026!
38
+ LANGSMITH_API_KEY=lsv2_pt_... (optional, for tracing)
39
+ LANGSMITH_TRACING=true (set false to disable)
40
+
41
+ (Change the default password before deploying)
42
+
43
+ 3. Run the Gradio web UI:
44
+ python cybersecurityGradio.py
45
+
46
+ This opens a browser-based interface with:
47
+ - Scenario selector (4 built-in examples + custom input)
48
+ - Tabbed results: Report, Log Findings, Threat Intel, Vulnerabilities, Compliance, Trace
49
+ - Green βœ… status indicators showing initialization state
50
+
51
+ 4. Run via CLI (headless):
52
+ python cybersecurityAgents.py ssh_brute_force
53
+ python cybersecurityAgents.py vulnerable_code
54
+ python cybersecurityAgents.py docker_misconfig
55
+ python cybersecurityAgents.py policy_audit
56
+
57
+ 5. Run programmatically:
58
+ from cybersecurityAgents import run_analysis
59
+ results = run_analysis("your logs or code here")
60
+
61
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
62
+ PROJECT FILES
63
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
64
+
65
+ File Purpose
66
+ ──────────────────────── ──────────────────────────────────────────
67
+ cybersecurityAgents.py Core multi-agent system (LangGraph pipeline)
68
+ cybersecurityGradio.py Gradio web UI wrapper
69
+ cs.env API keys (OPENROUTER_API_KEY)
70
+ requirements.txt Python dependencies
71
+ README.md This file
72
+ claude.md Gradio integration analysis & architecture
73
+ skill.md Team skills & technology breakdown
74
+
75
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
76
+ VECTOR STORE PERSISTENCE
77
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
78
+
79
+ The system checks if ChromaDB already has indexed data on startup:
80
+
81
+ - If ./chroma_cybersec_db/ exists with data β†’ loads existing index (fast)
82
+ - If not β†’ indexes the knowledge base into ChromaDB (first run only)
83
+
84
+ The Gradio UI displays green βœ… checkboxes showing:
85
+ βœ… OpenRouter LLM Connected
86
+ βœ… HuggingFace Embeddings Loaded
87
+ βœ… ChromaDB + LlamaIndex Vector Store (loaded existing / freshly indexed)
88
+ βœ… LangGraph Pipeline Compiled
89
+
90
+ Use the "πŸ” Check Status" button to inspect without running analysis.
91
+
92
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
93
+ AGENTS & LANGGRAPH FLOW
94
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
95
+
96
+ [Input]
97
+ β”‚
98
+ β–Ό
99
+ classify_input ← Detects if input is log/code/config/policy
100
+ β”‚
101
+ β–Ό
102
+ rag_retrieve ← LlamaIndex retrieves relevant KB chunks from ChromaDB
103
+ β”‚
104
+ β–Ό
105
+ log_monitor ← Detects attacks, anomalies, IoCs
106
+ β”‚
107
+ β–Ό
108
+ threat_intel ← Maps to CVEs, MITRE ATT&CK, threat actors
109
+ β”‚
110
+ β–Ό
111
+ vuln_scanner ← OWASP/CWE vulnerability assessment
112
+ β”‚
113
+ β–Ό
114
+ incident_response ← NIST 800-61 playbook with 3-phase timeline
115
+ β”‚
116
+ β–Ό
117
+ policy_checker ← NIST CSF / ISO 27001 / SOC 2 gap analysis
118
+ β”‚
119
+ β–Ό
120
+ synthesize_report ← Combines all outputs into final report
121
+ β”‚
122
+ β–Ό
123
+ [Report + JSON saved to disk]
124
+
125
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
126
+ GRADIO WEB UI
127
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
128
+
129
+ Launch:
130
+ python cybersecurityGradio.py
131
+
132
+ Features:
133
+ - Login gate (username/password from cs.env)
134
+ - Page accessible to unauthenticated users (read-only view)
135
+ - Run Analysis disabled until login (tooltip: "Login Required")
136
+ - Login bar hides after successful authentication
137
+ - Dropdown to select built-in scenarios or paste custom input
138
+ - Tabbed output panels (Report, Findings, Threat Intel, Vulns, Compliance, Trace)
139
+ - Real-time system status panel with green βœ… checkboxes
140
+ - Singleton pipeline β€” initializes once, reuses across requests
141
+ - Vector store persistence check β€” skips re-indexing if data exists
142
+ - Rate limiting (30s cooldown between requests)
143
+ - Input validation (max 10,000 characters)
144
+ - Localhost-only binding (no external network access)
145
+
146
+ Architecture:
147
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
148
+ β”‚ Gradio UI │──────▢│ cybersecurityAgents │──────▢│ LangGraph β”‚
149
+ β”‚ (Browser) │◀──────│ (pipeline singleton) │◀──────│ Pipeline β”‚
150
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
151
+
152
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
153
+ MODEL OPTIONS (OpenRouter)
154
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
155
+
156
+ Free tier (no billing required):
157
+ mistralai/mistral-7b-instruct ← Default
158
+ meta-llama/llama-3.1-8b-instruct:free
159
+ google/gemma-2-9b-it:free
160
+
161
+ Paid (higher quality):
162
+ openai/gpt-4o
163
+ anthropic/claude-3-5-sonnet
164
+ mistralai/mixtral-8x7b-instruct
165
+
166
+ Change in Config.LLM_MODEL in cybersecurityAgents.py
167
+
168
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
169
+ EMBEDDING OPTIONS (HuggingFace, all local)
170
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
171
+
172
+ sentence-transformers/all-MiniLM-L6-v2 ← Default (~90MB, fast)
173
+ BAAI/bge-base-en-v1.5 ← Better quality (~440MB)
174
+ sentence-transformers/all-mpnet-base-v2 ← Balanced (~420MB)
175
+
176
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
177
+ OUTPUT FILES
178
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
179
+
180
+ cybersec_report_YYYYMMDD_HHMMSS.txt ← Human-readable report
181
+ cybersec_results_YYYYMMDD_HHMMSS.json ← Structured JSON for all agents
182
+ ./chroma_cybersec_db/ ← Persistent ChromaDB vector store
183
+
184
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
185
+ EXTENDING THE SYSTEM
186
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
187
+
188
+ Add knowledge to the RAG database:
189
+ kb.add_document("Your threat intel text...", {"category": "threat_intel"})
190
+
191
+ Add a new agent:
192
+ 1. Write a node function: def node_my_agent(state) β†’ state
193
+ 2. graph.add_node("my_agent", node_my_agent)
194
+ 3. graph.add_edge("policy_checker", "my_agent")
195
+ 4. Add result key to CyberAgentState TypedDict
196
 
197
+ Add conditional routing (e.g., only run incident response for CRITICAL):
198
+ graph.add_conditional_edges(
199
+ "vuln_scanner",
200
+ lambda s: "incident_response" if s["vuln_scan"]["risk_score"] > 70 else "policy_checker",
201
+ {"incident_response": "incident_response", "policy_checker": "policy_checker"}
202
+ )
app.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from cybersecurityAgents import (
3
+ run_analysis,
4
+ EXAMPLE_INPUTS,
5
+ build_llm,
6
+ build_embeddings,
7
+ build_cybersec_graph,
8
+ VectorKnowledgeBase,
9
+ CyberAgentState,
10
+ Config,
11
+ check_vector_store_exists,
12
+ )
13
+ from datetime import datetime
14
+ import json
15
+ import time
16
+ import os
17
+ from dotenv import load_dotenv
18
+
19
+ load_dotenv("cs.env")
20
+
21
+ # ── Security Configuration ─────────────────────────────────────────────
22
+ GRADIO_USER = os.getenv("GRADIO_USER", "admin")
23
+ GRADIO_PASSWORD = os.getenv("GRADIO_PASSWORD", "CyberSec@2026!")
24
+ MAX_INPUT_LENGTH = 10000
25
+ REQUEST_COOLDOWN_SECONDS = 30
26
+ MAX_CONCURRENT_THREADS = 2
27
+
28
+ _last_request_time: float = 0.0
29
+ _is_authenticated: bool = False
30
+
31
+ # ── Singleton pipeline ─────────────────────────────────────────────────
32
+ _graph = None
33
+ _kb = None
34
+ _init_status = {}
35
+
36
+
37
+ def get_pipeline():
38
+ global _graph, _kb, _init_status
39
+ if _graph is None:
40
+ store_exists = check_vector_store_exists()
41
+ _init_status["vector_store_preexisted"] = store_exists
42
+
43
+ llm = build_llm()
44
+ _init_status["llm"] = True
45
+
46
+ embeddings = build_embeddings()
47
+ _init_status["embeddings"] = True
48
+
49
+ _kb = VectorKnowledgeBase(embeddings)
50
+ _init_status["vector_store"] = True
51
+ _init_status["vector_store_loaded_existing"] = _kb.loaded_existing
52
+
53
+ _graph = build_cybersec_graph(llm, _kb)
54
+ _init_status["graph"] = True
55
+
56
+ return _graph
57
+
58
+
59
+ def get_status_markdown():
60
+ if not _init_status:
61
+ return (
62
+ "### ⏳ Not Initialized\n\n"
63
+ "Click **Run Analysis** to initialize.\n\n"
64
+ "---\n"
65
+ "#### Components\n"
66
+ "- ⬜ OpenRouter LLM\n"
67
+ "- ⬜ HuggingFace Embeddings\n"
68
+ "- ⬜ ChromaDB Vector Store\n"
69
+ "- ⬜ LangGraph Pipeline"
70
+ )
71
+
72
+ lines = ["### 🟒 Initialized\n"]
73
+ checks = [
74
+ ("llm", "OpenRouter LLM"),
75
+ ("embeddings", "HuggingFace Embeddings"),
76
+ ("vector_store", "ChromaDB Vector Store"),
77
+ ("graph", "LangGraph Pipeline"),
78
+ ]
79
+ for key, label in checks:
80
+ if _init_status.get(key):
81
+ lines.append(f"- βœ… {label}")
82
+ else:
83
+ lines.append(f"- ⬜ {label}")
84
+
85
+ lines.append("\n---")
86
+ if _init_status.get("vector_store_loaded_existing"):
87
+ lines.append("πŸ“‚ **Loaded from disk**\n(no re-indexing)")
88
+ elif _init_status.get("vector_store"):
89
+ lines.append("πŸ†• **Freshly indexed**\n(knowledge base built)")
90
+
91
+ lines.append(f"\n---\n**Model:** `{Config.LLM_MODEL}`")
92
+ lines.append(f"\n**Embeddings:** `{Config.EMBEDDING_MODEL.split('/')[-1]}`")
93
+ lines.append(f"\n**Vector DB:** `{Config.CHROMA_PERSIST_DIR}`")
94
+
95
+ return "\n".join(lines)
96
+
97
+
98
+ LANGGRAPH_PIPELINE_MD = """### πŸ”— LangGraph Pipeline
99
+
100
+ ```
101
+ START
102
+ β”‚
103
+ β–Ό
104
+ 🏷️ classify_input
105
+ β”‚
106
+ β–Ό
107
+ πŸ“š rag_retrieve
108
+ β”‚
109
+ β–Ό
110
+ πŸ“‘ log_monitor
111
+ β”‚
112
+ β–Ό
113
+ πŸ•΅οΈ threat_intel
114
+ β”‚
115
+ β–Ό
116
+ πŸ” vuln_scanner
117
+ β”‚
118
+ β–Ό
119
+ πŸ”§ code_fixer ◄──┐
120
+ β”‚ (loop max 3x)
121
+ β”‚ fixed? β”‚
122
+ β”œβ”€β”€ No β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
123
+ β–Ό Yes
124
+ 🚨 incident_response
125
+ β”‚
126
+ β–Ό
127
+ πŸ“‹ policy_checker
128
+ β”‚
129
+ β–Ό
130
+ πŸ“ synthesize_report
131
+ β”‚
132
+ β–Ό
133
+ END
134
+ ```
135
+
136
+ ---
137
+
138
+ ### πŸ€– Agents
139
+
140
+ | # | Agent | Role |
141
+ |---|-------|------|
142
+ | 1 | Log Monitor | Detect attacks in logs |
143
+ | 2 | Threat Intel | CVE & MITRE mapping |
144
+ | 3 | Vuln Scanner | OWASP/CWE scan |
145
+ | 4 | Code Fixer | Iterative bug fix |
146
+ | 5 | Incident Response | NIST 800-61 plan |
147
+ | 6 | Policy Checker | ISO/NIST/SOC2 gaps |
148
+ """
149
+
150
+
151
+ SCENARIO_MAP = {
152
+ "Log Monitor Agent": "ssh_brute_force",
153
+ "Threat Intelligence Agent": "ssh_brute_force",
154
+ "Vulnerability Scanner Agent": "vulnerable_code",
155
+ "Code Fixer Agent": "vulnerable_code",
156
+ "Incident Response Agent": "docker_misconfig",
157
+ "Policy Checker Agent": "policy_audit",
158
+ }
159
+
160
+ SCENARIO_DESCRIPTIONS = {
161
+ "custom": "> **Paste your own logs, code, config, or policy text below.**",
162
+ "Log Monitor Agent": "> **Reads system and network logs to detect unusual activity or attacks.**",
163
+ "Threat Intelligence Agent": "> **Looks up known security threats (CVE data, reports) and checks if your system is affected.**",
164
+ "Vulnerability Scanner Agent": "> **Scans code, APIs, or Docker images to find security weaknesses.**",
165
+ "Code Fixer Agent": "> **Iteratively fixes security vulnerabilities and bugs in your code (up to 3 passes).**",
166
+ "Incident Response Agent": "> **Creates step-by-step action plans when an issue is found.**",
167
+ "Policy Checker Agent": "> **Checks your setup against standards like ISO, NIST, or SOC2 and shows where you need fixes.**",
168
+ }
169
+
170
+
171
+ def authenticate(username, password):
172
+ """Validate login credentials against cs.env values."""
173
+ return username == GRADIO_USER and password == GRADIO_PASSWORD
174
+
175
+
176
+ def do_login(username, password):
177
+ """In-app login that enables Run Analysis button."""
178
+ global _is_authenticated
179
+ if username == GRADIO_USER and password == GRADIO_PASSWORD:
180
+ _is_authenticated = True
181
+ return (
182
+ gr.update(visible=False),
183
+ gr.update(interactive=True, value="Run Analysis", variant="primary"),
184
+ "Logged in as **" + username + "**",
185
+ )
186
+ return (
187
+ gr.update(visible=True),
188
+ gr.update(interactive=False, value="Run Analysis (Login Required)", variant="secondary"),
189
+ "Invalid credentials. Try again.",
190
+ )
191
+
192
+
193
+ def analyze(text, scenario):
194
+ global _last_request_time
195
+
196
+ if not _is_authenticated:
197
+ return "Login required to run analysis. Use the login form at the top.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
198
+
199
+ # Rate limiting: enforce cooldown between requests
200
+ now = time.time()
201
+ elapsed_since_last = now - _last_request_time
202
+ if elapsed_since_last < REQUEST_COOLDOWN_SECONDS and _last_request_time > 0:
203
+ wait = int(REQUEST_COOLDOWN_SECONDS - elapsed_since_last)
204
+ return f"⏳ Rate limited. Please wait {wait}s before next request.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
205
+ _last_request_time = now
206
+
207
+ # Input validation: enforce max length
208
+ input_text = text
209
+ if not input_text or not input_text.strip():
210
+ return "⚠️ Please provide input or select a scenario.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
211
+ if len(input_text) > MAX_INPUT_LENGTH:
212
+ return f"❌ Input too long ({len(input_text)} chars). Maximum is {MAX_INPUT_LENGTH} characters.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
213
+
214
+ try:
215
+ app = get_pipeline()
216
+ except Exception as e:
217
+ return f"❌ Pipeline initialization failed: {e}", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
218
+
219
+ initial_state: CyberAgentState = {
220
+ "raw_input": input_text,
221
+ "input_type": "general",
222
+ "log_findings": None,
223
+ "threat_intel": None,
224
+ "vuln_scan": None,
225
+ "code_fix": None,
226
+ "incident_plan": None,
227
+ "policy_gaps": None,
228
+ "agent_trace": [],
229
+ "errors": [],
230
+ "rag_context": None,
231
+ "final_report": None,
232
+ "started_at": datetime.now().isoformat(),
233
+ }
234
+
235
+ t0 = time.time()
236
+ state = app.invoke(initial_state)
237
+ elapsed = time.time() - t0
238
+
239
+ report = state.get("final_report", "No report generated.")
240
+ report += f"\n\n⏱ Analysis completed in {elapsed:.1f}s"
241
+
242
+ # Extract fixed code for display
243
+ code_fix = state.get("code_fix") or {}
244
+ fixed_code = code_fix.get("fixed_code", "")
245
+ if not fixed_code or code_fix.get("skipped"):
246
+ fixed_code = "# No code fix generated (input was not code or code fixer was skipped)"
247
+
248
+ return (
249
+ report,
250
+ state.get("log_findings") or {},
251
+ state.get("threat_intel") or {},
252
+ state.get("vuln_scan") or {},
253
+ code_fix,
254
+ state.get("policy_gaps") or {},
255
+ "\n".join(state.get("agent_trace", [])),
256
+ get_status_markdown(),
257
+ fixed_code,
258
+ )
259
+
260
+
261
+ def load_scenario(scenario):
262
+ if scenario == "custom":
263
+ return "", SCENARIO_DESCRIPTIONS["custom"]
264
+ key = SCENARIO_MAP.get(scenario, "ssh_brute_force")
265
+ return EXAMPLE_INPUTS.get(key, ""), SCENARIO_DESCRIPTIONS.get(scenario, "")
266
+
267
+
268
+ def check_init_status():
269
+ store_exists = check_vector_store_exists()
270
+ if store_exists:
271
+ return get_status_markdown() if _init_status else (
272
+ "### 🟒 Ready\n\n"
273
+ "- βœ… ChromaDB vector store found on disk\n\n"
274
+ "---\n"
275
+ "Pipeline will load existing data on first run.\n\n"
276
+ f"**Path:** `{Config.CHROMA_PERSIST_DIR}`"
277
+ )
278
+ else:
279
+ return (
280
+ "### 🟑 First Run\n\n"
281
+ "- ⬜ No vector store found\n\n"
282
+ "---\n"
283
+ "Knowledge base will be indexed on first analysis run."
284
+ )
285
+
286
+
287
+ # ── Gradio UI ──────────────────────────────────────────────────────────
288
+
289
+ custom_css = """
290
+ .auth-container {
291
+ max-width: 700px;
292
+ padding: 8px 15px;
293
+ background: #0b0f19;
294
+ border: 1px solid #1e293b;
295
+ border-radius: 12px;
296
+ box-shadow: 0 10px 15px -5px rgb(0 0 0 / 0.3);
297
+ align-items: center;
298
+ margin-top: -5px;
299
+ }
300
+ .auth-container input::placeholder {
301
+ color: #60a5fa !important;
302
+ opacity: 1 !important;
303
+ }
304
+ .login-btn {
305
+ font-weight: 600 !important;
306
+ background: linear-gradient(135deg, #7c3aed 0%, #4c1d95 100%) !important;
307
+ border: none !important;
308
+ color: white !important;
309
+ transition: all 0.2s ease !important;
310
+ min-height: 42px !important;
311
+ }
312
+ .login-btn:hover {
313
+ transform: translateY(-1px);
314
+ box-shadow: 0 4px 12px rgba(124, 58, 237, 0.3);
315
+ }
316
+ """
317
+
318
+ with gr.Blocks(title="CyberSec Multi-Agent Analyzer", theme=gr.themes.Soft(), css=custom_css) as demo:
319
+
320
+ with gr.Row():
321
+ with gr.Column(scale=3):
322
+ gr.Markdown("# CyberSecurity Multi-Agent Analyzer")
323
+ auth_status_md = gr.Markdown("Not logged in. Run Analysis is disabled.")
324
+ with gr.Column(scale=2):
325
+ with gr.Row(elem_classes="auth-container") as login_row:
326
+ login_user = gr.Textbox(
327
+ placeholder="Enter Username",
328
+ type="text",
329
+ max_lines=1,
330
+ interactive=True,
331
+ scale=2,
332
+ show_label=False,
333
+ container=False,
334
+ )
335
+ login_pass = gr.Textbox(
336
+ placeholder="Enter Password",
337
+ type="password",
338
+ max_lines=1,
339
+ interactive=True,
340
+ scale=2,
341
+ show_label=False,
342
+ container=False,
343
+ )
344
+ login_btn = gr.Button(
345
+ "Login",
346
+ variant="primary",
347
+ elem_classes="login-btn",
348
+ scale=1,
349
+ )
350
+
351
+ gr.Markdown("---")
352
+
353
+ with gr.Row():
354
+ # ── LEFT: LangGraph Pipeline ───────────────────────────────────
355
+ with gr.Column(scale=1, min_width=250):
356
+ gr.Markdown(LANGGRAPH_PIPELINE_MD)
357
+
358
+ # ── CENTER: Main Playground ────────────────────────────────────
359
+ with gr.Column(scale=3):
360
+ scenario = gr.Dropdown(
361
+ choices=[
362
+ "custom",
363
+ "Log Monitor Agent",
364
+ "Threat Intelligence Agent",
365
+ "Vulnerability Scanner Agent",
366
+ "Code Fixer Agent",
367
+ "Incident Response Agent",
368
+ "Policy Checker Agent",
369
+ ],
370
+ value="Log Monitor Agent",
371
+ label="Select Agent Scenario",
372
+ )
373
+
374
+ scenario_desc = gr.Markdown(value=SCENARIO_DESCRIPTIONS["Log Monitor Agent"])
375
+
376
+ input_box = gr.Textbox(
377
+ lines=8,
378
+ label="Input (logs, code, config, or policy)",
379
+ placeholder="Paste your input here or select a scenario above...",
380
+ value=EXAMPLE_INPUTS["ssh_brute_force"],
381
+ )
382
+
383
+ with gr.Row():
384
+ run_btn = gr.Button(
385
+ "Run Analysis (Login Required)",
386
+ variant="secondary",
387
+ interactive=False,
388
+ scale=2,
389
+ )
390
+ status_btn = gr.Button("πŸ” Check Status", scale=1)
391
+
392
+ with gr.Tabs():
393
+ with gr.Tab("πŸ“„ Report"):
394
+ report_out = gr.Markdown()
395
+ with gr.Tab("πŸ” Log Findings"):
396
+ log_out = gr.JSON()
397
+ with gr.Tab("πŸ•΅οΈ Threat Intel"):
398
+ threat_out = gr.JSON()
399
+ with gr.Tab("⚠️ Vulnerabilities"):
400
+ vuln_out = gr.JSON()
401
+ with gr.Tab("πŸ”§ Code Fix"):
402
+ codefix_out = gr.JSON()
403
+ with gr.Tab("πŸ“‹ Compliance"):
404
+ policy_out = gr.JSON()
405
+ with gr.Tab("πŸ“ Trace"):
406
+ trace_out = gr.Textbox(lines=12, label="Agent Execution Trace")
407
+
408
+ # ── RIGHT: Storage & Initialization ────────────────────────────
409
+ with gr.Column(scale=1, min_width=250):
410
+ gr.Markdown("### πŸ“¦ Storage & Init")
411
+ status_out = gr.Markdown(value=check_init_status())
412
+ gr.Markdown("---")
413
+ gr.Markdown("### πŸ”§ Fixed Code Output")
414
+ fixed_code_out = gr.Code(
415
+ label="Fixed Code (read-only)",
416
+ language="python",
417
+ interactive=False,
418
+ lines=15,
419
+ )
420
+
421
+ # ── Event Handlers ─────────────────────────────────────────────────
422
+ login_btn.click(
423
+ fn=do_login,
424
+ inputs=[login_user, login_pass],
425
+ outputs=[login_row, run_btn, auth_status_md],
426
+ )
427
+ scenario.change(fn=load_scenario, inputs=[scenario], outputs=[input_box, scenario_desc])
428
+ run_btn.click(
429
+ fn=analyze,
430
+ inputs=[input_box, scenario],
431
+ outputs=[report_out, log_out, threat_out, vuln_out, codefix_out, policy_out, trace_out, status_out, fixed_code_out],
432
+ )
433
+ status_btn.click(fn=check_init_status, inputs=[], outputs=[status_out])
434
+
435
+ if __name__ == "__main__":
436
+ demo.launch(
437
+ auth_message="πŸ” CyberSecurity Multi-Agent System β€” Login Required",
438
+ server_name="0.0.0.0",
439
+ max_threads=MAX_CONCURRENT_THREADS,
440
+ share=False,
441
+ ssr_mode=False,
442
+ )
claude.md ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gradio Visual Integration Analysis for CyberSecurity Multi-Agent System
2
+
3
+ ## Overview
4
+
5
+ This document analyzes the **Gradio** web UI integration for `cybersecurityAgents.py`, providing users with an interactive visual interface to run security analyses and view agent results.
6
+
7
+ ---
8
+
9
+ ## Current Entry Points (from `cybersecurityAgents.py`)
10
+
11
+ | Entry Point | Description |
12
+ |---|---|
13
+ | `run_analysis(user_input, save_report=True)` | Main function β€” accepts text, returns full `CyberAgentState` dict |
14
+ | `check_vector_store_exists()` | Pre-check if ChromaDB has data β€” avoids unnecessary initialization |
15
+ | `EXAMPLE_INPUTS` dict | 4 built-in scenarios: `ssh_brute_force`, `vulnerable_code`, `docker_misconfig`, `policy_audit` |
16
+ | CLI `__main__` | Runs a named scenario from sys.argv |
17
+
18
+ The `run_analysis` function returns a dict containing:
19
+ - `input_type` β€” classified type (log/code/config/policy)
20
+ - `log_findings` β€” dict with severity, findings, IoCs
21
+ - `threat_intel` β€” dict with CVEs, MITRE TTPs, threat actors
22
+ - `vuln_scan` β€” dict with risk_score, vulnerabilities list
23
+ - `incident_plan` β€” dict with priority, timeline, containment steps
24
+ - `policy_gaps` β€” dict with framework scores, gaps, quick wins
25
+ - `final_report` β€” full text report string
26
+ - `agent_trace` β€” execution log list
27
+
28
+ ---
29
+
30
+ ## Vector Store Persistence Check
31
+
32
+ Before any heavy initialization, the system calls `check_vector_store_exists()`:
33
+
34
+ ```python
35
+ def check_vector_store_exists() -> bool:
36
+ """Check if ChromaDB persistent vector store already exists with data."""
37
+ if not os.path.exists(Config.CHROMA_PERSIST_DIR):
38
+ return False
39
+ client = chromadb.PersistentClient(path=Config.CHROMA_PERSIST_DIR)
40
+ collection = client.get_or_create_collection(name=Config.CHROMA_COLLECTION)
41
+ return collection.count() > 0
42
+ ```
43
+
44
+ **Behavior:**
45
+ - If `./chroma_cybersec_db/` exists and has vectors β†’ loads existing index (no re-indexing)
46
+ - If not β†’ indexes the `CYBERSEC_KNOWLEDGE_BASE` documents into ChromaDB (first run only)
47
+ - `VectorKnowledgeBase.loaded_existing` flag tracks which path was taken
48
+
49
+ ---
50
+
51
+ ## Gradio UI Layout
52
+
53
+ ### Tab-Based Interface with Status Panel
54
+
55
+ ```
56
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
57
+ β”‚ πŸ›‘οΈ CyberSecurity Multi-Agent Analyzer β”‚
58
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
59
+ β”‚ [Scenario Dropdown] [πŸš€ Run] [πŸ” Status] β”‚ 🟒 System Status β”‚
60
+ β”‚ β”‚ βœ… OpenRouter LLM β”‚
61
+ β”‚ [Input Textbox] β”‚ βœ… HuggingFace Embeddings β”‚
62
+ β”‚ β”‚ βœ… ChromaDB Vector Store β”‚
63
+ β”‚ β”‚ βœ… LangGraph Pipeline β”‚
64
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
65
+ β”‚ [Report] [Log Findings] [Threat Intel] [Vulns] [Compliance] [Trace] β”‚
66
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
67
+ β”‚ Tab content area β”‚
68
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
69
+ ```
70
+
71
+ ### Status Indicators
72
+
73
+ The right panel shows green βœ… checkboxes after initialization:
74
+
75
+ | State | Display |
76
+ |---|---|
77
+ | Not yet initialized | ⏳ Pipeline not yet initialized |
78
+ | Vector store found on disk | βœ… + "loaded from existing persistent data" |
79
+ | Freshly indexed | βœ… + "freshly initialized (knowledge base indexed)" |
80
+ | Component ready | βœ… Component Name |
81
+ | Component pending | ⬜ Component Name |
82
+
83
+ ---
84
+
85
+ ## Integration Architecture
86
+
87
+ ```
88
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
89
+ β”‚ Gradio UI │──────▢│ cybersecurityAgents │──────▢│ LangGraph β”‚
90
+ β”‚ (Browser) │◀──────│ (pipeline singleton) │◀──────│ Pipeline β”‚
91
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
92
+ β”‚
93
+ β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
94
+ β”‚ @tool utils β”‚
95
+ β”‚ query_kb β”‚
96
+ β”‚ lookup_cve β”‚
97
+ β”‚ check_control β”‚
98
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
99
+ ```
100
+
101
+ ### Hybrid Architecture: Nodes + Tools
102
+
103
+ The pipeline uses **deterministic node-based flow** (LangGraph edges define execution order),
104
+ but agent nodes internally call **@tool utilities** for enriched analysis:
105
+
106
+ | Tool | Used By | Purpose |
107
+ |------|---------|--------|
108
+ | `@tool query_knowledge_base` | RAG Retriever | Search ChromaDB for relevant context |
109
+ | `@tool lookup_cve` | Threat Intel Agent | Enrich with CVE-specific knowledge |
110
+ | `@tool check_compliance_control` | Policy Checker Agent | Lookup specific framework controls |
111
+
112
+ This hybrid gives you:
113
+ - Deterministic, predictable pipeline flow (no missed agents)
114
+ - Richer context via tool calls inside nodes
115
+ - Proper `@tool` annotations for LangGraph/LangChain compatibility
116
+
117
+ ### Startup Flow
118
+
119
+ ```
120
+ 1. User opens Gradio UI
121
+ 2. check_vector_store_exists() β†’ shows pre-check status
122
+ 3. User clicks "Run Analysis"
123
+ 4. get_pipeline() called (singleton):
124
+ a. check_vector_store_exists() β†’ determines if re-indexing needed
125
+ b. build_llm() β†’ connect to OpenRouter
126
+ c. build_embeddings() β†’ load HuggingFace model
127
+ d. VectorKnowledgeBase() β†’ load or index ChromaDB
128
+ e. build_cybersec_graph() β†’ compile LangGraph
129
+ 5. Status panel updates with all βœ… green checkboxes
130
+ 6. Analysis runs, results populate tabs
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Key Implementation Details
136
+
137
+ ### Singleton Pipeline (avoids re-init per request)
138
+
139
+ ```python
140
+ _graph = None
141
+ _kb = None
142
+ _init_status = {}
143
+
144
+ def get_pipeline():
145
+ global _graph, _kb, _init_status
146
+ if _graph is None:
147
+ store_exists = check_vector_store_exists()
148
+ _init_status["vector_store_preexisted"] = store_exists
149
+ # ... initialize once ...
150
+ return _graph
151
+ ```
152
+
153
+ ### cs.env for Credentials
154
+
155
+ ```
156
+ OPENROUTER_API_KEY=<your_key_here>
157
+ GRADIO_USER=admin
158
+ GRADIO_PASSWORD=CyberSec@2026!
159
+ LANGSMITH_API_KEY=<your_langsmith_key_here>
160
+ LANGSMITH_PROJECT=cybersec-multi-agent
161
+ LANGSMITH_TRACING=true
162
+ LANGSMITH_ENDPOINT=https://api.smith.langchain.com
163
+ ```
164
+
165
+ Loaded via `python-dotenv` at module import time β€” no hardcoded keys in source.
166
+
167
+ ### LangSmith Observability
168
+
169
+ When `LANGSMITH_TRACING=true` is set in cs.env, the system auto-traces:
170
+
171
+ | What | Visibility |
172
+ |------|------------|
173
+ | Every `ChatOpenAI.invoke()` | Prompt, response, tokens, latency |
174
+ | `@tool` calls (lookup_cve, check_compliance_control) | Tool name, input, output, duration |
175
+ | LangGraph node transitions | State flow, conditional edge decisions |
176
+ | Full pipeline runs | End-to-end trace per analysis request |
177
+
178
+ To disable: set `LANGSMITH_TRACING=false` β€” no code changes needed.
179
+
180
+ ### Security Layers
181
+
182
+ | Layer | Implementation |
183
+ |-------|---------------|
184
+ | Authentication | In-app login form β€” page visible to all, Run Analysis disabled until login, login row hides after auth |
185
+ | Rate Limiting | 30s cooldown between requests per session |
186
+ | Input Validation | Max 10,000 chars β€” rejects oversized prompts |
187
+ | Network Binding | `server_name="127.0.0.1"` β€” localhost only |
188
+ | Concurrency | `max_threads=2` β€” prevents resource exhaustion |
189
+ | Share Disabled | `share=False` β€” no public Gradio links |
190
+
191
+ ---
192
+
193
+ ## Gradio Components Used
194
+
195
+ | Component | Purpose |
196
+ |---|---|
197
+ | `gr.Textbox` | Input area for logs/code/config/policy |
198
+ | `gr.Dropdown` | Select built-in example scenarios |
199
+ | `gr.Button` | Trigger analysis / check status |
200
+ | `gr.Markdown` | Render final report + status panel with βœ… checkboxes |
201
+ | `gr.JSON` | Display structured agent outputs |
202
+ | `gr.Textbox` (readonly) | Agent execution trace |
203
+ | `gr.Tab` | Organize output sections |
204
+ | `gr.Row` / `gr.Column` | Layout with status sidebar |
205
+
206
+ ---
207
+
208
+ ## Dependency
209
+
210
+ Added to `requirements.txt`:
211
+ ```
212
+ gradio>=4.0.0
213
+ ```
214
+
215
+ ---
216
+
217
+ ## Summary
218
+
219
+ | Aspect | Approach |
220
+ |---|---|
221
+ | Wrapper | Gradio Blocks wrapping singleton pipeline from `cybersecurityAgents.py` |
222
+ | Layout | Tabbed output + status sidebar with green βœ… checkboxes |
223
+ | Persistence | `check_vector_store_exists()` before init; skip re-indexing if data exists |
224
+ | Secrets | API keys in `cs.env`, loaded via python-dotenv |
225
+ | Status | Real-time βœ…/⬜ indicators for LLM, Embeddings, Vector Store, Graph |
226
+ | Performance | Singleton initialization, fast subsequent requests |
227
+ | Deployment | `python cybersecurityGradio.py` β†’ launches local browser UI |
cs.env ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ OPENROUTER_API_KEY=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
2
+ GRADIO_USER=admin
3
+ GRADIO_PASSWORD=CyberSec@2026!
4
+ LANGSMITH_API_KEY=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
5
+ LANGSMITH_PROJECT=cybersec-multi-agent
6
+ LANGSMITH_TRACING=true
7
+ LANGSMITH_ENDPOINT=https://api.smith.langchain.com
cybersecurityAgents.py ADDED
@@ -0,0 +1,1218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ╔══════════════════════════════════════════════════════════════════════╗
3
+ β•‘ CyberSecurity Multi-Agent System β•‘
4
+ β•‘ Stack: LangGraph Β· HuggingFace Embeddings Β· OpenRouter LLM β•‘
5
+ β•‘ LlamaIndex RAG Β· ChromaDB Vector Store β•‘
6
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
7
+ """
8
+
9
+ import os
10
+ import json
11
+ import time
12
+ import hashlib
13
+ from datetime import datetime
14
+ from typing import TypedDict, Annotated, List, Optional, Any
15
+ from dotenv import load_dotenv
16
+
17
+ load_dotenv("cs.env")
18
+
19
+ # ── LangSmith Tracing (auto-enabled if env vars are set) ─────────────
20
+ if os.getenv("LANGSMITH_TRACING", "false").lower() == "true":
21
+ os.environ.setdefault("LANGCHAIN_TRACING_V2", "true")
22
+ os.environ.setdefault("LANGCHAIN_API_KEY", os.getenv("LANGSMITH_API_KEY", ""))
23
+ os.environ.setdefault("LANGCHAIN_PROJECT", os.getenv("LANGSMITH_PROJECT", "cybersec-multi-agent"))
24
+ os.environ.setdefault("LANGCHAIN_ENDPOINT", os.getenv("LANGSMITH_ENDPOINT", "https://api.smith.langchain.com"))
25
+ print(" [LangSmith] Tracing enabled β†’ project:", os.getenv("LANGSMITH_PROJECT"))
26
+
27
+ # ── LangGraph ──────────────────────────────────────────────────────────
28
+ from langgraph.graph import StateGraph, END
29
+
30
+ # ── LangChain ─────────────────────────────────────────────────────────
31
+ from langchain_openai import ChatOpenAI
32
+ from langchain_core.messages import HumanMessage, SystemMessage
33
+ from langchain_core.tools import tool
34
+ from langchain_huggingface import HuggingFaceEmbeddings
35
+
36
+ # ── LlamaIndex ─────────────────────────────────────────────────────────
37
+ from llama_index.core import (
38
+ VectorStoreIndex,
39
+ Document,
40
+ Settings,
41
+ StorageContext,
42
+ )
43
+ from llama_index.core.retrievers import VectorIndexRetriever
44
+ from llama_index.core.query_engine import RetrieverQueryEngine
45
+ from llama_index.vector_stores.chroma import ChromaVectorStore
46
+
47
+ # ── ChromaDB ───────────────────────────────────────────────────────────
48
+ import chromadb
49
+ from chromadb.config import Settings as ChromaSettings
50
+
51
+
52
+ # ══════════════════════════════════════════════════════════════════════
53
+ # CONFIGURATION
54
+ # ══════════════════════════════════════════════════════════════════════
55
+
56
+ class Config:
57
+ # ── LLM Configuration ──────────────────────────────────────────────
58
+ OPENROUTER_API_KEY: str = os.getenv("OPENROUTER_API_KEY", "ollama")
59
+ OPENROUTER_BASE_URL: str = os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")
60
+ #OPENROUTER_BASE_URL: str = os.getenv("OPENROUTER_BASE_URL", "http://localhost:11434/v1")
61
+
62
+
63
+ # ── Model (local Ollama) ───────────────────────────────────────────
64
+ # LLM_MODEL: str = "gpt-oss:120b-cloud"
65
+ # LLM_MODEL = "openai/gpt-4o" # Premium option
66
+ LLM_MODEL = "qwen/qwen-2.5-72b-instruct" # Alternative
67
+ # LLM_MODEL = "meta-llama/llama-3.1-8b-instruct:free" # Llama free
68
+ # ── HuggingFace Embeddings (runs locally, no API key needed) ───────
69
+ EMBEDDING_MODEL: str = "sentence-transformers/all-MiniLM-L6-v2"
70
+ # EMBEDDING_MODEL = "BAAI/bge-base-en-v1.5" # Higher quality
71
+ # EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
72
+
73
+ # ── ChromaDB (persistent local vector store) ────────────────────────
74
+ CHROMA_PERSIST_DIR: str = "./chroma_cybersec_db"
75
+ CHROMA_COLLECTION: str = "cybersecurity_knowledge"
76
+
77
+ # ── RAG settings ────────────────────────────────────────────────────
78
+ TOP_K_RETRIEVAL: int = 3
79
+ LLM_TEMPERATURE: float = 0.1
80
+ LLM_MAX_TOKENS: int = 2048
81
+
82
+
83
+ # ══════════════════════════════════════════════════════════════════════
84
+ # LANGGRAPH STATE DEFINITION
85
+ # ══════════════════════════════════════════════════════════════════════
86
+
87
+ class CyberAgentState(TypedDict):
88
+ """Shared state flowing through all LangGraph nodes."""
89
+ # Input
90
+ raw_input: str
91
+ input_type: str # "log", "code", "config", "policy"
92
+
93
+ # Per-agent results
94
+ log_findings: Optional[dict]
95
+ threat_intel: Optional[dict]
96
+ vuln_scan: Optional[dict]
97
+ code_fix: Optional[dict] # Iterative code fixer results
98
+ incident_plan: Optional[dict]
99
+ policy_gaps: Optional[dict]
100
+
101
+ # Orchestration metadata
102
+ agent_trace: List[str] # Execution log
103
+ errors: List[str] # Any errors encountered
104
+ rag_context: Optional[str] # Retrieved knowledge base context
105
+ final_report: Optional[str] # Synthesized final report
106
+ started_at: str
107
+
108
+
109
+ # ══════════════════════════════════════════════════════════════════════
110
+ # LLM CLIENT β€” OpenRouter
111
+ # ══════════════════════════════════════════════════════════════════════
112
+
113
+ def build_llm(model: str = None) -> ChatOpenAI:
114
+ """
115
+ Build LangChain ChatOpenAI client pointed at OpenRouter.
116
+ OpenRouter is OpenAI-API-compatible, so no custom wrapper needed.
117
+ """
118
+ if not Config.OPENROUTER_API_KEY:
119
+ Config.OPENROUTER_API_KEY = "ollama"
120
+
121
+ return ChatOpenAI(
122
+ model=model or Config.LLM_MODEL,
123
+ openai_api_key=Config.OPENROUTER_API_KEY,
124
+ openai_api_base=Config.OPENROUTER_BASE_URL,
125
+ temperature=Config.LLM_TEMPERATURE,
126
+ max_tokens=Config.LLM_MAX_TOKENS,
127
+ )
128
+
129
+
130
+ # ══════════════════════════════════════════════════════════════════════
131
+ # HUGGINGFACE EMBEDDINGS
132
+ # ══════════════════════════════════════════════════════════════════════
133
+
134
+ def build_embeddings() -> HuggingFaceEmbeddings:
135
+ """
136
+ Local HuggingFace sentence-transformer embeddings.
137
+ Downloads model on first run (~90MB), cached locally after that.
138
+ """
139
+ print(f" [HuggingFace] Loading embedding model: {Config.EMBEDDING_MODEL}")
140
+ return HuggingFaceEmbeddings(
141
+ model_name=Config.EMBEDDING_MODEL,
142
+ model_kwargs={"device": "cpu"},
143
+ encode_kwargs={"normalize_embeddings": True},
144
+ )
145
+
146
+
147
+ # ══════════════════════════════════════════════════════════════════════
148
+ # VECTOR STORE β€” ChromaDB + LlamaIndex
149
+ # ══════════════════════════════════════════════════════════════════════
150
+
151
+ CYBERSEC_KNOWLEDGE_BASE = [
152
+ # Log Analysis
153
+ Document(
154
+ text="SSH brute force attack pattern: multiple failed authentication attempts "
155
+ "from the same IP within a short timeframe. Typical threshold: >5 failures "
156
+ "in 60 seconds. Common source IPs often belong to Tor exit nodes or VPS providers. "
157
+ "Mitigation: fail2ban, rate limiting, disable password auth, use key-based auth only.",
158
+ metadata={"category": "log_analysis", "threat": "brute_force", "severity": "HIGH"},
159
+ ),
160
+ Document(
161
+ text="SQL Injection in web logs appears as unusual characters in URL parameters: "
162
+ "UNION, SELECT, OR 1=1, --, '; DROP TABLE. WAF bypass techniques include "
163
+ "URL encoding (%27 for '), case variation (SeLeCt), comments (/*!SELECT*/). "
164
+ "CVE references: multiple CVEs exist per application. OWASP A03:2021.",
165
+ metadata={"category": "log_analysis", "threat": "sql_injection", "severity": "CRITICAL"},
166
+ ),
167
+ Document(
168
+ text="Port scanning indicators in network logs: sequential port access, RST responses, "
169
+ "SYN packets to multiple ports in rapid succession. Tools: nmap, masscan, zmap. "
170
+ "Nmap default scan leaves fingerprint in IDS logs as SYN to common ports.",
171
+ metadata={"category": "log_analysis", "threat": "reconnaissance", "severity": "MEDIUM"},
172
+ ),
173
+ # Threat Intel
174
+ Document(
175
+ text="CVE-2021-44228 Log4Shell: Critical RCE in Apache Log4j 2.x. CVSS 10.0. "
176
+ "Exploited by JNDI lookup injection via user-controlled log data. "
177
+ "Affected versions: log4j-core 2.0-beta9 to 2.14.1. "
178
+ "Patch: upgrade to 2.15.0+. Widely exploited in the wild by nation-state actors.",
179
+ metadata={"category": "threat_intel", "cve": "CVE-2021-44228", "cvss": "10.0"},
180
+ ),
181
+ Document(
182
+ text="CVE-2023-44487 HTTP/2 Rapid Reset: DDoS vulnerability in HTTP/2 protocol. "
183
+ "CVSS 7.5. Allows attackers to send RST_STREAM frames to reset connections rapidly. "
184
+ "Affected: nginx, Apache, Go HTTP/2 servers. Patch available in nginx 1.25.3+. "
185
+ "Exploited by botnet in record-breaking DDoS campaigns (October 2023).",
186
+ metadata={"category": "threat_intel", "cve": "CVE-2023-44487", "cvss": "7.5"},
187
+ ),
188
+ Document(
189
+ text="MITRE ATT&CK T1110 Brute Force: Adversaries may use brute force techniques "
190
+ "to gain access to accounts. Sub-techniques: T1110.001 Password Guessing, "
191
+ "T1110.003 Password Spraying, T1110.004 Credential Stuffing. "
192
+ "Relevant threat groups: APT28, Lazarus Group, FIN7.",
193
+ metadata={"category": "threat_intel", "mitre": "T1110"},
194
+ ),
195
+ # Vulnerability Patterns
196
+ Document(
197
+ text="SQL Injection (CWE-89, OWASP A03:2021): Occurs when user input is concatenated "
198
+ "directly into SQL queries without parameterization. Fix: use prepared statements "
199
+ "with parameterized queries. Example vulnerable: query = 'SELECT * FROM users WHERE id=' + id. "
200
+ "Secure: cursor.execute('SELECT * FROM users WHERE id = %s', (id,))",
201
+ metadata={"category": "vulnerability", "cwe": "CWE-89", "owasp": "A03:2021"},
202
+ ),
203
+ Document(
204
+ text="Hardcoded credentials (CWE-798): Embedding passwords, API keys, or tokens "
205
+ "in source code is a critical vulnerability. Secret scanning tools: truffleHog, "
206
+ "git-secrets, GitHub Secret Scanning. Remediation: use environment variables, "
207
+ "AWS Secrets Manager, HashiCorp Vault, or similar secret management systems.",
208
+ metadata={"category": "vulnerability", "cwe": "CWE-798", "severity": "CRITICAL"},
209
+ ),
210
+ Document(
211
+ text="Docker security misconfigurations: Running as root increases attack surface. "
212
+ "Privileged containers can escape to host. Exposed Docker socket (/var/run/docker.sock) "
213
+ "allows full host compromise. Mounting /etc exposes sensitive host files. "
214
+ "Best practices: non-root USER, read-only filesystem, drop capabilities, "
215
+ "network policies, scan images with Trivy or Snyk.",
216
+ metadata={"category": "vulnerability", "topic": "docker", "severity": "HIGH"},
217
+ ),
218
+ # Incident Response
219
+ Document(
220
+ text="NIST SP 800-61 Incident Response phases: Preparation (policies, tools, training), "
221
+ "Detection & Analysis (identify, classify, prioritize), Containment (short/long term), "
222
+ "Eradication (remove threat artifacts), Recovery (restore operations), "
223
+ "Post-Incident Activity (lessons learned, evidence retention). "
224
+ "Severity P1: respond within 15 minutes. P2: 1 hour. P3: 4 hours. P4: 24 hours.",
225
+ metadata={"category": "incident_response", "framework": "NIST_800-61"},
226
+ ),
227
+ Document(
228
+ text="Digital forensics evidence preservation: Capture volatile memory first (RAM) "
229
+ "using tools like LiME or WinPmem. Disk imaging with dd or FTK Imager. "
230
+ "Preserve network logs (PCAP), system logs (/var/log/), "
231
+ "process list, open connections (netstat), scheduled tasks (cron, at). "
232
+ "Chain of custody must be documented for legal proceedings.",
233
+ metadata={"category": "incident_response", "topic": "forensics"},
234
+ ),
235
+ # Compliance
236
+ Document(
237
+ text="NIST CSF 2.0 Core Functions: Govern (GV), Identify (ID), Protect (PR), "
238
+ "Detect (DE), Respond (RS), Recover (RC). "
239
+ "Critical controls: asset inventory (ID.AM), risk assessment (ID.RA), "
240
+ "access control (PR.AA), awareness training (PR.AT), "
241
+ "anomaly detection (DE.AE), incident management (RS.MA).",
242
+ metadata={"category": "compliance", "framework": "NIST_CSF"},
243
+ ),
244
+ Document(
245
+ text="SOC 2 Trust Service Criteria: Security (CC), Availability (A), "
246
+ "Processing Integrity (PI), Confidentiality (C), Privacy (P). "
247
+ "Common CC controls: CC6.1 logical access, CC6.3 MFA, CC7.2 monitoring, "
248
+ "CC8.1 change management, CC9.1 risk management. "
249
+ "Annual penetration testing and vulnerability scans typically required.",
250
+ metadata={"category": "compliance", "framework": "SOC2"},
251
+ ),
252
+ Document(
253
+ text="ISO 27001:2022 Annex A controls include: A.5 Organizational controls, "
254
+ "A.6 People controls (background checks, training), "
255
+ "A.7 Physical controls (clean desk, screen lock), "
256
+ "A.8 Technological controls (endpoint protection, SIEM, vulnerability management, "
257
+ "backup, encryption, MFA, logging). 93 controls total in 2022 version.",
258
+ metadata={"category": "compliance", "framework": "ISO_27001"},
259
+ ),
260
+ ]
261
+
262
+
263
+ def check_vector_store_exists() -> bool:
264
+ """Check if ChromaDB persistent vector store already exists with data."""
265
+ if not os.path.exists(Config.CHROMA_PERSIST_DIR):
266
+ return False
267
+ try:
268
+ client = chromadb.PersistentClient(
269
+ path=Config.CHROMA_PERSIST_DIR,
270
+ settings=ChromaSettings(anonymized_telemetry=False),
271
+ )
272
+ collection = client.get_or_create_collection(name=Config.CHROMA_COLLECTION)
273
+ return collection.count() > 0
274
+ except Exception:
275
+ return False
276
+
277
+
278
+ class VectorKnowledgeBase:
279
+ """
280
+ LlamaIndex + ChromaDB persistent vector store with HuggingFace embeddings.
281
+ Provides RAG retrieval for all agents.
282
+ """
283
+
284
+ def __init__(self, hf_embeddings: HuggingFaceEmbeddings):
285
+ self.hf_embeddings = hf_embeddings
286
+ self._index: Optional[VectorStoreIndex] = None
287
+ self._query_engine: Optional[RetrieverQueryEngine] = None
288
+ self.loaded_existing: bool = False
289
+ self._setup()
290
+
291
+ def _setup(self):
292
+ print(f" [ChromaDB] Initializing persistent store: {Config.CHROMA_PERSIST_DIR}")
293
+
294
+ # ChromaDB persistent client
295
+ chroma_client = chromadb.PersistentClient(
296
+ path=Config.CHROMA_PERSIST_DIR,
297
+ settings=ChromaSettings(anonymized_telemetry=False),
298
+ )
299
+
300
+ # Get or create collection
301
+ chroma_collection = chroma_client.get_or_create_collection(
302
+ name=Config.CHROMA_COLLECTION,
303
+ metadata={"hnsw:space": "cosine"},
304
+ )
305
+
306
+ # LlamaIndex ChromaVectorStore wrapper
307
+ vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
308
+
309
+ # Custom LlamaIndex-compatible embedding wrapper around HuggingFace
310
+ from llama_index.core.embeddings import BaseEmbedding
311
+ from typing import List as TList
312
+
313
+ hf_emb = self.hf_embeddings
314
+
315
+ class HFEmbeddingAdapter(BaseEmbedding):
316
+ """Adapts LangChain HuggingFaceEmbeddings β†’ LlamaIndex BaseEmbedding."""
317
+
318
+ def _get_query_embedding(self, query: str) -> TList[float]:
319
+ return hf_emb.embed_query(query)
320
+
321
+ def _get_text_embedding(self, text: str) -> TList[float]:
322
+ return hf_emb.embed_documents([text])[0]
323
+
324
+ def _get_text_embeddings(self, texts: TList[str]) -> TList[TList[float]]:
325
+ return hf_emb.embed_documents(texts)
326
+
327
+ async def _aget_query_embedding(self, query: str) -> TList[float]:
328
+ return self._get_query_embedding(query)
329
+
330
+ async def _aget_text_embedding(self, text: str) -> TList[float]:
331
+ return self._get_text_embedding(text)
332
+
333
+ # Configure LlamaIndex global settings
334
+ Settings.embed_model = HFEmbeddingAdapter()
335
+ Settings.llm = None # We use LangChain LLM directly
336
+
337
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
338
+
339
+ # Check if collection already has data β€” skip indexing if so
340
+ existing_count = chroma_collection.count()
341
+ if existing_count == 0:
342
+ print(f" [LlamaIndex] Indexing {len(CYBERSEC_KNOWLEDGE_BASE)} knowledge documents...")
343
+ self._index = VectorStoreIndex.from_documents(
344
+ CYBERSEC_KNOWLEDGE_BASE,
345
+ storage_context=storage_context,
346
+ show_progress=True,
347
+ )
348
+ self.loaded_existing = False
349
+ else:
350
+ print(f" [LlamaIndex] Loaded existing index ({existing_count} vectors from ChromaDB)")
351
+ self._index = VectorStoreIndex.from_vector_store(
352
+ vector_store=vector_store,
353
+ storage_context=storage_context,
354
+ )
355
+ self.loaded_existing = True
356
+
357
+ # Build retriever
358
+ retriever = VectorIndexRetriever(
359
+ index=self._index,
360
+ similarity_top_k=Config.TOP_K_RETRIEVAL,
361
+ )
362
+ self._query_engine = RetrieverQueryEngine(retriever=retriever)
363
+
364
+ def retrieve(self, query: str) -> str:
365
+ """Retrieve top-K relevant documents for a query."""
366
+ try:
367
+ retriever = self._index.as_retriever(similarity_top_k=Config.TOP_K_RETRIEVAL)
368
+ nodes = retriever.retrieve(query)
369
+ if not nodes:
370
+ return "No relevant context found in knowledge base."
371
+ parts = []
372
+ for i, node in enumerate(nodes, 1):
373
+ score = getattr(node, "score", 0.0) or 0.0
374
+ category = node.metadata.get("category", "general")
375
+ parts.append(
376
+ f"[Context {i} | category={category} | relevance={score:.2f}]\n"
377
+ f"{node.text}"
378
+ )
379
+ return "\n\n".join(parts)
380
+ except Exception as e:
381
+ return f"RAG retrieval error: {e}"
382
+
383
+ def add_document(self, text: str, metadata: dict = None):
384
+ """Dynamically add new knowledge to the vector store."""
385
+ doc = Document(text=text, metadata=metadata or {})
386
+ self._index.insert(doc)
387
+ print(f" [VectorDB] Added new document (category={metadata.get('category','?')})")
388
+
389
+
390
+ # ══════════════════════════════════════════════════════════════════════
391
+ # LANGCHAIN TOOLS (@tool utilities for agent nodes)
392
+ # ══════════════════════════════════════════════════════════════════════
393
+
394
+ # These tools are callable utilities used INSIDE agent nodes.
395
+ # They provide structured access to the knowledge base and external lookups.
396
+ # The pipeline flow remains node-based (deterministic), but agents can
397
+ # invoke these tools internally for enriched analysis.
398
+
399
+ _kb_instance: Optional[Any] = None # Set during pipeline build
400
+
401
+
402
+ @tool
403
+ def query_knowledge_base(query: str) -> str:
404
+ """Search the cybersecurity knowledge base (ChromaDB) for relevant context on threats, vulnerabilities, compliance, or incident response."""
405
+ if _kb_instance is None:
406
+ return "Knowledge base not initialized."
407
+ return _kb_instance.retrieve(query)
408
+
409
+
410
+ @tool
411
+ def lookup_cve(cve_id: str) -> str:
412
+ """Look up a specific CVE identifier in the knowledge base and return relevant threat intelligence."""
413
+ if _kb_instance is None:
414
+ return "Knowledge base not initialized."
415
+ return _kb_instance.retrieve(f"CVE vulnerability {cve_id} exploit patch")
416
+
417
+
418
+ @tool
419
+ def check_compliance_control(framework: str, control: str) -> str:
420
+ """Check a specific compliance control (e.g., framework='NIST CSF', control='PR.AT-1') against the knowledge base."""
421
+ if _kb_instance is None:
422
+ return "Knowledge base not initialized."
423
+ return _kb_instance.retrieve(f"{framework} {control} compliance requirement")
424
+
425
+
426
+ # List of all available tools for agent nodes
427
+ AGENT_TOOLS = [query_knowledge_base, lookup_cve, check_compliance_control]
428
+
429
+
430
+ # ══════════════════════════════════════════════════════════════════════
431
+ # AGENT NODE FACTORY
432
+ # ══════════════════════════════════════════════════════════════════════
433
+
434
+ def _call_llm(llm: ChatOpenAI, system_prompt: str, user_prompt: str) -> str:
435
+ """Call LLM via OpenRouter with system + user messages."""
436
+ messages = [
437
+ SystemMessage(content=system_prompt),
438
+ HumanMessage(content=user_prompt),
439
+ ]
440
+ response = llm.invoke(messages)
441
+ return response.content
442
+
443
+
444
+ def _parse_json_safe(text: str) -> dict:
445
+ """Safely parse JSON from LLM response, stripping markdown fences."""
446
+ clean = text.strip()
447
+ for fence in ["```json", "```JSON", "```"]:
448
+ if clean.startswith(fence):
449
+ clean = clean[len(fence):]
450
+ if clean.endswith("```"):
451
+ clean = clean[:-3]
452
+ clean = clean.strip()
453
+ try:
454
+ return json.loads(clean)
455
+ except json.JSONDecodeError:
456
+ # Return structured error fallback
457
+ return {"raw_output": text, "parse_error": "JSON decode failed"}
458
+
459
+
460
+ # ══════════════════════════════════════════════════════════════════════
461
+ # NODE 1 β€” INPUT CLASSIFIER
462
+ # ══════════════════════════════════════════════════════════════════════
463
+
464
+ def node_input_classifier(state: CyberAgentState) -> CyberAgentState:
465
+ """Classify input type and route accordingly."""
466
+ text = state["raw_input"].lower()
467
+ input_type = "general"
468
+
469
+ log_keywords = ["failed password", "sshd", "auth", "nov ", "dec ", "timestamp", "kernel", "iptables"]
470
+ code_keywords = ["def ", "function", "import ", "require(", "const ", "class ", "SELECT", "query"]
471
+ config_keywords = ["docker", "privileged", "volume", "--", "env", "container", "nginx", "aws_"]
472
+ policy_keywords = ["mfa", "policy", "compliance", "training", "audit", "siem", "retention", "encryption at rest"]
473
+
474
+ scores = {
475
+ "log": sum(k in text for k in log_keywords),
476
+ "code": sum(k in text for k in code_keywords),
477
+ "config": sum(k in text for k in config_keywords),
478
+ "policy": sum(k in text for k in policy_keywords),
479
+ }
480
+ input_type = max(scores, key=scores.get) if max(scores.values()) > 0 else "general"
481
+
482
+ trace = state.get("agent_trace", [])
483
+ trace.append(f"[{_ts()}] InputClassifier β†’ detected input_type='{input_type}' | scores={scores}")
484
+
485
+ return {**state, "input_type": input_type, "agent_trace": trace}
486
+
487
+
488
+ # ══════════════════════════════════════════════════════════════════════
489
+ # NODE 2 β€” RAG CONTEXT RETRIEVER
490
+ # ══════════════════════════════════════════════════════════════════════
491
+
492
+ def build_rag_node(kb: VectorKnowledgeBase):
493
+ def node_rag_retriever(state: CyberAgentState) -> CyberAgentState:
494
+ """Retrieve relevant knowledge base context before agent analysis."""
495
+ query = f"cybersecurity {state['input_type']} analysis: {state['raw_input'][:300]}"
496
+ print(f" [RAG] Retrieving context for: {query[:80]}...")
497
+ context = kb.retrieve(query)
498
+
499
+ trace = state.get("agent_trace", [])
500
+ trace.append(f"[{_ts()}] RAGRetriever β†’ retrieved {len(context)} chars of context")
501
+ return {**state, "rag_context": context, "agent_trace": trace}
502
+ return node_rag_retriever
503
+
504
+
505
+ # ══════════════════════════════════════════════════════════════════════
506
+ # NODE 3 β€” LOG MONITOR AGENT
507
+ # ══════════════════════════════════════════════════════════════════════
508
+
509
+ LOG_MONITOR_SYSTEM = """You are an expert Security Log Analysis Agent.
510
+ Analyze the provided input for security threats, anomalies, and indicators of compromise.
511
+ Use the RAG knowledge context to enrich your analysis.
512
+
513
+ Return ONLY valid JSON (no markdown fences) with this exact structure:
514
+ {
515
+ "severity": "CRITICAL|HIGH|MEDIUM|LOW",
516
+ "summary": "one-line overview",
517
+ "findings": [
518
+ {"type": "attack type", "detail": "specific detail", "severity": "HIGH", "source_ip": "if present"}
519
+ ],
520
+ "indicators_of_compromise": ["ioc1", "ioc2"],
521
+ "attack_timeline": "reconstructed sequence if possible",
522
+ "recommended_next_step": "immediate action"
523
+ }"""
524
+
525
+ def build_log_monitor_node(llm: ChatOpenAI):
526
+ def node_log_monitor(state: CyberAgentState) -> CyberAgentState:
527
+ print(" [Agent] Log Monitor Agent running...")
528
+ user_prompt = (
529
+ f"RAG CONTEXT:\n{state.get('rag_context', 'None')}\n\n"
530
+ f"INPUT TO ANALYZE:\n{state['raw_input']}"
531
+ )
532
+ try:
533
+ raw = _call_llm(llm, LOG_MONITOR_SYSTEM, user_prompt)
534
+ result = _parse_json_safe(raw)
535
+ except Exception as e:
536
+ result = {"error": str(e), "severity": "UNKNOWN"}
537
+
538
+ trace = state.get("agent_trace", [])
539
+ trace.append(f"[{_ts()}] LogMonitorAgent β†’ severity={result.get('severity','?')} | {len(result.get('findings',[]))} findings")
540
+ return {**state, "log_findings": result, "agent_trace": trace}
541
+ return node_log_monitor
542
+
543
+
544
+ # ══════════════════════════════════════════════════════════════════════
545
+ # NODE 4 β€” THREAT INTELLIGENCE AGENT
546
+ # ══════════════════════════════════════════════════════════════════════
547
+
548
+ THREAT_INTEL_SYSTEM = """You are a Cyber Threat Intelligence Agent with expertise in CVEs,
549
+ threat actors, and MITRE ATT&CK framework.
550
+ Use RAG context to identify real CVEs and known threats related to the input.
551
+
552
+ Return ONLY valid JSON (no markdown fences):
553
+ {
554
+ "exposure_level": "CRITICAL|HIGH|MEDIUM|LOW",
555
+ "summary": "threat landscape summary",
556
+ "cves": [
557
+ {"id": "CVE-XXXX-XXXXX", "cvss_score": 9.8, "description": "brief", "exploited_in_wild": true}
558
+ ],
559
+ "mitre_ttps": [
560
+ {"id": "T1110", "name": "Brute Force", "tactic": "Credential Access"}
561
+ ],
562
+ "threat_actors": ["APT28", "FIN7"],
563
+ "intelligence_assessment": "detailed assessment paragraph"
564
+ }"""
565
+
566
+ def build_threat_intel_node(llm: ChatOpenAI):
567
+ def node_threat_intel(state: CyberAgentState) -> CyberAgentState:
568
+ print(" [Agent] Threat Intelligence Agent running...")
569
+ # Use @tool: lookup_cve for enrichment
570
+ extra_context = ""
571
+ rag_text = state.get("rag_context", "")
572
+ if "cve" in state["raw_input"].lower() or "cve" in rag_text.lower():
573
+ cve_result = lookup_cve.invoke("known CVEs related to detected attack patterns")
574
+ extra_context = f"\nTOOL(lookup_cve) RESULT:\n{cve_result}\n"
575
+
576
+ prior_context = ""
577
+ if state.get("log_findings"):
578
+ prior_context = f"\nLOG MONITOR FINDINGS:\n{json.dumps(state['log_findings'], indent=2)}\n"
579
+
580
+ user_prompt = (
581
+ f"RAG CONTEXT:\n{state.get('rag_context', 'None')}\n"
582
+ f"{extra_context}"
583
+ f"{prior_context}"
584
+ f"\nINPUT TO ANALYZE:\n{state['raw_input']}"
585
+ )
586
+ try:
587
+ raw = _call_llm(llm, THREAT_INTEL_SYSTEM, user_prompt)
588
+ result = _parse_json_safe(raw)
589
+ except Exception as e:
590
+ result = {"error": str(e), "exposure_level": "UNKNOWN"}
591
+
592
+ trace = state.get("agent_trace", [])
593
+ trace.append(f"[{_ts()}] ThreatIntelAgent β†’ {len(result.get('cves',[]))} CVEs | {len(result.get('mitre_ttps',[]))} TTPs")
594
+ return {**state, "threat_intel": result, "agent_trace": trace}
595
+ return node_threat_intel
596
+
597
+
598
+ # ══════════════════════════════════════════════════════════════════════
599
+ # NODE 5 β€” VULNERABILITY SCANNER AGENT
600
+ # ══════════════════════════════════════════════════════════════════════
601
+
602
+ VULN_SCANNER_SYSTEM = """You are an expert Vulnerability Assessment Agent.
603
+ Analyze the input for security vulnerabilities, misconfigurations, and coding flaws.
604
+ Map findings to OWASP Top 10, CWE, and CVE identifiers where applicable.
605
+
606
+ Return ONLY valid JSON (no markdown fences):
607
+ {
608
+ "risk_score": 85,
609
+ "summary": "scan overview",
610
+ "total_findings": 5,
611
+ "vulnerabilities": [
612
+ {
613
+ "id": "VULN-001",
614
+ "title": "SQL Injection",
615
+ "cwe": "CWE-89",
616
+ "owasp": "A03:2021",
617
+ "severity": "CRITICAL",
618
+ "exploitable": true,
619
+ "location": "file.py line 42",
620
+ "description": "detailed description",
621
+ "remediation": "how to fix it"
622
+ }
623
+ ],
624
+ "secure_coding_recommendations": ["recommendation 1", "recommendation 2"]
625
+ }"""
626
+
627
+ def build_vuln_scanner_node(llm: ChatOpenAI):
628
+ def node_vuln_scanner(state: CyberAgentState) -> CyberAgentState:
629
+ print(" [Agent] Vulnerability Scanner Agent running...")
630
+ user_prompt = (
631
+ f"RAG CONTEXT:\n{state.get('rag_context', 'None')}\n\n"
632
+ f"INPUT TO SCAN:\n{state['raw_input']}"
633
+ )
634
+ try:
635
+ raw = _call_llm(llm, VULN_SCANNER_SYSTEM, user_prompt)
636
+ result = _parse_json_safe(raw)
637
+ except Exception as e:
638
+ result = {"error": str(e), "risk_score": 0}
639
+
640
+ trace = state.get("agent_trace", [])
641
+ trace.append(f"[{_ts()}] VulnScannerAgent β†’ risk_score={result.get('risk_score','?')} | {result.get('total_findings','?')} findings")
642
+ return {**state, "vuln_scan": result, "agent_trace": trace}
643
+ return node_vuln_scanner
644
+
645
+
646
+ # ══════════════════════════════════════════════════════════════════════
647
+ # NODE 5B β€” ITERATIVE CODE FIXER AGENT
648
+ # ══════════════════════════════════════════════════════════════════════
649
+
650
+ CODE_FIXER_SYSTEM = """You are an expert Secure Code Fixer Agent.
651
+ You receive buggy/vulnerable code along with vulnerability findings.
652
+ Your job is to fix ALL security vulnerabilities and bugs in the provided code.
653
+
654
+ IMPORTANT RULES:
655
+ - You MUST return the SAME code that was given to you, but with security fixes applied.
656
+ - Do NOT generate new/different code. Only modify the vulnerable lines.
657
+ - Keep the same imports, structure, function names, and logic.
658
+ - Only change what is necessary to fix the vulnerabilities.
659
+
660
+ After fixing, verify:
661
+ 1. Path traversal: Is user input sanitized before file access?
662
+ 2. SQL injection: Are parameterized queries used?
663
+ 3. Hardcoded credentials: Are they removed/externalized?
664
+ 4. Input validation: Is it added where needed?
665
+
666
+ Return ONLY valid JSON (no markdown fences):
667
+ {
668
+ "iteration": 1,
669
+ "fixed_code": "the complete fixed source code preserving original structure",
670
+ "changes_made": [
671
+ {"issue": "Path Traversal", "fix": "Added os.path.realpath check", "line": "10"}
672
+ ],
673
+ "remaining_issues": [],
674
+ "is_fully_fixed": true,
675
+ "confidence": 95,
676
+ "explanation": "Summary of all fixes applied"
677
+ }
678
+
679
+ If there are still remaining issues, set is_fully_fixed to false and list them.
680
+ """
681
+
682
+ MAX_CODE_FIX_ITERATIONS = 3
683
+
684
+
685
+ def build_code_fixer_node(llm: ChatOpenAI):
686
+ def node_code_fixer(state: CyberAgentState) -> CyberAgentState:
687
+ # Skip if input is not code
688
+ if state.get("input_type") not in ("code", "general"):
689
+ trace = state.get("agent_trace", [])
690
+ trace.append(f"[{_ts()}] CodeFixerAgent β†’ skipped (input_type={state.get('input_type')})")
691
+ return {**state, "code_fix": {"skipped": True, "reason": "not code input"}, "agent_trace": trace}
692
+
693
+ existing_fix = state.get("code_fix") or {}
694
+ iteration = existing_fix.get("iteration", 0) + 1
695
+
696
+ print(f" [Agent] Code Fixer Agent running (iteration {iteration}/{MAX_CODE_FIX_ITERATIONS})...")
697
+
698
+ # Build prompt with vuln findings and previous fix attempt
699
+ vuln_context = json.dumps(state.get("vuln_scan") or {}, indent=2)
700
+ code_to_fix = existing_fix.get("fixed_code", state["raw_input"])
701
+ previous_issues = existing_fix.get("remaining_issues", [])
702
+
703
+ user_prompt = (
704
+ f"VULNERABILITY SCAN FINDINGS:\n{vuln_context}\n\n"
705
+ )
706
+ if iteration > 1:
707
+ user_prompt += (
708
+ f"PREVIOUS FIX ATTEMPT (iteration {iteration - 1}) STILL HAD ISSUES:\n"
709
+ f"{json.dumps(previous_issues, indent=2)}\n\n"
710
+ )
711
+ user_prompt += f"CODE TO FIX:\n{code_to_fix}"
712
+
713
+ try:
714
+ raw = _call_llm(llm, CODE_FIXER_SYSTEM, user_prompt)
715
+ result = _parse_json_safe(raw)
716
+ result["iteration"] = iteration
717
+ except Exception as e:
718
+ result = {"error": str(e), "iteration": iteration, "is_fully_fixed": True}
719
+
720
+ trace = state.get("agent_trace", [])
721
+ is_fixed = result.get("is_fully_fixed", True)
722
+ n_changes = len(result.get("changes_made", []))
723
+ n_remaining = len(result.get("remaining_issues", []))
724
+ trace.append(
725
+ f"[{_ts()}] CodeFixerAgent β†’ iteration={iteration} | "
726
+ f"{n_changes} fixes | {n_remaining} remaining | fully_fixed={is_fixed}"
727
+ )
728
+
729
+ return {**state, "code_fix": result, "agent_trace": trace}
730
+ return node_code_fixer
731
+
732
+
733
+ def code_fixer_should_loop(state: CyberAgentState) -> str:
734
+ """Conditional edge: loop back to code_fixer if not fully fixed and under max iterations."""
735
+ code_fix = state.get("code_fix") or {}
736
+ if code_fix.get("skipped"):
737
+ return "incident_response"
738
+ iteration = code_fix.get("iteration", 0)
739
+ is_fixed = code_fix.get("is_fully_fixed", True)
740
+ if not is_fixed and iteration < MAX_CODE_FIX_ITERATIONS:
741
+ return "code_fixer"
742
+ return "incident_response"
743
+
744
+
745
+ # ══════════════════════════════════════════════════════════════════════
746
+ # NODE 6 β€” INCIDENT RESPONSE AGENT
747
+ # ══════════════════════════════════════════════════════════════════════
748
+
749
+ INCIDENT_RESPONSE_SYSTEM = """You are an Incident Response Commander following NIST SP 800-61.
750
+ Based on all prior agent findings, create a comprehensive incident response plan.
751
+
752
+ Return ONLY valid JSON (no markdown fences):
753
+ {
754
+ "incident_classification": "Credential Attack / Data Breach / etc",
755
+ "priority": "P1|P2|P3|P4",
756
+ "timeline": {
757
+ "immediate_0_1h": ["isolate affected systems", "preserve logs"],
758
+ "short_term_1_24h": ["forensic analysis", "patch systems"],
759
+ "long_term_1_7d": ["root cause analysis", "policy updates"]
760
+ },
761
+ "containment_steps": ["step 1", "step 2"],
762
+ "eradication_steps": ["step 1", "step 2"],
763
+ "recovery_steps": ["step 1", "step 2"],
764
+ "evidence_to_preserve": ["/var/log/auth.log", "memory dump"],
765
+ "stakeholders": ["CISO", "Legal", "PR"],
766
+ "communications_template": "Brief incident notification text",
767
+ "lessons_learned_items": ["item 1", "item 2"]
768
+ }"""
769
+
770
+ def build_incident_response_node(llm: ChatOpenAI):
771
+ def node_incident_response(state: CyberAgentState) -> CyberAgentState:
772
+ print(" [Agent] Incident Response Agent running...")
773
+ aggregated = json.dumps({
774
+ "log_findings": state.get("log_findings"),
775
+ "threat_intel": state.get("threat_intel"),
776
+ "vuln_scan": state.get("vuln_scan"),
777
+ }, indent=2)
778
+
779
+ user_prompt = (
780
+ f"RAG CONTEXT:\n{state.get('rag_context', 'None')}\n\n"
781
+ f"ALL PRIOR AGENT FINDINGS:\n{aggregated}\n\n"
782
+ f"ORIGINAL INPUT:\n{state['raw_input']}"
783
+ )
784
+ try:
785
+ raw = _call_llm(llm, INCIDENT_RESPONSE_SYSTEM, user_prompt)
786
+ result = _parse_json_safe(raw)
787
+ except Exception as e:
788
+ result = {"error": str(e), "priority": "UNKNOWN"}
789
+
790
+ trace = state.get("agent_trace", [])
791
+ trace.append(f"[{_ts()}] IncidentResponseAgent β†’ priority={result.get('priority','?')}")
792
+ return {**state, "incident_plan": result, "agent_trace": trace}
793
+ return node_incident_response
794
+
795
+
796
+ # ══════════════════════════════════════════════════════════════════════
797
+ # NODE 7 β€” POLICY CHECKER AGENT
798
+ # ═══════════════���══════════════════════════════════════════════════════
799
+
800
+ POLICY_CHECKER_SYSTEM = """You are a Security Compliance and Policy Expert.
801
+ Evaluate the provided information against NIST CSF 2.0, ISO 27001:2022, and SOC 2 Type II.
802
+ Use RAG context for specific control requirements.
803
+
804
+ Return ONLY valid JSON (no markdown fences):
805
+ {
806
+ "overall_score": 45,
807
+ "summary": "compliance overview",
808
+ "frameworks": {
809
+ "nist_csf": {
810
+ "score": 50,
811
+ "passing": ["ID.AM-1: Asset inventory exists"],
812
+ "failing": ["PR.AT-1: No security training"],
813
+ "partial": ["DE.AE-1: Partial anomaly detection"]
814
+ },
815
+ "iso_27001": {
816
+ "score": 40,
817
+ "passing": [],
818
+ "failing": ["A.8.5: Secure authentication not enforced"],
819
+ "partial": []
820
+ },
821
+ "soc2": {
822
+ "score": 35,
823
+ "passing": [],
824
+ "failing": ["CC6.3: MFA not required"],
825
+ "partial": []
826
+ }
827
+ },
828
+ "gaps": [
829
+ {
830
+ "control": "CC6.3",
831
+ "framework": "SOC2",
832
+ "gap": "MFA not enforced",
833
+ "risk": "HIGH",
834
+ "remediation": "Implement MFA for all user accounts"
835
+ }
836
+ ],
837
+ "quick_wins": ["Enable MFA", "Set 90-day log retention"],
838
+ "compliance_roadmap": "Step-by-step prioritized path to compliance"
839
+ }"""
840
+
841
+ def build_policy_checker_node(llm: ChatOpenAI):
842
+ def node_policy_checker(state: CyberAgentState) -> CyberAgentState:
843
+ print(" [Agent] Policy Checker Agent running...")
844
+ # Use @tool: check_compliance_control for enrichment
845
+ compliance_context = ""
846
+ input_lower = state["raw_input"].lower()
847
+ if "mfa" in input_lower or "encryption" in input_lower or "training" in input_lower:
848
+ compliance_context = check_compliance_control.invoke({"framework": "NIST CSF", "control": "access control MFA encryption"})
849
+ compliance_context = f"\nTOOL(check_compliance_control) RESULT:\n{compliance_context}\n"
850
+
851
+ user_prompt = (
852
+ f"RAG CONTEXT:\n{state.get('rag_context', 'None')}\n"
853
+ f"{compliance_context}\n"
854
+ f"CONFIGURATION/POLICY TO EVALUATE:\n{state['raw_input']}\n\n"
855
+ f"VULNERABILITY FINDINGS:\n{json.dumps(state.get('vuln_scan', {}), indent=2)}"
856
+ )
857
+ try:
858
+ raw = _call_llm(llm, POLICY_CHECKER_SYSTEM, user_prompt)
859
+ result = _parse_json_safe(raw)
860
+ except Exception as e:
861
+ result = {"error": str(e), "overall_score": 0}
862
+
863
+ trace = state.get("agent_trace", [])
864
+ trace.append(f"[{_ts()}] PolicyCheckerAgent β†’ overall_score={result.get('overall_score','?')}")
865
+ return {**state, "policy_gaps": result, "agent_trace": trace}
866
+ return node_policy_checker
867
+
868
+
869
+ # ══════════════════════════════════════════════════════════════════════
870
+ # NODE 8 β€” REPORT SYNTHESIZER
871
+ # ══════════════════════════════════════════════════════════════════════
872
+
873
+ def node_synthesize_report(state: CyberAgentState) -> CyberAgentState:
874
+ """Combine all agent outputs into a Markdown-formatted final report."""
875
+ lf = state.get("log_findings") or {}
876
+ ti = state.get("threat_intel") or {}
877
+ vs = state.get("vuln_scan") or {}
878
+ cf = state.get("code_fix") or {}
879
+ ir = state.get("incident_plan") or {}
880
+ pc = state.get("policy_gaps") or {}
881
+
882
+ lines = [
883
+ f"πŸ“‹ **Analysis Report** | Generated: `{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}` | Input: `{state.get('input_type', 'unknown').upper()}`",
884
+ "",
885
+ "---",
886
+ "",
887
+ "#### Agent Summary",
888
+ "",
889
+ "| Agent | Key Metric | Details |",
890
+ "|-------|-----------|---------|" ,
891
+ f"| πŸ“‘ Log Monitor | Severity: **{lf.get('severity','N/A')}** | {len(lf.get('findings',[]))} findings |",
892
+ f"| πŸ•΅οΈ Threat Intel | Exposure: **{ti.get('exposure_level','N/A')}** | {len(ti.get('cves',[]))} CVEs, {len(ti.get('mitre_ttps',[]))} TTPs |",
893
+ f"| πŸ” Vuln Scanner | Risk: **{vs.get('risk_score','N/A')}/100** | {vs.get('total_findings',0)} findings |",
894
+ f"| πŸ”§ Code Fixer | {'Skipped' if cf.get('skipped') else f'Iter {cf.get("iteration",0)}/3'} | {'β€”' if cf.get('skipped') else ('βœ… Fixed' if cf.get('is_fully_fixed') else '❌ Remaining issues')} |",
895
+ f"| 🚨 Incident Response | Priority: **{ir.get('priority','N/A')}** | {ir.get('incident_classification','N/A')} |",
896
+ f"| πŸ“‹ Policy Checker | Score: **{pc.get('overall_score','N/A')}/100** | {len(pc.get('gaps',[]))} gaps |",
897
+ ]
898
+
899
+ # Detailed findings (only show sections with data)
900
+ if lf.get("findings"):
901
+ lines += ["", "---", "", "#### πŸ“‘ Log Findings", "",
902
+ f"> {lf.get('summary','')}", "",
903
+ "| Severity | Type | Detail | Source IP |",
904
+ "|----------|------|--------|-----------|"]
905
+ for f in lf.get("findings", []):
906
+ lines.append(f"| {f.get('severity','?')} | {f.get('type','?')} | {f.get('detail','?')} | `{f.get('source_ip','β€”')}` |")
907
+ iocs = lf.get("indicators_of_compromise", [])
908
+ if iocs:
909
+ lines += ["", f"**IoCs:** `{'`, `'.join(iocs)}`"]
910
+
911
+ if ti.get("cves") or ti.get("mitre_ttps"):
912
+ lines += ["", "---", "", "#### πŸ•΅οΈ Threat Intelligence", ""]
913
+ if ti.get("summary"):
914
+ lines.append(f"> {ti['summary']}")
915
+ lines.append("")
916
+ if ti.get("cves"):
917
+ lines += ["| CVE | CVSS | Description | In Wild |", "|-----|------|-------------|---------|"]
918
+ for cve in ti["cves"]:
919
+ wild = "πŸ”΄ Yes" if cve.get("exploited_in_wild") else "β€”"
920
+ lines.append(f"| `{cve.get('id','?')}` | {cve.get('cvss_score','?')} | {cve.get('description','?')} | {wild} |")
921
+ if ti.get("mitre_ttps"):
922
+ lines += ["", "**MITRE ATT&CK:**"]
923
+ for ttp in ti["mitre_ttps"]:
924
+ lines.append(f"- `{ttp.get('id','?')}` {ttp.get('name','?')} ({ttp.get('tactic','?')})")
925
+
926
+ if vs.get("vulnerabilities"):
927
+ lines += ["", "---", "", "#### πŸ” Vulnerabilities", "",
928
+ "| ID | Severity | Title | CWE | Fix |",
929
+ "|----|----------|-------|-----|-----|"]
930
+ for v in vs.get("vulnerabilities", []):
931
+ lines.append(f"| {v.get('id','?')} | {v.get('severity','?')} | {v.get('title','?')} | `{v.get('cwe','?')}` | {v.get('remediation','β€”')} |")
932
+
933
+ if not cf.get("skipped") and cf.get("changes_made"):
934
+ lines += ["", "---", "", f"#### πŸ”§ Code Fixer (Iteration {cf.get('iteration',0)}/3)", "",
935
+ "| Issue | Fix | Line |", "|-------|-----|------|"]
936
+ for c in cf.get("changes_made", []):
937
+ lines.append(f"| {c.get('issue','?')} | {c.get('fix','?')} | {c.get('line','?')} |")
938
+ if cf.get("explanation"):
939
+ lines += ["", f"> {cf['explanation']}"]
940
+
941
+ if ir.get("timeline"):
942
+ lines += ["", "---", "", "#### 🚨 Incident Response", "",
943
+ f"> **{ir.get('incident_classification','N/A')}**", "",
944
+ "| Phase | Actions |", "|-------|---------|"]
945
+ tl = ir["timeline"]
946
+ for phase, label in [("immediate_0_1h","πŸ”΄ 0-1h"),("short_term_1_24h","🟑 1-24h"),("long_term_1_7d","🟒 1-7d")]:
947
+ actions = tl.get(phase, [])
948
+ if actions:
949
+ lines.append(f"| {label} | {'; '.join(actions)} |")
950
+ evidence = ir.get("evidence_to_preserve", [])
951
+ if evidence:
952
+ lines += ["", f"**Preserve:** `{'`, `'.join(evidence)}`"]
953
+
954
+ if pc.get("frameworks"):
955
+ lines += ["", "---", "", "#### πŸ“‹ Compliance", "",
956
+ "| Framework | Score | Gaps |", "|-----------|------:|-----:|"]
957
+ fw = pc["frameworks"]
958
+ for fk, fl in [("nist_csf","NIST CSF"),("iso_27001","ISO 27001"),("soc2","SOC 2")]:
959
+ if fk in fw:
960
+ lines.append(f"| {fl} | {fw[fk].get('score','?')}/100 | {len(fw[fk].get('failing',[]))} |")
961
+ qw = pc.get("quick_wins", [])
962
+ if qw:
963
+ lines += ["", "**Quick Wins:** " + ", ".join(qw[:5])]
964
+
965
+ # Execution Trace (collapsible)
966
+ lines += ["", "---", "",
967
+ "<details><summary>πŸ“ <b>Execution Trace</b></summary>", "", "```"]
968
+ for t in state.get("agent_trace", []):
969
+ lines.append(t)
970
+ lines += ["```", "", "</details>"]
971
+
972
+ report = "\n".join(lines)
973
+ trace = state.get("agent_trace", [])
974
+ trace.append(f"[{_ts()}] ReportSynthesizer β†’ report generated ({len(report)} chars)")
975
+ return {**state, "final_report": report, "agent_trace": trace}
976
+
977
+
978
+ # ══════════════════════════════════════════════════════════════════════
979
+ # LANGGRAPH ORCHESTRATOR
980
+ # ══════════════════════════════════════════════════════════════════════
981
+
982
+ def build_cybersec_graph(llm: ChatOpenAI, kb: VectorKnowledgeBase) -> Any:
983
+ """
984
+ Build and compile the LangGraph state machine.
985
+
986
+ Flow:
987
+ classify_input β†’ rag_retrieve β†’ log_monitor β†’ threat_intel
988
+ β†’ vuln_scanner β†’ incident_response
989
+ β†’ policy_checker
990
+ β†’ synthesize_report β†’ END
991
+ """
992
+ graph = StateGraph(CyberAgentState)
993
+
994
+ # Set global kb reference for @tool functions
995
+ global _kb_instance
996
+ _kb_instance = kb
997
+
998
+ # Register nodes
999
+ graph.add_node("classify_input", node_input_classifier)
1000
+ graph.add_node("rag_retrieve", build_rag_node(kb))
1001
+ graph.add_node("log_monitor", build_log_monitor_node(llm))
1002
+ graph.add_node("threat_intel", build_threat_intel_node(llm))
1003
+ graph.add_node("vuln_scanner", build_vuln_scanner_node(llm))
1004
+ graph.add_node("code_fixer", build_code_fixer_node(llm))
1005
+ graph.add_node("incident_response", build_incident_response_node(llm))
1006
+ graph.add_node("policy_checker", build_policy_checker_node(llm))
1007
+ graph.add_node("synthesize_report", node_synthesize_report)
1008
+
1009
+ # Define edges
1010
+ graph.set_entry_point("classify_input")
1011
+ graph.add_edge("classify_input", "rag_retrieve")
1012
+ graph.add_edge("rag_retrieve", "log_monitor")
1013
+ graph.add_edge("log_monitor", "threat_intel")
1014
+ graph.add_edge("threat_intel", "vuln_scanner")
1015
+ graph.add_edge("vuln_scanner", "code_fixer")
1016
+ # Conditional loop: code_fixer β†’ code_fixer (if not fixed) OR β†’ incident_response
1017
+ graph.add_conditional_edges(
1018
+ "code_fixer",
1019
+ code_fixer_should_loop,
1020
+ {"code_fixer": "code_fixer", "incident_response": "incident_response"},
1021
+ )
1022
+ graph.add_edge("incident_response", "policy_checker")
1023
+ graph.add_edge("policy_checker", "synthesize_report")
1024
+ graph.add_edge("synthesize_report", END)
1025
+
1026
+ return graph.compile()
1027
+
1028
+
1029
+ # ══════════════════════════════════════════════════════════════════════
1030
+ # HELPER
1031
+ # ══════════════════════════════════════════════════════════════════════
1032
+
1033
+ def _ts() -> str:
1034
+ return datetime.now().strftime("%H:%M:%S")
1035
+
1036
+
1037
+ # ══════════════════════════════════════════════════════════════════════
1038
+ # MAIN ENTRY POINT
1039
+ # ══════════════════════════════════════════════════════════════════════
1040
+
1041
+ def run_analysis(user_input: str, save_report: bool = True) -> dict:
1042
+ """
1043
+ Run the full multi-agent cybersecurity analysis pipeline.
1044
+
1045
+ Args:
1046
+ user_input: Logs, code, config, or policy text to analyze
1047
+ save_report: Whether to save the final report to disk
1048
+
1049
+ Returns:
1050
+ Final CyberAgentState dict with all agent results
1051
+ """
1052
+ print("\n" + "=" * 60)
1053
+ print(" CyberSecurity Multi-Agent System")
1054
+ print(" Stack: LangGraph Β· OpenRouter Β· HuggingFace Β· LlamaIndex Β· ChromaDB")
1055
+ print("=" * 60)
1056
+
1057
+ # 1. Initialize LLM (OpenRouter)
1058
+ print("\n[1/4] Connecting to OpenRouter LLM...")
1059
+ llm = build_llm()
1060
+ print(f" Model: {Config.LLM_MODEL}")
1061
+
1062
+ # 2. Initialize HuggingFace embeddings
1063
+ print("\n[2/4] Loading HuggingFace embedding model...")
1064
+ embeddings = build_embeddings()
1065
+
1066
+ # 3. Initialize vector knowledge base
1067
+ print("\n[3/4] Setting up LlamaIndex + ChromaDB vector store...")
1068
+ kb = VectorKnowledgeBase(embeddings)
1069
+
1070
+ # 4. Build and run LangGraph
1071
+ print("\n[4/4] Building LangGraph pipeline and running agents...\n")
1072
+ app = build_cybersec_graph(llm, kb)
1073
+
1074
+ initial_state: CyberAgentState = {
1075
+ "raw_input": user_input,
1076
+ "input_type": "general",
1077
+ "log_findings": None,
1078
+ "threat_intel": None,
1079
+ "vuln_scan": None,
1080
+ "code_fix": None,
1081
+ "incident_plan": None,
1082
+ "policy_gaps": None,
1083
+ "agent_trace": [],
1084
+ "errors": [],
1085
+ "rag_context": None,
1086
+ "final_report": None,
1087
+ "started_at": datetime.now().isoformat(),
1088
+ }
1089
+
1090
+ t0 = time.time()
1091
+ final_state = app.invoke(initial_state)
1092
+ elapsed = time.time() - t0
1093
+
1094
+ # Print report
1095
+ print("\n" + final_state.get("final_report", "No report generated"))
1096
+ print(f"\n⏱ Total analysis time: {elapsed:.1f}s")
1097
+
1098
+ # Save report
1099
+ if save_report and final_state.get("final_report"):
1100
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
1101
+ fname = f"cybersec_report_{ts}.txt"
1102
+ with open(fname, "w", encoding="utf-8") as f:
1103
+ f.write(final_state["final_report"])
1104
+ print(f"πŸ’Ύ Report saved: {fname}")
1105
+
1106
+ # Also save JSON results
1107
+ json_fname = f"cybersec_results_{ts}.json"
1108
+ json_data = {k: v for k, v in final_state.items() if k != "final_report"}
1109
+ with open(json_fname, "w", encoding="utf-8") as f:
1110
+ json.dump(json_data, f, indent=2, default=str)
1111
+ print(f"πŸ’Ύ JSON results saved: {json_fname}")
1112
+
1113
+ return final_state
1114
+
1115
+
1116
+ # ═════════════════════════════════════════════════════════════════════��
1117
+ # EXAMPLE SCENARIOS
1118
+ # ══════════════════════════════════════════════════════════════════════
1119
+
1120
+ EXAMPLE_INPUTS = {
1121
+ "ssh_brute_force": """
1122
+ Nov 12 03:14:22 web01 sshd[12345]: Failed password for root from 192.168.1.105 port 54321 ssh2
1123
+ Nov 12 03:14:23 web01 sshd[12346]: Failed password for root from 192.168.1.105 port 54322 ssh2
1124
+ Nov 12 03:14:24 web01 sshd[12347]: Failed password for admin from 192.168.1.105 port 54323 ssh2
1125
+ Nov 12 03:14:25 web01 sshd[12348]: Failed password for ubuntu from 192.168.1.105 port 54324 ssh2
1126
+ Nov 12 03:14:30 web01 sshd[12350]: Failed password for root from 185.220.101.45 port 12345 ssh2
1127
+ Nov 12 03:14:50 web01 sshd[12360]: Accepted password for deploy from 185.220.101.45 port 12346 ssh2
1128
+ """,
1129
+
1130
+ "vulnerable_code": """
1131
+ import sqlite3, flask
1132
+ app = flask.Flask(__name__)
1133
+ DB_PASSWORD = "supersecret123"
1134
+
1135
+ @app.route('/user')
1136
+ def get_user():
1137
+ user_id = flask.request.args.get('id')
1138
+ conn = sqlite3.connect('users.db')
1139
+ cursor = conn.cursor()
1140
+ # Vulnerable to SQL injection!
1141
+ cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
1142
+ return str(cursor.fetchall())
1143
+
1144
+ @app.route('/login', methods=['POST'])
1145
+ def login():
1146
+ username = flask.request.form['username']
1147
+ password = flask.request.form['password']
1148
+ query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
1149
+ # No password hashing!
1150
+ conn = sqlite3.connect('users.db')
1151
+ result = conn.execute(query).fetchone()
1152
+ if result:
1153
+ return "Logged in!"
1154
+ return "Failed"
1155
+
1156
+ if __name__ == '__main__':
1157
+ app.run(debug=True, host='0.0.0.0') # debug=True in production!
1158
+ """,
1159
+
1160
+ "docker_misconfig": """
1161
+ Docker Compose Configuration:
1162
+ services:
1163
+ app:
1164
+ image: myapp:latest
1165
+ user: root
1166
+ privileged: true
1167
+ ports:
1168
+ - "0.0.0.0:22:22"
1169
+ - "0.0.0.0:3306:3306"
1170
+ - "0.0.0.0:6379:6379"
1171
+ volumes:
1172
+ - /etc:/etc:rw
1173
+ - /var/run/docker.sock:/var/run/docker.sock
1174
+ environment:
1175
+ - AWS_SECRET_KEY=AKIAIOSFODNN7EXAMPLE
1176
+ - DB_PASSWORD=admin123
1177
+ - NODE_ENV=development
1178
+ cap_add:
1179
+ - ALL
1180
+ security_opt:
1181
+ - no-new-privileges:false
1182
+ network_mode: host
1183
+ """,
1184
+
1185
+ "policy_audit": """
1186
+ Company Security Policy Review:
1187
+ - Password policy: minimum 6 characters, no complexity requirements, no rotation
1188
+ - MFA: not enforced for any accounts (including admin)
1189
+ - Security training: no formal program exists
1190
+ - Log retention: 7 days only (on local servers, no SIEM)
1191
+ - Vulnerability scanning: ad-hoc only, no scheduled scans
1192
+ - Incident response: undocumented, informal process
1193
+ - Data encryption: databases NOT encrypted at rest
1194
+ - Backup testing: last tested 18 months ago
1195
+ - Access reviews: never formally conducted
1196
+ - Vendor risk: no third-party risk assessments
1197
+ - Penetration testing: never performed
1198
+ - Change management: informal, no approval process
1199
+ - Endpoint protection: basic antivirus only, no EDR
1200
+ """
1201
+ }
1202
+
1203
+
1204
+ if __name__ == "__main__":
1205
+ import sys
1206
+
1207
+ # Force UTF-8 encoding for stdout to prevent UnicodeEncodeError on Windows terminals
1208
+ if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
1209
+ sys.stdout.reconfigure(encoding='utf-8')
1210
+
1211
+ # Select input (pass scenario name as argument, or default to ssh_brute_force)
1212
+ scenario = sys.argv[1] if len(sys.argv) > 1 else "ssh_brute_force"
1213
+ user_input = EXAMPLE_INPUTS.get(scenario, EXAMPLE_INPUTS["ssh_brute_force"])
1214
+
1215
+ print(f"\nRunning scenario: {scenario}")
1216
+ print(f"Input preview: {user_input.strip()[:120]}...")
1217
+
1218
+ results = run_analysis(user_input, save_report=True)
generate_graph_image.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate a visual image of the LangGraph pipeline."""
2
+ from cybersecurityAgents import (
3
+ build_llm,
4
+ build_embeddings,
5
+ build_cybersec_graph,
6
+ VectorKnowledgeBase,
7
+ )
8
+
9
+ print("Initializing pipeline to generate graph image...")
10
+ llm = build_llm()
11
+ embeddings = build_embeddings()
12
+ kb = VectorKnowledgeBase(embeddings)
13
+ app = build_cybersec_graph(llm, kb)
14
+
15
+ # Method 1: LangGraph built-in (requires pygraphviz or grandalf)
16
+ try:
17
+ png_data = app.get_graph().draw_png()
18
+ with open("langgraph_pipeline.png", "wb") as f:
19
+ f.write(png_data)
20
+ print("βœ… Graph saved as langgraph_pipeline.png (using LangGraph draw_png)")
21
+ except Exception as e:
22
+ print(f"draw_png not available ({e}), falling back to matplotlib...")
23
+
24
+ # Method 2: Matplotlib fallback with code_fixer loop
25
+ import matplotlib.pyplot as plt
26
+ import matplotlib.patches as FancyArrowPatch
27
+
28
+ nodes = [
29
+ ("classify_input", "🏷️ Classify Input"),
30
+ ("rag_retrieve", "πŸ“š RAG Retrieve"),
31
+ ("log_monitor", "πŸ“‘ Log Monitor Agent"),
32
+ ("threat_intel", "πŸ•΅οΈ Threat Intel Agent"),
33
+ ("vuln_scanner", "πŸ” Vuln Scanner Agent"),
34
+ ("code_fixer", "πŸ”§ Code Fixer Agent (iterative)"),
35
+ ("incident_response", "🚨 Incident Response Agent"),
36
+ ("policy_checker", "πŸ“‹ Policy Checker Agent"),
37
+ ("synthesize_report", "πŸ“ Synthesize Report"),
38
+ ]
39
+
40
+ fig, ax = plt.subplots(1, 1, figsize=(8, 14))
41
+ ax.set_xlim(-2, 12)
42
+ ax.set_ylim(-0.5, len(nodes) + 2.5)
43
+ ax.axis("off")
44
+ ax.set_title("CyberSecurity Multi-Agent LangGraph Pipeline\n(with iterative Code Fixer loop)",
45
+ fontsize=13, fontweight="bold", pad=20)
46
+
47
+ center_x = 5
48
+ node_positions = {}
49
+
50
+ # Draw START
51
+ start_y = len(nodes) + 1.5
52
+ ax.annotate("START", xy=(center_x, start_y), fontsize=11, ha="center", va="center",
53
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="#4CAF50", edgecolor="black"),
54
+ color="white", fontweight="bold")
55
+
56
+ # Draw nodes
57
+ for i, (key, label) in enumerate(nodes):
58
+ y = len(nodes) - i
59
+ node_positions[key] = (center_x, y)
60
+
61
+ # Highlight code_fixer differently
62
+ if key == "code_fixer":
63
+ facecolor = "#FF9800"
64
+ edgecolor = "#E65100"
65
+ else:
66
+ facecolor = "#2196F3"
67
+ edgecolor = "#1565C0"
68
+
69
+ ax.annotate(label, xy=(center_x, y), fontsize=9.5, ha="center", va="center",
70
+ bbox=dict(boxstyle="round,pad=0.4", facecolor=facecolor, edgecolor=edgecolor, alpha=0.9),
71
+ color="white", fontweight="bold")
72
+
73
+ # Draw END
74
+ end_y = 0
75
+ ax.annotate("END", xy=(center_x, end_y), fontsize=11, ha="center", va="center",
76
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="#f44336", edgecolor="black"),
77
+ color="white", fontweight="bold")
78
+
79
+ # Draw arrows between sequential nodes
80
+ # START -> first node
81
+ ax.annotate("", xy=(center_x, node_positions["classify_input"][1] + 0.3),
82
+ xytext=(center_x, start_y - 0.25),
83
+ arrowprops=dict(arrowstyle="->", color="black", lw=1.5))
84
+
85
+ # Sequential edges
86
+ sequential = [
87
+ ("classify_input", "rag_retrieve"),
88
+ ("rag_retrieve", "log_monitor"),
89
+ ("log_monitor", "threat_intel"),
90
+ ("threat_intel", "vuln_scanner"),
91
+ ("vuln_scanner", "code_fixer"),
92
+ # code_fixer -> incident_response is conditional (drawn separately)
93
+ ("incident_response", "policy_checker"),
94
+ ("policy_checker", "synthesize_report"),
95
+ ]
96
+
97
+ for src, dst in sequential:
98
+ src_y = node_positions[src][1]
99
+ dst_y = node_positions[dst][1]
100
+ ax.annotate("", xy=(center_x, dst_y + 0.3),
101
+ xytext=(center_x, src_y - 0.3),
102
+ arrowprops=dict(arrowstyle="->", color="black", lw=1.5))
103
+
104
+ # code_fixer -> incident_response (conditional: when fixed)
105
+ cf_y = node_positions["code_fixer"][1]
106
+ ir_y = node_positions["incident_response"][1]
107
+ ax.annotate("", xy=(center_x, ir_y + 0.3),
108
+ xytext=(center_x, cf_y - 0.3),
109
+ arrowprops=dict(arrowstyle="->", color="green", lw=2))
110
+ ax.text(center_x + 1.8, (cf_y + ir_y) / 2, "fixed βœ…", fontsize=8, color="green", fontweight="bold")
111
+
112
+ # code_fixer LOOP (conditional: when not fixed)
113
+ loop_x = center_x + 4.2
114
+ ax.annotate("",
115
+ xy=(center_x + 2.5, cf_y + 0.15),
116
+ xytext=(center_x + 2.5, cf_y - 0.15),
117
+ arrowprops=dict(arrowstyle="->", color="#FF5722", lw=2,
118
+ connectionstyle="arc3,rad=-1.8"))
119
+ # Loop label
120
+ ax.text(loop_x - 0.5, cf_y, "loop\n(max 3x)", fontsize=8, color="#FF5722",
121
+ fontweight="bold", ha="center", va="center",
122
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="#FFF3E0", edgecolor="#FF5722", alpha=0.8))
123
+
124
+ # Last node -> END
125
+ ax.annotate("", xy=(center_x, end_y + 0.25),
126
+ xytext=(center_x, node_positions["synthesize_report"][1] - 0.3),
127
+ arrowprops=dict(arrowstyle="->", color="black", lw=1.5))
128
+
129
+ plt.tight_layout()
130
+ plt.savefig("langgraph_pipeline.png", dpi=150, bbox_inches="tight")
131
+ print("βœ… Graph saved as langgraph_pipeline.png (using matplotlib)")
langgraph_pipeline.png ADDED
requirements.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CyberSecurity Multi-Agent System β€” Dependencies
2
+ # Python >= 3.10 required
3
+
4
+ # ── LangGraph (orchestration state machine) ────────────────────────────
5
+ langgraph>=0.2.0
6
+ langchain>=0.3.0
7
+ langchain-community>=0.3.0
8
+ langchain-openai>=0.2.0 # OpenAI-compatible client (used for OpenRouter)
9
+
10
+ # ── LLM: OpenRouter (OpenAI-compatible API, 200+ models) ──────────────
11
+ openai>=1.40.0 # OpenRouter uses OpenAI SDK format
12
+
13
+ # ── Embeddings: HuggingFace (runs locally, no API key) ────────────────
14
+ sentence-transformers>=3.0.0 # Local embedding models
15
+ huggingface-hub>=0.24.0
16
+ langchain-huggingface>=0.1.0 # LangChain HuggingFace integration
17
+ torch>=2.0.0 # CPU-only fine for embeddings
18
+
19
+ # ── Vector Store: ChromaDB (persistent local DB) ──────────────────────
20
+ chromadb>=0.5.0
21
+
22
+ # ── RAG Framework: LlamaIndex ─────────────────────────────────────────
23
+ llama-index>=0.11.0
24
+ llama-index-core>=0.11.0
25
+ llama-index-vector-stores-chroma>=0.2.0
26
+ llama-index-embeddings-huggingface>=0.3.0
27
+
28
+ # ── UI: Gradio ─────────────────────────────────────────────────────────
29
+ gradio>=4.0.0 # Web UI for the multi-agent system
30
+
31
+ # ── Observability: LangSmith ─────────────────────────────────────────────
32
+ langsmith>=0.1.0 # LangChain tracing & observability
33
+
34
+ # ── Graph Visualization ────────────────────────────────────────────────
35
+ matplotlib>=3.7.0 # Fallback graph rendering
36
+ grandalf>=0.8 # LangGraph draw_png/draw_mermaid support
37
+
38
+ # ── Utilities ──────────────────────────────────────────────────────────
39
+ python-dotenv>=1.0.0 # Load .env API keys
40
+ rich>=13.0.0 # Pretty terminal output (optional)