my project : is a simulation of a ddos attack in a vanet network under the NS3.29 simulator, I developed an intrusion detection model so that it detects attacks in my simulation, So, I I linked my simulation with NS3-GYM (OpenAI Gym). OpenAI Gym is based on reinforcement Learning ( Agent), I want to declare my ML detection code in the AGENT so that the agent communicates with my simulation, and detects the attack. My codes are ready but I don't know exactly where the problem is.
Help me please .
Thanks !
My code :
My simulation is (sim.cc) , The codde is {
#include "ns3/core-module.h"
#include "ns3/opengym-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("OpenGymVANET");
void SimulateStep(Ptr<OpenGymInterface> openGym, double envStepTime) {
// Notify the current state and execute actions
openGym->NotifyCurrentState();
// Schedule the next step
Simulator::Schedule(Seconds(envStepTime), &SimulateStep, openGym, envStepTime);
}
Ptr<OpenGymDataContainer> GetVANETObservation(void) {
// Collect VANET-specific observations
float trafficDensity = 0.5; // Example: Traffic density
float vehicleSpeed = 30.0; // Example: Vehicle speed
float connectivityStatus = 1.0; // Example: Connectivity status
// Convert float values to uint32_t
std::vector<uint32_t> observationData = {
static_cast<uint32_t>(trafficDensity * 100),
static_cast<uint32_t>(vehicleSpeed),
static_cast<uint32_t>(connectivityStatus * 100)
};
// Log the observations
NS_LOG_UNCOND("VANET Observation: ");
NS_LOG_UNCOND("Traffic Density: " << trafficDensity);
NS_LOG_UNCOND("Vehicle Speed: " << vehicleSpeed);
NS_LOG_UNCOND("Connectivity Status: " << connectivityStatus);
Ptr<OpenGymBoxContainer<uint32_t>> observation = CreateObject<OpenGymBoxContainer<uint32_t>>(observationData);
// NS_LOG_UNCOND("VANET Observation: " << observation);
return observation;
}
bool ExecuteVANETActions(Ptr<OpenGymDataContainer> action) {
// Execute VANET-specific actions based on the received action
NS_LOG_UNCOND("VANET Action Executed: " << action);
return true; // Placeholder
}
int main(int argc, char *argv[]) {
// Parameters of the scenario
uint32_t simSeed = 0;
double simulationTime = 1; //seconds
double envStepTime = 0.1; //seconds, OpenGym environment step time interval
uint32_t openGymPort = 5555;
uint32_t numLegitimateVehicles = 15;
CommandLine cmd;
// Required parameters for OpenGym interface
cmd.AddValue("openGymPort", "Port number for OpenGym env. Default: 5555", openGymPort);
cmd.AddValue ("simSeed", "Seed for random generator. Default: 1", simSeed);
cmd.Parse(argc, argv);
NS_LOG_UNCOND("Ns3Env parameters:");
NS_LOG_UNCOND("--simulationTime: " << simulationTime);
NS_LOG_UNCOND("--openGymPort: " << openGymPort);
NS_LOG_UNCOND("--envStepTime: " << envStepTime);
NS_LOG_UNCOND("--seed: " << simSeed);
NS_LOG_UNCOND("Number of legitimate vehicles: " << numLegitimateVehicles);
RngSeedManager::SetSeed(1);
RngSeedManager::SetRun(simSeed);
// OpenGym Env
Ptr<OpenGymInterface> openGym = CreateObject<OpenGymInterface>(openGymPort);
openGym->SetGetObservationCb(MakeCallback(&GetVANETObservation));
openGym->SetExecuteActionsCb(MakeCallback(&ExecuteVANETActions));
Simulator::Schedule(Seconds(0.0), &SimulateStep, openGym, envStepTime);
NS_LOG_UNCOND("Simulation start");
Simulator::Stop(Seconds(simulationTime));
Simulator::Run();
NS_LOG_UNCOND("Simulation stop");
openGym->NotifySimulationEnd();
Simulator::Destroy();
return 0;
}}
and this is my code agent.py
{import argparse
from ns3gym import ns3env
import ns3gym
import IDS # Importez votre modèle de détection d'intrusion
# Parsez les arguments de la ligne de commande
parser = argparse.ArgumentParser(description='Start simulation script on/off')
parser.add_argument('--start',
type=int,
default=1,
help='Start ns-3 simulation script 0/1, Default: 1')
parser.add_argument('--iterations',
type=int,
default=1,
help='Number of iterations, Default: 1')
args = parser.parse_args()
startSim = bool(args.start)
iterationNum = int(args.iterations)
# Initialisation de l'environnement NS3
# Paramètres pour la simulation
port = 5555
simTime = 20 # secondes
stepTime = 0.5 # secondes
seed = 0
simArgs = {"--simTime": simTime,
"--testArg": 123}
debug = False
# Initialisation de l'environnement ns3
env = ns3env.Ns3Env(port=port, stepTime=stepTime, startSim=startSim, simSeed=seed, simArgs=simArgs, debug=debug)
# Charger le modèle de détection d'intrusion
intrusion_detection_model = IDS.IntrusionDetection()
try:
while True:
# Recevoir les observations de l'environnement
observation, info = env.reset()
# Utiliser le modèle de détection d'intrusion pour détecter les attaques
intrusion_detected = intrusion_detection_model.detect(observation)
# Prendre une décision en fonction de la détection d'attaque
if intrusion_detected:
# Annoncer la détection d'attaque
action = "Intrusion detected!"
else:
# Annoncer l'absence d'attaque
action = "No intrusion detected."
# Renvoyer les informations au simulateur VANET
# Vous devez implémenter cette partie pour renvoyer l'action au simulateur VANET
except KeyboardInterrupt:
print("Arrêt de l'agent...")
env.close() # Fermer l'environnement proprement
print("L'agent a été arrêté correctement.")}
and this is the IDS.py (the model ML)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
class IntrusionDetection:
def __init__(self, data_path):
self.data_path = data_path
self.model = None
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
def load_data(self):
data = pd.read_csv(self.data_path)
data = data.drop(columns=['messageID'])
self.X = data.drop(columns=['class'])
self.y = data['class']
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
self.X, self.y, test_size=0.2, random_state=42)
def train_model(self):
self.model = RandomForestClassifier(random_state=42)
self.model.fit(self.X_train, self.y_train)
def evaluate_model(self):
y_pred = self.model.predict(self.X_test)
print("Confusion Matrix:")
print(confusion_matrix(self.y_test, y_pred))
print("\nClassification Report:")
print(classification_report(self.y_test, y_pred))
if __name__ == "__main__":
# Instantiate IntrusionDetection class
intrusion_detection = IntrusionDetection('/home/pfe/Téléchargements/Try.csv')
# Load data
intrusion_detection.load_data()
# Train the model
intrusion_detection.train_model()
# Evaluate the model
intrusion_detection.evaluate_model()