File size: 12,210 Bytes
3cb23da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5786a73
3cb23da
5d16299
5786a73
 
3cb23da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import gradio as gr
from cybersecurityAgents import (
    run_analysis,
    EXAMPLE_INPUTS,
    build_llm,
    build_embeddings,
    build_cybersec_graph,
    VectorKnowledgeBase,
    CyberAgentState,
    Config,
    check_vector_store_exists,
)
from datetime import datetime
import json
import time
import os
from dotenv import load_dotenv

load_dotenv("cs.env")

# ── Security Configuration ─────────────────────────────────────────────
GRADIO_USER = os.getenv("GRADIO_USER", "admin")
GRADIO_PASSWORD = os.getenv("GRADIO_PASSWORD", "CyberSec@2026!")
MAX_INPUT_LENGTH = 10000
REQUEST_COOLDOWN_SECONDS = 30
MAX_CONCURRENT_THREADS = 2

_last_request_time: float = 0.0

# ── Singleton pipeline ─────────────────────────────────────────────────
_graph = None
_kb = None
_init_status = {}


def get_pipeline():
    global _graph, _kb, _init_status
    if _graph is None:
        store_exists = check_vector_store_exists()
        _init_status["vector_store_preexisted"] = store_exists

        llm = build_llm()
        _init_status["llm"] = True

        embeddings = build_embeddings()
        _init_status["embeddings"] = True

        _kb = VectorKnowledgeBase(embeddings)
        _init_status["vector_store"] = True
        _init_status["vector_store_loaded_existing"] = _kb.loaded_existing

        _graph = build_cybersec_graph(llm, _kb)
        _init_status["graph"] = True

    return _graph


def get_status_markdown():
    if not _init_status:
        return (
            "### ⏳ Not Initialized\n\n"
            "Click **Run Analysis** to initialize.\n\n"
            "---\n"
            "#### Components\n"
            "- ⬜ OpenRouter LLM\n"
            "- ⬜ HuggingFace Embeddings\n"
            "- ⬜ ChromaDB Vector Store\n"
            "- ⬜ LangGraph Pipeline"
        )

    lines = ["### 🟒 Initialized\n"]
    checks = [
        ("llm", "OpenRouter LLM"),
        ("embeddings", "HuggingFace Embeddings"),
        ("vector_store", "ChromaDB Vector Store"),
        ("graph", "LangGraph Pipeline"),
    ]
    for key, label in checks:
        if _init_status.get(key):
            lines.append(f"- βœ… {label}")
        else:
            lines.append(f"- ⬜ {label}")

    lines.append("\n---")
    if _init_status.get("vector_store_loaded_existing"):
        lines.append("πŸ“‚ **Loaded from disk**\n(no re-indexing)")
    elif _init_status.get("vector_store"):
        lines.append("πŸ†• **Freshly indexed**\n(knowledge base built)")

    lines.append(f"\n---\n**Model:** `{Config.LLM_MODEL}`")
    lines.append(f"\n**Embeddings:** `{Config.EMBEDDING_MODEL.split('/')[-1]}`")
    lines.append(f"\n**Vector DB:** `{Config.CHROMA_PERSIST_DIR}`")

    return "\n".join(lines)


LANGGRAPH_PIPELINE_MD = """### πŸ”— LangGraph Pipeline

```
START
  β”‚
  β–Ό
🏷️ classify_input
  β”‚
  β–Ό
πŸ“š rag_retrieve
  β”‚
  β–Ό
πŸ“‘ log_monitor
  β”‚
  β–Ό
πŸ•΅οΈ threat_intel
  β”‚
  β–Ό
πŸ” vuln_scanner
  β”‚
  β–Ό
πŸ”§ code_fixer ◄──┐
  β”‚    (loop max 3x)
  β”‚ fixed?         β”‚
  β”œβ”€β”€ No β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  β–Ό Yes
🚨 incident_response
  β”‚
  β–Ό
πŸ“‹ policy_checker
  β”‚
  β–Ό
πŸ“ synthesize_report
  β”‚
  β–Ό
 END
```

---

### πŸ€– Agents

| # | Agent | Role |
|---|-------|------|
| 1 | Log Monitor | Detect attacks in logs |
| 2 | Threat Intel | CVE & MITRE mapping |
| 3 | Vuln Scanner | OWASP/CWE scan |
| 4 | Code Fixer | Iterative bug fix |
| 5 | Incident Response | NIST 800-61 plan |
| 6 | Policy Checker | ISO/NIST/SOC2 gaps |
"""


SCENARIO_MAP = {
    "Log Monitor Agent": "ssh_brute_force",
    "Threat Intelligence Agent": "ssh_brute_force",
    "Vulnerability Scanner Agent": "vulnerable_code",
    "Code Fixer Agent": "vulnerable_code",
    "Incident Response Agent": "docker_misconfig",
    "Policy Checker Agent": "policy_audit",
}

SCENARIO_DESCRIPTIONS = {
    "custom": "> **Paste your own logs, code, config, or policy text below.**",
    "Log Monitor Agent": "> **Reads system and network logs to detect unusual activity or attacks.**",
    "Threat Intelligence Agent": "> **Looks up known security threats (CVE data, reports) and checks if your system is affected.**",
    "Vulnerability Scanner Agent": "> **Scans code, APIs, or Docker images to find security weaknesses.**",
    "Code Fixer Agent": "> **Iteratively fixes security vulnerabilities and bugs in your code (up to 3 passes).**",
    "Incident Response Agent": "> **Creates step-by-step action plans when an issue is found.**",
    "Policy Checker Agent": "> **Checks your setup against standards like ISO, NIST, or SOC2 and shows where you need fixes.**",
}


def authenticate(username, password):
    """Validate login credentials against cs.env values."""
    return username == GRADIO_USER and password == GRADIO_PASSWORD


def analyze(text, scenario):
    global _last_request_time

    # Rate limiting: enforce cooldown between requests
    now = time.time()
    elapsed_since_last = now - _last_request_time
    if elapsed_since_last < REQUEST_COOLDOWN_SECONDS and _last_request_time > 0:
        wait = int(REQUEST_COOLDOWN_SECONDS - elapsed_since_last)
        return f"⏳ Rate limited. Please wait {wait}s before next request.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
    _last_request_time = now

    # Input validation: enforce max length
    input_text = text
    if not input_text or not input_text.strip():
        return "⚠️ Please provide input or select a scenario.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""
    if len(input_text) > MAX_INPUT_LENGTH:
        return f"❌ Input too long ({len(input_text)} chars). Maximum is {MAX_INPUT_LENGTH} characters.", {}, {}, {}, {}, {}, "", get_status_markdown(), ""

    try:
        app = get_pipeline()
    except Exception as e:
        return f"❌ Pipeline initialization failed: {e}", {}, {}, {}, {}, {}, "", get_status_markdown(), ""

    initial_state: CyberAgentState = {
        "raw_input": input_text,
        "input_type": "general",
        "log_findings": None,
        "threat_intel": None,
        "vuln_scan": None,
        "code_fix": None,
        "incident_plan": None,
        "policy_gaps": None,
        "agent_trace": [],
        "errors": [],
        "rag_context": None,
        "final_report": None,
        "started_at": datetime.now().isoformat(),
    }

    t0 = time.time()
    state = app.invoke(initial_state)
    elapsed = time.time() - t0

    report = state.get("final_report", "No report generated.")
    report += f"\n\n⏱ Analysis completed in {elapsed:.1f}s"

    # Extract fixed code for display
    code_fix = state.get("code_fix") or {}
    fixed_code = code_fix.get("fixed_code", "")
    if not fixed_code or code_fix.get("skipped"):
        fixed_code = "# No code fix generated (input was not code or code fixer was skipped)"

    return (
        report,
        state.get("log_findings") or {},
        state.get("threat_intel") or {},
        state.get("vuln_scan") or {},
        code_fix,
        state.get("policy_gaps") or {},
        "\n".join(state.get("agent_trace", [])),
        get_status_markdown(),
        fixed_code,
    )


def load_scenario(scenario):
    if scenario == "custom":
        return "", SCENARIO_DESCRIPTIONS["custom"]
    key = SCENARIO_MAP.get(scenario, "ssh_brute_force")
    return EXAMPLE_INPUTS.get(key, ""), SCENARIO_DESCRIPTIONS.get(scenario, "")


def check_init_status():
    store_exists = check_vector_store_exists()
    if store_exists:
        return get_status_markdown() if _init_status else (
            "### 🟒 Ready\n\n"
            "- βœ… ChromaDB vector store found on disk\n\n"
            "---\n"
            "Pipeline will load existing data on first run.\n\n"
            f"**Path:** `{Config.CHROMA_PERSIST_DIR}`"
        )
    else:
        return (
            "### 🟑 First Run\n\n"
            "- ⬜ No vector store found\n\n"
            "---\n"
            "Knowledge base will be indexed on first analysis run."
        )


# ── Gradio UI ──────────────────────────────────────────────────────────
with gr.Blocks(title="CyberSec Multi-Agent Analyzer", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸ›‘οΈ CyberSecurity Multi-Agent Analyzer")

    with gr.Row():
        # ── LEFT: LangGraph Pipeline ───────────────────────────────────
        with gr.Column(scale=1, min_width=250):
            gr.Markdown(LANGGRAPH_PIPELINE_MD)

        # ── CENTER: Main Playground ────────────────────────────────────
        with gr.Column(scale=3):
            scenario = gr.Dropdown(
                choices=[
                    "custom",
                    "Log Monitor Agent",
                    "Threat Intelligence Agent",
                    "Vulnerability Scanner Agent",
                    "Code Fixer Agent",
                    "Incident Response Agent",
                    "Policy Checker Agent",
                ],
                value="Log Monitor Agent",
                label="Select Agent Scenario",
            )

            scenario_desc = gr.Markdown(value=SCENARIO_DESCRIPTIONS["Log Monitor Agent"])

            input_box = gr.Textbox(
                lines=8,
                label="Input (logs, code, config, or policy)",
                placeholder="Paste your input here or select a scenario above...",
                value=EXAMPLE_INPUTS["ssh_brute_force"],
            )

            with gr.Row():
                run_btn = gr.Button("πŸš€ Run Analysis", variant="primary", scale=2)
                status_btn = gr.Button("πŸ” Check Status", scale=1)

            with gr.Tabs():
                with gr.Tab("πŸ“„ Report"):
                    report_out = gr.Markdown()
                with gr.Tab("πŸ” Log Findings"):
                    log_out = gr.JSON()
                with gr.Tab("πŸ•΅οΈ Threat Intel"):
                    threat_out = gr.JSON()
                with gr.Tab("⚠️ Vulnerabilities"):
                    vuln_out = gr.JSON()
                with gr.Tab("πŸ”§ Code Fix"):
                    codefix_out = gr.JSON()
                with gr.Tab("πŸ“‹ Compliance"):
                    policy_out = gr.JSON()
                with gr.Tab("πŸ“ Trace"):
                    trace_out = gr.Textbox(lines=12, label="Agent Execution Trace")

        # ── RIGHT: Storage & Initialization ────────────────────────────
        with gr.Column(scale=1, min_width=250):
            gr.Markdown("### πŸ“¦ Storage & Init")
            status_out = gr.Markdown(value=check_init_status())
            gr.Markdown("---")
            gr.Markdown("### πŸ”§ Fixed Code Output")
            fixed_code_out = gr.Code(
                label="Fixed Code (read-only)",
                language="python",
                interactive=False,
                lines=15,
            )

    # ── Event Handlers ─────────────────────────────────────────────────
    scenario.change(fn=load_scenario, inputs=[scenario], outputs=[input_box, scenario_desc])
    run_btn.click(
        fn=analyze,
        inputs=[input_box, scenario],
        outputs=[report_out, log_out, threat_out, vuln_out, codefix_out, policy_out, trace_out, status_out, fixed_code_out],
    )
    status_btn.click(fn=check_init_status, inputs=[], outputs=[status_out])

if __name__ == "__main__":
    demo.launch(
        auth=authenticate,
        auth_message="πŸ” CyberSecurity Multi-Agent System β€” Login Required",
        server_name="0.0.0.0",
        max_threads=MAX_CONCURRENT_THREADS,
        share=False,
        ssr_mode=False,  # Disabling SSR is recommended for multi-agent streaming UIs on HF
        
    )