A comprehensive, AI-powered incident response automation system that parses security logs, detects threats, and provides intelligent analysis using the Foundation-Sec-8B security language model.
auth.log): SSH authentication, sudo commands, session managementIncident Response Automation/
βββ src/
β βββ __init__.py
β βββ core/
β β βββ __init__.py
β β βββ log_parser.py # Log parsing for multiple formats
β β βββ detection.py # Threat detection engine
β β βββ export.py # JSON/PDF export functionality
β βββ ai/
β β βββ __init__.py
β β βββ analyzer.py # AI analysis with Foundation-Sec-8B
β βββ db/
β β βββ __init__.py
β β βββ database.py # SQLite database operations
β βββ dashboard/
β βββ __init__.py
β βββ app.py # Streamlit dashboard
βββ tests/
β βββ __init__.py
β βββ test_log_parser.py # Log parser tests
β βββ test_detection.py # Detection engine tests
β βββ test_ai_analyzer.py # AI analyzer tests
β βββ test_database.py # Database tests
βββ logs/
β βββ sample_auth.log # Sample Linux auth logs
β βββ sample_windows_security.json # Sample Windows events
β βββ sample_ids.json # Sample IDS alerts
β βββ iocs.json # Indicators of Compromise
βββ reports/ # Generated reports directory
βββ requirements.txt # Python dependencies
βββ README.md # This file
Clone or download the project
cd "Incident Response Automation"
Create a virtual environment (recommended)
python -m venv venv
# Windows
.\venv\Scripts\activate
# Linux/Mac
source venv/bin/activate
Install dependencies
pip install -r requirements.txt
Download the AI Model (Optional)
The Foundation-Sec-8B model will be downloaded automatically on first use. However, you can pre-download it:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "fdtn-ai/Foundation-Sec-8B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
Note: The model requires approximately 16GB of disk space and 16GB+ RAM. For systems without these resources, use the Mock AI mode.
python -m streamlit run src/dashboard/app.py
The dashboard will open in your default browser at http://localhost:8501.
Windows note (Python 3.13): if streamlit run ... prints Failed to find real location of ...python.exe, always use python -m streamlit ....
The dashboard reads incidents from data/incidents.db. To generate demo incidents from the sample logs in logs/, run:
python test_populate.py
Then refresh the dashboard.
UnifiedLogParser.parse_file() yields normalized ParsedLogEntry records from Linux auth logs, Windows Security events, or IDS JSON.DetectionEngine.detect_all() runs several detectors and returns Detection objects (type, severity, alert, IOCs, related log entries).detection_to_incident() converts a Detection into an Incident and stores it in SQLite via IncidentDatabase.add_incident().src/ai/analyzer.py and stores the resulting summary back into the incident.src/core/export.py.src/dashboard/app.pytest_populate.pysrc/core/log_parser.py + src/core/detection.py + src/db/database.pyfrom src.core.log_parser import UnifiedLogParser
parser = UnifiedLogParser()
events = parser.parse_file("logs/sample_auth.log")
for event in events:
print(f"[{event.timestamp}] {event.event_type}: {event.message}")
from src.core.log_parser import UnifiedLogParser
from src.core.detection import DetectionEngine
# Parse logs
parser = UnifiedLogParser()
events = list(parser.parse_file("logs/sample_auth.log"))
# Initialize detection engine with IOCs
engine = DetectionEngine(ioc_file="logs/iocs.json")
# Detect threats
detections = engine.detect_all(events)
for detection in detections:
print(f"[{detection.severity.value}] {detection.detection_type.value}: {detection.alert}")
from src.ai.analyzer import analyze_incident
# Analyze an incident
result = analyze_incident(
alert="Multiple failed SSH login attempts from 203.0.113.50",
log_snippet="Dec 27 08:15:23 server sshd[1234]: Failed password for root from 203.0.113.50",
iocs=["203.0.113.50"],
use_mock=False # Set to True for testing without GPU
)
print(f"Severity: {result.severity}")
print(f"Summary: {result.summary}")
print(f"Recommendations: {result.recommendations}")
from src.db.database import IncidentDatabase, Incident
# Initialize database
db = IncidentDatabase("incidents.db")
# Create an incident
incident = Incident(
alert="Brute Force Attack Detected",
ioc="203.0.113.50",
log_snippet="Multiple failed SSH attempts...",
severity="high",
status="new"
)
# Save to database
incident_id = db.add_incident(incident)
# Query incidents
high_severity = db.get_incidents_by_severity("high")
recent = db.get_recent_incidents(hours=24)
from src.core.export import export_incidents_json, export_incidents_pdf
from src.db.database import IncidentDatabase
db = IncidentDatabase("incidents.db")
incidents = db.get_all_incidents()
# Export to JSON
export_incidents_json(incidents, "reports/incidents.json")
# Export to PDF
export_incidents_pdf(incidents, "reports/incidents.pdf")
# Run all tests
pytest tests/ -v
# Run with coverage
pytest tests/ -v --cov=src --cov-report=html
# Run specific test file
pytest tests/test_detection.py -v
# Run specific test
pytest tests/test_log_parser.py::TestLinuxAuthLogParser::test_parse_failed_password -v
src/core/log_parser.pyGoal: convert raw logs into a single normalized format (ParsedLogEntry) so detection rules can be log-source-agnostic.
Key types
LogType: LINUX_AUTH, WINDOWS_SECURITY, WINDOWS_SYSTEM, IDS_LOG, UNKNOWNParsedLogEntry: normalized fields: timestamp, source, event_type, user, source_ip, message, raw_log, metadata, log_typeKey classes
LinuxAuthLogParser: parses auth.log-style files (SSH failed/success, sudo command, sessions)WindowsEventLogParser: parses Windows Security event logs (JSON arrays / JSON lines / XML-like sources)IDSLogParser: parses IDS alert JSON (Snort/Suricata EVE-like)UnifiedLogParser: detects file type and routes to the correct parserHow to use
from src.core.log_parser import UnifiedLogParser
parser = UnifiedLogParser()
entries = list(parser.parse_file("logs/sample_auth.log"))
src/core/detection.pyGoal: transform parsed entries into actionable detections.
Key types
DetectionType: BRUTE_FORCE, SUSPICIOUS_LOGIN, UNKNOWN_PROCESS, IOC_MATCH, etc.Severity: LOW, MEDIUM, HIGH, CRITICALDetection: includes alert, severity, iocs, timestamp, log_entries, and helper get_log_snippet()Detectors
BruteForceDetector: identifies repeated failed logins and distributed attemptsSuspiciousLoginDetector: flags unusual hours, privileged users, rapid successive logins, etc.UnknownProcessDetector: identifies suspicious or known-bad process patterns (Windows 4688, Linux command patterns)IOCMatcher: matches parsed content against the IOC databaseOrchestrator
DetectionEngine.detect_all(log_entries): runs all detectors and returns sorted detectionsConfig knobs
DetectionEngine(brute_force_threshold=5, brute_force_window=10, ioc_file=...)logs/iocs.json (loaded by IOCDatabase)The tool expects a JSON object with an indicators section containing lists like ip_addresses, domains, file_hashes, process_names, etc. The loader extracts the value fields and compiles any custom regex patterns.
src/db/database.pyGoal: store incidents in SQLite and provide query/stats helpers for the dashboard.
Key type
Incident: dataclass representation of stored records.Key API
IncidentDatabase.add_incident(incident) -> intIncidentDatabase.get_incident(id) -> Incident | NoneIncidentDatabase.get_all_incidents() -> list[Incident]IncidentDatabase.get_statistics() -> dictImportant helper
detection_to_incident(detection) -> Incident: converts detections into database-ready incidents.src/ai/analyzer.pyGoal: produce a structured incident-analysis response (summary, classification, severity, response steps).
Two modes
MockAIAnalyzer: fast, deterministic testing without downloading/loading the modelAIAnalyzer: loads fdtn-ai/Foundation-Sec-8B via Transformers and generates analysis text, then parses it into AIAnalysisResultMain function used by the dashboard
analyze_incident(...) (wrapper that can run mock or real model)src/ai/ai_engine.pyThis file was added per request. It loads the model at import time and returns a raw generated string. It is not used by the dashboard (the dashboard uses src/ai/analyzer.py).
src/dashboard/app.pyGoal: provide an interactive UI to inspect incidents, trigger AI analysis, update statuses, and export reports.
Pages
src/core/export.pyJSON export
export_incidents_json(incidents, output_path, include_metadata=True)PDF export
export_incidents_pdf(incidents, output_path, title=...)reportlab if available.The SQLite database stores incidents with the following schema:
CREATE TABLE incidents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
alert TEXT NOT NULL,
ioc TEXT,
log_snippet TEXT,
ai_summary TEXT,
severity TEXT DEFAULT 'medium',
status TEXT DEFAULT 'new',
timestamp TEXT NOT NULL,
detection_type TEXT,
source_ips TEXT,
users TEXT,
metadata TEXT DEFAULT '{}'
);
Where it lives
data/incidents.db (created automatically)data/incidents.db.python test_populate.py
python -m streamlit run src/dashboard/app.py
Use Mock AI in the dashboard settings (default). This avoids large downloads and GPU/CPU memory pressure.
transformers + torch are installed and you have enough RAM/disk.This tool uses the fdtn-ai/Foundation-Sec-8B model from Hugging Face, specifically designed for cybersecurity tasks.
Model Capabilities:
Requirements:
Using Mock Mode: For testing or systems without sufficient resources:
from src.ai.analyzer import analyze_incident
result = analyze_incident(
alert="Test alert",
log_snippet="Test log",
use_mock=True # Uses mock analyzer
)
{
"detection_type": "brute_force",
"severity": "high",
"confidence": 0.95,
"description": "Detected 47 failed login attempts from 203.0.113.50 within 5 minutes",
"source_ip": "203.0.113.50",
"target_user": "root",
"recommendation": "Block source IP, investigate for compromise"
}
{
"severity": "high",
"summary": "SSH brute force attack targeting root account from known malicious IP",
"attack_type": "Credential Access - Brute Force (T1110)",
"indicators": ["203.0.113.50", "Multiple failed authentications", "Root account targeting"],
"recommendations": [
"Immediately block 203.0.113.50 at firewall",
"Review successful logins from this IP",
"Enable account lockout policies",
"Consider implementing fail2ban",
"Audit root account for unauthorized access"
],
"mitre_techniques": ["T1110.001", "T1078"],
"confidence": 0.92
}
Edit detection parameters in src/core/detection.py:
# Brute force detection
BRUTE_FORCE_THRESHOLD = 5 # Failed attempts
BRUTE_FORCE_WINDOW = 300 # Seconds (5 minutes)
# Suspicious login hours
SUSPICIOUS_HOURS_START = 22 # 10 PM
SUSPICIOUS_HOURS_END = 6 # 6 AM
Add custom IOCs to logs/iocs.json:
{
"indicators": {
"ip_addresses": [
{
"value": "1.2.3.4",
"type": "ipv4",
"threat_type": "c2",
"description": "Custom threat",
"confidence": "high"
}
]
}
}
Model download fails
# Clear Hugging Face cache and retry
rm -rf ~/.cache/huggingface
Out of memory during AI analysis
use_mock=TrueStreamlit port conflict
streamlit run src/dashboard/app.py --server.port 8502
Database locked error
pytest tests/ -vThis project is licensed under the MIT License - see the LICENSE file for details.
For issues and feature requests, please open an issue on the project repository.
β οΈ Disclaimer: This tool is for educational and authorized security testing purposes only. Always obtain proper authorization before analyzing logs from systems you do not own.
A comprehensive, AI-powered incident response automation system that parses security logs, detects threats, and provides intelligent analysis using the Foundation-Sec-8B security language model.
auth.log): SSH authentication, sudo commands, session managementIncident Response Automation/
βββ src/
β βββ __init__.py
β βββ core/
β β βββ __init__.py
β β βββ log_parser.py # Log parsing for multiple formats
β β βββ detection.py # Threat detection engine
β β βββ export.py # JSON/PDF export functionality
β βββ ai/
β β βββ __init__.py
β β βββ analyzer.py # AI analysis with Foundation-Sec-8B
β βββ db/
β β βββ __init__.py
β β βββ database.py # SQLite database operations
β βββ dashboard/
β βββ __init__.py
β βββ app.py # Streamlit dashboard
βββ tests/
β βββ __init__.py
β βββ test_log_parser.py # Log parser tests
β βββ test_detection.py # Detection engine tests
β βββ test_ai_analyzer.py # AI analyzer tests
β βββ test_database.py # Database tests
βββ logs/
β βββ sample_auth.log # Sample Linux auth logs
β βββ sample_windows_security.json # Sample Windows events
β βββ sample_ids.json # Sample IDS alerts
β βββ iocs.json # Indicators of Compromise
βββ reports/ # Generated reports directory
βββ requirements.txt # Python dependencies
βββ README.md # This file
Clone or download the project
cd "Incident Response Automation"
Create a virtual environment (recommended)
python -m venv venv
# Windows
.\venv\Scripts\activate
# Linux/Mac
source venv/bin/activate
Install dependencies
pip install -r requirements.txt
Download the AI Model (Optional)
The Foundation-Sec-8B model will be downloaded automatically on first use. However, you can pre-download it:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "fdtn-ai/Foundation-Sec-8B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
Note: The model requires approximately 16GB of disk space and 16GB+ RAM. For systems without these resources, use the Mock AI mode.
python -m streamlit run src/dashboard/app.py
The dashboard will open in your default browser at http://localhost:8501.
Windows note (Python 3.13): if streamlit run ... prints Failed to find real location of ...python.exe, always use python -m streamlit ....
The dashboard reads incidents from data/incidents.db. To generate demo incidents from the sample logs in logs/, run:
python test_populate.py
Then refresh the dashboard.
UnifiedLogParser.parse_file() yields normalized ParsedLogEntry records from Linux auth logs, Windows Security events, or IDS JSON.DetectionEngine.detect_all() runs several detectors and returns Detection objects (type, severity, alert, IOCs, related log entries).detection_to_incident() converts a Detection into an Incident and stores it in SQLite via IncidentDatabase.add_incident().src/ai/analyzer.py and stores the resulting summary back into the incident.src/core/export.py.src/dashboard/app.pytest_populate.pysrc/core/log_parser.py + src/core/detection.py + src/db/database.pyfrom src.core.log_parser import UnifiedLogParser
parser = UnifiedLogParser()
events = parser.parse_file("logs/sample_auth.log")
for event in events:
print(f"[{event.timestamp}] {event.event_type}: {event.message}")
from src.core.log_parser import UnifiedLogParser
from src.core.detection import DetectionEngine
# Parse logs
parser = UnifiedLogParser()
events = list(parser.parse_file("logs/sample_auth.log"))
# Initialize detection engine with IOCs
engine = DetectionEngine(ioc_file="logs/iocs.json")
# Detect threats
detections = engine.detect_all(events)
for detection in detections:
print(f"[{detection.severity.value}] {detection.detection_type.value}: {detection.alert}")
from src.ai.analyzer import analyze_incident
# Analyze an incident
result = analyze_incident(
alert="Multiple failed SSH login attempts from 203.0.113.50",
log_snippet="Dec 27 08:15:23 server sshd[1234]: Failed password for root from 203.0.113.50",
iocs=["203.0.113.50"],
use_mock=False # Set to True for testing without GPU
)
print(f"Severity: {result.severity}")
print(f"Summary: {result.summary}")
print(f"Recommendations: {result.recommendations}")
from src.db.database import IncidentDatabase, Incident
# Initialize database
db = IncidentDatabase("incidents.db")
# Create an incident
incident = Incident(
alert="Brute Force Attack Detected",
ioc="203.0.113.50",
log_snippet="Multiple failed SSH attempts...",
severity="high",
status="new"
)
# Save to database
incident_id = db.add_incident(incident)
# Query incidents
high_severity = db.get_incidents_by_severity("high")
recent = db.get_recent_incidents(hours=24)
from src.core.export import export_incidents_json, export_incidents_pdf
from src.db.database import IncidentDatabase
db = IncidentDatabase("incidents.db")
incidents = db.get_all_incidents()
# Export to JSON
export_incidents_json(incidents, "reports/incidents.json")
# Export to PDF
export_incidents_pdf(incidents, "reports/incidents.pdf")
# Run all tests
pytest tests/ -v
# Run with coverage
pytest tests/ -v --cov=src --cov-report=html
# Run specific test file
pytest tests/test_detection.py -v
# Run specific test
pytest tests/test_log_parser.py::TestLinuxAuthLogParser::test_parse_failed_password -v
src/core/log_parser.pyGoal: convert raw logs into a single normalized format (ParsedLogEntry) so detection rules can be log-source-agnostic.
Key types
LogType: LINUX_AUTH, WINDOWS_SECURITY, WINDOWS_SYSTEM, IDS_LOG, UNKNOWNParsedLogEntry: normalized fields: timestamp, source, event_type, user, source_ip, message, raw_log, metadata, log_typeKey classes
LinuxAuthLogParser: parses auth.log-style files (SSH failed/success, sudo command, sessions)WindowsEventLogParser: parses Windows Security event logs (JSON arrays / JSON lines / XML-like sources)IDSLogParser: parses IDS alert JSON (Snort/Suricata EVE-like)UnifiedLogParser: detects file type and routes to the correct parserHow to use
from src.core.log_parser import UnifiedLogParser
parser = UnifiedLogParser()
entries = list(parser.parse_file("logs/sample_auth.log"))
src/core/detection.pyGoal: transform parsed entries into actionable detections.
Key types
DetectionType: BRUTE_FORCE, SUSPICIOUS_LOGIN, UNKNOWN_PROCESS, IOC_MATCH, etc.Severity: LOW, MEDIUM, HIGH, CRITICALDetection: includes alert, severity, iocs, timestamp, log_entries, and helper get_log_snippet()Detectors
BruteForceDetector: identifies repeated failed logins and distributed attemptsSuspiciousLoginDetector: flags unusual hours, privileged users, rapid successive logins, etc.UnknownProcessDetector: identifies suspicious or known-bad process patterns (Windows 4688, Linux command patterns)IOCMatcher: matches parsed content against the IOC databaseOrchestrator
DetectionEngine.detect_all(log_entries): runs all detectors and returns sorted detectionsConfig knobs
DetectionEngine(brute_force_threshold=5, brute_force_window=10, ioc_file=...)logs/iocs.json (loaded by IOCDatabase)The tool expects a JSON object with an indicators section containing lists like ip_addresses, domains, file_hashes, process_names, etc. The loader extracts the value fields and compiles any custom regex patterns.
src/db/database.pyGoal: store incidents in SQLite and provide query/stats helpers for the dashboard.
Key type
Incident: dataclass representation of stored records.Key API
IncidentDatabase.add_incident(incident) -> intIncidentDatabase.get_incident(id) -> Incident | NoneIncidentDatabase.get_all_incidents() -> list[Incident]IncidentDatabase.get_statistics() -> dictImportant helper
detection_to_incident(detection) -> Incident: converts detections into database-ready incidents.src/ai/analyzer.pyGoal: produce a structured incident-analysis response (summary, classification, severity, response steps).
Two modes
MockAIAnalyzer: fast, deterministic testing without downloading/loading the modelAIAnalyzer: loads fdtn-ai/Foundation-Sec-8B via Transformers and generates analysis text, then parses it into AIAnalysisResultMain function used by the dashboard
analyze_incident(...) (wrapper that can run mock or real model)src/ai/ai_engine.pyThis file was added per request. It loads the model at import time and returns a raw generated string. It is not used by the dashboard (the dashboard uses src/ai/analyzer.py).
src/dashboard/app.pyGoal: provide an interactive UI to inspect incidents, trigger AI analysis, update statuses, and export reports.
Pages
src/core/export.pyJSON export
export_incidents_json(incidents, output_path, include_metadata=True)PDF export
export_incidents_pdf(incidents, output_path, title=...)reportlab if available.The SQLite database stores incidents with the following schema:
CREATE TABLE incidents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
alert TEXT NOT NULL,
ioc TEXT,
log_snippet TEXT,
ai_summary TEXT,
severity TEXT DEFAULT 'medium',
status TEXT DEFAULT 'new',
timestamp TEXT NOT NULL,
detection_type TEXT,
source_ips TEXT,
users TEXT,
metadata TEXT DEFAULT '{}'
);
Where it lives
data/incidents.db (created automatically)data/incidents.db.python test_populate.py
python -m streamlit run src/dashboard/app.py
Use Mock AI in the dashboard settings (default). This avoids large downloads and GPU/CPU memory pressure.
transformers + torch are installed and you have enough RAM/disk.This tool uses the fdtn-ai/Foundation-Sec-8B model from Hugging Face, specifically designed for cybersecurity tasks.
Model Capabilities:
Requirements:
Using Mock Mode: For testing or systems without sufficient resources:
from src.ai.analyzer import analyze_incident
result = analyze_incident(
alert="Test alert",
log_snippet="Test log",
use_mock=True # Uses mock analyzer
)
{
"detection_type": "brute_force",
"severity": "high",
"confidence": 0.95,
"description": "Detected 47 failed login attempts from 203.0.113.50 within 5 minutes",
"source_ip": "203.0.113.50",
"target_user": "root",
"recommendation": "Block source IP, investigate for compromise"
}
{
"severity": "high",
"summary": "SSH brute force attack targeting root account from known malicious IP",
"attack_type": "Credential Access - Brute Force (T1110)",
"indicators": ["203.0.113.50", "Multiple failed authentications", "Root account targeting"],
"recommendations": [
"Immediately block 203.0.113.50 at firewall",
"Review successful logins from this IP",
"Enable account lockout policies",
"Consider implementing fail2ban",
"Audit root account for unauthorized access"
],
"mitre_techniques": ["T1110.001", "T1078"],
"confidence": 0.92
}
Edit detection parameters in src/core/detection.py:
# Brute force detection
BRUTE_FORCE_THRESHOLD = 5 # Failed attempts
BRUTE_FORCE_WINDOW = 300 # Seconds (5 minutes)
# Suspicious login hours
SUSPICIOUS_HOURS_START = 22 # 10 PM
SUSPICIOUS_HOURS_END = 6 # 6 AM
Add custom IOCs to logs/iocs.json:
{
"indicators": {
"ip_addresses": [
{
"value": "1.2.3.4",
"type": "ipv4",
"threat_type": "c2",
"description": "Custom threat",
"confidence": "high"
}
]
}
}
Model download fails
# Clear Hugging Face cache and retry
rm -rf ~/.cache/huggingface
Out of memory during AI analysis
use_mock=TrueStreamlit port conflict
streamlit run src/dashboard/app.py --server.port 8502
Database locked error
pytest tests/ -vThis project is licensed under the MIT License - see the LICENSE file for details.
For issues and feature requests, please open an issue on the project repository.
β οΈ Disclaimer: This tool is for educational and authorized security testing purposes only. Always obtain proper authorization before analyzing logs from systems you do not own.