-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextracted_code.txt
More file actions
4868 lines (4004 loc) · 189 KB
/
extracted_code.txt
File metadata and controls
4868 lines (4004 loc) · 189 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Code Extraction from: J:\Hackathons\cybersecurity_hack\building\frontend\forensiq-api
================================================================================
Total files extracted: 17
Extraction date: 2026-02-04 09:43:04.650041
================================================================================
================================================================================
FILE 1/17: app\main.py
================================================================================
from fastapi import FastAPI, Request, File, UploadFile, Form
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import os
import shutil
import traceback
from pathlib import Path
app = FastAPI(
title="ForensIQ API",
description="Cybersecurity Threat Detection Platform",
version="1.0.0"
)
# Get the project root directory (parent of app/)
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / "templates"
STATIC_DIR = BASE_DIR / "static"
UPLOAD_DIR = BASE_DIR / "data" / "uploads"
# Create directories if they don't exist
STATIC_DIR.mkdir(exist_ok=True)
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
# CORS Configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Setup templates (pointing to root-level templates folder)
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
# Mount static files
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
# Serve frontend at root URL
@app.get("/", response_class=HTMLResponse)
async def serve_frontend(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
# Health check
@app.get("/health")
async def health_check():
return {
"status": "healthy",
"models_loaded": True,
"data_available": True,
"config": {
"version": "1.0.0"
}
}
# Main pipeline endpoint with file upload
@app.post("/api/v1/run-full-pipeline")
async def run_full_pipeline(
file: UploadFile = File(...),
threshold: float = Form(0.5)
):
"""Run the full ForensIQ detection pipeline with uploaded CSV file"""
try:
print("="*50)
print(f"Received file upload request")
print(f"Filename: {file.filename}")
print(f"Content Type: {file.content_type}")
print(f"Threshold: {threshold}")
print("="*50)
# Validate file is CSV
if not file.filename.endswith('.csv'):
return JSONResponse(
status_code=400,
content={
"status": "error",
"message": "Only CSV files are accepted"
}
)
# Save uploaded file
file_path = UPLOAD_DIR / file.filename
with file_path.open("wb") as buffer:
shutil.copyfileobj(file.file, buffer)
print(f"✓ File saved to: {file_path}")
# Now run your pipeline with the uploaded file
input_file = str(file_path)
# ================================================
# TODO: Replace this with your actual pipeline code
# ================================================
# Example:
# from app.modules.module_1_anomaly_detection import detect_anomalies
# from app.modules.module_2_correlation import correlate_attacks
# from app.modules.module_3_enrichment import enrich_ips
# from app.modules.module_4_mitre_mapping import map_mitre
# from app.modules.module_5_story_generation import generate_stories
# import time
# start_time = time.time()
# Module 1: Anomaly Detection
# print("Running Module 1: Anomaly Detection...")
# anomaly_results = detect_anomalies(input_file, threshold)
# Module 2: Correlation
# print("Running Module 2: Correlation Engine...")
# correlation_results = correlate_attacks(
# anomaly_results['forensiq_results'],
# anomaly_results['anomalies_only']
# )
# Module 3: IP Enrichment
# print("Running Module 3: IP Enrichment...")
# enrichment_results = enrich_ips(
# correlation_results['attack_chains'],
# input_file
# )
# Module 4: MITRE Mapping
# print("Running Module 4: MITRE ATT&CK Mapping...")
# mitre_results = map_mitre(enrichment_results['enriched_chains'])
# Module 5: Story Generation
# print("Running Module 5: Story Generation...")
# story_results = generate_stories(mitre_results['mitre_chains'])
# total_time = time.time() - start_time
# ================================================
# TEMPORARY: Mock response for testing
# Remove this when you integrate your actual modules
response = {
"status": "success",
"message": f"Pipeline completed successfully for {file.filename}",
"input_file": file.filename,
"module_outputs": {
"module_1_anomaly_detection": {
"forensiq_results": f"output/forensiq_results_{file.filename}",
"anomalies_only": f"output/anomalies_only_{file.filename}",
"statistics": {
"total_events": 175341,
"anomalies_detected": 8767,
"anomaly_rate": 0.05,
"threshold": threshold
}
},
"module_2_correlation": {
"attack_chains": f"output/attack_chains_{file.filename}.json",
"chain_summary": f"output/chain_summary_{file.filename}.csv",
"statistics": {
"total_chains": 45,
"unique_attackers": 23,
"baseline_deviations": 12,
"escalations_detected": 8
}
},
"module_3_enrichment": {
"enriched_chains": f"output/enriched_chains_{file.filename}.json",
"statistics": {
"total_chains": 45,
"chains_with_ground_truth": 38,
"average_abuse_score": 67.3
}
},
"module_4_mitre_mapping": {
"mitre_chains": f"output/mitre_chains_{file.filename}.json",
"mitre_report": f"output/mitre_report_{file.filename}.md",
"statistics": {
"total_chains": 45,
"unique_tactics": 8,
"unique_techniques": 15
}
},
"module_5_story_generation": {
"attack_stories": f"output/attack_stories_{file.filename}.json",
"stories_report": f"output/stories_report_{file.filename}.md",
"statistics": {
"total_stories": 45,
"critical_incidents": 8,
"high_risk_incidents": 15
}
}
},
"attack_chains": [
{
"chain_id": "CHAIN_0001",
"severity": "CRITICAL",
"attacker_ip": "192.168.1.100",
"pattern": "Lateral Movement + Data Exfiltration",
"event_count": 147,
"attack_story": "Attacker from 192.168.1.100 initiated reconnaissance scan at 14:23:45, followed by credential access attempts using stolen credentials. Lateral movement detected via SMB protocol to multiple internal hosts. Data exfiltration observed through encrypted channel to external C2 server.",
"mitre_tactics": ["Reconnaissance", "Lateral Movement", "Exfiltration"],
"mitre_techniques": ["T1046", "T1021.002", "T1041"],
"timeline": [
{"timestamp": "14:23:45", "description": "Initial port scan detected"},
{"timestamp": "14:25:12", "description": "Credential access attempt"},
{"timestamp": "14:27:33", "description": "Lateral movement to HOST-02"},
{"timestamp": "14:30:18", "description": "Data staging in C:\\Temp"},
{"timestamp": "14:32:45", "description": "Exfiltration to 203.0.113.45"}
],
"recommendations": [
"Isolate affected hosts immediately",
"Reset credentials for compromised accounts",
"Block C2 IP address 203.0.113.45",
"Review firewall rules for SMB traffic"
]
},
{
"chain_id": "CHAIN_0002",
"severity": "HIGH",
"attacker_ip": "10.0.0.45",
"pattern": "Reconnaissance + Exploitation",
"event_count": 82,
"attack_story": "Multiple port scans detected from 10.0.0.45 targeting internal web servers. Exploitation attempt using known CVE-2024-1234 vulnerability. Successful privilege escalation detected.",
"mitre_tactics": ["Reconnaissance", "Initial Access", "Privilege Escalation"],
"mitre_techniques": ["T1046", "T1190", "T1068"],
"timeline": [
{"timestamp": "15:10:22", "description": "Port scan on web servers"},
{"timestamp": "15:12:45", "description": "Exploitation attempt CVE-2024-1234"},
{"timestamp": "15:15:03", "description": "Privilege escalation successful"}
],
"recommendations": [
"Patch CVE-2024-1234 on all web servers",
"Review access logs for IOCs",
"Implement network segmentation"
]
},
{
"chain_id": "CHAIN_0003",
"severity": "MEDIUM",
"attacker_ip": "172.16.0.23",
"pattern": "Credential Access",
"event_count": 34,
"attack_story": "Suspicious authentication attempts detected. Multiple failed login attempts followed by successful access using valid credentials.",
"mitre_tactics": ["Credential Access", "Initial Access"],
"mitre_techniques": ["T1110.001", "T1078"],
"timeline": [
{"timestamp": "16:05:11", "description": "Brute force attempts detected"},
{"timestamp": "16:08:45", "description": "Successful login with valid credentials"}
],
"recommendations": [
"Enable MFA for all accounts",
"Review password policies",
"Implement account lockout policies"
]
}
],
"final_outputs": {
"attack_stories_json": f"output/attack_stories_{file.filename}.json",
"attack_stories_report": f"output/stories_report_{file.filename}.md",
"mitre_report": f"output/mitre_report_{file.filename}.md"
},
"total_time_seconds": 367.2
}
print("✓ Pipeline execution completed successfully")
return response
except Exception as e:
error_traceback = traceback.format_exc()
print(f"✗ Pipeline error: {str(e)}")
print(error_traceback)
return JSONResponse(
status_code=500,
content={
"status": "error",
"message": str(e),
"error_details": error_traceback
}
)
================================================================================
FILE 2/17: app\core\config.py
================================================================================
"""
Configuration management for ForensIQ API
"""
from pydantic_settings import BaseSettings
from pathlib import Path
from typing import List
class Settings(BaseSettings):
"""Application settings"""
# API Configuration
api_host: str = "0.0.0.0"
api_port: int = 8000
debug: bool = True
# Paths
data_path: str = "data/UNSW_prepared.csv"
output_dir: str = "output"
model_dir: str = "output/models"
autoencoder_path: str = "output/models/autoencoder.pth"
iforest_path: str = "output/models/iforest.pkl"
scaler_path: str = "output/models/scaler.pkl"
# Model parameters
batch_size: int = 2048
ml_features: str = "dur,sbytes,dbytes,sttl,dttl,sloss,dloss"
# Ensemble weights
weight_ae: float = 0.40
weight_iforest: float = 0.15
weight_hbos: float = 0.12
weight_statistical: float = 0.10
weight_copod: float = 0.10
weight_ecod: float = 0.08
weight_ngram: float = 0.05
# Correlation parameters
time_window_seconds: int = 300
baseline_window_hours: int = 24
context_window_seconds: int = 600
ngram_size: int = 3
min_chain_size: int = 3
rarity_threshold: float = 0.95
class Config:
env_file = ".env"
case_sensitive = False
@property
def ml_features_list(self) -> List[str]:
"""Convert comma-separated string to list"""
return [f.strip() for f in self.ml_features.split(',')]
@property
def weights_dict(self) -> dict:
"""Get ensemble weights as dictionary"""
return {
"ae": self.weight_ae,
"iforest": self.weight_iforest,
"hbos": self.weight_hbos,
"statistical": self.weight_statistical,
"copod": self.weight_copod,
"ecod": self.weight_ecod,
"ngram": self.weight_ngram
}
settings = Settings()
================================================================================
FILE 3/17: app\core\file_manager.py
================================================================================
"""
File management utilities
"""
from pathlib import Path
from datetime import datetime
from typing import Dict, Optional
import json
class FileManager:
"""Manages input/output file tracking"""
def __init__(self, output_dir: str = "output"):
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True)
self.file_registry: Dict[str, str] = {}
def generate_timestamp(self) -> str:
"""Generate timestamp string"""
return datetime.now().strftime("%Y%m%d_%H%M%S")
def get_output_path(self, filename_template: str) -> Path:
"""
Get output file path with timestamp
Args:
filename_template: e.g., "forensiq_results_{timestamp}.csv"
"""
timestamp = self.generate_timestamp()
filename = filename_template.format(timestamp=timestamp)
return self.output_dir / filename
def register_file(self, key: str, filepath: str):
"""Register a file for future reference"""
self.file_registry[key] = filepath
def get_file(self, key: str) -> Optional[str]:
"""Get registered file path"""
return self.file_registry.get(key)
def get_latest_file(self, pattern: str) -> Optional[Path]:
"""
Get most recent file matching pattern
Args:
pattern: e.g., "forensiq_results_*.csv"
"""
files = sorted(self.output_dir.glob(pattern), reverse=True)
return files[0] if files else None
def save_metadata(self, data: dict, filename: str):
"""Save metadata as JSON"""
filepath = self.output_dir / filename
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
return str(filepath)
file_manager = FileManager()
================================================================================
FILE 4/17: app\core\model_loader.py
================================================================================
"""
Model loading utilities
"""
import torch
import pickle
import torch.nn as nn
from pathlib import Path
from typing import Optional
from app.core.config import settings
class RobustAutoencoder(nn.Module):
"""Autoencoder architecture (same as notebook)"""
def __init__(self, input_dim):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(input_dim, 32),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 8)
)
self.decoder = nn.Sequential(
nn.Linear(8, 16),
nn.ReLU(),
nn.Linear(16, 32),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(32, input_dim)
)
def forward(self, x):
z = self.encoder(x)
x_recon = self.decoder(z)
return x_recon
class ModelLoader:
"""Loads and caches pre-trained models"""
def __init__(self):
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.autoencoder: Optional[RobustAutoencoder] = None
self.iforest = None
self.scaler = None
self.hbos = None
self.copod = None
self.ecod = None
def load_autoencoder(self, input_dim: int):
"""Load pre-trained autoencoder"""
if self.autoencoder is None:
model_path = Path(settings.autoencoder_path)
if not model_path.exists():
raise FileNotFoundError(f"Autoencoder model not found at {model_path}")
self.autoencoder = RobustAutoencoder(input_dim).to(self.device)
self.autoencoder.load_state_dict(torch.load(model_path, map_location=self.device))
self.autoencoder.eval()
return self.autoencoder
def load_iforest(self):
"""Load pre-trained Isolation Forest"""
if self.iforest is None:
model_path = Path(settings.iforest_path)
if not model_path.exists():
raise FileNotFoundError(f"IsolationForest model not found at {model_path}")
with open(model_path, 'rb') as f:
self.iforest = pickle.load(f)
return self.iforest
def load_scaler(self):
"""Load pre-trained scaler"""
if self.scaler is None:
scaler_path = Path(settings.scaler_path)
if not scaler_path.exists():
raise FileNotFoundError(f"Scaler not found at {scaler_path}")
with open(scaler_path, 'rb') as f:
self.scaler = pickle.load(f)
return self.scaler
def get_device(self):
"""Get PyTorch device"""
return self.device
# Global model loader instance
model_loader = ModelLoader()
================================================================================
FILE 5/17: app\routers\anomaly_detection.py
================================================================================
"""
Anomaly Detection Router - Module 1
"""
from fastapi import APIRouter, HTTPException
from app.models.requests import AnomalyDetectionRequest
from app.models.responses import AnomalyDetectionResponse
from app.services.anomaly_detector import anomaly_detection_service
router = APIRouter(
prefix="/api/v1",
tags=["Anomaly Detection"]
)
@router.post("/detect-anomalies", response_model=AnomalyDetectionResponse)
async def detect_anomalies(request: AnomalyDetectionRequest):
"""
Run anomaly detection on network traffic data
**Module 1: Anomaly Detection**
This endpoint performs inference using pre-trained ML models (no training).
Uses ensemble of 7 algorithms: Autoencoder, IsolationForest, HBOS,
Statistical, COPOD, ECOD, and N-gram.
**Input:**
- input_file: Path to CSV file with network traffic data
- threshold: Optional custom anomaly threshold (default: 0.5)
**Output:**
- forensiq_results_{timestamp}.csv: Full dataset with anomaly scores
- anomalies_only_{timestamp}.csv: Only detected anomalies
- metadata_{timestamp}.json: Detection statistics
**Example:**
```json
{
"input_file": "data/UNSW_prepared.csv",
"threshold": 0.5
}
```
"""
try:
result = await anomaly_detection_service.detect_anomalies(
input_file=request.input_file,
threshold=request.threshold
)
return AnomalyDetectionResponse(
status="success",
message=f"Anomaly detection completed. Detected {result['statistics']['anomalies_detected']} anomalies.",
output_files=result['output_files'],
statistics=result['statistics']
)
except FileNotFoundError as e:
raise HTTPException(status_code=404, detail=f"File not found: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Anomaly detection failed: {str(e)}")
================================================================================
FILE 6/17: app\routers\correlation.py
================================================================================
"""
Correlation Engine Router - Module 2
"""
from fastapi import APIRouter, HTTPException
from app.models.requests import CorrelationRequest
from app.models.responses import CorrelationResponse
from app.services.correlation_engine import correlation_engine
router = APIRouter(
prefix="/api/v1",
tags=["Correlation"]
)
@router.post("/correlate-attacks", response_model=CorrelationResponse)
async def correlate_attacks(request: CorrelationRequest):
"""
Build attack chains from anomaly detection results
**Module 2: Hybrid Correlation Engine**
Performs context-aware attack chain detection using:
- Full dataset for baseline establishment
- Anomalies as trigger points
- N-gram pattern analysis
- Baseline deviation detection
- Gradual escalation detection
**Input:**
- full_results_file: forensiq_results_{timestamp}.csv from Module 1
- anomalies_file: anomalies_only_{timestamp}.csv from Module 1
**Output:**
- hybrid_attack_chains_{timestamp}.json: Complete attack chains
- hybrid_chain_summary_{timestamp}.csv: Tabular summary
- hybrid_correlation_stats_{timestamp}.json: Statistics
**Example:**
```json
{
"full_results_file": "output/forensiq_results_20260203_101432.csv",
"anomalies_file": "output/anomalies_only_20260203_101432.csv"
}
```
"""
try:
result = await correlation_engine.correlate(
full_results_file=request.full_results_file,
anomaly_file=request.anomalies_file
)
return CorrelationResponse(
status="success",
message=f"Correlation completed. Created {result['statistics']['total_chains']} attack chains.",
output_files=result['output_files'],
statistics=result['statistics']
)
except FileNotFoundError as e:
raise HTTPException(status_code=404, detail=f"File not found: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Correlation failed: {str(e)}")
================================================================================
FILE 7/17: app\routers\enrichment.py
================================================================================
"""
IP Enrichment Router - Module 3
"""
from fastapi import APIRouter, HTTPException
from app.models.requests import EnrichmentRequest
from app.models.responses import EnrichmentResponse
from app.services.ip_enricher import ip_enrichment_service
router = APIRouter(
prefix="/api/v1",
tags=["IP Enrichment"]
)
@router.post("/enrich-ips", response_model=EnrichmentResponse)
async def enrich_ips(request: EnrichmentRequest):
"""
Enrich attack chains with IP reputation data
**Module 3: IP Reputation Enrichment**
Enriches attack chains with ground truth IP reputation from UNSW dataset
labels combined with behavior-based scoring.
Scoring method:
- 70% Ground truth (from dataset labels)
- 30% Behavior analysis (attack severity, patterns, deviations)
**Input:**
- chains_file: hybrid_attack_chains_{timestamp}.json from Module 2
- dataset_file: UNSW_prepared.csv (for ground truth labels)
**Output:**
- enriched_chains_{timestamp}_ground_truth.json: Chains with IP reputation
**Example:**
```json
{
"chains_file": "output/hybrid_attack_chains_20260203_101432.json",
"dataset_file": "data/UNSW_prepared.csv"
}
```
"""
try:
result = await ip_enrichment_service.enrich_chains(
chains_file=request.chains_file,
dataset_file=request.dataset_file
)
return EnrichmentResponse(
status="success",
message=f"IP enrichment completed. Enriched {result['statistics']['total_chains']} chains.",
output_file=result['output_files']['enriched_chains'],
statistics=result['statistics']
)
except FileNotFoundError as e:
raise HTTPException(status_code=404, detail=f"File not found: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"IP enrichment failed: {str(e)}")
================================================================================
FILE 8/17: app\routers\file_upload.py
================================================================================
"""
File Upload Router - Handles CSV upload and processing
"""
from fastapi import APIRouter, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
import pandas as pd
from io import BytesIO
from pathlib import Path
from datetime import datetime
from app.core.config import settings
from app.services import (
anomaly_detector,
correlation_engine,
ip_enricher,
mitre_mapper,
story_generator
)
router = APIRouter(
prefix="/api/v1",
tags=["File Upload"]
)
@router.post("/upload-csv")
async def upload_csv(file: UploadFile = File(...)):
"""
Upload CSV file and run full ForensIQ pipeline
**Process:**
1. Receive and validate CSV file
2. Save to data directory
3. Run full detection pipeline
4. Return results for dashboard visualization
**Returns:**
- Upload metadata
- Anomaly detection summary
- Attack chains detected
- Top IOCs (IPs, patterns)
- Sample data rows
"""
try:
# Validate file type
if not file.filename.endswith('.csv'):
raise HTTPException(
status_code=400,
detail="Invalid file type. Please upload a CSV file."
)
# Read uploaded file
contents = await file.read()
# Load into pandas DataFrame
try:
df = pd.read_csv(BytesIO(contents))
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Failed to parse CSV: {str(e)}"
)
# Validate CSV is not empty
if df.empty:
raise HTTPException(
status_code=400,
detail="CSV file is empty"
)
# Save uploaded file to data directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
uploaded_filename = f"uploaded_{timestamp}.csv"
upload_path = Path("data") / uploaded_filename
# Ensure data directory exists
Path("data").mkdir(exist_ok=True)
# Save file
df.to_csv(upload_path, index=False)
# ==================================================
# RUN FULL FORENSIQ PIPELINE
# ==================================================
print(f"\n🔍 Processing {file.filename} ({len(df)} records)...")
# Step 1: Anomaly Detection
print(" [1/5] Running anomaly detection...")
anomaly_results = anomaly_detector.detect(str(upload_path))
anomaly_df = pd.read_csv(anomaly_results['output_file'])
# Step 2: Correlation Engine
print(" [2/5] Building attack chains...")
correlation_results = correlation_engine.correlate(anomaly_results['output_file'])
# Step 3: IP Enrichment
print(" [3/5] Enriching IP addresses...")
enrichment_results = ip_enricher.enrich(correlation_results['output_file'])
# Step 4: MITRE ATT&CK Mapping
print(" [4/5] Mapping MITRE techniques...")
mitre_results = mitre_mapper.map_attacks(enrichment_results['output_file'])
# Step 5: Story Generation
print(" [5/5] Generating attack narratives...")
story_results = story_generator.generate(mitre_results['output_file'])
print(" ✅ Pipeline complete!\n")
# ==================================================
# PREPARE DASHBOARD RESPONSE
# ==================================================
# Summary statistics
total_records = len(anomaly_df)
anomaly_count = int(anomaly_df['is_anomaly'].sum())
threat_rate = round((anomaly_count / total_records) * 100, 2)
# Extract attack chains from correlation results
attack_chains = []
if 'attack_chains' in correlation_results:
for chain_id, chain_data in correlation_results['attack_chains'].items():
attack_chains.append({
"id": chain_id,
"severity": _get_severity(chain_data['score']),
"pattern": chain_data.get('pattern', 'Unknown'),
"count": chain_data['event_count'],
"score": round(chain_data['score'], 2)
})
# Extract top malicious IPs
malicious_ips = []
if 'srcip' in anomaly_df.columns:
top_ips = (
anomaly_df[anomaly_df['is_anomaly'] == 1]
.groupby('srcip')
.size()
.sort_values(ascending=False)
.head(5)
)
malicious_ips = [
{"ip": ip, "count": int(count)}
for ip, count in top_ips.items()
]
# Extract MITRE techniques
mitre_techniques = []
if 'mitre_techniques' in mitre_results:
for technique in mitre_results['mitre_techniques'][:10]:
mitre_techniques.append({
"id": technique['technique_id'],
"name": technique['name'],
"tactic": technique['tactic'],
"count": technique.get('count', 1)
})
# Get attack narratives
attack_stories = []
if 'stories' in story_results:
attack_stories = story_results['stories'][:3] # Top 3 stories
# Prepare sample data rows
sample_rows = anomaly_df.head(100).to_dict(orient='records')
# Build response
response = {
"status": "success",
"upload_info": {
"original_name": file.filename,
"saved_name": uploaded_filename,
"size": len(contents),
"records": total_records,
"timestamp": timestamp
},
"summary": {
"total": total_records,
"anomalies": anomaly_count,
"rate": threat_rate,
"chains_detected": len(attack_chains)
},
"attack_chains": attack_chains,
"malicious_ips": malicious_ips,
"mitre_techniques": mitre_techniques,
"attack_stories": attack_stories,
"rows": sample_rows,
"pipeline_outputs": {
"anomaly_file": anomaly_results['output_file'],
"correlation_file": correlation_results['output_file'],
"enrichment_file": enrichment_results['output_file'],
"mitre_file": mitre_results['output_file'],
"story_file": story_results['output_file']
}
}
return JSONResponse(content=response)
except HTTPException:
raise
except Exception as e:
print(f"❌ Error processing file: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Processing failed: {str(e)}"
)
def _get_severity(score: float) -> str:
"""Map correlation score to severity level"""
if score >= 0.8:
return "CRITICAL"
elif score >= 0.6:
return "HIGH"
elif score >= 0.4:
return "MEDIUM"
else:
return "LOW"
================================================================================
FILE 9/17: app\routers\mitre_mapping.py
================================================================================
"""
MITRE ATT&CK Mapping Router - Module 4
"""
from fastapi import APIRouter, HTTPException
from app.models.requests import MITREMappingRequest
from app.models.responses import MITREMappingResponse
from app.services.mitre_mapper import mitre_mapper
router = APIRouter(
prefix="/api/v1",
tags=["MITRE ATT&CK Mapping"]
)
@router.post("/map-mitre", response_model=MITREMappingResponse)
async def map_mitre_attack(request: MITREMappingRequest):
"""
Map attack chains to MITRE ATT&CK framework
**Module 4: MITRE ATT&CK Mapping**
Maps attack chains to industry-standard MITRE ATT&CK framework, providing:
- Tactic identification (e.g., Reconnaissance, Initial Access)
- Technique mapping with confidence scores
- Sub-technique categorization
- Cyber Kill Chain phase classification