Skip to content

Latest commit

Β 

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Network Security - Phishing Detection System

Network Security Python Status

An automated ML-Ops pipeline for detecting phishing URLs using machine learning

Overview β€’ Architecture β€’ Features β€’ Installation β€’ Usage


πŸ“‹ Table of Contents


πŸ“Œ Project Overview

Network Security is an end-to-end machine learning operations (MLOps) pipeline designed to classify and detect phishing URLs in web traffic. The system automates the entire workflow from data ingestion to model deployment, enabling organizations to identify malicious URLs and protect users from phishing attacks.

Key Capabilities:

  • Automated ML Pipeline: Orchestrated data processing, validation, and model training
  • Real-time Prediction: REST API for predicting whether a URL is phishing or legitimate
  • Model Monitoring: Integration with MLflow and DagsHub for experiment tracking and model versioning
  • Cloud Integration: AWS S3 support for model artifact storage and synchronization
  • Production-Ready: Containerized with Docker for seamless deployment

🎯 Why This Project?

The Problem:

Phishing attacks are one of the most prevalent cybersecurity threats, causing billions of dollars in damage annually. Attackers use:

  • Fake domain registrations
  • SSL certificate manipulation
  • URL obfuscation techniques
  • DOM-based attacks

Traditional rule-based systems struggle to keep pace with evolving attack patterns.

The Solution:

This project implements a data-driven machine learning approach to:

  1. Learn patterns from a dataset of 31 phishing indicators
  2. Generalize to new, unseen URLs using ensemble methods
  3. Scale through automated pipeline orchestration
  4. Monitor model performance with built-in MLOps infrastructure
  5. Deploy with confidence using containerization and cloud storage

πŸ”§ How It Works

End-to-End Workflow:

Raw Data (MongoDB)
    ↓
[Data Ingestion] β†’ Split into Train/Test
    ↓
[Data Validation] β†’ Check schema, detect drift
    ↓
[Data Transformation] β†’ Encode, scale, impute missing values
    ↓
[Model Training] β†’ Train ensemble models, select best
    ↓
[Model Evaluation] β†’ Track metrics with MLflow
    ↓
[Model Deployment] β†’ Save to final_model/
    ↓
REST API
    ↓
Predictions on New URLs

Phishing Detection Features (31 indicators):

The model analyzes these URL characteristics:

Domain Features:

  • having_IP_Address - Uses IP instead of domain name
  • URL_Length - Suspicious if overly long
  • Prefix_Suffix - Contains hyphen in domain
  • having_Sub_Domain - Multiple subdomains present
  • SSLfinal_State - SSL certificate status
  • Domain_registeration_length - Domain age
  • DNSRecord - DNS record presence

URL Structure:

  • having_At_Symbol - @ symbol used to obfuscate domain
  • Shortining_Service - URL shortening service used
  • double_slash_redirecting - Double slash for redirection
  • Abnormal_URL - Non-standard URL format
  • Redirect - URL redirect behavior

Web Content Features:

  • Favicon - Custom favicon presence
  • port - Non-standard port used
  • HTTPS_token - Inconsistent HTTPS usage
  • Request_URL - Requests from different domain
  • URL_of_Anchor - Anchor links to different domain
  • Links_in_tags - External links in meta tags
  • SFH (Server Form Handler) - Form submission endpoint
  • Submitting_to_email - Mail link in form
  • on_mouseover - Mouseover event handlers
  • RightClick - Right-click disabled
  • popUpWidnow - Popup windows used
  • Iframe - Iframes embedded

Reputation Features:

  • web_traffic - Traffic statistics
  • Page_Rank - Google PageRank score
  • Google_Index - Google indexing status
  • Links_pointing_to_page - Backlink count
  • age_of_domain - Domain registration age
  • Statistical_report - Statistical phishing reports

Target:

  • Result - Classification (Legitimate: 1, Phishing: -1)

πŸ—οΈ Architecture & Components

Component Overview:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          NetworkSecurity Package (ML Pipeline)      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   1. Data Ingestion Component                β”‚   β”‚
β”‚  β”‚   ─ MongoDB β†’ Pandas DataFrame               β”‚   β”‚
β”‚  β”‚   ─ Train/Test split (80/20)                 β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                     ↓                                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   2. Data Validation Component               β”‚   β”‚
β”‚  β”‚   ─ Schema validation (YAML)                 β”‚   β”‚
β”‚  β”‚   ─ Data drift detection                     β”‚   β”‚
β”‚  β”‚   ─ Separate valid/invalid data              β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                     ↓                                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   3. Data Transformation Component           β”‚   β”‚
β”‚  β”‚   ─ Handle missing values (KNN Imputation)   β”‚   β”‚
β”‚  β”‚   ─ Feature encoding & scaling               β”‚   β”‚
β”‚  β”‚   ─ Save preprocessing object                β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                     ↓                                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   4. Model Training Component                β”‚   β”‚
β”‚  β”‚   ─ Train multiple algorithms:               β”‚   β”‚
β”‚  β”‚     β€’ Logistic Regression                    β”‚   β”‚
β”‚  β”‚     β€’ Random Forest                          β”‚   β”‚
β”‚  β”‚     β€’ Gradient Boosting                      β”‚   β”‚
β”‚  β”‚     β€’ Decision Tree                          β”‚   β”‚
β”‚  β”‚     β€’ AdaBoost                               β”‚   β”‚
β”‚  β”‚   ─ Hyperparameter tuning                    β”‚   β”‚
β”‚  β”‚   ─ Model evaluation & selection             β”‚   β”‚
β”‚  β”‚   ─ MLflow tracking                          β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                     ↓                                β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   5. Model Estimator                         β”‚   β”‚
β”‚  β”‚   ─ Combines preprocessor + trained model    β”‚   β”‚
β”‚  β”‚   ─ Handles prediction pipeline              β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   6. Cloud Integration (S3)                  β”‚   β”‚
β”‚  β”‚   ─ Sync models to AWS S3                    β”‚   β”‚
β”‚  β”‚   ─ Versioning & backup                      β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚   7. Logging & Exception Handling            β”‚   β”‚
β”‚  β”‚   ─ Custom exception class                   β”‚   β”‚
β”‚  β”‚   ─ Logger instance                          β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                         ↓
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚   FastAPI REST Application   β”‚
          β”‚   ─ Training endpoint        β”‚
          β”‚   ─ Prediction endpoint      β”‚
          β”‚   ─ CORS middleware support  β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Core Modules:

Module Path Purpose
Data Ingestion components/data_ingestion.py Fetch data from MongoDB, perform train-test split
Data Validation components/data_validation.py Validate schema, detect data drift
Data Transformation components/data_transformation.py Handle missing values, scale features
Model Training components/model_trainer.py Train & evaluate multiple ML algorithms
Estimator utils/ml_utils/model/estimator.py Production model wrapper
Classification Metrics utils/ml_utils/metric/classification_metric.py Compute F1, Precision, Recall
Utilities utils/main_utils/utils.py Helper functions (save/load objects)
Training Pipeline pipeline/training_pipeline.py Orchestrate full pipeline
Batch Prediction pipeline/batch_prediction.py Batch prediction on datasets
Config Entity entity/config_entity.py Configuration classes
Artifact Entity entity/artifact_entity.py Artifact classes for component outputs
Exception Handling exceptionHandling/exception.py Custom exception class
Logger logging/logger.py Logging utility

πŸš€ Build Flow & Pipeline

Execution Steps:

Step 1: Data Ingestion

# Retrieve phishing data from MongoDB
# Input: MongoDB connection URL, database name, collection name
# Process:
#   - Connect to MongoDB
#   - Load collection as Pandas DataFrame
#   - Remove MongoDB _id field
#   - Replace "na" strings with NaN
#   - Split into train (80%) and test (20%)
# Output: DataIngestionArtifact
#   - train.csv β†’ artifacts/data_ingestion/ingested/
#   - test.csv β†’ artifacts/data_ingestion/ingested/
#   - Full data β†’ artifacts/data_ingestion/feature_store/

Step 2: Data Validation

# Validate data against schema and detect drift
# Input: DataIngestionArtifact, schema.yaml
# Process:
#   - Load schema from data_schema/schema.yaml
#   - Validate column names and data types
#   - Check for missing values
#   - Detect data drift using statistical tests
#   - Separate valid and invalid records
# Output: DataValidationArtifact
#   - valid data β†’ artifacts/data_validation/validated/
#   - invalid data β†’ artifacts/data_validation/invalid/
#   - drift report β†’ artifacts/data_validation/drift_report/report.yaml

Step 3: Data Transformation

# Transform and preprocess data
# Input: DataValidationArtifact
# Process:
#   - Separate features (X) and target (y)
#   - Handle missing values using KNN Imputer
#   - Encode categorical variables (if any)
#   - Scale numerical features using StandardScaler
#   - Save preprocessing pipeline as .pkl
# Output: DataTransformationArtifact
#   - transformed_train β†’ .npy (NumPy array)
#   - transformed_test β†’ .npy (NumPy array)
#   - preprocessor.pkl β†’ artifacts/data_transformation/transformed_object/

Step 4: Model Training

# Train and evaluate multiple ML algorithms
# Input: DataTransformationArtifact
# Process:
#   - Load transformed training data
#   - Train 5 algorithms:
#     β€’ LogisticRegression(max_iter=1000)
#     β€’ RandomForestClassifier(verbose=1)
#     β€’ GradientBoostingClassifier(verbose=1)
#     β€’ DecisionTreeClassifier()
#     β€’ AdaBoostClassifier()
#   - Perform hyperparameter tuning (GridSearchCV)
#   - Evaluate on test set
#   - Log metrics to MLflow (F1, Precision, Recall)
#   - Select best model based on F1-score
# Output: ModelTrainerArtifact
#   - model.pkl β†’ artifacts/model_trainer/trained_model/
#   - Metrics logged to DagsHub/MLflow

Step 5: Model Deployment

# Save model to production location
# Input: ModelTrainerArtifact
# Process:
#   - Copy trained model to final_model/model.pkl
#   - Copy preprocessor to final_model/preprocessor.pkl
#   - Sync artifacts to AWS S3 (optional)
# Output: Production-ready models in final_model/

Pipeline Execution Diagram:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  Training Pipeline Flow                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

START
  β”‚
  β”œβ”€β†’ Initialize TrainingPipelineConfig
  β”‚     └─ Set artifact directory with timestamp
  β”‚
  β”œβ”€β†’ start_data_ingestion()
  β”‚     β”œβ”€ Load phisingData.csv from MongoDB
  β”‚     β”œβ”€ Split into train (80%) & test (20%)
  β”‚     └─ Save β†’ artifacts/data_ingestion/ingested/
  β”‚
  β”œβ”€β†’ start_data_validation()
  β”‚     β”œβ”€ Validate schema against schema.yaml
  β”‚     β”œβ”€ Check data types and columns
  β”‚     β”œβ”€ Detect drift
  β”‚     └─ Save β†’ artifacts/data_validation/validated/
  β”‚
  β”œβ”€β†’ start_data_transformation()
  β”‚     β”œβ”€ Impute missing values (KNN)
  β”‚     β”œβ”€ Scale features (StandardScaler)
  β”‚     └─ Save β†’ artifacts/data_transformation/transformed/
  β”‚
  β”œβ”€β†’ start_model_trainer()
  β”‚     β”œβ”€ Load transformed data
  β”‚     β”œβ”€ Train 5 algorithms
  β”‚     β”œβ”€ Evaluate models
  β”‚     β”œβ”€ Log to MLflow
  β”‚     └─ Save best model β†’ artifacts/model_trainer/trained_model/
  β”‚
  β”œβ”€β†’ start_model_pusher()
  β”‚     β”œβ”€ Copy model to final_model/model.pkl
  β”‚     β”œβ”€ Copy preprocessor to final_model/preprocessor.pkl
  β”‚     └─ Sync to S3 (optional)
  β”‚
  └─→ END (Success/Failure notification)

πŸ—ΊοΈ Component Map

πŸ“¦ networkSecurity/
β”‚
β”œβ”€β”€ πŸ“‚ components/              # Core ML pipeline components
β”‚   β”œβ”€β”€ data_ingestion.py       # Fetch & split data
β”‚   β”œβ”€β”€ data_validation.py      # Validate schema & detect drift
β”‚   β”œβ”€β”€ data_transformation.py  # Impute, encode, scale features
β”‚   └── model_trainer.py        # Train & evaluate models
β”‚
β”œβ”€β”€ πŸ“‚ pipeline/                # High-level orchestration
β”‚   β”œβ”€β”€ training_pipeline.py    # Main pipeline orchestrator
β”‚   └── batch_prediction.py     # Batch prediction interface
β”‚
β”œβ”€β”€ πŸ“‚ entity/                  # Configuration & artifact classes
β”‚   β”œβ”€β”€ config_entity.py        # Config classes for each component
β”‚   └── artifact_entity.py      # Artifact classes for outputs
β”‚
β”œβ”€β”€ πŸ“‚ utils/                   # Utility functions
β”‚   β”œβ”€β”€ πŸ“‚ main_utils/
β”‚   β”‚   └── utils.py            # Save/load objects, evaluate models
β”‚   └── πŸ“‚ ml_utils/
β”‚       β”œβ”€β”€ πŸ“‚ model/
β”‚       β”‚   └── estimator.py    # Production model wrapper
β”‚       └── πŸ“‚ metric/
β”‚           └── classification_metric.py  # F1, Precision, Recall
β”‚
β”œβ”€β”€ πŸ“‚ cloud/                   # Cloud integration
β”‚   └── s3_syncer.py            # AWS S3 sync utility
β”‚
β”œβ”€β”€ πŸ“‚ constant/                # Constants & configuration
β”‚   └── πŸ“‚ training_pipeline/
β”‚       └── __init__.py         # Pipeline constants
β”‚
β”œβ”€β”€ πŸ“‚ exceptionHandling/       # Custom exceptions
β”‚   └── exception.py
β”‚
β”œβ”€β”€ πŸ“‚ logging/                 # Logging utility
β”‚   └── logger.py
β”‚
└── πŸ“‚ __init__.py

πŸ› οΈ Tech Stack

Category Technology Purpose
Language Python 3.8+ Core programming language
ML/Data scikit-learn Training algorithms, preprocessing
pandas Data manipulation
NumPy Numerical computing
Database MongoDB Data storage (with MongoDB Atlas)
API FastAPI REST API framework
Uvicorn ASGI web server
Starlette Web framework (FastAPI dependency)
MLOps MLflow Experiment tracking & model registry
DagsHub ML collaboration platform
Cloud AWS S3 Model artifact storage
Containerization Docker Production deployment
Utilities python-dotenv Environment variable management
PyYAML Schema configuration
dill Object serialization
certifi SSL certificate verification

πŸ“‹ Prerequisites

System Requirements:

  • Python 3.8 or higher
  • pip or conda package manager
  • Docker (for containerized deployment)
  • Git (for version control)

External Services (Required):

  1. MongoDB Atlas Account

  2. AWS Account (Optional, for S3 integration)

    • AWS Access Key ID
    • AWS Secret Access Key
    • S3 bucket for model storage
  3. DagsHub Account (Optional, for MLOps)

    • DagsHub MLflow remote URI
    • Repository credentials

Environment Variables:

Create a .env file in the project root:

MONGODB_URL_KEY=mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority

# Optional: AWS S3 credentials
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_BUCKET_NAME=your_bucket_name

# Optional: DagsHub credentials
DAGSHUB_REPO_OWNER=your_username
DAGSHUB_REPO_NAME=your_repo_name

πŸ“¦ Installation & Setup

1. Clone the Repository:

git clone https://github.com/realadityagupta/NIDS_with_Automated_MLOPS_pipeline.git
cd networksecurity

2. Create Virtual Environment:

# Using venv
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Using conda
conda create -n networksecurity python=3.8
conda activate networksecurity

3. Install Dependencies:

pip install -r requirements.txt

# Or install in development mode:
pip install -e .

4. Set Up Environment:

# Create .env file with MongoDB connection
echo "MONGODB_URL_KEY=your_mongodb_uri" > .env

5. Prepare Data:

# Ensure phisingData.csv is in Network_Data/ directory
# Or configure MongoDB connection with phishing dataset

🎯 Usage

Option 1: Run Training Pipeline (main.py)

python main.py

This executes the full ML pipeline:

  • Data ingestion β†’ Validation β†’ Transformation β†’ Model Training

Option 2: Run via FastAPI Web Application (app.py)

Start the server:

python app.py
# or
uvicorn app:app --reload --host 0.0.0.0 --port 8000

Access the API:

Training Endpoint:

curl -X GET "http://localhost:8000/train"

Prediction Endpoint:

# Upload CSV file for batch prediction
curl -X POST "http://localhost:8000/predict" \
  -F "file=@test.csv"

Option 3: Docker Deployment

# Build Docker image
docker build -t networksecurity:latest .

# Run container
docker run -p 8000:8000 \
  -e MONGODB_URL_KEY="your_mongodb_uri" \
  networksecurity:latest

Example Prediction:

from networkSecurity.utils.main_utils.utils import load_object
from networkSecurity.utils.ml_utils.model.estimator import NetworkModel
import pandas as pd

# Load trained model and preprocessor
preprocessor = load_object("final_model/preprocessor.pkl")
model = load_object("final_model/model.pkl")

# Create NetworkModel wrapper
network_model = NetworkModel(preprocessor=preprocessor, model=model)

# Load test data
df = pd.read_csv("test.csv")

# Make predictions
predictions = network_model.predict(df)
print(predictions)  # Output: [1, -1, 1, ...] (1 = Legitimate, -1 = Phishing)

πŸ“ Project Structure

networksecurity/
β”œβ”€β”€ app.py                          # FastAPI application
β”œβ”€β”€ main.py                         # Training pipeline entry point
β”œβ”€β”€ push_data.py                    # MongoDB data upload utility
β”œβ”€β”€ test_mongodb.py                 # MongoDB connection test
β”œβ”€β”€ setup.py                        # Package setup configuration
β”œβ”€β”€ requirements.txt                # Python dependencies
β”œβ”€β”€ Dockerfile                      # Docker configuration
β”œβ”€β”€ README.md                       # This file
β”‚
β”œβ”€β”€ networkSecurity/                # Main package
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚
β”‚   β”œβ”€β”€ components/                 # ML pipeline components
β”‚   β”‚   β”œβ”€β”€ data_ingestion.py
β”‚   β”‚   β”œβ”€β”€ data_validation.py
β”‚   β”‚   β”œβ”€β”€ data_transformation.py
β”‚   β”‚   └── model_trainer.py
β”‚   β”‚
β”‚   β”œβ”€β”€ pipeline/                   # Pipeline orchestration
β”‚   β”‚   β”œβ”€β”€ training_pipeline.py
β”‚   β”‚   └── batch_prediction.py
β”‚   β”‚
β”‚   β”œβ”€β”€ entity/                     # Config & artifact classes
β”‚   β”‚   β”œβ”€β”€ config_entity.py
β”‚   β”‚   └── artifact_entity.py
β”‚   β”‚
β”‚   β”œβ”€β”€ utils/                      # Utility functions
β”‚   β”‚   β”œβ”€β”€ main_utils/
β”‚   β”‚   β”‚   └── utils.py
β”‚   β”‚   └── ml_utils/
β”‚   β”‚       β”œβ”€β”€ model/
β”‚   β”‚       β”‚   └── estimator.py
β”‚   β”‚       └── metric/
β”‚   β”‚           └── classification_metric.py
β”‚   β”‚
β”‚   β”œβ”€β”€ cloud/                      # Cloud integration
β”‚   β”‚   └── s3_syncer.py
β”‚   β”‚
β”‚   β”œβ”€β”€ constant/                   # Constants
β”‚   β”‚   └── training_pipeline/
β”‚   β”‚       └── __init__.py
β”‚   β”‚
β”‚   β”œβ”€β”€ exceptionHandling/          # Exception handling
β”‚   β”‚   └── exception.py
β”‚   β”‚
β”‚   └── logging/                    # Logging
β”‚       └── logger.py
β”‚
β”œβ”€β”€ data_schema/                    # Schema configuration
β”‚   └── schema.yaml
β”‚
β”œβ”€β”€ Network_Data/                   # Input data
β”‚   └── phisingData.csv
β”‚
β”œβ”€β”€ Artifacts/                      # Generated artifacts (timestamped)
β”‚   └── mm_dd_yyyy_hh_mm_ss/
β”‚       β”œβ”€β”€ data_ingestion/
β”‚       β”œβ”€β”€ data_validation/
β”‚       β”œβ”€β”€ data_transformation/
β”‚       └── model_trainer/
β”‚
β”œβ”€β”€ final_model/                    # Production models
β”‚   β”œβ”€β”€ model.pkl
β”‚   └── preprocessor.pkl
β”‚
β”œβ”€β”€ prediction_output/              # Prediction results
β”‚   └── output.csv
β”‚
β”œβ”€β”€ valid_data/                     # Validated test data
β”‚   └── test.csv
β”‚
β”œβ”€β”€ templates/                      # HTML templates
β”‚   └── table.html
β”‚
β”œβ”€β”€ notebooks/                      # Jupyter notebooks
β”‚
└── NetworkSecurity.egg-info/       # Package metadata

πŸ”Œ API Documentation

Base URL:

http://localhost:8000

Endpoints:

1. Training Endpoint

GET /train

Description: Trigger the full ML pipeline training

Response (Success):

{
  "message": "Training is successful"
}

Response (Error):

{
  "detail": "Error message"
}

2. Prediction Endpoint

POST /predict

Description: Upload CSV file and get phishing predictions

Parameters:

  • file (multipart/form-data): CSV file with 30 features (no Result column)

Response (Success):

  • Returns HTML table with predictions
  • Saves results to prediction_output/output.csv
  • Prediction column: 1 (Legitimate), -1 (Phishing)

Example Request:

curl -X POST "http://localhost:8000/predict" \
  -H "accept: text/html" \
  -F "file=@test.csv"

3. Auto Documentation

GET /docs          # Swagger UI
GET /redoc         # ReDoc

πŸ“Š Model Performance

The system trains and compares 5 classification algorithms:

Algorithm Speed Accuracy Robustness
Logistic Regression ⚑⚑⚑ ⭐⭐ ⭐⭐⭐
Decision Tree ⚑⚑⚑ ⭐⭐ ⭐⭐
Random Forest ⚑⚑ ⭐⭐⭐ ⭐⭐⭐⭐
Gradient Boosting ⚑ ⭐⭐⭐⭐ ⭐⭐⭐
AdaBoost ⚑⚑ ⭐⭐⭐ ⭐⭐⭐

Evaluation Metrics:

  • F1-Score: Harmonic mean of precision and recall
  • Precision: True positives / (True positives + False positives)
  • Recall: True positives / (True positives + False negatives)

πŸ”’ Security Considerations

  1. Environment Variables: Store sensitive credentials in .env, never commit
  2. MongoDB: Use MongoDB Atlas with network access restrictions
  3. AWS S3: Use IAM roles with minimal required permissions
  4. CORS: API allows all origins (*), restrict in production
  5. Input Validation: Always validate and sanitize user inputs

πŸ› Troubleshooting

Issue: MongoDB Connection Failed

Error: Unable to connect to MongoDB

Solution:

  • Verify MONGODB_URL_KEY in .env
  • Check MongoDB Atlas network access settings
  • Ensure cluster is running

Issue: Missing Dependencies

Error: ModuleNotFoundError: No module named 'sklearn'

Solution:

pip install -r requirements.txt

Issue: Port 8000 Already in Use

# Use different port
uvicorn app:app --port 8080

πŸ“ˆ Future Enhancements

  • Real-time model monitoring and retraining triggers
  • Explainable AI (SHAP) for prediction interpretability
  • Kubernetes deployment orchestration
  • Advanced feature engineering with domain knowledge
  • Multi-model ensemble with voting mechanisms
  • A/B testing framework for model versions
  • GraphQL API alternative to REST
  • Mobile app for predictions

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“œ License

This project is licensed under the MIT License - see LICENSE file for details.


πŸ‘€ Author

Aditya Gupta


πŸ™ Acknowledgments

  • Data Source: Phishing URL dataset
  • MLOps Framework: MLflow + DagsHub
  • Inspiration: Modern ML pipeline best practices

πŸ“ž Support

For issues, questions, or suggestions:

  1. Open an issue on GitHub
  2. Check existing issues for solutions
  3. Email: ajaygupta995566@gmail.com

πŸ—‚οΈ Related Documentation


πŸ“ Conclusion

Network Security demonstrates an enterprise-grade ML pipeline for cybersecurity applications. By combining:

  • Automated data processing via orchestrated components
  • Ensemble machine learning with multiple algorithms
  • MLOps best practices using MLflow and cloud integration
  • Production readiness through containerization and REST APIs

This system provides a robust, scalable solution for phishing URL detection. The modular architecture allows easy extension with new features, algorithms, or data sources while maintaining code quality and reproducibility.

The project serves as a reference implementation for building production-ready ML systems that can: βœ… Process data at scale
βœ… Train models reliably
βœ… Monitor performance continuously
βœ… Deploy confidently to production

Deploy this system to protect your organization from phishing attacks today!


Last Updated: September 2026
Version: 1.0.0
Status: βœ… Production Ready

⬆ Back to Top

About

Network Security is an end-to-end machine learning operations (MLOps) pipeline designed to classify and detect phishing URLs in web traffic. The system automates the entire workflow from data ingestion to model deployment, enabling organizations to identify malicious URLs and protect users from phishing attacks.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages