Python for Cybersecurity: Building a Network Scanner

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up
  4. Building the Network Scanner
  5. Conclusion

Introduction

In this tutorial, we will explore how to build a network scanner using Python. Network scanning is an important tool in cybersecurity that allows you to discover devices, services, and vulnerabilities in a network. By the end of this tutorial, you will have a basic understanding of network scanning concepts and be able to create your own network scanner using Python.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming. It is recommended to have Python 3 installed on your machine. Additionally, some knowledge of networking concepts such as IP addresses, ports, and sockets would be beneficial but not necessary.

Setting Up

Before getting started, let’s set up our Python environment and install any required libraries.

  1. Install Python 3: Visit the Python website and download the latest version of Python 3 for your operating system. Follow the installation instructions provided by the Python installer. Verify the installation by opening a terminal or command prompt and running the command python3 --version. You should see the version number printed on the screen.

  2. Install Scapy Library: Scapy is a powerful Python library used for network packet manipulation. To install Scapy, open your terminal or command prompt and run the command pip install scapy. This will download and install the Scapy library along with its dependencies.

Now that we have our Python environment set up, we can proceed to build our network scanner.

Building the Network Scanner

Step 1: Importing Required Libraries

Let’s start by importing the necessary libraries. Open your favorite text editor or integrated development environment (IDE) and create a new Python file. Name it network_scanner.py, and add the following code: ```python from scapy.all import ARP, Ether, srp

# TODO: Add the rest of the code
``` Here, we import the `ARP` and `Ether` classes from Scapy, which will help us construct ARP packets. We also import the `srp` function, which allows us to send and receive packets at the same time.

Step 2: Retrieving Network Interface

The next step is to retrieve the network interface details that we will be using for scanning. This will allow us to select the correct network interface in case we have multiple interfaces. Add the following code to your network_scanner.py file: ```python import os

def get_interface():
    # Get the names of all network interfaces
    interfaces = os.listdir('/sys/class/net/')
    
    print("Available Interfaces:")
    for index, interface in enumerate(interfaces, start=1):
        print(f"{index}. {interface}")
    
    while True:
        try:
            choice = int(input("Select the interface to use: "))
            selected_interface = interfaces[choice-1]
            break
        except (ValueError, IndexError):
            print("Invalid choice. Please try again.")
    
    return selected_interface

# Call the get_interface function
interface = get_interface()

# TODO: Add the rest of the code
``` In this code, we first import the `os` module to retrieve the network interface names. We define a function `get_interface` to interactively ask the user to choose an interface from the available options. The selected interface is then returned by the function. We also call the `get_interface` function and store the returned value in the variable `interface`.

Step 3: Scanning the Network

Now, we can proceed to scan the network for devices. Add the following code to your network_scanner.py file: ```python def scan_network(interface): # Create an ARP request packet arp_request = Ether(dst=”ff:ff:ff:ff:ff:ff”) / ARP(pdst=”192.168.1.1/24”)

    # Send and receive packets
    result = srp(arp_request, timeout=3, verbose=0, iface=interface)[0]
    
    # Process the response
    devices = []
    for sent, received in result:
        devices.append({'ip': received.psrc, 'mac': received.hwsrc})
    
    return devices

# Call the scan_network function
devices = scan_network(interface)

print("Scanned Devices:")
for device in devices:
    print(f"IP: {device['ip']}, MAC: {device['mac']}")

# TODO: Add the rest of the code
``` Here, we define a function `scan_network` that takes the network interface as a parameter. Inside the function, we create an ARP request packet using the target IP range (e.g., `192.168.1.1/24`) and the broadcast MAC address. We then use the `srp` function to send and receive ARP packets, specifying a timeout of 3 seconds and setting the interface to the selected interface.

After receiving the response, we process the packets and extract the IP and MAC addresses of the devices. We store this information in a list of dictionaries named devices. Finally, we print the scanned devices to the console.

Step 4: Executing the Network Scanner

We are now ready to execute our network scanner. Add the following code to your network_scanner.py file: ```python if name == “main”: print(“Starting Network Scanner…”) print(f”Using Interface: {interface}”)

    devices = scan_network(interface)
    
    print("Scanned Devices:")
    for device in devices:
        print(f"IP: {device['ip']}, MAC: {device['mac']}")
``` In this code, we use the `if __name__ == "__main__":` construct to ensure that the code inside this block only runs when the script is executed directly, not when it is imported as a module. We print a starting message and mention the interface being used. We then call the `scan_network` function and print the scanned devices to the console.

Conclusion

Congratulations! You have successfully built a network scanner using Python and the Scapy library. Network scanning is a fundamental tool in cybersecurity, allowing you to identify devices and potential vulnerabilities in a network. By understanding the concepts covered in this tutorial, you can further enhance the network scanner or even build more advanced cybersecurity tools using Python.

In this tutorial, we covered the basics of building a network scanner, including importing required libraries, retrieving the network interface, scanning the network, and executing the scanner. We also learned about the Scapy library and its usage in constructing and sending ARP packets.

Now that you have a fundamental understanding of network scanning in Python, feel free to explore more advanced features and techniques. Experiment with different IP ranges, modify the scanned device information, or integrate the scanner into a larger cybersecurity project.

Keep learning and experimenting with Python, as it is a powerful language with a wide range of applications in the cybersecurity field and beyond!