Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - OkeyAmy/ddos-attack · GitHub
Skip to content

Repository files navigation

Network Traffic Prediction 📶📊

GitHubMediumX (formerly Twitter)

Welcome to the Network Traffic Prediction project! This project aims to classify network traffic to aid in traffic management and security analysis, using a machine learning model deployed with FastAPI.

Data Cleaning and Preprocessing

In the process of preparing the dataset, several columns were removed or retained based on their relevance to model performance and privacy concerns:

  • Dropped Columns:

    • ip.src and ip.dst were removed due to privacy concerns, as they contain sensitive IP information that could identify specific devices.
    • frame.time was also removed because feature importance analysis indicated it contributed minimally to prediction accuracy.
  • Retained Columns with Fixed Values:

    • Columns such as tcp.dstport, ip.proto, tcp.flags.syn, tcp.flags.reset, ip.flags.mf, and ip.flags.rb have fixed or constant values across the dataset. Despite their lack of variability, they were retained as they do not impact data security and might provide contextual consistency for certain traffic patterns.

This data-cleaning approach balances the need for privacy with maintaining feature diversity for model training.

Dataset Column Details

The following table provides an in-depth explanation of each column in the dataset. Understanding each feature helps in analyzing network traffic patterns and building an effective classification model.

Column NameDescriptionMeaning
tcp.srcportSource TCP PortThe port number on the sender's device. Ports identify specific processes or services on devices.
tcp.dstportDestination TCP PortThe port number on the receiver's device, directing traffic to a specific service.
ip.protoIP ProtocolProtocol used for communication, represented by a number (e.g., 6 for TCP, 17 for UDP). Protocols define data transmission rules.
frame.lenFrame LengthTotal packet size, including headers and data payload, measured in bytes. Packet size affects network performance.
tcp.flags.synTCP SYN FlagFlag indicating if the SYN (synchronize) bit is set to initiate a TCP connection.
tcp.flags.resetTCP RST FlagFlag indicating if the RST (reset) bit is set, used to reset a TCP connection.
tcp.flags.pushTCP PSH FlagFlag indicating if the PSH (push) bit is set, requesting immediate data transmission.
tcp.flags.ackTCP ACK FlagFlag indicating if the ACK (acknowledge) bit is set, used to confirm receipt of packets.
ip.flags.mfIP More Fragments FlagIndicates if more fragments follow, used when data is split into multiple packets.
ip.flags.dfIP Don't Fragment FlagIndicates if fragmentation is allowed (0 = allowed, 1 = don’t fragment).
ip.flags.rbIP Reserved BitReserved for future use in IP headers; should be set to 0.
tcp.seqTCP Sequence NumberIdentifies the order of a series of packets sent by TCP. Helps track data in sequence.
tcp.ackTCP Acknowledgment NumberAcknowledges receipt of packets, maintaining reliable data transfer.
PacketsTotal Packet CountTotal number of packets sent in a session or flow, gauging the session's volume.
BytesTotal Bytes SentTotal data volume transmitted in a session or flow. Indicates bandwidth usage.
Tx PacketsTransmitted PacketsNumber of packets sent from the source to the destination. Measures outbound traffic.
Tx BytesTransmitted BytesAmount of data sent from source to destination, in bytes.
Rx PacketsReceived PacketsNumber of packets received by the source from the destination. Measures inbound traffic.
Rx BytesReceived BytesAmount of data received by the source from the destination, in bytes.
LabelTraffic LabelClassification label assigned to the traffic, indicating its type (e.g., Benign', DDoS-ACK, DDoS-PSH-ACK).

Label Structure

  • Benign: This label indicates normal, non-malicious network traffic. Packets labeled as Benign represent routine communications with no threat to network security. This traffic is generally safe and expected in regular network activity.

  • DDoS-ACK: This label identifies network traffic associated with a Distributed Denial of Service (DDoS) attack that primarily utilizes the ACK (Acknowledgment) flag in TCP packets. In a DDoS-ACK attack, attackers flood the target with a high volume of ACK packets, aiming to exhaust resources and disrupt normal service. This type of traffic is usually high in volume and can impact server response times.

  • DDoS-PSH-ACK: This label refers to traffic linked to a DDoS attack using both the PSH (Push) and ACK (Acknowledgment) flags in TCP packets. In a DDoS-PSH-ACK attack, the attacker sends numerous PSH-ACK packets to overwhelm the target. The PSH flag is used to request immediate data transmission, while the ACK flag acknowledges receipt of previous packets. This type of attack aims to congest the target network and slow down or prevent legitimate traffic from being processed.

Raw Data Overview Raw Data Overview Cleaned Data Overview Clean Data Overview

Project Structure

Here’s an overview of the project’s main files and folders:

.
├── app.py # FastAPI app for model inference
├── config.py # Configuration for MLflow tracking
├── data/ # Folder containing training and test datasets
├── Dockerfile # Docker configuration
├── main.py # Main script for data processing and model training
├── models/ # Folder where trained model files are saved
├── monitor.py # Script for monitoring model performance
├── requirements.txt # Python dependencies
├── webpage.html # Frontend HTML for submitting predictions
├── classification_test.html # Accuracy metrics created by monitor.py to monitor the model
├── data_drift_report.html # Overview of dataset observability and monitoring
├── source dataset # Original dataset for training
├── sample.json # Sample set to test the model
└── README.md # Project documentation

Getting Started

Follow these steps to set up the project and get started.

1. Clone the Repository

Clone the repository from GitHub and navigate into the project directory:

git clone https://github.com/OkeyAmy/network-traffic-project.git
cd network-traffic-project

2. Set Up the Environment

Ensure Python 3.8+ is installed. Set up a virtual environment and install the required dependencies:

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

3. Data Preparation

Ensure your training and testing datasets are available in the data folder. If you have DVC set up, pull the data:

dvc pull

4. Train the Model

To train the model, execute:

python main.py

5. Start the FastAPI Server

To serve predictions, start the FastAPI application:

uvicorn app:app --reload

The API will be available at http://127.0.0.1:8000, where you can make requests to the /predict endpoint.

6. Dockerize the Application

To containerize the application:

  1. Build the Docker image:
    docker build -t network_traffic_api .
  2. Run the Docker container:
    docker run -p 80:80 network_traffic_api
  3. Push to Docker Hub for deployment:
    docker tag network_traffic_api your-dockerhub-username/network_traffic_api
    docker push your-dockerhub-username/network_traffic_api

7. Frontend (HTML)

This project includes a frontend HTML file (webpage.html) for entering network packet data and submitting it to the FastAPI backend for predictions. To use the frontend:

  1. Open webpage.html in your browser.
  2. Enter the necessary network traffic data.
  3. Submit the form to see the prediction on the page.

Network Prediction

Ensure the FastAPI server is running to process requests from the HTML form.

8. Model Monitoring with Evidently AI

To monitor model performance and detect data drift, use the monitor.py script:

python monitor.py

This script generates data drift and performance reports, saved as data_drift_report.html and classification_tests.html.

Configuration Details

app.py - FastAPI Setup

The FastAPI app (app.py) handles incoming requests for predictions, loading the model from models/model.pkl. It defines an input schema for network packet attributes like tcp.srcport, ip.proto, and frame.len.

monitor.py - Model Monitoring

This script integrates Evidently AI to check for data drift and model performance over time. It loads training and testing data, applies the model, and generates drift and performance reports.

main.py - Model Training

The main.py script ingests, cleans, and trains the model on network traffic data. It uses MLflow to track training metrics and saves the trained model for FastAPI predictions.

API Endpoints

POST /predict

  • Request: JSON payload containing network packet attributes.
  • Response: Returns the predicted class label (e.g., "Benign" or "DDoS-ACK").

Example request:

{
"tcp.srcport": 52332,
"tcp.dstport": 8000,
"ip.proto": 6,
"frame.len": 66,
"tcp.flags.syn": 0,
"tcp.flags.reset": 0,
"tcp.flags.push": 0,
"tcp.flags.ack": 1,
"ip.flags.mf": 0,
"ip.flags.df": 1,
"ip.flags.rb": 0,
"tcp.seq": 1,
"tcp.ack": 1,
"Packets": 10,
"Bytes": 1144,
"Tx Packets": 6,
"Tx Bytes": 560,
"Rx Packets": 4,
"Rx Bytes": 584
}

Example response:

{
"predicted_class": 0,
"class_label": "Benign"
}

License

This project is licensed under the MIT License. For details, see the LICENSE file.


Happy coding! If you encounter any issues, feel free to open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages