Build Your First Port Scanner using Python
Tags: python, programming, cybersecurity, devops
Published: 2023-02-04 04:11:17


<p data-pm-slice="1 1 []">Cyber security has become necessary for every business today, with over seven websites created <strong>every second, 380 websites every minute, and 547,000 daily.</strong></p>
Security specialists at <a href="https://community.ibm.com/community/user/security/blogs/lissa-coffeey1/2020/11/30/global-website-hacking-statistics-in-2020#:~:text=How%20many%20websites%20are%20hacked,that%20are%20unwittingly%20distributing%20malware." target="_blank" rel="noopener noreferrer nofollow">IBM</a> cannot emphasize this importance enough, with the current statistics of <strong><em>30,000 websites being lost to hackers daily</em></strong>.

Learning how to build a port scanner and use it to find vulnerability/open ports in your website or infrastructure and see how to mitigate against hacks is critical.
<h4>What is a port scanner?</h4>
A port scanner is a network observation technique that tracks and identifies open and closed ports in an infrastructure.

A scanner can identify which infrastructure is running and what kind of program, like the Operating system, while listening to traffic.

Port scanners are said to be surveillance tools. When such surveillance is retrieved, they perform attacks on ports that listen for traffic, such as ports 80 and 443, and attacks such as DDOS attacks (Distributed Denial of Service), MITH attacks (Man in The Middle), and many others.
<h4>PING SCAN</h4>
This scan checks the network to see if the target is alive, and it sends an ICMP (<b>Internet</b><b> Control Message Protocol</b>) request to the target machine. When there is ICMP feedback, the target is active. However, firewalls and routers are enhanced to see and block these pings; accurate reading of the target machine/website might be difficult even if the target is alive.
<h4>TCP HALF-OPEN</h4>
The most widely used port scan, TCP HALF OPEN, scans many ports in seconds as it does not complete the TCP(Transmission Control Protocol) handshake of acknowledging the synchronization from the target machine.

The half handshake makes it faster to pick up which ports are open as the response from the SYN-ACK flag sent to the target will not be acknowledged by our scanner, which tells us the port is active and listening for traffic, but when we get an RST (reset), the port is alive but closed.
<h4>TCP CONNECT</h4>
TCP Connect functions almost like the half-open, but this time the connection is acknowledged by our scanner; while it is slow, it allows for a more accurate reading of the target infrastructure.
<h4>UDP</h4>
UDP (User Datagram Protocol) scan mainly detects ports 53, 161, and 67, which are DNS, DHCP, and SNMP; however, these scans are very slow as they wait for feedback that might never come.

<strong>Create your first scanner. </strong>

In creating our first scanner, you must have a few prerequisites.
<ul>
 	<li>Any code editor (Vs. Code)</li>
 	<li>basic understanding of python</li>
 	<li>if you do not have python installed on your machine, download one <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer nofollow noopener" data-target-href="https://www.python.org/downloads/">here</a></li>
</ul>
Find the code repo <a href="https://gist.github.com/Scofield-Idehen/d97c5709ac8347fd70b47f7744c75c9c" target="_blank" rel="noreferrer nofollow noopener" data-target-href="https://gist.github.com/Scofield-Idehen/d97c5709ac8347fd70b47f7744c75c9c">here</a> to get started.
Open your code editor and create a file name of scanner.py
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659850208245_new_day+1.PNG" /><figcaption></figcaption></figure>
Next, we start by importing our first library called socket.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659850814533_new_day+2.PNG" /><figcaption></figcaption></figure>
A socket is <b>an endpoint of communication between two programs on the network</b>. A socket is tied to a port number so the TCP layer can identify the application.

Next, we define our target = “IP/URL”

A target is the <b>destined URL/IP of the machine we intend to scan</b>. A target might be one or multiple targets.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659851013445_new_day+3.PNG" /><figcaption></figcaption></figure>
Next, we define a function, call an argument of port, and say try; if it does not work, return false.

Here we said the socket type. AF_INET is the Internet address structure for <a href="https://en.wikipedia.org/wiki/IPv4" target="_blank" rel="noreferrer nofollow noopener" data-target-href="https://en.wikipedia.org/wiki/IPv4">IPv4</a>. SOCK_STREAM is the socket type for <a href="https://realpython.com/python-sockets/#tcp-sockets" target="_blank" rel="noreferrer nofollow noopener" data-target-href="https://realpython.com/python-sockets/#tcp-sockets">TCP</a> protocol for transporting messages in the network.

Next line, we said to connect to the target IP and ports in that IP, and if it does, it returns true when there is an exception, it returns false.

Next, we create our output data.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659865782262_updated_new.PNG" /><figcaption></figcaption></figure>
Here we said that for the first <b>1020 ports</b>, the most critical ports, scan them and show output if the ports are open or closed.

Our scanner is ready. Let us test it.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659852722587_new_day+5.PNG" /></figure>
Here we see the open ports, but it might take some while to get this done as it is a bit slow, and very few people build ports like this today.

Let us, therefore, remove the last part of our code and import a new <b>library</b> called <b>Threading</b> and <b>Queue.</b> Threading allows us to run multiple threads simultaneously, saving time, while Queue allows each port scan to be kept in a queue list.

Delete the last line in your code, as we will not be building our scanner this way. Let us import the following modules.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659866133655_udate_new.PNG" /><figcaption></figcaption></figure>
Notice we also created a list for all the ports in the Queue, and we will see how it ties up at the end. We also created an array for the ports.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659866495789_updated_new2.PNG" /><figcaption></figcaption></figure>
We created a new method called fill_queue which we called an argument that for every port scanned in the `list_port`, it should be queued and put in our queue list.
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659867864234_updated_create.PNG" /><figcaption></figcaption></figure>
Here we specify that if our queue is not empty, our scanner should get a port from the scanner(port) and print if the port is open.

Append the port to the array we created called ope_port .
<figure><img src="https://paper-attachments.dropboxusercontent.com/s_A76048B556D29DB039C74137054593F69DB012613D132CCA382D76B5996EF21D_1659869965546_final_user_1.PNG" /><figcaption></figcaption></figure>
Next, we said list_port = range(1, 100)  which means the number of the port that our scanner should scan should be 100 for every list and in a queue, and after checking a port, that port should be added to the list_port

Next, we created a new thrend_list to target the threads.
<pre><code spellcheck="false"> for sc in range(10): </code></pre>
<code spellcheck="false">
</code>
Here we specify that for scan in a thread, it should scan ten ports at once, and this scan should target the worker, which is where we set the scan syntax.

After scanning, it should append the scanned port to the thread_list

Next, we begin the thread by starting it.

Next, we join the thread together and print the output.
<h4>Conclusion</h4>
This article taught us how to create a port scanner and the steps to take to build a comprehensive and scalable scanner.

Please check the following resources if you require further help becoming a better python developer.
<h4>Resource</h4>
<ul>
 	<li><a href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noreferrer nofollow noopener" data-target-href="https://www.python.org/about/gettingstarted/">Python</a></li>
 	<li><a href="http://datacamp.com" target="_blank" rel="noreferrer nofollow noopener" data-target-href="http://datacamp.com">Datacamp</a></li>
 	<li><a href="http://blog.learnhub.africa">LearnHub</a></li>
</ul>