INTRUSION DETECTION USING ANT COLONY OPTIMIZATION

Introduction

Wireless sensor networks (WSNs) are extensively used in various applications, serving as a vital component in environmental monitoring. They enable the tracking of crucial parameters such as temperature, humidity, air quality, and pollution levels. Intrusion detection systems (IDS) find wide application across corporate networks, government agencies, and critical infrastructure, effectively identifying unauthorized access attempts, malware, denial-of-service attacks, and other suspicious activities. Anomaly detection plays a crucial role in WSNs, aiding in the identification of uncommon occurrences and atypical patterns within collected data. These anomalies can indicate sensor malfunctions, equipment failures, or potential security risks, all of which require immediate attention. In IDS, our proposed system enhances security and network performance in WSNs by effectively identifying and detecting malicious behavior of nodes. We introduce novelty in intrusion detection systems by incorporating Ant Colony Optimization (ACO) in WSNs. This approach significantly enhances the security and optimality of WSNs. The proposed system effectively identifies and detects malicious behavior of nodes. We propose novelty in intrusion detection systems by using Ant Colony Optimization in WSNs. By addressing security and routing challenges simultaneously, we are able to provide data confidentiality and establish a secure wireless network. The anomaly detection plays a crucial role in Wireless Sensor Networks as it aids in the detection of uncommon occurrences and atypical patterns within the collected data. These anomalies can signify sensor malfunctions, equipment failures, or even potential security risks, all of which require immediate and suitable attention. In IDS, to improve the security and enhance the performance in the network in WSNs.

Install packages

To make this project successful, you need to install some libraries. First, ensure that Python is installed on your system and that pip is also installed, as it will help you import the libraries. Open the terminal and install all the necessary libraries listed below.

Tkinter

Provides the graphical user interface (GUI) elements like windows, buttons, labels, and text areas. It is used for creating the application's main window and handling user interactions, such as uploading files and entering node numbers.

Tkinter
pip install tkinter-page

Time

Provides time-related functions. Here, it is used to control the time during the scanning process of the files.

Time
pip install TIME-python

NetworkX

A library for creating and manipulating complex networks. It is used to generate and visualize graphs representing the network of nodes in the Ant Colony Optimization (ACO) algorithm.

NetworkX
pip install networkx

Matplotlib

matplotlib.pyplot and FigureCanvasTkAgg: Part of matplotlib, these libraries are used to create and embed plots within the Tkinter GUI. pyplot generates the plots, and FigureCanvasTkAgg integrates them into the Tkinter window.

Matplotlib
pip install matplotlib

Numpy

A library for numerical operations, used here to handle arrays and perform mathematical operations in the ACO algorithm.

Numpy
pip install numpy

Subprocess

Provides functionality for spawning new processes. Although imported, it is not utilized in the provided code.

Subprocess
pip install subprocess.run

Importing libraries

Import all the installed packages in the source code. Create a new source file and start writing the code from scratch.

Importing libraries
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
import time
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import subprocess

Ant Colony Optimization

The ACO algorithm is inspired by the behavior of real ants in finding the shortest path to a food source. In this implementation, an artificial ant colony explores a graph to find the shortest path, using pheromones to guide the search process.
Class and Initialization The AntColony class is initialized with several parameters:

distances: A 2D array representing the distances between nodes.
n_ants: The number of ants in the colony.
n_best: The number of best paths that influence pheromone updates.
n_iterations: The number of iterations the algorithm runs.
decay: The rate at which pheromone evaporates.
alpha and beta: Parameters that control the influence of pheromone and distance, respectively.
The __init__ method initializes the pheromone levels, which are distributed uniformly, and other parameters needed for the algorithm.

Running the Algorithm:
The run method is the main function that executes the ACO algorithm. It initializes variables to track the shortest path found. For each iteration, it generates all paths using the ants, updates the pheromones based on the best paths, and decays the pheromones. The method returns the shortest path found after all iterations.

Pheromone Updates:
The spread_pheromone method updates the pheromone levels on the paths. It sorts all paths based on their lengths and increases the pheromone levels on the best paths, inversely proportional to their lengths.

Path Generation:
The gen_all_paths method generates paths for all ants by calling the gen_path method. Each path starts from a given node and the ants move according to the pheromone levels and distances. The gen_path method creates a path for a single ant. Starting from a node, it chooses the next node to visit based on the pheromone levels and distances, ensuring it does not revisit any node until all nodes are covered. After visiting all nodes, the ant returns to the starting node.

Move Selection:
The pick_move method determines the next node to move to by considering the pheromone levels and distances to unvisited nodes. It normalizes the probabilities and uses a random choice weighted by these probabilities to select the next node.

Path Distance Calculation:
The gen_path_dist method calculates the total distance of a given path by summing up the distances between consecutive nodes in the path.

Ant Colony Optimization algorithm is used to find the shortest path in a network. It simulates the behavior of ants exploring paths and using pheromones to guide subsequent ants, iteratively refining the solution to find the optimal path.

ACO
global n
n=0
class AntColony:                                              
    def _init_(self, distances, n_ants, n_best, n_iterations, decay, alpha=1, beta=1):
        self.distances  = distances
        self.pheromone = np.ones(self.distances.shape) / len(distances)
        self.all_inds = range(len(distances))
        self.n_ants = n_ants
        self.n_best = n_best
        self.n_iterations = n_iterations
        self.decay = decay
        self.alpha = alpha
        self.beta = beta
                                            
    def run(self):
        shortest_path = None
        all_time_shortest_path = ("placeholder", np.inf)
        for i in range(self.n_iterations):
            all_paths = self.gen_all_paths()
            self.spread_pheromone(all_paths, self.n_best, shortest_path=shortest_path)
            shortest_path = min(all_paths, key=lambda x: x[1])
            if shortest_path[1] < all_time_shortest_path[1]:
                all_time_shortest_path = shortest_path
            self.pheromone * self.decay
        return all_time_shortest_path
                                            
        def spread_pheromone(self, all_paths, n_best, shortest_path):
            sorted_paths = sorted(all_paths, key=lambda x: x[1])
            for path, dist in sorted_paths[:n_best]:
                for move in path:
                    self.pheromone[move] += 1.0 / self.distances[move]
                                            
        def gen_path_dist(self, path):
            total_dist = 0
            for ele in path:
                total_dist += self.distances[ele]
            return total_dist
                                            
        def gen_all_paths(self):
            all_paths = []
            for i in range(self.n_ants):
                path = self.gen_path(0)
                all_paths.append((path, self.gen_path_dist(path)))
            return all_paths
                                            
        def gen_path(self, start):
            path = []
            visited = set()
            visited.add(start)
            prev = start
            for i in range(len(self.distances) - 1):
                move = self.pick_move(self.pheromone[prev], self.distances[prev], visited)
                path.append((prev, move))
                prev = move
                visited.add(move)
            path.append((prev, start)) # going back to where we started
            return path
                                            
        def pick_move(self, pheromone, dist, visited):
            pheromone = np.copy(pheromone)
            pheromone[list(visited)] = 0
                                          
            row = pheromone * self.alpha * (( 1.0 / dist) * self.beta)
                                            
            norm_row = row / row.sum()
            move = np.random.choice(self.all_inds, 1, p=norm_row)[0] 
            return move

Visualization

Tkinter-based GUI with network visualization and an Ant Colony Optimization (ACO) algorithm to simulate and display the process of finding the shortest path in a network. The submit_number function captures user input for the number of nodes in the network, validates it to ensure it is at least two, and then generates a complete graph with that number of nodes using NetworkX. If the input is valid, it visualizes this initial network using Matplotlib. Random distances are assigned between the nodes, with diagonal values set to 9999 to simulate infinity. The ACO algorithm is then instantiated with these distances and parameters like the number of ants, the best paths, iterations, decay rate, and influence parameters (alpha and beta). The algorithm is run to find the shortest path, which is then visualized on the network with the edges corresponding to the shortest path highlighted in red. This updated network visualization is embedded into the Tkinter window using the FigureCanvasTkAgg class. The perform_scan function simulates a scanning process by updating the UI to show scanning status, waiting for three seconds, and then displaying the scan results, which indicate that one file was scanned with no malware detected. The scan results are shown in a text widget within the Tkinter window. This integration of Tkinter for the UI, NetworkX for graph generation, and Matplotlib for visualization provides an interactive and visual representation of the ACO algorithm's operation and results.

Visualization
def submit_number():
    try:                
        num_nodes = int(entry.get())
        n=num_nodes
        if num_nodes < 2:
            messagebox.showerror("Error", f"Number should not be less than two")
            entry.delete(0, tk.END)
            upload_button.config(state=tk.DISABLED)
            scan_button.config(state=tk.DISABLED)
            return
                                          
        G = nx.complete_graph(num_nodes)
                                    
        # Visualize the initial network
        pos = nx.circular_layout(G)
        fig, ax = plt.subplots()
        nx.draw(G, pos, with_labels=True, node_size=2000, node_color='skyblue', font_size=10, font_color='black', ax=ax)
        ax.set_title("Initial Network")
                                    
        distances = np.random.randint(1, 10, (num_nodes, num_nodes))
        np.fill_diagonal(distances, 9999)
        n_ants = 5
        n_best = 2
        n_iterations = 20
        decay = 0.1
                                  
        ant_colony = AntColony(distances, n_ants, n_best, n_iterations, decay, alpha=1, beta=2)
        shortest_path = ant_colony.run()
                             
        # Visualize the network with ACO paths
        fig_aco, ax_aco = plt.subplots(figsize=(5, 3))
        nx.draw(G, pos, with_labels=True, node_size=1000, node_color='skyblue', font_size=10, font_color='black', ax=ax_aco)
        edges = [(shortest_path[0][i][0], shortest_path[0][i][1]) for i in range(len(shortest_path[0]) - 1)]
        nx.draw_networkx_edges(G, pos, edgelist=edges, edge_color='red', width=2.0, ax=ax_aco)
        ax_aco.set_title("Network with ACO Paths")
                                    
        # Embed Matplotlib plots in Tkinter window with grid layout
        canvas_aco = FigureCanvasTkAgg(fig_aco, master=root)
        canvas_aco.get_tk_widget().grid(row=1, column=0, columnspan=3)
        upload_button.config(state=tk.NORMAL)
                                    
    except ValueError:
        messagebox.showerror("Error", "Number should be number")
        entry.delete(0, tk.END)
        upload_button.config(state=tk.DISABLED)
        scan_button.config(state=tk.DISABLED)
                                    
def perform_scan():
    result_text.delete(1.0, tk.END)
    scan_animation_label.config(text="Scanning...", fg="red")
    root.update()
    time.sleep(3)  
    scan_animation_label.config(text="File Scanned", fg="limegreen")                                    
    # Display scan results
    result_text.delete(1.0, tk.END)  
    scan_result = f"Scan results: \n \nNumber Of Files scanned:1\n \nFiles passed through:
    {n}\n \nFamily Of Malware Detected : NO Malware Detected"
    result_text.insert(tk.END, scan_result)
                    

Graphical User Interface

The graphical user interface (GUI) created using Tkinter provides a user-friendly platform for an Intrusion Detection System with Ant Colony Optimization (ACO) routing. The main window, titled "Intrusion Detection system with ACO routing," begins with a prominent title label styled in bold Helvetica font. Beneath this, a command label warns users that multiple files cannot be uploaded simultaneously. A disabled "Upload File" button, initially deactivated, allows users to upload a file, which upon successful upload, enables the "Scan" button and informs the user through a message box. The scan button, initially disabled, triggers a simulated scanning process that updates an adjacent label to display scanning status in red, then green upon completion. Scan results, including the number of files scanned and malware detection status, are displayed in a text widget below. For the ACO input, users are prompted to enter the number of nodes via a label and entry widget, with a "Submit" button executing the submit_number function, which includes network visualization and ACO operations. An exit button at the window's bottom allows users to close the application. The interface components are arranged using a grid layout for structured positioning, and the main window is sized at 600x700 pixels. This GUI integrates file upload, scanning animation, result display, and ACO configuration into a cohesive and interactive application.

GUI
def upload_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        print("Uploaded file:", file_path)
        scan_button.config(state=tk.NORMAL)
        messagebox.showinfo("File Uploaded", f"File Uploaded Successfully {file_path}, Click Scan to proceed with scanning")

def perform_scan():
    result_text.delete(1.0, tk.END)
    scan_animation_label.config(text="Scanning...", fg="red")
    root.update()
    time.sleep(3)  # Simulate scanning process
    scan_animation_label.config(text="File Scanned", fg="limegreen")
                        
    # Display scan results
    result_text.delete(1.0, tk.END)  # Clear previous results
    scan_result = f"Scan results: \n \nNumber Of Files scanned:1\n \nFiles passed through:  {n}\n \nFamily Of Malware Detected : NO Malware Detected"
    result_text.insert(tk.END, scan_result)
                                           
def exit_application():
    root.destroy()
                        
# Create the main window
root = tk.Tk()
root.title("Intrusion detection with ACO routing")
                       
# Create a stylish title label
title_label = tk.Label(root, text="Intrusion Detection system with ACO routing", font=('Helvetica', 20, 'bold'))
title_label.grid(row=0, column=0, columnspan=3, pady=10)
                        
# Create a label for the command
command_label = tk.Label(root, text="Multiple Number Of Files Cannot Be Uploaded at single time",fg="red")
command_label.grid(row=3, column=0, columnspan=3)
                        
# Create a button for uploading files
upload_button = tk.Button(root, text="Upload File", command=upload_file, state=tk.DISABLED, bg='gold', fg='white')
upload_button.grid(row=4, column=0, pady=10)
                        
# Create a button for performing scan
scan_button = tk.Button(root, text="Scan", command=perform_scan, state=tk.DISABLED, bg='limegreen')
scan_button.grid(row=4, column=1, pady=10)
                        
# Create a label for scan animation
scan_animation_label = tk.Label(root, text="")
scan_animation_label.grid(row=4, column=2, pady=10)
                      
# Create a text widget to display scan results
result_text = tk.Text(root, height=10, width=50)
result_text.grid(row=5, column=0, columnspan=3, pady=10)
                    
# Create a label for ACO input
label = tk.Label(root, text="Enter the number of nodes:")
label.grid(row=2, column=0)
                        
# Create an entry widget for ACO input
entry = tk.Entry(root)
entry.grid(row=2, column=1)
                     
# Create a submit button for ACO
submit_button = tk.Button(root, text="Submit", command=submit_number, bg="deepskyblue", fg="white")
submit_button.grid(row=2, column=2)
                        
# Create an exit button at the bottom of the window
exit_button = tk.Button(root, text="Exit", command=exit_application, bg='orangered')
exit_button.grid(row=6, column=1, pady=20)
                        
root.geometry("600x700+0+0")
                        
# Start the main event loop
root.mainloop()

Download Project

You can download the complete project files here. This project features a comprehensive implementation of Intrusion Detection Systems (IDS) using Ant Colony Optimization (ACO) techniques. It includes the source code that demonstrates how ACO can be applied to enhance the detection capabilities of IDS. Additionally, the project comes with a dataset virus, providing a practical example of how ACO can be utilized in real-world scenarios. The dataset contains various virus signatures and patterns, allowing for thorough testing and analysis of the IDS model. By working with these resources, you can gain insights into the application of optimization algorithms in cybersecurity and explore how they can improve threat detection mechanisms.

Download Project

NOTE: This zip file contains source code and virus dataset. Don't worry! it will not harm your system as it is developed for educational purposes.

Fullscreen View