Initial commit

This commit is contained in:
2025-08-16 19:43:44 +02:00
commit ea9a2627b4
64 changed files with 9232 additions and 0 deletions

393
docs/DOCKER_DEPLOYMENT.md Normal file
View File

@@ -0,0 +1,393 @@
# Docker Deployment Guide
This guide covers deploying the Drone Detection System using Docker and Docker Compose.
## Prerequisites
- Docker Engine 20.10+
- Docker Compose 2.0+
- At least 4GB RAM
- 10GB available disk space
## Quick Start
### 1. Environment Setup
```bash
# Copy environment template
cp .env.docker .env
# Edit .env with your Twilio credentials
nano .env
```
### 2. Basic Deployment
```bash
# Build and start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Check service status
docker-compose ps
```
### 3. Access the Application
- **Frontend**: http://localhost:3000
- **Backend API**: http://localhost:3001/api
- **Database**: localhost:5432
- **Redis**: localhost:6379
## Service Architecture
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend │ │ Backend │ │ PostgreSQL │
│ (React) │◄──►│ (Node.js) │◄──►│ Database │
│ Port: 3000 │ │ Port: 3001 │ │ Port: 5432 │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
│ ┌─────────────────┐ │
└──────────────►│ Redis │◄────────────┘
│ (Caching) │
│ Port: 6379 │
└─────────────────┘
```
## Docker Compose Profiles
### Development Profile (Default)
```bash
docker-compose up -d
```
Includes: Frontend, Backend, Database, Redis
### Production Profile
```bash
docker-compose --profile production up -d
```
Includes: All services + Nginx reverse proxy
### Simulation Profile
```bash
docker-compose --profile simulation up -d
```
Includes: All services + Python drone simulator
## Service Details
### Frontend Container
- **Image**: Custom Nginx + React build
- **Port**: 3000:80
- **Features**:
- Gzip compression
- SPA routing support
- API proxying
- Security headers
### Backend Container
- **Image**: Node.js 18 Alpine
- **Port**: 3001:3001
- **Features**:
- Health checks
- Non-root user
- Log persistence
- Signal handling
### Database Container
- **Image**: PostgreSQL 15 Alpine
- **Port**: 5432:5432
- **Features**:
- Persistent storage
- Health checks
- Initialization scripts
- Performance tuning
### Redis Container
- **Image**: Redis 7 Alpine
- **Port**: 6379:6379
- **Features**:
- Persistent storage
- AOF logging
- Health checks
### Nginx Proxy (Production)
- **Image**: Nginx Alpine
- **Ports**: 80:80, 443:443
- **Features**:
- SSL termination
- Load balancing
- Static file serving
- WebSocket support
## Environment Variables
### Backend Environment
```bash
NODE_ENV=production
PORT=3001
DB_HOST=postgres
DB_PORT=5432
DB_NAME=drone_detection
DB_USER=postgres
DB_PASSWORD=postgres123
REDIS_HOST=redis
REDIS_PORT=6379
JWT_SECRET=your-jwt-secret
TWILIO_ACCOUNT_SID=your-twilio-sid
TWILIO_AUTH_TOKEN=your-twilio-token
TWILIO_PHONE_NUMBER=your-twilio-phone
CORS_ORIGIN=http://localhost:3000
```
### Frontend Build Arguments
```bash
VITE_API_URL=http://localhost:3001/api
VITE_WS_URL=ws://localhost:3001
```
## Data Persistence
### Volumes
- `postgres_data`: Database files
- `redis_data`: Redis persistence
- `./server/logs`: Application logs
### Backup Strategy
```bash
# Database backup
docker-compose exec postgres pg_dump -U postgres drone_detection > backup.sql
# Restore database
docker-compose exec -T postgres psql -U postgres drone_detection < backup.sql
# Volume backup
docker run --rm -v uamils_postgres_data:/data -v $(pwd):/backup alpine tar czf /backup/postgres_backup.tar.gz /data
```
## Monitoring and Logs
### View Logs
```bash
# All services
docker-compose logs -f
# Specific service
docker-compose logs -f backend
# Last 100 lines
docker-compose logs --tail=100 backend
```
### Health Checks
```bash
# Check service health
docker-compose ps
# Manual health check
curl http://localhost:3001/api/health
curl http://localhost:3000/health
```
### Resource Monitoring
```bash
# Container stats
docker stats
# Detailed container info
docker-compose exec backend top
```
## Troubleshooting
### Common Issues
#### 1. Database Connection Issues
```bash
# Check database status
docker-compose exec postgres pg_isready -U postgres
# View database logs
docker-compose logs postgres
# Reset database
docker-compose down -v
docker-compose up -d
```
#### 2. Frontend Build Issues
```bash
# Rebuild frontend
docker-compose build --no-cache frontend
# Check build logs
docker-compose logs frontend
```
#### 3. Backend API Issues
```bash
# Check backend health
curl http://localhost:3001/api/health/detailed
# View backend logs
docker-compose logs backend
# Restart backend
docker-compose restart backend
```
#### 4. Port Conflicts
```bash
# Check port usage
netstat -tulpn | grep :3000
netstat -tulpn | grep :3001
# Stop conflicting services
docker-compose down
```
### Performance Tuning
#### 1. Database Optimization
```bash
# Increase shared_buffers for PostgreSQL
docker-compose exec postgres psql -U postgres -c "ALTER SYSTEM SET shared_buffers = '256MB';"
docker-compose restart postgres
```
#### 2. Memory Limits
```yaml
# Add to docker-compose.yml services
services:
backend:
mem_limit: 512m
mem_reservation: 256m
frontend:
mem_limit: 256m
mem_reservation: 128m
```
## Production Deployment
### 1. SSL Configuration
```bash
# Generate SSL certificates
mkdir -p docker/ssl
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout docker/ssl/nginx.key \
-out docker/ssl/nginx.crt
```
### 2. Environment Security
```bash
# Use Docker secrets for sensitive data
echo "your-jwt-secret" | docker secret create jwt_secret -
echo "your-twilio-token" | docker secret create twilio_token -
```
### 3. Nginx Configuration
```bash
# Enable production profile
docker-compose --profile production up -d
# Update nginx config for your domain
# Edit docker/nginx/default.conf
```
### 4. Monitoring Setup
```bash
# Add monitoring services
docker-compose -f docker-compose.yml -f docker-compose.monitoring.yml up -d
```
## Scaling
### Horizontal Scaling
```yaml
# Scale backend instances
docker-compose up -d --scale backend=3
# Load balancer configuration required
```
### Database Scaling
```yaml
# Add read replicas
postgres-replica:
image: postgres:15-alpine
environment:
POSTGRES_MASTER_SERVICE: postgres
POSTGRES_REPLICA_USER: replica
POSTGRES_REPLICA_PASSWORD: replica123
```
## Maintenance
### Updates
```bash
# Update images
docker-compose pull
# Rebuild and restart
docker-compose down
docker-compose up -d --build
```
### Cleanup
```bash
# Remove unused containers
docker system prune
# Remove unused volumes
docker volume prune
# Clean build cache
docker builder prune
```
## Testing with Simulator
### Run Simulation
```bash
# Start simulation profile
docker-compose --profile simulation up -d
# Run custom simulation
docker-compose run --rm simulator python drone_simulator.py \
--devices 10 \
--duration 3600 \
--detection-interval 30
```
### Monitor Simulation
```bash
# View simulator logs
docker-compose logs -f simulator
# Check API stats
curl http://localhost:3001/api/dashboard/stats
```
## Security Considerations
### Container Security
- Non-root users in all containers
- Read-only root filesystems where possible
- Limited container capabilities
- Security scanning with `docker scan`
### Network Security
- Custom bridge network isolation
- No unnecessary port exposures
- Internal service communication
### Data Security
- Encrypted environment variables
- SSL/TLS termination at proxy
- Database connection encryption
- Regular security updates
For additional security hardening, see [Security Best Practices](../docs/SECURITY.md).

View File

@@ -0,0 +1,141 @@
# Enhanced Drone Detection System - Threat Assessment Summary
## 🚨 Security Enhancements for Government Sites
Your drone detection system has been significantly enhanced with intelligent threat assessment capabilities specifically designed for Swedish government sites, water facilities, nuclear plants, and other sensitive installations.
## 🎯 Key Security Features Added
### 1. **RSSI-Based Threat Classification**
- **Critical Threats** (0-50m): Immediate security response
- **High Threats** (50-200m): Security response recommended
- **Medium Threats** (200m-1km): Enhanced monitoring
- **Low Threats** (1-5km): Standard monitoring
- **Monitoring** (5-15km): Passive surveillance
### 2. **Intelligent Distance Calculation**
- Real-time distance estimation using RSSI signal strength
- Path loss calculations adapted for outdoor security environments
- Accurate threat zone determination for perimeter security
### 3. **Enhanced Alert System**
- **Critical threats automatically trigger all alert channels**
- Threat-specific alert messages with security descriptions
- Immediate action notifications for high-priority threats
- Bypasses cooldown periods for critical security situations
### 4. **Swedish Location Integration**
Pre-configured monitoring for sensitive Swedish facilities:
- Government offices and Riksdag
- Water treatment facilities (Norsborg, Lovö, etc.)
- Nuclear power plants (Forsmark, Ringhals, Oskarshamn)
- Military installations (Karlsborg, Boden, etc.)
- Major airports (Arlanda, Landvetter, etc.)
## 🐍 Python Simulation Script
### Comprehensive Testing Tool
The `drone_simulator.py` script provides realistic testing with:
- **Swedish coordinates** for actual sensitive locations
- **Threat-based scenarios** with realistic probability distributions
- **RSSI calculations** based on actual physics formulas
- **Continuous device monitoring** with heartbeat simulation
- **Multiple facility types** (government, water, nuclear, military)
### Usage Examples
```bash
# Basic simulation with 5 devices
python drone_simulator.py
# Extended simulation for stress testing
python drone_simulator.py --devices 15 --duration 7200 --detection-interval 30
# List all available Swedish monitoring locations
python drone_simulator.py --list-locations
```
## 📊 Threat Statistics
The simulator generates realistic threat distributions:
- **70%** - Low threats (5-15km range)
- **20%** - Medium threats (200m-5km range)
- **8%** - High threats (50-200m range)
- **2%** - Critical threats (0-50m range)
## 🔧 Implementation Details
### Database Schema Updates
- Added `threat_level` field to drone detections
- Added `estimated_distance` for distance tracking
- Added `requires_action` flag for security protocols
### API Enhancements
- Real-time threat assessment processing
- Enhanced alert message generation
- Threat-based filtering and alerting
### Frontend Integration
- Threat level indicators on maps and dashboards
- Color-coded threat visualization
- Enhanced alert rule configuration
## 📋 Recommended Configuration
### For Government Sites
```javascript
{
"min_threat_level": "high",
"max_distance": 200,
"cooldown_minutes": 2,
"channels": ["sms", "email", "webhook"]
}
```
### For Water Facilities
```javascript
{
"min_threat_level": "medium",
"max_distance": 500,
"cooldown_minutes": 10,
"channels": ["sms"]
}
```
### For Nuclear Facilities
```javascript
{
"min_threat_level": "medium",
"max_distance": 1000,
"cooldown_minutes": 0,
"channels": ["sms", "email", "webhook"],
"force_critical_alerts": true
}
```
## 🚀 Deployment Recommendations
1. **Test with Simulator**: Use the Python script to generate realistic test data
2. **Configure Threat Thresholds**: Set appropriate threat levels for each facility type
3. **Set Up Alert Channels**: Configure SMS, email, and webhook notifications
4. **Train Security Personnel**: Ensure staff understand threat levels and response protocols
5. **Monitor and Adjust**: Fine-tune threat thresholds based on real-world usage
## 📞 Emergency Response Integration
The system now supports:
- **Immediate escalation** for critical threats
- **Security protocol activation** based on threat levels
- **Multi-channel alerting** for redundancy
- **Real-time threat tracking** with distance monitoring
## 🔒 Security Compliance
Features designed for:
- **Government security standards**
- **Critical infrastructure protection**
- **Perimeter security monitoring**
- **Incident response protocols**
- **Audit and compliance logging**
This enhanced system provides enterprise-grade security monitoring specifically tailored for Swedish sensitive installations, with realistic testing capabilities and intelligent threat assessment.

209
docs/THREAT_ASSESSMENT.md Normal file
View File

@@ -0,0 +1,209 @@
# Threat Assessment and Security Features
## RSSI-Based Threat Classification
The drone detection system now includes intelligent threat assessment based on signal strength (RSSI) and drone type classification. This is specifically designed for government sites, water facilities, nuclear plants, and other sensitive Swedish installations.
### Threat Levels
The system automatically classifies detections into 5 threat levels:
#### 🔴 CRITICAL THREAT (RSSI ≥ -40 dBm)
- **Distance**: 0-50 meters from device
- **Action**: Immediate security response required
- **Description**: Drone within security perimeter
- **Alerts**: All available channels (SMS, email, webhook)
#### 🟠 HIGH THREAT (RSSI -55 to -40 dBm)
- **Distance**: 50-200 meters from device
- **Action**: Security response recommended
- **Description**: Drone approaching facility
- **Alerts**: SMS and email notifications
#### 🟡 MEDIUM THREAT (RSSI -70 to -55 dBm)
- **Distance**: 200m-1km from device
- **Action**: Enhanced monitoring
- **Description**: Drone in facility vicinity
- **Alerts**: SMS notifications (configurable)
#### 🟢 LOW THREAT (RSSI -85 to -70 dBm)
- **Distance**: 1-5 kilometers from device
- **Action**: Standard monitoring
- **Description**: Drone detected at distance
- **Alerts**: Log only (configurable)
#### ⚪ MONITORING (RSSI < -85 dBm)
- **Distance**: 5-15 kilometers from device
- **Action**: Passive monitoring
- **Description**: Long-range detection
- **Alerts**: Log only
### Drone Type Classification
Threat levels are adjusted based on drone type:
- **Type 0 (Consumer/Hobby)**: Standard threat assessment
- **Type 1 (Professional/Military)**: Escalated threat level
- **Type 2 (Racing/High-speed)**: Escalated if within close range
- **Type 3 (Unknown/Custom)**: Standard threat assessment
### Distance Calculation
The system estimates drone distance using RSSI with the formula:
```
Distance (m) = 10^((RSSI_at_1m - RSSI) / (10 * path_loss_exponent))
```
Where:
- `RSSI_at_1m = -30 dBm` (typical RSSI at 1 meter)
- `path_loss_exponent = 3` (outdoor environment with obstacles)
## Alert Rule Configuration
### Enhanced Alert Conditions
Alert rules now support advanced threat-based conditions:
```javascript
{
"conditions": {
"min_threat_level": "high", // Minimum threat level to trigger
"rssi_threshold": -55, // Minimum RSSI value
"max_distance": 200, // Maximum distance in meters
"drone_types": [0, 1, 2], // Allowed drone types
"device_ids": [1941875381] // Specific devices to monitor
},
"actions": {
"sms": true,
"phone_number": "+46701234567",
"email": true,
"channels": ["sms", "email"] // Alert channels
},
"cooldown_minutes": 5 // Cooldown between alerts
}
```
### Security Features for Sensitive Sites
#### Automatic Critical Threat Handling
- Critical threats (RSSI ≥ -40 dBm) automatically trigger all available alert channels
- Bypasses normal cooldown periods for immediate notification
- Includes estimated distance and threat description in alerts
#### Swedish Government Site Integration
The system is pre-configured with coordinates for:
- Government offices and Riksdag
- Water treatment facilities
- Nuclear power plants
- Military installations
- Major airports
## Python Simulation Script
### Swedish Drone Detection Simulator
The included `drone_simulator.py` script generates realistic drone detection data with Swedish coordinates:
```bash
# Install dependencies
pip install -r requirements.txt
# Run basic simulation
python drone_simulator.py
# Custom simulation parameters
python drone_simulator.py --devices 10 --detection-interval 30 --duration 7200
# List available Swedish locations
python drone_simulator.py --list-locations
```
### Simulation Features
- **Realistic RSSI Calculation**: Based on actual distance and path loss
- **Threat-Based Scenarios**: Different probability weights for each threat level
- **Swedish Coordinates**: Real coordinates for sensitive facilities
- **Multiple Device Types**: Government, water, nuclear, military, airport sites
- **Continuous Heartbeats**: Device health monitoring
- **Battery Simulation**: Realistic battery drain and status changes
### Threat Scenario Probabilities
- **Low Threat**: 70% (5-15km range, RSSI -90 to -70 dBm)
- **Medium Threat**: 20% (200m-5km range, RSSI -70 to -55 dBm)
- **High Threat**: 8% (50-200m range, RSSI -55 to -40 dBm)
- **Critical Threat**: 2% (0-50m range, RSSI -40 to -25 dBm)
## API Enhancements
### Detection Response Format
The API now returns threat assessment data:
```json
{
"id": "uuid",
"device_id": 1941875381,
"drone_id": 1001,
"rssi": -45,
"threat_level": "high",
"estimated_distance": 150,
"requires_action": true,
"geo_lat": 59.3293,
"geo_lon": 18.0686,
"timestamp": "2025-08-16T10:30:00Z"
}
```
### Enhanced Alert Messages
SMS alerts now include comprehensive threat information:
```
🚨 SECURITY ALERT 🚨
THREAT LEVEL: HIGH
HIGH THREAT: Drone approaching facility (50-200m)
📍 LOCATION: Riksdag Stockholm
🔧 DEVICE: SecureGuard-001
📏 DISTANCE: ~150m
📶 SIGNAL: -45 dBm
🚁 DRONE TYPE: Professional/Military
⏰ TIME: 2025-08-16 10:30:00
⚠️ IMMEDIATE ACTION REQUIRED
Security personnel should respond immediately.
```
## Database Schema Updates
New fields added to `DroneDetection` model:
- `threat_level`: ENUM('monitoring', 'low', 'medium', 'high', 'critical')
- `estimated_distance`: INTEGER (meters)
- `requires_action`: BOOLEAN
## Security Recommendations
### For Government Sites
- Set `min_threat_level` to "high" for critical facilities
- Use multiple alert channels for redundancy
- Configure short cooldown periods (2-5 minutes)
- Monitor all drone types including consumer drones
### For Water Facilities
- Set `min_threat_level` to "medium" for early warning
- Focus on perimeter monitoring (max_distance: 500m)
- Longer cooldown periods acceptable (10-15 minutes)
### For Nuclear Facilities
- Set `min_threat_level` to "medium" with escalation to "critical"
- Immediate response required for high/critical threats
- No cooldown for critical threats
- Monitor professional/military drone types with high priority
### For Military Installations
- Maximum security configuration
- All threat levels trigger alerts
- Multiple redundant alert channels
- Real-time monitoring and response protocols