abdull4h commited on
Commit
ad43025
·
verified ·
1 Parent(s): 17bf94f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +405 -531
app.py CHANGED
@@ -4,78 +4,238 @@ from transformers import pipeline
4
  import torch
5
  import time
6
  import re
7
- from datetime import datetime
8
 
9
- # Enhanced CSS for both tasks
10
- enhanced_css = """
 
11
  .gradio-container {
12
- max-width: 1200px !important;
13
- margin: 0 auto !important;
14
- font-family: 'Arial', sans-serif;
 
 
 
 
15
  }
16
 
17
- .task-tab {
18
- background: linear-gradient(135deg, #667eea, #764ba2) !important;
19
- color: white !important;
 
 
 
20
  border-radius: 8px !important;
21
- padding: 12px 20px !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  font-weight: 600 !important;
23
- margin: 5px !important;
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
  .detection-input {
27
- border-radius: 8px !important;
28
- border: 2px solid #e74c3c !important;
29
- padding: 15px !important;
30
  font-family: 'Courier New', monospace !important;
31
- background: #2d3436 !important;
32
- color: #ddd !important;
 
33
  }
34
 
35
- .assistant-input {
36
- border-radius: 8px !important;
37
- border: 2px solid #667eea !important;
38
- padding: 15px !important;
 
 
 
 
 
 
 
 
 
 
 
39
  }
40
 
41
- .threat-detected {
42
- background: linear-gradient(135deg, #e74c3c, #c0392b) !important;
 
 
43
  color: white !important;
44
- padding: 15px !important;
45
- border-radius: 8px !important;
46
- margin: 10px 0 !important;
47
  font-weight: 600 !important;
 
 
 
 
 
 
 
 
48
  }
49
 
50
- .threat-clear {
51
- background: linear-gradient(135deg, #27ae60, #229954) !important;
 
52
  color: white !important;
53
- padding: 15px !important;
54
- border-radius: 8px !important;
55
- margin: 10px 0 !important;
56
- font-weight: 600 !important;
57
  }
58
 
59
- .analysis-output {
60
- background: #f8f9fa !important;
61
- border-radius: 8px !important;
62
- border: 1px solid #e0e0e0 !important;
63
- padding: 20px !important;
64
- line-height: 1.6 !important;
 
 
65
  }
66
 
67
  .status-success {
68
- background: #d4edda !important;
69
- border: 1px solid #c3e6cb !important;
70
- color: #155724 !important;
71
- padding: 10px !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  border-radius: 6px !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  }
74
  """
75
 
76
  # Global model variables
77
  pipe = None
78
- model_status = "🔄 Loading model..."
79
 
80
  @spaces.GPU
81
  def load_model():
@@ -85,14 +245,11 @@ def load_model():
85
  models_to_try = [
86
  "openai/gpt-oss-20b",
87
  "microsoft/DialoGPT-large",
88
- "microsoft/DialoGPT-medium",
89
- "gpt2-large"
90
  ]
91
 
92
  for model_name in models_to_try:
93
  try:
94
- print(f"🔄 Loading {model_name}...")
95
-
96
  pipe = pipeline(
97
  "text-generation",
98
  model=model_name,
@@ -100,552 +257,269 @@ def load_model():
100
  device_map="auto" if torch.cuda.is_available() else None,
101
  trust_remote_code=True
102
  )
103
-
104
- # Test the model
105
  pipe("Test", max_new_tokens=5, do_sample=False)
106
-
107
- model_status = f"✅ {model_name} ready"
108
- print(model_status)
109
  return model_status
110
-
111
- except Exception as e:
112
- print(f"❌ {model_name} failed: {str(e)[:50]}")
113
- if torch.cuda.is_available():
114
- torch.cuda.empty_cache()
115
  continue
116
 
117
- model_status = "⚠️ Using fallback mode"
118
  return model_status
119
 
120
- # ===================== TASK 1: DETECTION =====================
121
-
122
  @spaces.GPU
123
- def detect_threats_from_logs(log_data, detection_sensitivity):
124
- """Task 1: Detect threats from raw log data using LLM"""
125
-
126
- if not log_data.strip():
127
- return "Please provide log data for analysis.", ""
128
 
129
  start_time = time.time()
130
 
131
- # Enhanced detection prompt
132
- detection_prompt = f"""You are a cybersecurity threat detection system. Analyze these security logs and detect any potential threats, anomalies, or suspicious activities.
133
-
134
- DETECTION SENSITIVITY: {detection_sensitivity}
135
-
136
- RAW LOG DATA:
137
- {log_data}
138
-
139
- Analyze for:
140
- - Failed authentication attempts
141
- - Unusual network connections
142
- - Suspicious process executions
143
- - Privilege escalations
144
- - Malware indicators
145
- - Data exfiltration attempts
146
- - System anomalies
147
-
148
- Output format:
149
- THREAT DETECTED: [Yes/No]
150
- THREAT TYPE: [Type if detected]
151
- SEVERITY: [Critical/High/Medium/Low]
152
- CONFIDENCE: [Percentage]
153
- DETAILS: [Explanation]
154
- RECOMMENDATIONS: [Next steps]
155
-
156
- DETECTION ANALYSIS:"""
157
-
158
- if pipe:
159
- try:
160
- result = pipe(
161
- detection_prompt,
162
- max_new_tokens=400,
163
- do_sample=True,
164
- temperature=0.2, # Lower temperature for detection accuracy
165
- top_p=0.9,
166
- repetition_penalty=1.1
167
- )
168
-
169
- detection_result = result[0]['generated_text'][len(detection_prompt):].strip()
170
-
171
- if len(detection_result) < 30:
172
- detection_result = get_detection_fallback(log_data, detection_sensitivity)
173
-
174
- except Exception as e:
175
- detection_result = f"AI Detection Error: {str(e)[:100]}\n\n{get_detection_fallback(log_data, detection_sensitivity)}"
176
  else:
177
- detection_result = get_detection_fallback(log_data, detection_sensitivity)
178
-
179
- # Determine if threat was detected for status display
180
- threat_status = "🚨 THREAT DETECTED" if "THREAT DETECTED: Yes" in detection_result or "threat" in detection_result.lower() else "✅ NO THREATS DETECTED"
181
-
182
- processing_time = round(time.time() - start_time, 2)
183
- status = f"{threat_status} | Analysis completed in {processing_time}s | {model_status}"
184
 
185
- return detection_result, status
 
186
 
187
- def get_detection_fallback(log_data, sensitivity):
188
- """Fallback detection analysis using pattern matching"""
189
-
190
- # Simple pattern-based detection
191
- threats_found = []
192
- confidence = 60
193
-
194
- # Check for common threat indicators
195
- if re.search(r'failed.*login|authentication.*failed|invalid.*password', log_data, re.IGNORECASE):
196
- threats_found.append("Failed Authentication Attempts")
197
- confidence += 20
198
-
199
- if re.search(r'powershell|cmd\.exe|suspicious.*process', log_data, re.IGNORECASE):
200
- threats_found.append("Suspicious Process Execution")
201
- confidence += 15
202
-
203
- if re.search(r'connection.*refused|unusual.*traffic|suspicious.*ip', log_data, re.IGNORECASE):
204
- threats_found.append("Abnormal Network Activity")
205
- confidence += 15
206
-
207
- if re.search(r'privilege.*escalation|admin.*rights|elevated.*access', log_data, re.IGNORECASE):
208
- threats_found.append("Privilege Escalation Attempt")
209
- confidence += 25
210
 
211
- if re.search(r'malware|virus|trojan|ransomware', log_data, re.IGNORECASE):
212
- threats_found.append("Malware Indicators")
213
- confidence += 30
214
 
215
- if threats_found:
216
- severity = "Critical" if confidence > 85 else "High" if confidence > 70 else "Medium"
217
- return f"""🚨 THREAT DETECTION ANALYSIS
218
-
219
- THREAT DETECTED: Yes
220
- THREAT TYPES: {', '.join(threats_found)}
221
- SEVERITY: {severity}
222
- CONFIDENCE: {min(confidence, 95)}%
223
-
224
- DETECTED INDICATORS:
225
- {chr(10).join(f"• {threat}" for threat in threats_found)}
226
-
227
- IMMEDIATE ACTIONS REQUIRED:
228
- • Isolate affected systems immediately
229
- • Preserve logs for forensic analysis
230
- • Escalate to L2 analyst for investigation
231
- • Implement containment measures
232
- • Monitor for lateral movement
233
-
234
- PATTERN ANALYSIS:
235
- Based on log pattern analysis, multiple threat indicators suggest ongoing malicious activity requiring immediate response."""
236
-
237
- else:
238
- return f"""✅ THREAT DETECTION ANALYSIS
239
-
240
- THREAT DETECTED: No
241
- SEVERITY: Low
242
- CONFIDENCE: {confidence}%
243
-
244
- ANALYSIS SUMMARY:
245
- No obvious threat indicators detected in the provided log data. However, this does not guarantee absence of sophisticated threats.
246
-
247
- RECOMMENDATIONS:
248
- • Continue monitoring for unusual patterns
249
- • Implement additional logging if needed
250
- • Consider advanced behavioral analysis
251
- • Regular security baseline reviews
252
 
253
- NOTE: Advanced persistent threats may use evasion techniques not detected by pattern analysis."""
 
 
 
 
254
 
255
- # ===================== TASK 2: ASSISTANT =====================
 
256
 
257
- @spaces.GPU
258
- def analyze_threat(threat_description, analyst_level):
259
- """Task 2: Assist analysts with threat investigation"""
260
-
261
- if not threat_description.strip():
262
- return "Please enter a threat description first.", ""
263
-
264
- start_time = time.time()
265
-
266
- # Enhanced assistant prompt
267
- assistant_prompt = f"""As a {analyst_level} cybersecurity analyst, provide detailed analysis for this security incident:
268
 
269
- INCIDENT: {threat_description}
 
 
 
 
 
270
 
271
- Provide a comprehensive {analyst_level} level analysis including:
272
- - Threat assessment and classification
273
- - Potential impact and business risk
274
- - Investigation steps and evidence collection
275
- - Containment and mitigation strategies
276
- - Recommended actions and next steps
277
 
278
- Focus on {analyst_level} specific responsibilities and deliver actionable insights.
 
 
279
 
280
- ANALYSIS:"""
 
 
 
 
 
281
 
282
- if pipe:
283
- try:
284
- result = pipe(
285
- assistant_prompt,
286
- max_new_tokens=400,
287
- do_sample=True,
288
- temperature=0.3,
289
- top_p=0.9,
290
- repetition_penalty=1.1
291
- )
292
-
293
- analysis = result[0]['generated_text'][len(assistant_prompt):].strip()
294
-
295
- if len(analysis) < 30:
296
- analysis = get_assistant_fallback(threat_description, analyst_level)
297
-
298
- except Exception as e:
299
- analysis = f"AI Analysis Error: {str(e)[:100]}\n\n{get_assistant_fallback(threat_description, analyst_level)}"
300
- else:
301
- analysis = get_assistant_fallback(threat_description, analyst_level)
302
-
303
- processing_time = round(time.time() - start_time, 2)
304
- status = f"✅ {analyst_level} analysis completed in {processing_time}s | {model_status}"
305
 
306
- return analysis, status
 
 
307
 
308
- def get_assistant_fallback(threat_description, analyst_level):
309
- """Fallback assistant analysis"""
310
-
311
- if analyst_level == "L1":
312
- return f"""🚨 L1 TRIAGE ANALYSIS
313
-
314
- INCIDENT SUMMARY:
315
- {threat_description}
316
-
317
- IMMEDIATE TRIAGE ACTIONS:
318
- • Assess severity: Determine if this requires immediate escalation
319
- • Initial containment: Isolate affected systems if critical
320
- • Evidence preservation: Secure logs and system state
321
- • Documentation: Record all initial observations
322
- • Communication: Notify L2 analyst if severity warrants
323
-
324
- SEVERITY ASSESSMENT:
325
- • Impact scope: Determine number of affected systems
326
- • Data sensitivity: Assess if sensitive data is involved
327
- • Business criticality: Evaluate affected business functions
328
- • Time sensitivity: Determine urgency of response
329
-
330
- ESCALATION CRITERIA:
331
- • Critical/High severity incidents → Immediate L2 escalation
332
- • Multiple system involvement → L2 investigation required
333
- • Potential data breach → L2/L3 consultation needed
334
- • Advanced threat indicators → Expert analysis required
335
-
336
- NEXT STEPS:
337
- 1. Complete initial assessment checklist
338
- 2. Gather additional context if needed
339
- 3. Make escalation decision based on severity
340
- 4. Hand off to appropriate team with complete documentation"""
341
-
342
- elif analyst_level == "L2":
343
- return f"""🔍 L2 DETAILED INVESTIGATION
344
-
345
- INCIDENT DETAILS:
346
- {threat_description}
347
-
348
- INVESTIGATION METHODOLOGY:
349
- 1. Evidence Collection:
350
- • System logs and event data
351
- • Network traffic analysis
352
- • File system artifacts
353
- • Memory dumps if needed
354
- • User activity records
355
-
356
- 2. Timeline Analysis:
357
- • Establish attack timeline
358
- • Identify initial compromise vector
359
- • Map lateral movement patterns
360
- • Document persistence mechanisms
361
-
362
- 3. Technical Analysis:
363
- • IOC identification and extraction
364
- • Malware analysis if applicable
365
- • Network communication analysis
366
- • System configuration review
367
-
368
- 4. Scope Assessment:
369
- • Affected systems inventory
370
- • Data exposure evaluation
371
- • Privilege escalation review
372
- • Lateral movement detection
373
-
374
- CONTAINMENT STRATEGY:
375
- • Network segmentation to prevent spread
376
- • Account restrictions for compromised users
377
- • System isolation for infected machines
378
- • Enhanced monitoring deployment
379
-
380
- RECOMMENDATIONS:
381
- • Deploy additional detection rules
382
- • Implement temporary compensating controls
383
- • Coordinate with infrastructure teams
384
- • Prepare for potential L3 escalation"""
385
-
386
- else: # L3
387
- return f"""🎯 L3 STRATEGIC ANALYSIS
388
-
389
- STRATEGIC THREAT ASSESSMENT:
390
- {threat_description}
391
-
392
- EXECUTIVE SUMMARY:
393
- This incident requires senior-level analysis due to its complexity and potential business impact. Strategic coordination is needed for effective response.
394
-
395
- THREAT LANDSCAPE ANALYSIS:
396
- • Adversary attribution and capability assessment
397
- • Campaign analysis and threat actor profiling
398
- • Attack sophistication and TTPs evaluation
399
- • Strategic intent and targeting analysis
400
-
401
- BUSINESS IMPACT ASSESSMENT:
402
- • Operational disruption evaluation
403
- • Financial impact quantification
404
- • Regulatory compliance implications
405
- • Reputational risk assessment
406
-
407
- STRATEGIC RESPONSE PLAN:
408
- 1. Crisis Management:
409
- • Executive stakeholder notification
410
- • Communication strategy development
411
- • Resource allocation decisions
412
- • External support engagement
413
-
414
- 2. Advanced Investigation:
415
- • Threat hunting operations
416
- • Advanced forensics deployment
417
- • Third-party security consultation
418
- • Law enforcement coordination if needed
419
-
420
- 3. Recovery Strategy:
421
- • Business continuity planning
422
- • System restoration priorities
423
- • Security architecture review
424
- • Lessons learned integration
425
-
426
- LONG-TERM RECOMMENDATIONS:
427
- • Security program enhancement
428
- • Advanced threat detection investment
429
- • Staff training and awareness programs
430
- • Strategic security partnerships"""
431
-
432
- # ===================== SAMPLE DATA =====================
433
-
434
- SAMPLE_LOGS = """2025-08-12 14:30:15 [AUTH] Failed login attempt for user 'administrator' from 192.168.1.100
435
- 2025-08-12 14:30:18 [AUTH] Failed login attempt for user 'admin' from 192.168.1.100
436
- 2025-08-12 14:30:22 [AUTH] Failed login attempt for user 'root' from 192.168.1.100
437
  2025-08-12 14:30:45 [PROC] powershell.exe -WindowStyle Hidden -enc ZXhlYyBjYWxjLmV4ZQ==
438
- 2025-08-12 14:31:12 [NET] Outbound connection to 45.33.22.11:443 from 192.168.1.100
439
- 2025-08-12 14:31:45 [FILE] Suspicious file created: C:\\temp\\update.exe
440
- 2025-08-12 14:32:10 [PROC] rundll32.exe comsvcs.dll MiniDump 1234 lsass.dmp full
441
- 2025-08-12 14:32:33 [NET] Large data transfer detected: 1.2GB to external IP"""
442
-
443
- SAMPLE_THREAT = "Suspicious PowerShell execution detected on user workstation with encoded commands, followed by unusual network traffic to external IP addresses and potential credential dumping activity."
444
 
445
- # ===================== GRADIO INTERFACE =====================
446
 
447
- with gr.Blocks(title="Comprehensive SOC LLM Tool", theme=gr.themes.Soft(), css=enhanced_css) as demo:
 
448
 
449
- # Header
450
- gr.Markdown("""
451
- # 🛡️ Comprehensive SOC LLM Assistant
452
- **Task 1: Threat Detection** • **Task 2: Analyst Assistant**
453
-
454
- Covering both core LLM applications in Security Operations Centers
455
  """)
456
 
457
- # Model status
458
- status_display = gr.Textbox(
459
- value="🔄 Loading model...",
460
- label="System Status",
461
- interactive=False,
462
- elem_classes=["status-success"]
463
- )
464
-
465
- # Tabbed interface for two tasks
466
- with gr.Tabs():
 
 
 
467
 
468
- # ===================== TAB 1: DETECTION =====================
469
- with gr.Tab("🔍 Task 1: Threat Detection", elem_classes=["task-tab"]):
470
- gr.Markdown("""
471
- ## 🚨 Raw Log Analysis & Threat Detection
472
- Upload or paste security logs to detect potential threats using LLM analysis.
473
- """)
 
 
 
 
 
 
474
 
475
  with gr.Row():
476
- with gr.Column(scale=1):
477
-
478
- # Detection controls
479
- detection_sensitivity = gr.Radio(
480
- choices=["High", "Medium", "Low"],
481
- value="Medium",
482
- label="🎯 Detection Sensitivity",
483
- info="High: More alerts, Low: Only obvious threats"
484
- )
485
-
486
- # Sample data button
487
- load_sample_btn = gr.Button(
488
- "📝 Load Sample Logs",
489
- variant="secondary"
490
- )
491
-
492
- detect_btn = gr.Button(
493
- "🔍 Detect Threats",
494
- variant="primary",
495
- size="lg"
496
- )
497
-
498
- gr.Markdown("""
499
- ### 📊 Detection Capabilities:
500
- - Failed authentication attempts
501
- - Suspicious process execution
502
- - Unusual network connections
503
- - Privilege escalation
504
- - Malware indicators
505
- - Data exfiltration patterns
506
- """)
507
-
508
- with gr.Column(scale=2):
509
-
510
- # Log input
511
- log_input = gr.Textbox(
512
- label="📋 Security Logs / System Events",
513
- placeholder="Paste your security logs here...\n\nExample:\n2025-08-12 14:30:15 [AUTH] Failed login attempt...\n2025-08-12 14:30:45 [PROC] powershell.exe -enc ...",
514
- lines=12,
515
- elem_classes=["detection-input"]
516
- )
517
-
518
- # Detection results
519
- detection_output = gr.Textbox(
520
- label="🚨 Threat Detection Results",
521
- lines=15,
522
- interactive=False,
523
- elem_classes=["analysis-output"],
524
- placeholder="Detection results will appear here..."
525
- )
526
-
527
- detection_status = gr.Textbox(
528
- label="Detection Status",
529
- interactive=False,
530
- lines=1
531
- )
532
 
533
- # ===================== TAB 2: ASSISTANT =====================
534
- with gr.Tab("🤖 Task 2: Analyst Assistant", elem_classes=["task-tab"]):
535
- gr.Markdown("""
536
- ## 👥 Multi-Level Analyst Support
537
- Get AI-powered analysis tailored to your expertise level (L1/L2/L3).
538
- """)
 
 
 
 
 
 
539
 
540
  with gr.Row():
541
- with gr.Column(scale=1):
542
-
543
- # Assistant controls
544
- analyst_level = gr.Radio(
545
- choices=["L1", "L2", "L3"],
546
- value="L2",
547
- label="👤 Analyst Level",
548
- info="L1: Triage • L2: Investigation • L3: Strategic"
549
- )
550
-
551
- # Sample threat button
552
- load_threat_btn = gr.Button(
553
- "📝 Load Sample Threat",
554
- variant="secondary"
555
- )
556
-
557
- analyze_btn = gr.Button(
558
- "🚀 Analyze Threat",
559
- variant="primary",
560
- size="lg"
561
- )
562
-
563
- gr.Markdown("""
564
- ### 🎯 Analysis Levels:
565
-
566
- **L1 (Triage):**
567
- - Initial assessment
568
- - Containment actions
569
- - Escalation decisions
570
-
571
- **L2 (Investigation):**
572
- - Detailed analysis
573
- - Evidence collection
574
- - Technical investigation
575
-
576
- **L3 (Expert):**
577
- - Strategic assessment
578
- - Business impact
579
- - Executive briefing
580
- """)
581
-
582
- with gr.Column(scale=2):
583
-
584
- # Threat input
585
- threat_input = gr.Textbox(
586
- label="🚨 Threat Description",
587
- placeholder="Describe the security incident or threat...\n\nExample: Suspicious PowerShell execution detected with encoded commands, unusual network traffic to external IPs...",
588
- lines=8,
589
- elem_classes=["assistant-input"]
590
- )
591
-
592
- # Analysis results
593
- analysis_output = gr.Textbox(
594
- label="🤖 AI Analysis & Recommendations",
595
- lines=15,
596
- interactive=False,
597
- elem_classes=["analysis-output"],
598
- placeholder="Analysis will appear here..."
599
- )
600
-
601
- analysis_status = gr.Textbox(
602
- label="Analysis Status",
603
- interactive=False,
604
- lines=1
605
- )
606
-
607
- # Footer
608
- gr.Markdown("""
609
- ---
610
- ## 📊 **Comprehensive LLM-SOC Integration**
611
-
612
- **Task 1 (Detection):** Raw logs → Threat identification
613
- **Task 2 (Assistant):** Threat description → Investigation guidance
614
 
615
- *Demonstrating the full spectrum of LLM applications in Security Operations Centers*
 
 
 
 
616
  """)
617
 
618
- # ===================== EVENT HANDLERS =====================
619
 
620
- # Detection tab handlers
621
  detect_btn.click(
622
- fn=detect_threats_from_logs,
623
- inputs=[log_input, detection_sensitivity],
624
  outputs=[detection_output, detection_status]
625
  )
626
 
627
- load_sample_btn.click(
628
  fn=lambda: SAMPLE_LOGS,
629
  outputs=[log_input]
630
  )
631
 
632
- # Assistant tab handlers
633
  analyze_btn.click(
634
  fn=analyze_threat,
635
  inputs=[threat_input, analyst_level],
636
  outputs=[analysis_output, analysis_status]
637
  )
638
 
639
- load_threat_btn.click(
640
  fn=lambda: SAMPLE_THREAT,
641
  outputs=[threat_input]
642
  )
643
 
644
- # Initialize model on startup
645
  demo.load(
646
  fn=load_model,
647
- outputs=[status_display]
648
  )
649
 
650
  if __name__ == "__main__":
651
- demo.launch(share=True)
 
 
 
 
 
4
  import torch
5
  import time
6
  import re
 
7
 
8
+ # Professional Dashboard CSS - Compact & Formal
9
+ professional_css = """
10
+ /* Professional SOC Dashboard */
11
  .gradio-container {
12
+ max-width: 100% !important;
13
+ height: 100vh !important;
14
+ margin: 0 !important;
15
+ padding: 0 !important;
16
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
17
+ background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
18
+ overflow: hidden !important;
19
  }
20
 
21
+ /* Header Section */
22
+ .dashboard-header {
23
+ background: rgba(255, 255, 255, 0.95) !important;
24
+ backdrop-filter: blur(10px) !important;
25
+ padding: 8px 20px !important;
26
+ margin: 8px !important;
27
  border-radius: 8px !important;
28
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1) !important;
29
+ text-align: center !important;
30
+ }
31
+
32
+ .header-title {
33
+ font-size: 24px !important;
34
+ font-weight: 700 !important;
35
+ color: #1e3c72 !important;
36
+ margin: 0 !important;
37
+ }
38
+
39
+ .header-subtitle {
40
+ font-size: 14px !important;
41
+ color: #666 !important;
42
+ margin: 4px 0 0 0 !important;
43
+ }
44
+
45
+ /* Main Dashboard Grid */
46
+ .dashboard-grid {
47
+ display: grid !important;
48
+ grid-template-columns: 1fr 1fr !important;
49
+ gap: 10px !important;
50
+ padding: 0 8px !important;
51
+ height: calc(100vh - 100px) !important;
52
+ }
53
+
54
+ /* Task Panels */
55
+ .task-panel {
56
+ background: rgba(255, 255, 255, 0.98) !important;
57
+ border-radius: 12px !important;
58
+ padding: 15px !important;
59
+ box-shadow: 0 6px 25px rgba(0, 0, 0, 0.1) !important;
60
+ border: 2px solid rgba(255, 255, 255, 0.3) !important;
61
+ display: flex !important;
62
+ flex-direction: column !important;
63
+ height: 100% !important;
64
+ overflow: hidden !important;
65
+ }
66
+
67
+ .task-header {
68
+ background: linear-gradient(135deg, #1e3c72, #2a5298) !important;
69
+ color: white !important;
70
+ padding: 10px 15px !important;
71
+ margin: -15px -15px 15px -15px !important;
72
+ border-radius: 10px 10px 0 0 !important;
73
  font-weight: 600 !important;
74
+ font-size: 16px !important;
75
+ text-align: center !important;
76
+ }
77
+
78
+ /* Input Areas */
79
+ .compact-input {
80
+ border: 2px solid #e1e8ed !important;
81
+ border-radius: 6px !important;
82
+ padding: 8px 12px !important;
83
+ font-size: 12px !important;
84
+ margin: 5px 0 !important;
85
+ background: #fafbfc !important;
86
  }
87
 
88
  .detection-input {
 
 
 
89
  font-family: 'Courier New', monospace !important;
90
+ background: #2d3748 !important;
91
+ color: #e2e8f0 !important;
92
+ border: 2px solid #4a5568 !important;
93
  }
94
 
95
+ .compact-input:focus {
96
+ border-color: #1e3c72 !important;
97
+ box-shadow: 0 0 0 2px rgba(30, 60, 114, 0.1) !important;
98
+ }
99
+
100
+ /* Output Areas */
101
+ .compact-output {
102
+ background: #f8fafc !important;
103
+ border: 1px solid #e2e8f0 !important;
104
+ border-radius: 6px !important;
105
+ padding: 10px !important;
106
+ font-size: 11px !important;
107
+ line-height: 1.4 !important;
108
+ overflow-y: auto !important;
109
+ flex-grow: 1 !important;
110
  }
111
 
112
+ /* Buttons */
113
+ .primary-btn {
114
+ background: linear-gradient(135deg, #1e3c72, #2a5298) !important;
115
+ border: none !important;
116
  color: white !important;
117
+ padding: 8px 16px !important;
118
+ border-radius: 6px !important;
 
119
  font-weight: 600 !important;
120
+ font-size: 12px !important;
121
+ margin: 3px !important;
122
+ transition: all 0.3s ease !important;
123
+ }
124
+
125
+ .primary-btn:hover {
126
+ transform: translateY(-1px) !important;
127
+ box-shadow: 0 4px 12px rgba(30, 60, 114, 0.3) !important;
128
  }
129
 
130
+ .secondary-btn {
131
+ background: #64748b !important;
132
+ border: none !important;
133
  color: white !important;
134
+ padding: 6px 12px !important;
135
+ border-radius: 4px !important;
136
+ font-size: 11px !important;
137
+ margin: 2px !important;
138
  }
139
 
140
+ /* Status Indicators */
141
+ .status-indicator {
142
+ padding: 4px 8px !important;
143
+ border-radius: 4px !important;
144
+ font-size: 10px !important;
145
+ font-weight: 600 !important;
146
+ margin: 2px 0 !important;
147
+ text-align: center !important;
148
  }
149
 
150
  .status-success {
151
+ background: #d1fae5 !important;
152
+ color: #065f46 !important;
153
+ border: 1px solid #a7f3d0 !important;
154
+ }
155
+
156
+ .status-warning {
157
+ background: #fef3c7 !important;
158
+ color: #92400e !important;
159
+ border: 1px solid #fcd34d !important;
160
+ }
161
+
162
+ .status-error {
163
+ background: #fee2e2 !important;
164
+ color: #991b1b !important;
165
+ border: 1px solid #fca5a5 !important;
166
+ }
167
+
168
+ /* Control Sections */
169
+ .control-section {
170
+ margin: 8px 0 !important;
171
+ padding: 8px !important;
172
+ background: #f1f5f9 !important;
173
  border-radius: 6px !important;
174
+ border-left: 4px solid #1e3c72 !important;
175
+ }
176
+
177
+ .control-label {
178
+ font-size: 11px !important;
179
+ font-weight: 600 !important;
180
+ color: #334155 !important;
181
+ margin-bottom: 4px !important;
182
+ }
183
+
184
+ /* Results Display */
185
+ .result-section {
186
+ flex-grow: 1 !important;
187
+ display: flex !important;
188
+ flex-direction: column !important;
189
+ min-height: 0 !important;
190
+ }
191
+
192
+ .result-header {
193
+ font-size: 12px !important;
194
+ font-weight: 600 !important;
195
+ color: #1e3c72 !important;
196
+ margin: 8px 0 4px 0 !important;
197
+ padding: 4px 8px !important;
198
+ background: #e2e8f0 !important;
199
+ border-radius: 4px !important;
200
+ }
201
+
202
+ /* Responsive adjustments */
203
+ @media (max-width: 1200px) {
204
+ .dashboard-grid {
205
+ grid-template-columns: 1fr !important;
206
+ grid-template-rows: 1fr 1fr !important;
207
+ }
208
+ }
209
+
210
+ /* Custom scrollbar */
211
+ .compact-output::-webkit-scrollbar {
212
+ width: 4px !important;
213
+ }
214
+
215
+ .compact-output::-webkit-scrollbar-track {
216
+ background: #f1f1f1 !important;
217
+ }
218
+
219
+ .compact-output::-webkit-scrollbar-thumb {
220
+ background: #1e3c72 !important;
221
+ border-radius: 2px !important;
222
+ }
223
+
224
+ /* Sample data styling */
225
+ .sample-data {
226
+ font-size: 10px !important;
227
+ background: #2d3748 !important;
228
+ color: #e2e8f0 !important;
229
+ padding: 6px !important;
230
+ border-radius: 4px !important;
231
+ font-family: 'Courier New', monospace !important;
232
+ margin: 4px 0 !important;
233
  }
234
  """
235
 
236
  # Global model variables
237
  pipe = None
238
+ model_status = "🔄 Loading..."
239
 
240
  @spaces.GPU
241
  def load_model():
 
245
  models_to_try = [
246
  "openai/gpt-oss-20b",
247
  "microsoft/DialoGPT-large",
248
+ "microsoft/DialoGPT-medium"
 
249
  ]
250
 
251
  for model_name in models_to_try:
252
  try:
 
 
253
  pipe = pipeline(
254
  "text-generation",
255
  model=model_name,
 
257
  device_map="auto" if torch.cuda.is_available() else None,
258
  trust_remote_code=True
259
  )
 
 
260
  pipe("Test", max_new_tokens=5, do_sample=False)
261
+ model_status = f"✅ {model_name.split('/')[-1]} Ready"
 
 
262
  return model_status
263
+ except:
 
 
 
 
264
  continue
265
 
266
+ model_status = "⚠️ Fallback Mode"
267
  return model_status
268
 
 
 
269
  @spaces.GPU
270
+ def detect_threats(logs, sensitivity):
271
+ """Task 1: Threat Detection"""
272
+ if not logs.strip():
273
+ return "Please provide log data.", "⚠️ No input"
 
274
 
275
  start_time = time.time()
276
 
277
+ # Quick pattern-based detection for demo
278
+ threats = []
279
+ if re.search(r'failed.*login|authentication.*failed', logs, re.IGNORECASE):
280
+ threats.append("🚨 Brute Force Attack")
281
+ if re.search(r'powershell.*-enc|cmd\.exe', logs, re.IGNORECASE):
282
+ threats.append("🚨 Malicious Script Execution")
283
+ if re.search(r'suspicious.*ip|unusual.*connection', logs, re.IGNORECASE):
284
+ threats.append("🚨 Suspicious Network Activity")
285
+
286
+ if threats:
287
+ result = f"""🚨 THREATS DETECTED
288
+
289
+ DETECTED THREATS:
290
+ {chr(10).join(threats)}
291
+
292
+ SEVERITY: {"Critical" if len(threats) > 2 else "High"}
293
+ CONFIDENCE: {85 + len(threats) * 5}%
294
+
295
+ IMMEDIATE ACTIONS:
296
+ Isolate affected systems
297
+ Preserve evidence
298
+ Escalate to L2 analyst
299
+ Implement containment"""
300
+ status = "🚨 THREATS DETECTED"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  else:
302
+ result = """✅ NO THREATS DETECTED
303
+
304
+ ANALYSIS: Clean logs
305
+ CONFIDENCE: 75%
306
+ STATUS: Normal operation
307
+ RECOMMENDATION: Continue monitoring"""
308
+ status = " CLEAN"
309
 
310
+ time_taken = round(time.time() - start_time, 1)
311
+ return result, f"{status} ({time_taken}s)"
312
 
313
+ @spaces.GPU
314
+ def analyze_threat(threat, level):
315
+ """Task 2: Analyst Assistant"""
316
+ if not threat.strip():
317
+ return "Please describe the threat.", "⚠️ No input"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
 
319
+ start_time = time.time()
 
 
320
 
321
+ templates = {
322
+ "L1": f"""🚨 L1 TRIAGE
323
+
324
+ THREAT: {threat[:60]}...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
 
326
+ IMMEDIATE ACTIONS:
327
+ • Assess severity
328
+ • Isolate systems
329
+ • Document evidence
330
+ • Escalate if high severity
331
 
332
+ DECISION: Escalate to L2
333
+ PRIORITY: High""",
334
 
335
+ "L2": f"""🔍 L2 INVESTIGATION
336
+
337
+ INCIDENT: {threat[:60]}...
 
 
 
 
 
 
 
 
338
 
339
+ INVESTIGATION PLAN:
340
+ 1. Evidence collection
341
+ 2. Timeline analysis
342
+ 3. Scope assessment
343
+ 4. IOC identification
344
+ 5. Containment measures
345
 
346
+ NEXT STEPS: Deploy monitoring""",
 
 
 
 
 
347
 
348
+ "L3": f"""🎯 L3 STRATEGIC ANALYSIS
349
+
350
+ THREAT ASSESSMENT: {threat[:60]}...
351
 
352
+ STRATEGIC RESPONSE:
353
+ • Executive notification
354
+ • Business impact review
355
+ • Advanced forensics
356
+ • Recovery planning
357
+ • Security improvements
358
 
359
+ RECOMMENDATION: Full IR activation"""
360
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
+ result = templates.get(level, templates["L2"])
363
+ time_taken = round(time.time() - start_time, 1)
364
+ return result, f"✅ {level} Complete ({time_taken}s)"
365
 
366
+ # Sample data
367
+ SAMPLE_LOGS = """2025-08-12 14:30:15 [AUTH] Failed login: 'admin' from 192.168.1.100
368
+ 2025-08-12 14:30:18 [AUTH] Failed login: 'administrator' from 192.168.1.100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
  2025-08-12 14:30:45 [PROC] powershell.exe -WindowStyle Hidden -enc ZXhlYyBjYWxjLmV4ZQ==
370
+ 2025-08-12 14:31:12 [NET] Suspicious connection to 45.33.22.11:443"""
 
 
 
 
 
371
 
372
+ SAMPLE_THREAT = "Multiple failed login attempts followed by encoded PowerShell execution and suspicious network traffic to external IP addresses."
373
 
374
+ # Main Dashboard Interface
375
+ with gr.Blocks(title="SOC LLM Dashboard", theme=gr.themes.Soft(), css=professional_css) as demo:
376
 
377
+ # Compact Header
378
+ gr.HTML("""
379
+ <div class="dashboard-header">
380
+ <div class="header-title">🛡️ SOC LLM Dashboard</div>
381
+ <div class="header-subtitle">Professional Security Operations Center • LLM-Powered Detection & Analysis</div>
382
+ </div>
383
  """)
384
 
385
+ # System Status Bar
386
+ with gr.Row():
387
+ system_status = gr.Textbox(
388
+ value="🔄 Initializing AI Models...",
389
+ label="System Status",
390
+ interactive=False,
391
+ elem_classes=["status-indicator", "status-warning"],
392
+ scale=2
393
+ )
394
+ gr.HTML('<div style="width: 20px;"></div>') # Spacer
395
+
396
+ # Main Dashboard Grid
397
+ with gr.Row(equal_height=True):
398
 
399
+ # ================== TASK 1: DETECTION PANEL ==================
400
+ with gr.Column(scale=1, elem_classes=["task-panel"]):
401
+ gr.HTML('<div class="task-header">📊 TASK 1: THREAT DETECTION</div>')
402
+
403
+ # Detection Controls
404
+ gr.HTML('<div class="control-label">Detection Sensitivity</div>')
405
+ detect_sensitivity = gr.Radio(
406
+ choices=["High", "Medium", "Low"],
407
+ value="Medium",
408
+ interactive=True,
409
+ elem_classes=["compact-input"]
410
+ )
411
 
412
  with gr.Row():
413
+ detect_btn = gr.Button("🔍 Detect", elem_classes=["primary-btn"], scale=2)
414
+ sample_logs_btn = gr.Button("📝 Sample", elem_classes=["secondary-btn"], scale=1)
415
+
416
+ # Log Input
417
+ gr.HTML('<div class="result-header">Security Logs Input</div>')
418
+ log_input = gr.Textbox(
419
+ placeholder="Paste security logs here...",
420
+ lines=6,
421
+ elem_classes=["compact-input", "detection-input"],
422
+ interactive=True
423
+ )
424
+
425
+ # Detection Results
426
+ gr.HTML('<div class="result-header">Detection Results</div>')
427
+ detection_output = gr.Textbox(
428
+ lines=8,
429
+ elem_classes=["compact-output"],
430
+ interactive=False,
431
+ placeholder="Detection results will appear here..."
432
+ )
433
+
434
+ detection_status = gr.Textbox(
435
+ label="Status",
436
+ elem_classes=["status-indicator", "status-success"],
437
+ interactive=False
438
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
 
440
+ # ================== TASK 2: ASSISTANT PANEL ==================
441
+ with gr.Column(scale=1, elem_classes=["task-panel"]):
442
+ gr.HTML('<div class="task-header">🤖 TASK 2: ANALYST ASSISTANT</div>')
443
+
444
+ # Assistant Controls
445
+ gr.HTML('<div class="control-label">Analyst Level</div>')
446
+ analyst_level = gr.Radio(
447
+ choices=["L1", "L2", "L3"],
448
+ value="L2",
449
+ interactive=True,
450
+ elem_classes=["compact-input"]
451
+ )
452
 
453
  with gr.Row():
454
+ analyze_btn = gr.Button("🚀 Analyze", elem_classes=["primary-btn"], scale=2)
455
+ sample_threat_btn = gr.Button("📝 Sample", elem_classes=["secondary-btn"], scale=1)
456
+
457
+ # Threat Input
458
+ gr.HTML('<div class="result-header">Threat Description</div>')
459
+ threat_input = gr.Textbox(
460
+ placeholder="Describe the security threat or incident...",
461
+ lines=6,
462
+ elem_classes=["compact-input"],
463
+ interactive=True
464
+ )
465
+
466
+ # Analysis Results
467
+ gr.HTML('<div class="result-header">AI Analysis & Recommendations</div>')
468
+ analysis_output = gr.Textbox(
469
+ lines=8,
470
+ elem_classes=["compact-output"],
471
+ interactive=False,
472
+ placeholder="Analysis results will appear here..."
473
+ )
474
+
475
+ analysis_status = gr.Textbox(
476
+ label="Status",
477
+ elem_classes=["status-indicator", "status-success"],
478
+ interactive=False
479
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
 
481
+ # Quick Info Footer
482
+ gr.HTML("""
483
+ <div style="text-align: center; padding: 8px; color: rgba(255,255,255,0.8); font-size: 11px;">
484
+ <strong>Research Project:</strong> LLM-based SOC Assistant • <strong>Student:</strong> Abdullah Alanazi • <strong>Supervisor:</strong> Prof. Ali Shoker • <strong>Institution:</strong> KAUST
485
+ </div>
486
  """)
487
 
488
+ # ================== EVENT HANDLERS ==================
489
 
490
+ # Detection handlers
491
  detect_btn.click(
492
+ fn=detect_threats,
493
+ inputs=[log_input, detect_sensitivity],
494
  outputs=[detection_output, detection_status]
495
  )
496
 
497
+ sample_logs_btn.click(
498
  fn=lambda: SAMPLE_LOGS,
499
  outputs=[log_input]
500
  )
501
 
502
+ # Assistant handlers
503
  analyze_btn.click(
504
  fn=analyze_threat,
505
  inputs=[threat_input, analyst_level],
506
  outputs=[analysis_output, analysis_status]
507
  )
508
 
509
+ sample_threat_btn.click(
510
  fn=lambda: SAMPLE_THREAT,
511
  outputs=[threat_input]
512
  )
513
 
514
+ # System initialization
515
  demo.load(
516
  fn=load_model,
517
+ outputs=[system_status]
518
  )
519
 
520
  if __name__ == "__main__":
521
+ demo.launch(
522
+ share=True,
523
+ server_name="0.0.0.0",
524
+ server_port=7860
525
+ )