NS3-gym

192 views
Skip to first unread message

ghofrane elgasmi

unread,
May 10, 2024, 1:19:43 PM5/10/24
to ns-3-users
Hi ns3-users,
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()

Charles Pandian

unread,
May 11, 2024, 6:42:07 AM5/11/24
to ns-3-...@googlegroups.com
"My codes are ready but I don't know exactly where the problem is."

Sorry. Could not understand your simulation script.

Since ns-3 is a network simulator, I tried to find a network in your simulation script (sim.cc) . But could not find any such  “network” where the actual DDoS attack is happening.

Could you explain where exactly the network of nodes and traffic are defined?

--
Posting to this group should follow these guidelines https://www.nsnam.org/wiki/Ns-3-users-guidelines-for-posting
---
You received this message because you are subscribed to the Google Groups "ns-3-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ns-3-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ns-3-users/f4056c03-f106-48f5-9de7-c98e6710683fn%40googlegroups.com.

ghofrane elgasmi

unread,
May 11, 2024, 6:53:23 AM5/11/24
to ns-3-...@googlegroups.com
Hello, 
Please   , Could you help me  to resolve the issue  of my code !  I want help  !I didn't understand the problem of the simulation DDOS  exactly  , Can you change the code 
Thanks 

ghofrane elgasmi

unread,
May 11, 2024, 7:03:32 AM5/11/24
to ns-3-...@googlegroups.com
My simulation with ns3-.29 ,with a DDOS attack  and it connected with without ns3-gym , but when I waN't to communicate my simulation with openAI GYm  it doesn't works (the action process....)         THis is my code   if there is any issue please help me 
Le sam. 11 mai 2024 à 11:42, Charles Pandian <igs...@gmail.com> a écrit :

ghofrane elgasmi

unread,
May 11, 2024, 7:04:06 AM5/11/24
to ns-3-...@googlegroups.com
Code   My AGENT 

ghofrane elgasmi

unread,
May 11, 2024, 7:10:09 AM5/11/24
to ns-3-...@googlegroups.com
#include "ns3/csma-helper.h"
#include "ns3/mobility-module.h"
#include "ns3/nstime.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/netanim-module.h"
#include "ns3/log.h"
#include <fstream>
#include "ns3/flow-monitor-helper.h"
#include "ns3/ipv4-flow-classifier.h"

#define TCP_SINK_PORT 9000
#define UDP_SINK_PORT 9001  

//experimental parameters
#define MAX_BULK_BYTES 100000
#define DDOS_RATE "20480kb/s"
#define MAX_SIMULATION_TIME 10.0

//Number of Bots for DDoS
#define NUMBER_OF_BOTS 10

using namespace ns3;

NS_LOG_COMPONENT_DEFINE("DDoSAttack");


int main(int argc, char *argv[])
{
    CommandLine cmd;
    cmd.Parse(argc, argv);

    Time::SetResolution(Time::NS);
    LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
    LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);

    //Legitimate connection bots
    NodeContainer nodes;
    nodes.Create(8);

    //Nodes for attack bots
    NodeContainer botNodes;
    botNodes.Create(NUMBER_OF_BOTS);

    // Define the Point-To-Point Links and their Parameters


PointToPointHelper pointToPoint;
   

    PointToPointHelper pp1, pp2;
    pp1.SetDeviceAttribute("DataRate", StringValue("100Mbps"));
    pp1.SetChannelAttribute("Delay", StringValue("1ms"));

    pp2.SetDeviceAttribute("DataRate", StringValue("100Mbps"));
    pp2.SetChannelAttribute("Delay", StringValue("1ms"));

    // Install the Point-To-Point Connections between Nodes
    NetDeviceContainer d02, d12, botDeviceContainer[NUMBER_OF_BOTS];
    d02 = pp1.Install(nodes.Get(0), nodes.Get(1));
    d12 = pp1.Install(nodes.Get(1), nodes.Get(2));

    for (int i = 0; i < NUMBER_OF_BOTS; ++i)
    {
        botDeviceContainer[i] = pp2.Install(botNodes.Get(i), nodes.Get(1));
    }

    //Assign IP to bots
    InternetStackHelper stack;
    stack.Install(nodes);
    stack.Install(botNodes);
    Ipv4AddressHelper ipv4_n;
    ipv4_n.SetBase("10.0.0.0", "255.255.255.252");

    Ipv4AddressHelper a02, a12;
    a02.SetBase("192.168.56.0", "255.255.255.0");
    a12.SetBase("192.168.50.0", "255.255.255.0");

    for (int j = 0; j < NUMBER_OF_BOTS; ++j)
    {
        ipv4_n.Assign(botDeviceContainer[j]);
        ipv4_n.NewNetwork();
    }

    //Assign IP to legitimate nodes
    Ipv4InterfaceContainer i02, i12;
    i02 = a02.Assign(d02);
    i12 = a12.Assign(d12);

    // DDoS Application Behaviour
    OnOffHelper onoff("ns3::UdpSocketFactory", Address(InetSocketAddress(i12.GetAddress(1), UDP_SINK_PORT)));
    onoff.SetConstantRate(DataRate(DDOS_RATE));
    onoff.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=30]"));
    onoff.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]"));

    ApplicationContainer onOffApp[NUMBER_OF_BOTS];

    //Install application in all bots
    for (int k = 0; k < NUMBER_OF_BOTS; ++k)
    {
        onOffApp[k] = onoff.Install(botNodes.Get(k));
        onOffApp[k].Start(Seconds(0.0));
        onOffApp[k].Stop(Seconds(MAX_SIMULATION_TIME));
    }

    // Sender Application (Packets generated by this application are throttled)
    BulkSendHelper bulkSend("ns3::TcpSocketFactory", InetSocketAddress(i12.GetAddress(1), TCP_SINK_PORT));
    bulkSend.SetAttribute("MaxBytes", UintegerValue(MAX_BULK_BYTES));
    ApplicationContainer bulkSendApp = bulkSend.Install(nodes.Get(0));
    bulkSendApp.Start(Seconds(0.0));
    bulkSendApp.Stop(Seconds(MAX_SIMULATION_TIME - 10));

    // UDPSink on receiver side
    PacketSinkHelper UDPsink("ns3::UdpSocketFactory",
                             Address(InetSocketAddress(Ipv4Address::GetAny(), UDP_SINK_PORT)));
    ApplicationContainer UDPSinkApp = UDPsink.Install(nodes.Get(2));
    UDPSinkApp.Start(Seconds(0.0));
    UDPSinkApp.Stop(Seconds(MAX_SIMULATION_TIME));

    // TCP Sink Application on server side
    PacketSinkHelper TCPsink("ns3::TcpSocketFactory",
                             InetSocketAddress(Ipv4Address::GetAny(), TCP_SINK_PORT));
    ApplicationContainer TCPSinkApp = TCPsink.Install(nodes.Get(2));
    TCPSinkApp.Start(Seconds(0.0));
    TCPSinkApp.Stop(Seconds(MAX_SIMULATION_TIME));

    Ipv4GlobalRoutingHelper::PopulateRoutingTables();

    //Simulation NetAnim configuration and node placement
    MobilityHelper mobility;
    mobility.SetPositionAllocator("ns3::GridPositionAllocator",
                                  "MinX", DoubleValue(0.0), "MinY", DoubleValue(0.0), "DeltaX", DoubleValue(5.0), "DeltaY", DoubleValue(10.0),
                                  "GridWidth", UintegerValue(5), "LayoutType", StringValue("RowFirst"));
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
    mobility.Install(nodes);
    mobility.Install(botNodes);

    AnimationInterface anim("DDoSim.xml");

    ns3::AnimationInterface::SetConstantPosition(nodes.Get(0), 0, 0);
    ns3::AnimationInterface::SetConstantPosition(nodes.Get(1), 10, 10);
    ns3::AnimationInterface::SetConstantPosition(nodes.Get(2), 20, 10);

    uint32_t x_pos = 0;
    for (int l = 0; l < NUMBER_OF_BOTS; ++l)
    {
        ns3::AnimationInterface::SetConstantPosition(botNodes.Get(l), x_pos++, 30);
    }

    // Enable packet capture on all devices
    NS_LOG_INFO("Enabling pcap output for all devices...");
    // Note: You need to define 'pointToPoint' before enabling pcap.
    // Commented out due to lack of declaration of 'pointToPoint'.
     pointToPoint.EnablePcapAll("attack1");

    // Install the flow monitor on all nodes
    FlowMonitorHelper flowmon;
    Ptr<FlowMonitor> monitor = flowmon.InstallAll();

    // Run the simulation
    Simulator::Stop(Seconds(MAX_SIMULATION_TIME));
    Simulator::Run();
    Simulator::Destroy();

    // Write statistics to CSV file
    std::ofstream file("output.csv");
    file << "Flow ID,Delay (s),Throughput (bps)\n";
    monitor->CheckForLostPackets();
    Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier>(flowmon.GetClassifier());
    std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats();
    for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin(); i != stats.end(); ++i)
    {
       // Ipv4FlowClassifier::FiveTuple  = classifier->FindFlow(i->first);
        file << i->first << "," << i->second.delaySum.GetSeconds() << ","
             << (i->second.rxBytes * 8.0) / (i->second.timeLastRxPacket.GetSeconds() - i->second.timeFirstTxPacket.GetSeconds()) << "\n";
    }
    file.close();

    return 0;
}  -------------------------------------------------------------> this my simulation DDOS attack exactly but when i integrate it in NS3-gym : i can't adapt it                                         

Le sam. 11 mai 2024 à 11:42, Charles Pandian <igs...@gmail.com> a écrit :

Charles Pandian

unread,
May 11, 2024, 7:56:33 AM5/11/24
to ns-3-...@googlegroups.com

"My codes are ready"

You said your code is ready - that's why I checked your code with curiosity to find the problem.
But It seems that, you didn't complete any integration with ns3-Gym. 

So first, you may need to learn the ns3-Gym and start your project. You may explore the examples available at https://github.com/tkn-tub/ns3-gym and design your project with the convention that they are using in those examples.



Reply all
Reply to author
Forward
0 new messages