iTranslated by AI
Building a Custom Port Scanner from Scratch for My Summer Project (Part 3: Implementation)
Background
- It's summer, so I want to build my own Port Scanner -> I'll introduce the process of creating my_portscanner.
- In the Technology Selection article, I considered what technologies to use for building a custom Port Scanner.
- In the Development Environment Setup article, I set up the development environment for the Port Scanner.
- This time, I will be implementing the Port Scanner.
Before Implementation
Packaging Python
By imitating the structure of yt-dlp, I was able to package it nicely.
The overall structure looks like this:
$ pwd
/home/tomita/my_portscanner/src
$ tree
.
├── my_portscanner
│ ├── get_datetime.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── options.py
│ ├── scan_tools
│ │ ├── ConnectScan.py
│ │ ├── __init__.py
│ │ ├── Scan.py
│ │ └── SynScan.py
│ └── version.py
└── tests
├── __init__.py
├── scan_tools
│ ├── __init__.py
│ ├── test_ConnectScan.py
│ └── test_SynScan.py
├── test_get_datetime.py
└── test_options.py
The general usage image is:
-
After
rye build, it can be executed as follows:my_portscanner localhost -sS -
my_portscannerexecutessrc/my_portscanner/__main__.py.import my_portscanner if __name__ == "__main__": my_portscanner.main() -
The
mainfunction insrc/my_portscanner/__init__.pyis executed. The entire process is written in the main function.
I made an effort to move detailed processing externally so that the main function in __init__.py doesn't become bloated, which would make the overall flow hard to follow and difficult to test.
For instance, options.py uses the argparse library to handle arguments.
I made the arguments similar to nmap, such as -sS and -sT, to make them easy to remember. It's a common issue with custom tools: you think the arguments you've designed are the coolest thing in the world while you're building it, but you completely forget them a few months later, haha.
Using rye for builds
Using rye build creates the packaged Python package in dist/.
rye build
ls dist
my_portscanner-0.1.0-py3-none-any.whl my_portscanner-0.1.0.tar.gz
Implementation of the Port Scan Part
Class Structure
- I decided to focus on two scan methods: Connect Scan and Syn Scan.
- Thinking about potentially adding other scan methods in the future, I extracted the common parts to a
Scanclass and had each scan class inherit from it.
Using the composition pattern would probably look cleaner than inheritance, but it seemed like a hassle, so I went with inheritance.
├── my_portscanner
│ ├── scan_tools
│ │ ├── ConnectScan.py
│ │ ├── __init__.py
│ │ ├── Scan.py
│ │ └── SynScan.py
│ ├── __init__.py
│ ├── __main__.py
About Each Scan Method
Looking at the code is the fastest way to understand, but since that might be hard to grasp, please refer to the nmap documentation for reference.
Building the Scan Part
Writing the code all at once makes it difficult to understand, so I started small, built a basic version, and packaged it so it could be called externally.
- Connect Scan
import socket
target_ip = 127.0.0.1
target_port = 22
s = socket.socket()
errno = s.connect_ex((target_ip, target_port))
s.close()
if errno == 0:
print(f"TCP port {target_port} is open")
else:
print(f"TCP port {target_port} is closed")
- SYN Scan
from scapy.all import IP, TCP, sr1
target_ip = 127.0.0.1
target_port = 22
# Create SYN packet
syn_packet = IP(dst=target_ip)/TCP(dport=target_port, flags="S")
response_packet = sr1(syn_packet)
# If a SYN/ACK packet is returned, judge the port as open
if (response_packet.haslayer(TCP) and
response_packet[TCP].flags == "SA"):
print(f"TCP port {target_port} is open")
else:
print(f"TCP port {target_port} is closed")
After learning how the libraries work like this, I turned them into classes so they could be called from __init__.py.
Enabling Argument Handling
├── my_portscanner
│ ├── scan_tools
│ │ ├── ConnectScan.py
│ │ ├── __init__.py
│ │ ├── Scan.py
│ │ └── SynScan.py
│ ├── __init__.py
│ ├── __main__.py
│ ├── options.py ☆new☆
I added options.py to handle argument processing.
I used the argparse library for this purpose.
Creating Tests
It seems that tests can be executed using rye test.
rye test searches for test_*.py files under the tests directory and executes them.
I performed tests by mocking the network communication parts. I used unittest.mock as the mock library, but if you use pytest, mocking might be even simpler. Since this was my first time writing mocks in unittest, implementing unit tests was the hardest part.
As this is a hobby project, I didn't aim for 100% coverage, sticking instead to verifying that each function works correctly.
from io import StringIO
import sys
import unittest
from unittest.mock import patch, MagicMock
from my_portscanner.scan_tools.ConnectScan import ConnectScan
class TestConnectScan(unittest.TestCase):
def setUp(self):
"""
Executed before every test,
creates a mocked instance of socket.socket.
"""
# Common test data
self.target_ip = "192.168.150.2"
self.target_port_list = [22, 80, 443]
self.expected_open_ports = [22, 443]
# Create mock_socket_instance
self.mock_socket_instance = MagicMock()
# Set return value for connect_ex
def connect_ex_side_effect(address):
ip, port = address
if port in self.expected_open_ports:
return 0 # open
else:
return 1 # close
self.mock_socket_instance.connect_ex.side_effect = connect_ex_side_effect
return
@patch("my_portscanner.scan_tools.ConnectScan.socket.socket")
def test_run(self, mock_socket):
mock_socket.return_value = self.mock_socket_instance
scan = ConnectScan(
target_ip=self.target_ip, target_port_list=self.target_port_list
)
open_ports = scan.run()
self.assertEqual(open_ports, self.expected_open_ports)
@patch("my_portscanner.scan_tools.ConnectScan.socket.socket")
def test_print_result(self, mock_socket):
mock_socket.return_value = self.mock_socket_instance
scan = ConnectScan(
target_ip=self.target_ip, target_port_list=self.target_port_list
)
scan.run()
# Capture standard output
captured_output = StringIO()
sys.stdout = captured_output
# Execute print_result method
scan.print_result()
# Get content from standard output
sys.stdout = sys.__stdout__
output = captured_output.getvalue().strip()
# Expected output
expected_output = "PORT STATE SERVICE\n22/tcp open unknown\n443/tcp open unknown"
self.assertEqual(output, expected_output)
if __name__ == "__main__":
unittest.main()
I have included the ConnectScan test as an example. By creating a mocked instance of socket.socket and setting a side_effect to return an "open" response for pre-set ports when connect_ex is called, you can test each function of ConnectScan without actually performing communication.
This testing approach is similar to what is known as the "London School".
Reference: Schools of Unit Testing
Completion and Future Activities
Here is the current completed product:
my_portscanner
Additional items I implemented include:
- Automating testing, releasing, and distribution to the Docker Container Registry using GitHub Actions
- Improving documentation
- Writing proper exception handling
- Improving to allow more detailed scanning
- And more.
In the future, I would like to continue implementing ideas that come to mind, such as asynchronous processing usingasync awaitand adding other scanning methods.
Discussion