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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
import time
|
| 5 |
+
from typing import List, Dict, Tuple
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
# Mock security entity patterns (in production, use spaCy/transformers)
|
| 9 |
+
ENTITY_PATTERNS = {
|
| 10 |
+
'ThreatActor': [r'APT\d+', r'Cozy Bear', r'Lazarus', r'FIN\d+', r'Carbanak'],
|
| 11 |
+
'Vulnerability': [r'CVE-\d{4}-\d{4,7}', r'MS\d{2}-\d{3}'],
|
| 12 |
+
'Software': [r'Microsoft \w+', r'Apache \w+', r'Windows \d+', r'Linux', r'Chrome'],
|
| 13 |
+
'Tool': [r'Cobalt Strike', r'Metasploit', r'PowerShell', r'Mimikatz', r'PsExec'],
|
| 14 |
+
'IOC': [r'\b(?:\d{1,3}\.){3}\d{1,3}\b', r'\b[a-fA-F0-9]{32,64}\b', r'https?://[^\s]+'],
|
| 15 |
+
'DetectionRule': [r'SIG-\d{4}-\d{3}', r'YARA-\d+', r'Sigma-\w+']
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# Mock MITRE ATT&CK techniques
|
| 19 |
+
MITRE_TECHNIQUES = {
|
| 20 |
+
'T1059.001': 'PowerShell',
|
| 21 |
+
'T1566.001': 'Spearphishing Attachment',
|
| 22 |
+
'T1055': 'Process Injection',
|
| 23 |
+
'T1003': 'OS Credential Dumping'
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
class SecurityKnowledgeGraph:
|
| 27 |
+
def __init__(self):
|
| 28 |
+
self.entities = []
|
| 29 |
+
self.relationships = []
|
| 30 |
+
|
| 31 |
+
def extract_entities(self, text: str) -> List[Dict]:
|
| 32 |
+
"""Mock entity extraction using regex patterns"""
|
| 33 |
+
entities = []
|
| 34 |
+
entity_id = 0
|
| 35 |
+
|
| 36 |
+
for entity_type, patterns in ENTITY_PATTERNS.items():
|
| 37 |
+
for pattern in patterns:
|
| 38 |
+
matches = re.finditer(pattern, text, re.IGNORECASE)
|
| 39 |
+
for match in matches:
|
| 40 |
+
entities.append({
|
| 41 |
+
'id': entity_id,
|
| 42 |
+
'text': match.group(),
|
| 43 |
+
'type': entity_type,
|
| 44 |
+
'start': match.start(),
|
| 45 |
+
'end': match.end(),
|
| 46 |
+
'confidence': round(0.85 + (hash(match.group()) % 15) / 100, 2)
|
| 47 |
+
})
|
| 48 |
+
entity_id += 1
|
| 49 |
+
|
| 50 |
+
# Remove duplicates
|
| 51 |
+
seen = set()
|
| 52 |
+
unique_entities = []
|
| 53 |
+
for entity in entities:
|
| 54 |
+
if entity['text'].lower() not in seen:
|
| 55 |
+
seen.add(entity['text'].lower())
|
| 56 |
+
unique_entities.append(entity)
|
| 57 |
+
|
| 58 |
+
return sorted(unique_entities, key=lambda x: x['start'])
|
| 59 |
+
|
| 60 |
+
def extract_relationships(self, entities: List[Dict], text: str) -> List[Dict]:
|
| 61 |
+
"""Mock relationship extraction based on proximity and keywords"""
|
| 62 |
+
relationships = []
|
| 63 |
+
|
| 64 |
+
# Define relationship keywords
|
| 65 |
+
rel_patterns = {
|
| 66 |
+
'exploits': ['exploit', 'exploits', 'exploiting', 'leverages'],
|
| 67 |
+
'uses': ['uses', 'utilizing', 'deploys', 'employs'],
|
| 68 |
+
'targets': ['targets', 'targeting', 'affects'],
|
| 69 |
+
'detects': ['detects', 'identifies', 'monitors'],
|
| 70 |
+
'mitigates': ['mitigates', 'prevents', 'blocks']
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
text_lower = text.lower()
|
| 74 |
+
|
| 75 |
+
for i, source in enumerate(entities):
|
| 76 |
+
for j, target in enumerate(entities):
|
| 77 |
+
if i >= j: # Avoid self-relationships and duplicates
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
# Check if entities are close to each other in text
|
| 81 |
+
distance = abs(source['start'] - target['start'])
|
| 82 |
+
if distance > 200: # Skip if too far apart
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
# Find relationship type based on context
|
| 86 |
+
context_start = min(source['start'], target['start']) - 50
|
| 87 |
+
context_end = max(source['end'], target['end']) + 50
|
| 88 |
+
context = text_lower[max(0, context_start):context_end]
|
| 89 |
+
|
| 90 |
+
for rel_type, keywords in rel_patterns.items():
|
| 91 |
+
if any(keyword in context for keyword in keywords):
|
| 92 |
+
# Determine relationship direction based on entity types
|
| 93 |
+
if self._is_valid_relationship(source['type'], target['type'], rel_type):
|
| 94 |
+
relationships.append({
|
| 95 |
+
'source': source['text'],
|
| 96 |
+
'target': target['text'],
|
| 97 |
+
'relationship': rel_type,
|
| 98 |
+
'confidence': round(0.75 + (hash(source['text'] + target['text']) % 20) / 100, 2),
|
| 99 |
+
'source_type': source['type'],
|
| 100 |
+
'target_type': target['type']
|
| 101 |
+
})
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
return relationships
|
| 105 |
+
|
| 106 |
+
def _is_valid_relationship(self, source_type: str, target_type: str, rel_type: str) -> bool:
|
| 107 |
+
"""Check if relationship makes sense given entity types"""
|
| 108 |
+
valid_relationships = {
|
| 109 |
+
'exploits': [('ThreatActor', 'Vulnerability'), ('Tool', 'Vulnerability')],
|
| 110 |
+
'uses': [('ThreatActor', 'Tool'), ('ThreatActor', 'Software')],
|
| 111 |
+
'targets': [('ThreatActor', 'Software'), ('Tool', 'Software'), ('Vulnerability', 'Software')],
|
| 112 |
+
'detects': [('DetectionRule', 'Tool'), ('DetectionRule', 'ThreatActor')],
|
| 113 |
+
'affects': [('Vulnerability', 'Software')]
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
return (source_type, target_type) in valid_relationships.get(rel_type, [])
|
| 117 |
+
|
| 118 |
+
# Initialize the knowledge graph
|
| 119 |
+
kg = SecurityKnowledgeGraph()
|
| 120 |
+
|
| 121 |
+
def process_threat_intel(text: str) -> Tuple[str, str, str]:
|
| 122 |
+
"""Process threat intelligence text and return formatted results"""
|
| 123 |
+
if not text.strip():
|
| 124 |
+
return "Please provide threat intelligence text to analyze.", "", ""
|
| 125 |
+
|
| 126 |
+
# Extract entities
|
| 127 |
+
entities = kg.extract_entities(text)
|
| 128 |
+
|
| 129 |
+
# Extract relationships
|
| 130 |
+
relationships = kg.extract_relationships(entities, text)
|
| 131 |
+
|
| 132 |
+
# Format entities output
|
| 133 |
+
entities_html = "<div style='display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0;'>"
|
| 134 |
+
for entity in entities:
|
| 135 |
+
color_map = {
|
| 136 |
+
'ThreatActor': '#fee2e2 border: 1px solid #fca5a5; color: #991b1b',
|
| 137 |
+
'Vulnerability': '#fed7aa border: 1px solid #fdba74; color: #9a3412',
|
| 138 |
+
'Software': '#dbeafe border: 1px solid #93c5fd; color: #1e40af',
|
| 139 |
+
'Tool': '#e9d5ff border: 1px solid #c4b5fd; color: #6b21a8',
|
| 140 |
+
'IOC': '#dcfce7 border: 1px solid #86efac; color: #166534',
|
| 141 |
+
'DetectionRule': '#e0e7ff border: 1px solid #a5b4fc; color: #3730a3'
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
style = f"background-color: {color_map.get(entity['type'], '#f3f4f6')}; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 500;"
|
| 145 |
+
entities_html += f"<span style='{style}'>{entity['text']} <small>({entity['type']} - {int(entity['confidence']*100)}%)</small></span>"
|
| 146 |
+
|
| 147 |
+
entities_html += "</div>"
|
| 148 |
+
|
| 149 |
+
# Format relationships output
|
| 150 |
+
relationships_html = "<div style='margin: 10px 0;'>"
|
| 151 |
+
for rel in relationships:
|
| 152 |
+
relationships_html += f"""
|
| 153 |
+
<div style='margin: 8px 0; padding: 10px; background-color: #f8fafc; border-left: 4px solid #3b82f6; border-radius: 4px;'>
|
| 154 |
+
<strong style='color: #1e40af;'>{rel['source']}</strong>
|
| 155 |
+
<span style='color: #7c3aed; font-weight: 600;'>{rel['relationship']}</span>
|
| 156 |
+
<strong style='color: #059669;'>{rel['target']}</strong>
|
| 157 |
+
<small style='float: right; color: #6b7280;'>{int(rel['confidence']*100)}% confidence</small>
|
| 158 |
+
</div>
|
| 159 |
+
"""
|
| 160 |
+
relationships_html += "</div>"
|
| 161 |
+
|
| 162 |
+
# Create graph query examples
|
| 163 |
+
queries_html = f"""
|
| 164 |
+
<div style='margin: 10px 0;'>
|
| 165 |
+
<h4>Example Graph Queries:</h4>
|
| 166 |
+
<div style='background-color: #1f2937; color: #e5e7eb; padding: 10px; border-radius: 6px; font-family: monospace; margin: 5px 0;'>
|
| 167 |
+
MATCH (ta:ThreatActor)-[:USES]->(tool:Tool) RETURN ta.name, tool.name
|
| 168 |
+
</div>
|
| 169 |
+
<div style='background-color: #1f2937; color: #e5e7eb; padding: 10px; border-radius: 6px; font-family: monospace; margin: 5px 0;'>
|
| 170 |
+
MATCH (v:Vulnerability)<-[:EXPLOITS]-(ta:ThreatActor) RETURN v.name, ta.name
|
| 171 |
+
</div>
|
| 172 |
+
<div style='background-color: #1f2937; color: #e5e7eb; padding: 10px; border-radius: 6px; font-family: monospace; margin: 5px 0;'>
|
| 173 |
+
MATCH path=(ta:ThreatActor)-[*2..4]->(s:Software) RETURN path
|
| 174 |
+
</div>
|
| 175 |
+
</div>
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
return entities_html, relationships_html, queries_html
|
| 179 |
+
|
| 180 |
+
def create_sample_data():
|
| 181 |
+
"""Generate sample threat intelligence data"""
|
| 182 |
+
return """APT29 (Cozy Bear) has been observed exploiting CVE-2023-23397 to target Microsoft Outlook vulnerabilities in financial institutions. The threat actor deploys Cobalt Strike beacons on compromised Windows 10 systems and uses PowerShell for lateral movement and credential dumping.
|
| 183 |
+
|
| 184 |
+
The attack chain typically begins with spearphishing emails containing malicious attachments. Once initial access is gained, APT29 utilizes Mimikatz for credential harvesting and PsExec for remote execution across the network.
|
| 185 |
+
|
| 186 |
+
Security teams can detect this activity using Sigma rule SIG-2023-001 which monitors for suspicious PowerShell execution patterns and YARA-2023-APT29 for Cobalt Strike beacon detection. The IOCs include IP addresses 192.168.1.100 and 10.0.0.50, along with hash values 7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730."""
|
| 187 |
+
|
| 188 |
+
# Create Gradio interface
|
| 189 |
+
with gr.Blocks(
|
| 190 |
+
theme=gr.themes.Base(),
|
| 191 |
+
css="""
|
| 192 |
+
.gradio-container {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important}
|
| 193 |
+
.gr-button {background: linear-gradient(90deg, #667eea, #764ba2) !important; border: none !important}
|
| 194 |
+
.gr-button:hover {transform: translateY(-1px) !important; box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important}
|
| 195 |
+
""",
|
| 196 |
+
title="π Security Knowledge Graph Builder"
|
| 197 |
+
) as demo:
|
| 198 |
+
|
| 199 |
+
gr.HTML("""
|
| 200 |
+
<div style='text-align: center; padding: 20px; background: rgba(255,255,255,0.1); border-radius: 10px; margin-bottom: 20px;'>
|
| 201 |
+
<h1 style='color: white; margin-bottom: 10px;'>π Security Knowledge Graph Builder</h1>
|
| 202 |
+
<p style='color: rgba(255,255,255,0.8); font-size: 16px;'>
|
| 203 |
+
Secure AI-powered threat intelligence without vector database vulnerabilities
|
| 204 |
+
</p>
|
| 205 |
+
<p style='color: rgba(255,255,255,0.6); font-size: 14px;'>
|
| 206 |
+
Build explainable, auditable security relationships instead of relying on risky RAG embeddings
|
| 207 |
+
</p>
|
| 208 |
+
</div>
|
| 209 |
+
""")
|
| 210 |
+
|
| 211 |
+
with gr.Row():
|
| 212 |
+
with gr.Column(scale=1):
|
| 213 |
+
gr.HTML("<h3 style='color: white;'>π Threat Intelligence Input</h3>")
|
| 214 |
+
|
| 215 |
+
input_text = gr.Textbox(
|
| 216 |
+
placeholder="Paste your threat intelligence report here...",
|
| 217 |
+
lines=8,
|
| 218 |
+
label="Threat Intelligence Text",
|
| 219 |
+
value=""
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
with gr.Row():
|
| 223 |
+
analyze_btn = gr.Button("π Analyze Threat Intelligence", variant="primary")
|
| 224 |
+
sample_btn = gr.Button("π Load Sample Data", variant="secondary")
|
| 225 |
+
|
| 226 |
+
gr.HTML("""
|
| 227 |
+
<div style='margin-top: 20px; padding: 15px; background: rgba(34, 197, 94, 0.1); border-left: 4px solid #22c55e; border-radius: 6px;'>
|
| 228 |
+
<h4 style='color: #22c55e; margin-top: 0;'>π‘οΈ Why Knowledge Graphs Beat RAG for Security:</h4>
|
| 229 |
+
<ul style='color: rgba(255,255,255,0.8); font-size: 14px;'>
|
| 230 |
+
<li><strong>No Vector Poisoning:</strong> Explicit relationships prevent embedding manipulation</li>
|
| 231 |
+
<li><strong>Full Auditability:</strong> Every connection can be traced and verified</li>
|
| 232 |
+
<li><strong>Access Control:</strong> Fine-grained permissions on nodes and edges</li>
|
| 233 |
+
<li><strong>Precise Queries:</strong> No ambiguous similarity matching</li>
|
| 234 |
+
</ul>
|
| 235 |
+
</div>
|
| 236 |
+
""")
|
| 237 |
+
|
| 238 |
+
with gr.Column(scale=1):
|
| 239 |
+
gr.HTML("<h3 style='color: white;'>π― Extracted Security Entities</h3>")
|
| 240 |
+
entities_output = gr.HTML()
|
| 241 |
+
|
| 242 |
+
gr.HTML("<h3 style='color: white;'>π Security Relationships</h3>")
|
| 243 |
+
relationships_output = gr.HTML()
|
| 244 |
+
|
| 245 |
+
gr.HTML("<h3 style='color: white;'>π Graph Query Examples</h3>")
|
| 246 |
+
queries_output = gr.HTML()
|
| 247 |
+
|
| 248 |
+
# Event handlers
|
| 249 |
+
sample_btn.click(
|
| 250 |
+
fn=create_sample_data,
|
| 251 |
+
outputs=input_text
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
analyze_btn.click(
|
| 255 |
+
fn=process_threat_intel,
|
| 256 |
+
inputs=input_text,
|
| 257 |
+
outputs=[entities_output, relationships_output, queries_output]
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# Footer
|
| 261 |
+
gr.HTML("""
|
| 262 |
+
<div style='text-align: center; margin-top: 30px; padding: 20px; background: rgba(0,0,0,0.2); border-radius: 10px;'>
|
| 263 |
+
<p style='color: rgba(255,255,255,0.8); margin-bottom: 10px;'>
|
| 264 |
+
π <strong>Secure-by-Design Threat Intelligence</strong> - No risky vector embeddings, just explainable relationships
|
| 265 |
+
</p>
|
| 266 |
+
<p style='color: rgba(255,255,255,0.6); font-size: 14px;'>
|
| 267 |
+
Built for blue teams who need trustworthy, auditable AI in cybersecurity operations
|
| 268 |
+
</p>
|
| 269 |
+
</div>
|
| 270 |
+
""")
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
demo.launch()
|