Skip to content

About

An **AI-driven smart intelligent cybersecurity system** built on **Zero Trust Architecture**, powered by 4 machine learning models for real-time threat detection, malicious PDF payload analysis, and automated policy enforcement.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

🛡️ CyberShield AI — Zero Trust Cybersecurity Platform

An AI-driven smart intelligent cybersecurity system built on Zero Trust Architecture, powered by 4 machine learning models for real-time threat detection, malicious PDF payload analysis, and automated policy enforcement.

Python FastAPI ML License


🏗️ System Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                        CyberShield AI Platform                         │
├─────────────┬──────────────┬──────────────┬──────────────┬─────────────┤
│  Phishing   │   Network    │    User      │     PDF      │  Zero Trust │
│  Detector   │   Anomaly    │  Behavior    │   Payload    │   Policy    │
│ (TF-IDF+LR) │ (Iso.Forest) │  (K-Means)  │ (Rand.Forest)│   Engine    │
├─────────────┴──────────────┴──────────────┴──────────────┤             │
│              Weighted Risk Scorer (0.28/0.28/0.22/0.22)  │ (Thresholds)│
├──────────────────────────────────────────────────────────┴─────────────┤
│                     FastAPI Backend + WebSocket                        │
├───────────────────────────────────────────────────────────────────────┤
│            Real-Time Dashboard (HTML/CSS/JS + Chart.js)               │
└───────────────────────────────────────────────────────────────────────┘

Data Flow

Raw Event → Feature Extraction → ML Model Prediction → Risk Score → Zero Trust Decision
                                                            ↓
                                              ALLOW / VERIFY / RESTRICT / DENY

📋 Features

Feature Technology Description
📧 Phishing Detection TF-IDF + Logistic Regression Classifies emails as phishing or legitimate using NLP
🌐 Network Anomaly Detection Isolation Forest Detects abnormal network traffic patterns (unsupervised)
👤 User Behavior Analytics K-Means Clustering Profiles users and identifies insider threats
📄 PDF Payload Detection Random Forest Classifier Detects malicious payloads embedded in PDF structure
🔒 Zero Trust Policy Engine Weighted Risk Scoring Automated ALLOW / VERIFY / RESTRICT / DENY decisions
📊 Real-Time Dashboard Chart.js + WebSocket Live threat monitoring with animated visualizations
🔄 Continuous Monitoring Async Background Tasks Simulates real-time event generation every 3-8 seconds
🧪 Interactive Scanners Frontend Forms Test email phishing and PDF payloads with live AI analysis

🚀 Quick Start

Prerequisites

  • Python 3.9 or higher
  • pip (Python package manager)

Step 1: Install Dependencies

cd cybersecurity-system/backend
pip install -r requirements.txt

Step 2: Run the System

cd cybersecurity-system/backend
python app.py

The system will automatically:

  1. ✅ Generate 4 synthetic datasets (~13,000 total samples)
  2. ✅ Train all 4 ML models
  3. ✅ Start the FastAPI server with CORS + static file serving
  4. ✅ Run initial threat analysis to populate dashboard data
  5. ✅ Begin continuous monitoring via background async tasks

Step 3: Open the Dashboard

Navigate to http://localhost:8000 in your browser.

API documentation is available at http://localhost:8000/docs


🧠 Machine Learning Models

1. Phishing Detection (TF-IDF + Logistic Regression)

  • Input: Email subject + body text
  • Features: TF-IDF vectorization (5,000 features), n-grams (1,2)
  • Training Data: 2,000 emails (balanced phishing/legitimate)
  • Output: Phishing probability, confidence score, risk level
  • Accuracy: ~95%

2. Network Anomaly Detection (Isolation Forest)

  • Input: Network traffic features (packet size, duration, flags, flow IAT)
  • Algorithm: Unsupervised anomaly detection (no labeled data required)
  • Training Data: 5,000 network flow records
  • Output: Anomaly score, threat level (NORMAL/SUSPICIOUS/MALICIOUS)
  • Accuracy: ~88%

3. User Behavior Analytics (K-Means Clustering)

  • Input: User activity features (login patterns, session duration, file access, failed attempts)
  • Algorithm: K-Means with 3 clusters (normal, suspicious, malicious)
  • Training Data: 3,000 user activity logs
  • Output: Behavioral profile, cluster assignment, risk score
  • Evaluation: Silhouette score ~0.3-0.5

4. PDF Payload Detection (Random Forest Classifier)

  • Input: 20 structural features extracted from PDF documents
  • Algorithm: Random Forest with 150 estimators, balanced class weights
  • Training Data: 3,000 PDFs (60% benign, 40% malicious across 5 attack types)
  • Output: Threat category, malicious probability, risk score, detailed indicator analysis
  • Accuracy: ~92%

PDF Feature Categories

Category Features Analyzed What They Detect
📄 File Metadata File size, pages, objects, streams Abnormal structure indicating hidden content
⚠️ Dangerous Indicators /JS tags, /OpenAction, /AA triggers, /Launch, /URI actions JavaScript injection, auto-execution, command launching, phishing URLs
📦 Embedding & Encoding Embedded files, encrypted streams, encoded filters, AcroForm, XFA Hidden executables, encrypted payloads, exploitable form types
🔒 Obfuscation Metrics Obfuscation score, entropy, metadata anomaly, suspicious names, JS code length, nesting depth Attempts to hide malicious content from scanners

PDF Threat Categories Detected

Category Description Example Attack
BENIGN Clean, safe PDF document Normal business document
JS_INJECTION Embedded malicious JavaScript Code executes when PDF is opened
ACTION_ABUSE Exploiting /OpenAction and /AA triggers Auto-executing actions without user consent
EMBEDDED_MALWARE Malicious files hidden in PDF streams Trojan or ransomware embedded as attachment
OBFUSCATION Heavily encoded content evading detection Multiple encoding layers hiding exploit code
LAUNCH_ATTACK /Launch action executing system commands Running system binaries from PDF viewer

🔒 Zero Trust Policy Engine

Principle

"Never Trust, Always Verify" — Every access request is evaluated independently, even from authenticated internal users.

Weighted Risk Scoring

All 4 model scores are combined using configurable weights:

Combined Score = (Phishing × 0.28) + (Network × 0.28) + (UBA × 0.22) + (PDF × 0.22)

Context Multipliers further adjust the score:

Context Factor Multiplier Description
Off-hours access ×1.20 Activity outside business hours
Unknown device ×1.30 New or unrecognized device
Unknown location ×1.25 Unusual geographic location
Weekend activity ×1.15 Weekend access patterns
Repeat offender ×1.40 Previous policy violations

Decision Thresholds

Risk Score Decision Automated Actions
< 0.3 ✅ ALLOW Log access, continue monitoring
0.3 – 0.6 ⚠️ VERIFY Require MFA, send verification email
0.6 – 0.8 🔶 RESTRICT Limit access scope, alert SOC team
≥ 0.8 🛑 DENY Block access, trigger incident response

🔌 API Endpoints

Method Endpoint Description
GET /api/dashboard/stats Dashboard statistics with all model metrics
GET /api/alerts Security alerts (filterable)
GET /api/events Monitoring events stream
POST /api/analyze/email Phishing analysis (subject, body, sender)
POST /api/analyze/network Network anomaly analysis
POST /api/analyze/user User behavior analysis
POST /api/analyze/pdf PDF malicious payload analysis
POST /api/policy/evaluate Full Zero Trust policy evaluation
GET /api/models/status ML model health and metrics
GET /api/threats/summary Threat distribution by type/level/decision
GET /api/timeline 24-hour event timeline for charts
GET /api/decisions/log Policy decision audit trail
POST /api/train Trigger model retraining
WS /ws Real-time WebSocket event stream

🖥️ Dashboard Sections

Section Description
Hero Stats 4 animated KPI cards — Threats Blocked, Events Analyzed, Active Alerts, System Health
Threat Activity Timeline 24-hour line chart showing threats detected vs events analyzed
Threat Distribution Doughnut chart breaking down threats by attack vector (6 categories)
Live Alert Feed Real-time event stream with severity indicators and risk scores
AI Model Performance 4 animated gauge rings showing accuracy for each ML model
Zero Trust Decision Log Tabular audit trail of all policy decisions with risk levels
Policy Decisions Doughnut chart showing ALLOW/VERIFY/RESTRICT/DENY distribution
Email Phishing Scanner Interactive form to test emails with live AI phishing analysis
PDF Payload Scanner Interactive form with 5 presets to test PDF payload detection

📁 Project Structure

cybersecurity-system/
├── README.md
├── backend/
│   ├── app.py                      # FastAPI main application (routes, WebSocket, startup)
│   ├── requirements.txt            # Python dependencies
│   ├── models/
│   │   ├── phishing_model.py       # TF-IDF + Logistic Regression phishing detector
│   │   ├── anomaly_model.py        # Isolation Forest network anomaly detector
│   │   ├── uba_model.py            # K-Means user behavior analyzer
│   │   └── pdf_payload_model.py    # Random Forest PDF payload detector
│   ├── engine/
│   │   ├── policy_engine.py        # Zero Trust policy engine (thresholds + alerts)
│   │   └── risk_scorer.py          # Weighted risk aggregation with context multipliers
│   ├── data/
│   │   ├── generate_data.py        # Synthetic data generator (4 datasets)
│   │   ├── preprocessor.py         # Data loading and preprocessing
│   │   └── datasets/               # Generated CSV files (auto-created)
│   └── saved_models/               # Trained model files (auto-created)
└── frontend/
    ├── index.html                  # Dashboard UI with sidebar navigation
    ├── css/
    │   └── style.css               # Premium dark theme with glassmorphism
    └── js/
        ├── app.js                  # Main app logic, particles, counters, scanners
        ├── charts.js               # Chart.js configurations and update helpers
        └── api.js                  # API communication layer + WebSocket client

🛠️ Tech Stack

Layer Technology
Backend Python 3.9+, FastAPI, Uvicorn
ML Engine scikit-learn (Logistic Regression, Isolation Forest, K-Means, Random Forest)
NLP TF-IDF Vectorizer, NLTK
Data Pandas, NumPy
Serialization Joblib (model persistence)
Frontend HTML5, CSS3 (Vanilla), JavaScript (ES6+)
Charts Chart.js 4.4
Fonts Google Fonts (Outfit, Inter, JetBrains Mono)
Real-Time WebSocket (native)
Design Glassmorphism, particle network animation, neon accent theme

📊 Datasets Generated

Dataset Samples Features File
Phishing Emails 2,000 12 phishing_emails.csv
Network Traffic Logs 5,000 15 network_logs.csv
User Activity Logs 3,000 13 user_activity.csv
PDF Payload Features 3,000 20 pdf_payloads.csv
Total 13,000

All datasets are synthetically generated on first run — no external data sources or API keys required.


🧪 Testing the Scanners

Email Phishing Scanner

Test a phishing email:

  • Subject: URGENT: Your account has been suspended! Verify now
  • Body: Click here to verify your identity: http://secure-verify.xyz/login
  • Sender: security@paypa1.com

Test a safe email:

  • Subject: Team Meeting Notes - Sprint 14
  • Body: Hi team, please find the meeting notes from today.
  • Sender: john.smith@company.com

PDF Payload Scanner

Use the Quick Scenario buttons to load preset attack configurations:

Preset Attack Type Expected Result
✅ Clean PDF None BENIGN, low risk
⚠️ JS Injection Embedded JavaScript MALICIOUS, high risk
🚀 Launch Attack System command execution MALICIOUS, critical risk
💀 Embedded Malware Hidden executables MALICIOUS, high risk
🔒 Obfuscated Multi-layer encoding MALICIOUS, high risk

📦 Dependencies

fastapi>=0.104.0
uvicorn>=0.24.0
scikit-learn>=1.3.0
pandas>=2.0.0
numpy>=1.24.0
joblib>=1.3.0
nltk>=3.8.0
python-multipart>=0.0.6

🔮 Future Enhancements

  • User authentication (JWT-based login)
  • Persistent database (SQLite/PostgreSQL) for audit trails
  • Transformer-based NLP models for advanced phishing detection
  • SHAP explainability for model predictions
  • Docker containerization for deployment
  • Automated model retraining pipeline
  • Real PDF file upload with binary parsing
  • SIEM integration for production environments

📝 License

This project is for educational and demonstration purposes.


Built with ❤️ using Python, FastAPI, scikit-learn, and modern web technologies.

About

An **AI-driven smart intelligent cybersecurity system** built on **Zero Trust Architecture**, powered by 4 machine learning models for real-time threat detection, malicious PDF payload analysis, and automated policy enforcement.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages