Ns3 Projects for B.E/B.Tech M.E/M.Tech PhD Scholars.  Phone-Number:9790238391   E-mail: ns3simulation@gmail.com

How to Implement Blockchain based IDS in ns3

To implement the Blockchain-based Intrusion Detection System (IDS) in ns3, through the blockchain nodes should detect intrusions and share their detection results using simulated network. This will make sure the integrity and reliability of the IDS alerts.

Here’s a step-by-step process on how to implement a basic Blockchain-based IDS in ns3:

Step-by-Step Implementation:

Step 1: Set Up ns3 Environment

  1. Install ns3: Make certain ns3 is installed. Follow the installation guide suitable for your operating system.
  2. Familiarize Yourself with ns3: To know better about the basic concepts and ns3’s simulation structure, we can use the ns3 tutorial.

Step 2: Set Up a Simple Blockchain Library

  1. Choose or Implement a Simple Blockchain Library: For simplicity, we can implement a basic blockchain directly in C++ for ns3. This blockchain will allow nodes to add blocks containing IDS alerts.
  2. Define Blockchain Structures: Create basic blockchain data structures in C++.

Step 3: Define the Network Topology

  1. Create a Simple Network: Creating nodes, setting up channels, and configuring IP addresses by defining a basic network topology using ns3.

Step 4: Implement the Blockchain-Based IDS

  1. Blockchain Data Structures: Define the basic blockchain and block structures following the below sample.

#include <iostream>

#include <vector>

#include <string>

#include <sstream>

#include <openssl/sha.h>

struct Block {

int index;

std::string previousHash;

std::string timestamp;

std::string data;  // IDS alert data

std::string hash;

Block(int idx, std::string prevHash, std::string time, std::string dat)

: index(idx), previousHash(prevHash), timestamp(time), data(dat) {

hash = calculateHash();

}

std::string calculateHash() const {

std::stringstream ss;

ss << index << previousHash << timestamp << data;

return sha256(ss.str());

}

static std::string sha256(const std::string str) {

unsigned char hash[SHA256_DIGEST_LENGTH];

SHA256_CTX sha256;

SHA256_Init(&sha256);

SHA256_Update(&sha256, str.c_str(), str.size());

SHA256_Final(hash, &sha256);

std::stringstream ss;

for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {

ss << std::hex << std::setw(2) << std::setfill(‘0’) << (int)hash[i];

}

return ss.str();

}

};

class Blockchain {

public:

Blockchain() {

chain.emplace_back(Block(0, “0”, “0”, “Genesis Block”));

}

void addBlock(const std::string &data) {

const Block &previousBlock = chain.back();

chain.emplace_back(Block(chain.size(), previousBlock.hash, “0”, data));

}

const Block &getLatestBlock() const {

return chain.back();

}

void printBlockchain() const {

for (const auto &block : chain) {

std::cout << “Block ” << block.index << ” [prevHash: ” << block.previousHash << “, hash: ” << block.hash << “, data: ” << block.data << “]\n”;

}

}

private:

std::vector<Block> chain;

};

  1. IDS Application: To detect breaches and joins the alerts to the blockchain by implementing an IDS application.

#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 <iostream>

#include <vector>

#include <string>

#include <sstream>

#include <openssl/sha.h>

#include <ctime>

using namespace ns3;

// Blockchain data structures

struct Block {

int index;

std::string previousHash;

std::string timestamp;

std::string data;

std::string hash;

Block(int idx, std::string prevHash, std::string time, std::string dat)

: index(idx), previousHash(prevHash), timestamp(time), data(dat) {

hash = calculateHash();

}

std::string calculateHash() const {

std::stringstream ss;

ss << index << previousHash << timestamp << data;

return sha256(ss.str());

}

static std::string sha256(const std::string str) {

unsigned char hash[SHA256_DIGEST_LENGTH];

SHA256_CTX sha256;

SHA256_Init(&sha256);

SHA256_Update(&sha256, str.c_str(), str.size());

SHA256_Final(hash, &sha256);

std::stringstream ss;

for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {

ss << std::hex << std::setw(2) << std::setfill(‘0’) << (int)hash[i];

}

return ss.str();

}

};

class Blockchain {

public:

Blockchain() {

chain.emplace_back(Block(0, “0”, currentTime(), “Genesis Block”));

}

void addBlock(const std::string &data) {

const Block &previousBlock = chain.back();

chain.emplace_back(Block(chain.size(), previousBlock.hash, currentTime(), data));

}

const Block &getLatestBlock() const {

return chain.back();

}

void printBlockchain() const {

for (const auto &block : chain) {

std::cout << “Block ” << block.index << ” [prevHash: ” << block.previousHash << “, hash: ” << block.hash << “, data: ” << block.data << “]\n”;

}

}

private:

std::vector<Block> chain;

std::string currentTime() const {

std::time_t now = std::time(nullptr);

char buf[sizeof “2021-10-08T07:07:09Z”];

std::strftime(buf, sizeof buf, “%FT%TZ”, std::gmtime(&now));

return buf;

}

};

// Custom application for IDS and Blockchain

class BlockchainIDSApp : public Application {

public:

BlockchainIDSApp() : m_blockchain(new Blockchain()) {}

virtual ~BlockchainIDSApp() {}

 

void Setup(Address address, uint16_t port) {

m_peerAddress = address;

m_peerPort = port;

}

void DetectAndAddAlert(const std::string &alert) {

m_blockchain->addBlock(alert);

m_blockchain->printBlockchain();

}

private:

virtual void StartApplication() {

m_socket = Socket::CreateSocket(GetNode(), TypeId::LookupByName(“ns3::UdpSocketFactory”));

m_socket->Bind();

m_socket->Connect(InetSocketAddress(m_peerAddress, m_peerPort));

 

// Schedule the first packet transmission

Simulator::Schedule(Seconds(1.0), &BlockchainIDSApp::SendPacket, this);

// Set up the receive callback

m_socket->SetRecvCallback(MakeCallback(&BlockchainIDSApp::ReceivePacket, this));

}

virtual void StopApplication() {

if (m_socket) {

m_socket->Close();

m_socket = 0;

}

}

void SendPacket() {

std::string message = “Hello, this is a test message!”;

Ptr<Packet> packet = Create<Packet>((uint8_t *)message.c_str(), message.size());

m_socket->Send(packet);

 

// Schedule the next packet transmission

Simulator::Schedule(Seconds(1.0), &BlockchainIDSApp::SendPacket, this);

}

void ReceivePacket(Ptr<Socket> socket) {

Ptr<Packet> packet = socket->Recv();

uint8_t buffer[1024];

packet->CopyData(buffer, packet->GetSize());

std::string receivedMessage((char *)buffer, packet->GetSize());

// Example: Detect an intrusion based on a simple condition

if (receivedMessage.find(“malicious”) != std::string::npos) {

std::string alert = “Intrusion detected: ” + receivedMessage;

DetectAndAddAlert(alert);

}

}

Ptr<Socket> m_socket;

Address m_peerAddress;

uint16_t m_peerPort;

std::unique_ptr<Blockchain> m_blockchain;

};

int main(int argc, char *argv[]) {

NodeContainer nodes;

nodes.Create(3); // Example: 3 nodes (1 client, 1 IDS, 1 server)

PointToPointHelper pointToPoint;

pointToPoint.SetDeviceAttribute(“DataRate”, StringValue(“1Gbps”));

pointToPoint.SetChannelAttribute(“Delay”, StringValue(“2ms”));

NetDeviceContainer devices1;

devices1 = pointToPoint.Install(nodes.Get(0), nodes.Get(1)); // Client to IDS

NetDeviceContainer devices2;

devices2 = pointToPoint.Install(nodes.Get(1), nodes.Get(2)); // IDS to Server

InternetStackHelper stack;

stack.Install(nodes);

Ipv4AddressHelper address;

address.SetBase(“10.1.1.0”, “255.255.255.0”);

Ipv4InterfaceContainer interfaces1 = address.Assign(devices1);

address.SetBase(“10.1.2.0”, “255.255.255.0”);

Ipv4InterfaceContainer interfaces2 = address.Assign(devices2);

Ipv4GlobalRoutingHelper::PopulateRoutingTables();

uint16_t port = 9;

Ptr<BlockchainIDSApp> clientApp = CreateObject<BlockchainIDSApp>();

clientApp->Setup(InetSocketAddress(interfaces1.GetAddress(1), port), port);

nodes.Get(0)->AddApplication(clientApp);

clientApp->SetStartTime(Seconds(2.0));

clientApp->SetStopTime(Seconds(10.0));

Ptr<BlockchainIDSApp> idsApp = CreateObject<BlockchainIDSApp>();

idsApp->Setup(InetSocketAddress(interfaces2.GetAddress(1), port), port);

nodes.Get(1)->AddApplication(idsApp);

idsApp->SetStartTime(Seconds(1.0));

idsApp->SetStopTime(Seconds(10.0));

Ptr<BlockchainIDSApp> serverApp = CreateObject<BlockchainIDSApp>();

serverApp->Setup(InetSocketAddress(Ipv4Address::GetAny(), port), port);

nodes.Get(2)->AddApplication(serverApp);

serverApp->SetStartTime(Seconds(1.0));

serverApp->SetStopTime(Seconds(10.0));

Simulator::Run();

Simulator::Destroy();

return 0;

}

Explanation:

  1. Blockchain Data Structures:
    • Block structure signifies a single block in the blockchain.
    • Chain of blocks is managed by the Blockchain class.
  2. BlockchainIDSApp Class:
    • This custom application class handles IDS functionality and communicate with the blockchain.
    • Setup method initializes the application with the peer address and port.
    • StartApplication method sets up the socket connection, schedules the first packet transmission, and sets up the receive callback.
    • SendPacket method sends a message to the peer node.
    • ReceivePacket method receives a message and checks for intrusion. If an intrusion is detected, it logs an alert in the blockchain.
  3. Main Function:
    • First, network topology is created then BlockchainIDSApp is installed on the client, IDS, and server nodes.
    • IDS checks for breaches in the messages that are send by the client and logs alerts in the blockchain if an intrusion is detected.

Compile and Run:

  1. Compile the Code: Make sure, OpenSSL is installed on your computer. Then, compile the code using the following command:

g++ -std=c++11 -o ns3-blockchain-ids main.cc -lssl -lcrypto `pkg-config –cflags –libs ns3-dev`

  1. Run the Simulation: Execute the compiled program:

./ns3-blockchain-ids

This setup demonstrates a simple implementation of a Blockchain-based IDS in ns3. You can expand it further to include more sophisticated intrusion detection algorithms, more complex blockchain features, and additional nodes and topologies as needed.In this script, we covered the entire step-by-step implementation of Blockchain based IDS  in the ns3 tool. For your future references, we will provide implementation and performance analysis details regarding blockchain or IDS.