A comprehensive autonomous vehicle safety system that detects CAN Bus attacks and executes safety maneuvers in response. This project integrates Suricata IDS for threat detection with a vehicle control module that automatically responds to threats through graduated safety actions.
NEW! This project now includes a complete safety system that:
- β Detects 7 classes of CAN Bus threats (floods, anomalies, sensor failures, etc.)
- β Scores threats on a 0-100 scale with intelligent aggregation
- β Executes 5 graduated safety maneuvers (SLOW_DOWN, STOP, PULL_OVER, EVASIVE, FULL_STOP)
- β Generates specific CAN messages for vehicle control modules
- β Enforces 8 physical safety constraints
- β Implements 5 fail-safe mechanisms
π Start with the Safety System Overview | Quick Start (5 minutes) | Full Architecture
- What This System Does
- Features
- Documentation
- Project Structure
- Prerequisites
- Installation
- Usage
- Threat Detection
- Safety Maneuvers
- Testing
- Troubleshooting
CAN Bus Traffic
β
Suricata IDS (10 Detection Rules)
β
eve.json Alerts
β
Safety Controller (7 Threat Classes)
β
Threat Scoring Algorithm (0-100)
β
Safety Decision Logic
β
Vehicle Control Commands
β
5 Safety Maneuvers (Graduated Response)
When Suricata detects a CAN flood attack (Rule 1000001):
- Alert is parsed and classified as "CAN Flooding" threat (Class 1)
- Threat score increases to 35/100 (YELLOW state)
- Safety controller triggers SLOW_DOWN maneuver
- Vehicle control module sends deceleration command to brake module (0x100)
- Brake applies 2 m/sΒ² deceleration while monitoring for further threats
If attack continues or escalates:
- Score increases to 65/100 (ORANGE state) β STOP maneuver
- Score reaches 85/100 (RED state) β FULL_STOP with emergency braking
- Threat Detection: 7-class threat detection system integrated with Suricata
- Intelligent Scoring: Threat scoring algorithm (0-100 scale) with time decay
- Graduated Response: 5 safety maneuvers triggered by threat level
- CAN Control: Specific CAN messages for 5 vehicle modules (Brake, Throttle, Steering, Perception, Safety)
- Safety Constraints: 8 physical safety limits (max deceleration, steering range, etc.)
- Fail-Safe Mechanisms: 5 redundant safety checks to prevent unintended behavior
- Incident Reporting: Detailed incident logs with threat timeline
- Real-Time Detection: Suricata IDS integration with eve.json output
- 10 Detection Rules: Comprehensive rules for CAN-specific threats
- CAN Traffic Generation: Simulate CAN bus traffic with various attack patterns
- Log Analysis: Parse and analyze Suricata logs
- Visualization: Interactive visualizations of detected alerts and threat timelines
- CAN Flood Detection - High-frequency repeated CAN ID patterns (Rule 1000001)
- Anomaly Detection - Abnormal message sequences (Rule 1000002)
- DoS Attacks - Zero payload suspicious patterns (Rule 1000003)
- Diagnostic Floods - FF payload flooding (Rule 1000004)
- Unauthorized Commands - Control frame anomalies (Rule 1000005)
- OBD Abuse - Malicious OBD-II access attempts (Rule 1000006)
- Unknown ECU IDs - Detection of unregistered ECU identifiers (Rule 1000007)
- Rapid Steering - Dangerous steering angle changes (Rule 1000008)
- Conflicting Controls - Simultaneous conflicting commands (Rule 1000009)
- Excessive Brake Pressure - Abnormal brake pressure values (Rule 1000010)
can-bus-simulation/
βββ code/
β βββ vehicle_control.py # Core threat detection & control (600+ lines)
β βββ safety_controller.py # Suricata integration & decisions (300+ lines)
β βββ test_safety_controller.py # 17 comprehensive unit tests (400+ lines)
β βββ generate_pcap.py # PCAP generator for CAN traffic
β βββ visualize.ipynb # Jupyter notebook for visualization
βββ packets/
β βββ can_sim.pcap # Generated CAN traffic capture
βββ inputdata/
β βββ simulated_can_logs.csv # Sample CAN log data
βββ rules/
β βββ can.rules # 10 Suricata detection rules (enhanced)
βββ suricata_logs/
β βββ fast.log # Alert summary
β βββ eve.json # Detailed JSON logs
βββ suricata.yaml # Suricata IDS configuration
βββ requirements.txt # Python dependencies
βββ screenshots/ # Documentation screenshots
β
βββ Documentation Files:
βββ README_SAFETY_SYSTEM.md # Safety system overview
βββ QUICKSTART.md # 5-minute quick start guide
βββ ARCHITECTURE.md # Complete system design (400 lines)
βββ IMPLEMENTATION_GUIDE.md # Step-by-step implementation (300 lines)
βββ COMPLETE_IMPLEMENTATION.md # Full technical specification (500 lines)
βββ DELIVERY_SUMMARY.md # Project completion status
βββ DOCUMENTATION_INDEX.md # Navigation guide for all docs
- Operating System: macOS, Linux, or Windows (WSL)
- Python: 3.10 or higher
- Suricata IDS: 7.0.0 or higher
- Sudo Access: Required for Suricata execution
# Install Homebrew (if not already installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install Suricata
brew install suricata
# Verify installation
suricata --version# Add Suricata PPA
sudo add-apt-repository ppa:oisf/suricata-stable
sudo apt-get update
# Install Suricata
sudo apt-get install suricata
# Verify installation
suricata --versioncd ~/Documents/MajorProject# Create virtual environment
python3 -m venv .venv
# Activate virtual environment
source .venv/bin/activate # On macOS/Linux
# OR
.venv\Scripts\activate # On Windows
# Upgrade pip and install dependencies
python3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt# Create conda environment
conda create -n can-ids python=3.11 -y
# Activate environment
conda activate can-ids
# Install dependencies from conda-forge
conda install -c conda-forge pandas matplotlib seaborn jupyter -ypython3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt# 1. Install Python dependencies
pip install -r requirements.txt
# 2. Run the safety controller with test alerts
python3 -c "
from code.safety_controller import SafetyController
# Create controller
controller = SafetyController()
# Process sample threats
alerts = [
{'alert': {'category': 'CAN Flood Detected'}, 'threat_score': 30},
{'alert': {'category': 'Anomaly Detection'}, 'threat_score': 25},
]
for alert in alerts:
controller.process_ids_alert(alert)
# View incident report
print(controller.generate_incident_report())
"
# 3. Run full test suite (17 tests)
python3 code/test_safety_controller.pyFor detailed setup, see QUICKSTART.md or IMPLEMENTATION_GUIDE.md.
Architecture: ARCHITECTURE.md
- System design with 5 vehicle modules
- 7 threat detection classes
- 5 safety maneuver sequences
- CAN message specifications
Implementation: IMPLEMENTATION_GUIDE.md
- Component integration
- 4 test scenarios with code examples
- Customization guide
- Incident reporting
Complete Specification: COMPLETE_IMPLEMENTATION.md
- Detailed threat criteria
- CAN message byte-level specs
- Safety constraints
- Real-world attack scenarios
python3 generate_pcap.pyOutput: Creates packets/can_sim.pcap with simulated CAN traffic including various attack vectors.
Execute Suricata to analyze the generated PCAP file:
# Clean previous logs and create fresh output directory
sudo rm -rf ~/Documents/MajorProject/suricata_logs && \
mkdir ~/Documents/MajorProject/suricata_logs
# Run Suricata analysis
sudo suricata -r ~/Documents/MajorProject/packets/can_sim.pcap \
-c ~/Documents/MajorProject/suricata.yaml \
-S ~/Documents/MajorProject/rules/can.rules \
-l ~/Documents/MajorProject/suricata_logs \
--runmode=single -vvParameters Explained:
-r: Read from PCAP file-c: Suricata configuration file-S: Custom rules file-l: Log output directory--runmode=single: Single-threaded mode for consistent results-vv: Verbose output for debugging
Expected Output:
suricata_logs/fast.log- Human-readable alert summarysuricata_logs/eve.json- JSON format detailed logs- Console output showing detected alerts
After running Suricata, check the generated logs:
# View fast.log (alert summary)
cat ~/Documents/MajorProject/suricata_logs/fast.log
# Count alerts by type
grep -o '\[.*\]' ~/Documents/MajorProject/suricata_logs/fast.log | sort | uniq -c-
Start Jupyter Notebook:
# If using virtual environment, make sure it's activated jupyter notebook -
Open the notebook:
- Navigate to
visualize_fastlog.ipynb - Run all cells sequentially (Cell β Run All)
- Navigate to
-
Interactive Analysis: The notebook provides:
- Alert frequency bar charts
- Timeline visualization of attacks
- Source vs Destination IP heatmaps
- Statistical summaries
If you prefer to run analysis without Jupyter:
python3 -c "
import pandas as pd
import re
from datetime import datetime
# Read and parse fast.log
with open('suricata_logs/fast.log', 'r') as f:
lines = [l.strip() for l in f if l.strip()]
pattern = re.compile(
r'(?P<timestamp>\d{2}/\d{2}/\d{4}-\d{2}:\d{2}:\d{2}\.\d+).*\[(?P<gid>\d+):(?P<sid>\d+):(?P<rev>\d+)\]\s+(?P<alert>.*?)\s+\[\*\*\]'
)
records = []
for line in lines:
match = pattern.search(line)
if match:
records.append(match.groupdict())
df = pd.DataFrame(records)
print('\nπ Alert Summary:')
print(df['alert'].value_counts())
print(f'\nπ’ Total Alerts: {len(df)}')
print(f'π‘ Unique Source IPs: {df[\"alert\"].nunique()}')
"The visualize_fastlog.ipynb notebook provides comprehensive visualizations:
- Bar chart showing count of each alert type
- Identifies most common attack vectors
- Chronological view of all detected alerts
- Helps identify attack patterns and timing
- Source IP vs Destination IP matrix
- Visualizes communication patterns
- Highlights suspicious connections
Parsed 78 alerts, skipped 0 lines.
π Summary of Alerts:
CAN Anomaly - ID 0x200 abnormal sequence 22
CAN Flood Detected - ID 0x100 pattern 21
CAN Diagnostic Flood - FF Payload 15
CAN Unknown ECU ID (>0x700) Detected 13
CAN Unauthorized Command - Control Frame 10
CAN DoS Suspicious - Zero Payload 4
Unique Source IPs: 5
Unique Destination IPs: 5
The safety system detects and responds to 7 threat classes:
| Class | Name | Examples | Threat Score | Response |
|---|---|---|---|---|
| 1 | CAN Flooding | Repeated ID patterns, high frequency | 15-40 | SLOW_DOWN |
| 2 | Anomalies | Abnormal sequences, unexpected data | 20-45 | SLOW_DOWN |
| 3 | Sensor Failure | Extreme values, missing data | 25-50 | STOP |
| 4 | Diagnostic Abuse | OBD-II floods, malicious probes | 30-55 | STOP |
| 5 | Unauthorized Cmd | Unknown ECUs, control anomalies | 35-60 | PULL_OVER |
| 6 | OBD Abuse | ECU parameter changes, memory access | 40-70 | EVASIVE |
| 7 | Unknown ECU | Unregistered IDs, spoofing | 45-75 | FULL_STOP |
Threats are scored 0-100 with intelligent aggregation:
- GREEN (0-25): No action, monitoring only
- YELLOW (26-50): SLOW_DOWN maneuver, reduce speed
- ORANGE (51-75): STOP maneuver, controlled stop
- RED (76-100): FULL_STOP maneuver, emergency stop
Scores decay over time as threats resolve (half-life: 30 seconds).
The system executes 5 graduated safety actions in response to threats:
| Maneuver | Trigger | Action | CAN Commands | Duration |
|---|---|---|---|---|
| SLOW_DOWN | Threat 26-50 | Reduce to 25 mph | Throttle -30%, Brake +20% | Until threat clears |
| STOP | Threat 51-75 | Controlled deceleration | Throttle OFF, Brake 2 m/sΒ² | Until stopped |
| PULL_OVER | Threat 76-85 | Pull to roadside | Steer Β±20Β°, Brake 3 m/sΒ² | Until stopped |
| EVASIVE | Threat 86-95 | Dodge obstacle | Steer Β±40Β°, Throttle +50% | 2-3 seconds |
| FULL_STOP | Threat 96-100 | Emergency stop | Brake 10 m/sΒ², Hazards ON | Until stopped |
Each maneuver includes:
- β CAN message generation for each vehicle module
- β Real-time feedback verification
- β Physical constraint enforcement
- β Watchdog timers for safety
- β Automated incident logging
Run the comprehensive test suite:
# Run all 17 tests
python3 code/test_safety_controller.py
# Run specific test class
python3 code/test_safety_controller.py TestVehicleControlModule
# Run with verbose output
python3 -v code/test_safety_controller.pyTest Coverage (17 tests):
- β Message parsing (3 tests)
- β Threat detection (6 tests)
- β Threat scoring (1 test)
- β State transitions (4 tests)
- β Maneuver execution (3 tests)
- β Suricata integration (2 tests)
Each CAN detection rule in rules/can.rules follows this structure:
alert udp any any -> any any (msg:"Alert Message";
content:"pattern"; sid:XXXXXX; rev:X; priority:3;)
| SID | Alert Type | Threat Class | Description |
|---|---|---|---|
| 1000001 | CAN Flood Detected | 1 | Repeated ID patterns |
| 1000002 | CAN Anomaly | 2 | Abnormal sequences |
| 1000003 | CAN DoS Suspicious | 3 | Zero payload attacks |
| 1000004 | CAN Diagnostic Flood | 4 | FF payload flooding |
| 1000005 | CAN Unauthorized Command | 5 | Control frame anomalies |
| 1000006 | CAN OBD Abuse | 6 | OBD-II parameter abuse |
| 1000007 | CAN Unknown ECU ID | 7 | ECU IDs greater than 0x700 |
| 1000008 | CAN Rapid Steering | 2 | Dangerous steering changes |
| 1000009 | CAN Conflicting Controls | 5 | Simultaneous conflicts |
| 1000010 | CAN Excessive Brake | 3 | Abnormal pressure values |
Edit rules/can.rules to add new detection patterns:
# Example: Detect specific CAN ID
alert udp any any -> any any (msg:"CAN Custom ID 0x300 Detected";
content:"|03 00|"; sid:1000010; rev:1; priority:2;)Error: Permission denied when accessing PCAP
Solution:
# Run with sudo
sudo suricata -r ...
# OR change file permissions
chmod 644 ~/Documents/MajorProject/packets/can_sim.pcapError: Failed building wheel for matplotlib
Solution for macOS:
# Install system dependencies
xcode-select --install
brew install pkg-config freetype libpng
# Retry installation
python3 -m pip install -r requirements.txtAlternative: Use conda/miniforge (see Installation section)
Error: suricata: command not found
Solution:
# macOS
brew install suricata
# Linux
sudo apt-get install suricata
# Verify
which suricataProblem: suricata_logs/fast.log is empty
Solutions:
- Check if PCAP file exists and has content
- Verify rules file path is correct
- Run Suricata with
-vvflag for verbose output - Check Suricata version compatibility
Error: Kernel errors or import failures
Solution:
# Reinstall kernel
python3 -m ipykernel install --user --name=can-ids
# Start Jupyter with specific kernel
jupyter notebook --kernel=can-idsRun Suricata with maximum verbosity for troubleshooting:
sudo suricata -r ~/Documents/MajorProject/packets/can_sim.pcap \
-c ~/Documents/MajorProject/suricata.yaml \
-S ~/Documents/MajorProject/rules/can.rules \
-l ~/Documents/MajorProject/suricata_logs \
--runmode=single -vvv --log-level=debugThis project includes comprehensive documentation for different audiences:
| Document | Purpose | Time | Best For |
|---|---|---|---|
| README_SAFETY_SYSTEM.md | High-level overview | 5-10 min | Understanding the system |
| QUICKSTART.md | Quick setup & reference | 5-15 min | Getting running fast |
| ARCHITECTURE.md | Complete system design | 20-30 min | Understanding design |
| IMPLEMENTATION_GUIDE.md | Step-by-step implementation | 20-30 min | Hands-on learning |
| COMPLETE_IMPLEMENTATION.md | Full technical spec | 45-60 min | Deep technical understanding |
| DELIVERY_SUMMARY.md | Project status & metrics | 15-20 min | Project overview |
| DOCUMENTATION_INDEX.md | Navigation guide | 5-10 min | Finding what you need |
π Start with: README_SAFETY_SYSTEM.md or QUICKSTART.md
Full documentation navigation: See DOCUMENTATION_INDEX.md
After completing all steps successfully, you should have:
β
Autonomous vehicle safety system protecting against 7 threat classes
β
Real-time threat detection with intelligent scoring (0-100)
β
Automated execution of 5 safety maneuvers via CAN commands
β
Incident reports with threat timelines
β
17 unit tests validating all safety mechanisms
β
Statistical analysis of attack patterns
- Safety System: README_SAFETY_SYSTEM.md - Overview of the autonomous vehicle protection system
- Quick Start: QUICKSTART.md - 5-minute setup and common tasks
- Architecture: ARCHITECTURE.md - Complete system design with 9 sections
- Implementation: IMPLEMENTATION_GUIDE.md - Step-by-step integration guide
- Full Spec: COMPLETE_IMPLEMENTATION.md - Comprehensive technical specification
- Suricata Documentation: Suricata Official Docs
- CAN Bus Protocol Overview: CAN Bus Wikipedia
- Writing Suricata Rules: Suricata Rules Guide
Feel free to enhance this project by:
- Adding new threat detection patterns
- Creating additional safety maneuvers
- Enhancing the threat scoring algorithm
- Expanding the test suite
- Improving visualization techniques
- Adding simulator integration (CARLA, LGSVL)
- Implementing machine learning anomaly detection
This project is for educational and research purposes.
| Metric | Value |
|---|---|
| Threat Classes | 7 |
| Safety Maneuvers | 5 |
| Detection Rules | 10 |
| Safety Constraints | 8 |
| Fail-Safe Mechanisms | 5 |
| Vehicle Control Modules | 5 |
| Threat Scoring Range | 0-100 |
| Unit Tests | 17 |
| Code Lines | 1,400+ |
| Documentation Lines | 1,950+ |
# 1. Install dependencies
pip install -r requirements.txt
# 2. Run test suite
python3 code/test_safety_controller.py
# 3. Try a quick example (see QUICKSTART.md)# 1. Generate traffic
python3 code/generate_pcap.py
# 2. Run Suricata
sudo suricata -r packets/can_sim.pcap \
-c suricata.yaml \
-S rules/can.rules \
-l suricata_logs \
--runmode=single -vv
# 3. Visualize
jupyter notebook code/visualize.ipynbPath 1: Executive Summary (15 minutes)
- README_SAFETY_SYSTEM.md (5 min)
- QUICKSTART.md overview (5 min)
- DELIVERY_SUMMARY.md (5 min)
Path 2: Technical Overview (1 hour)
- README_SAFETY_SYSTEM.md (5 min)
- QUICKSTART.md (10 min)
- ARCHITECTURE.md (30 min)
- COMPLETE_IMPLEMENTATION.md sections 1-2 (15 min)
Path 3: Full Implementation (2 hours)
- QUICKSTART.md (15 min)
- ARCHITECTURE.md (30 min)
- IMPLEMENTATION_GUIDE.md (30 min)
- Code review (30 min)
- Run tests (15 min)
π Welcome to the CAN Bus Autonomous Vehicle Safety System!
For detailed guidance, start with README_SAFETY_SYSTEM.md or QUICKSTART.md.
For documentation navigation, see DOCUMENTATION_INDEX.md.

