Creé un Escáner de Puertos desde Cero con Python
Introduction to Creating a Port Scanner with Python
Welcome and Equipment Update
- The speaker welcomes viewers to another video on their secondary channel, expressing hope that everyone is doing well.
- They mention acquiring a new camera lens, which they believe improves the video quality, making it more vivid and sharp.
Overview of the Video Content
- The main focus of the video is to teach viewers how to create a port scanner using Python, similar to Nmap but less complex.
- The speaker emphasizes that while Nmap has extensive features and parameters, this tutorial will focus on building an efficient port scanner inspired by Nmap's stealth scan mode.
Theory Behind Packet Creation
- Before diving into practical coding, the speaker highlights the importance of understanding certain theoretical aspects related to layers and encapsulation in networking.
- They aim for this lesson to provide deeper insights into how things work at a lower level in networking.
Setting Up the Environment
Initial Setup
- The speaker introduces their virtual machine setup running Arch Linux and prepares to demonstrate the scanning process.
Practical Demonstration: TCP Connect Scan
- They begin by showing how to perform a conventional TCP Connect Scan using Nmap on port 80 of their router's IP address.
- An explanation follows about packet transmission during this scan type, detailing the three-way handshake involving SYN, SYN ACK, and ACK packets.
Capturing Packets with T-Shark
Using T-Shark for Packet Analysis
- The speaker plans to capture packets using T-Shark after confirming that port 80 is open.
- They explain redirecting standard output (STDOUT) in T-Shark to avoid unnecessary warnings during packet capture.
Filtering Captured Packets
- To effectively capture relevant packets (SYN, SYN ACK, ACK), they discuss setting specific filters in T-Shark based on TCP flags.
Executing Scans and Capturing Responses
Configuring Filters for Specific Packets
- The speaker elaborates on configuring filters for capturing only desired packets like SYN or ACK by adjusting TCP flag settings accordingly.
Observing Packet Flow
- After launching scans with configured filters, they demonstrate capturing SYN packets successfully from their machine’s communication with the server.
Final Steps in Packet Capture
Completing the Handshake Process
- As part of completing the handshake process demonstration, they explain how to capture subsequent responses such as SYN ACK from the server.
This structured approach provides clarity on each segment discussed within the transcript while ensuring easy navigation through timestamps linked directly back to specific moments in the video.
Understanding TCP Port Scanning Techniques
Overview of Open and Closed Ports
- The discussion begins with an explanation of how to monitor responses when a port is open, emphasizing the importance of understanding these interactions.
- When sending a SYN packet to a closed port (e.g., port 83), the expected response is not a SYN-ACK but rather a different indication that the port is closed.
Analyzing Responses from Closed Ports
- If the port is closed, instead of receiving a SYN-ACK, one should expect to receive a RST (reset) packet. This information is crucial for scripting purposes.
- The reset ACK indicates that the connection attempt was unsuccessful due to the closed status of the port.
Stealth Scanning vs. TCP Connect Scan
- The concept of stealth scanning is introduced, which avoids leaving traces in logs by not completing the three-way handshake typical in standard connections.
- In stealth scanning, after sending a SYN and receiving a SYN-ACK, instead of sending an ACK to complete the handshake, a reset packet is sent.
Practical Implementation Steps
- To implement stealth scanning effectively, it’s essential to capture both SYN and RST packets during testing.
- A practical example illustrates how to set parameters for capturing packets using specific source and destination ports.
Setting Up the Scanning Script
- Emphasizing operational privileges: running scripts as root may be necessary for certain operations within network scanning tasks.
- The speaker discusses setting up a virtual environment with Python and installing necessary libraries like Scapy for crafting packets.
Developing the Scanner Functionality
- Initial setup involves creating functions that will handle target IP addresses and ports dynamically during scans.
- A loop structure will be implemented to scan through multiple ports (e.g., first 100 ports), checking their status based on previous discussions about open/closed responses.
Understanding Basic Encapsulation in Networking
Introduction to Encapsulation
- The concept of encapsulation is introduced, highlighting the layers involved, specifically the IP layer and TCP (Transmission Control Protocol) layer.
- Each protocol wraps around the previous one, illustrating how TCP is contained within the IP layer.
Building a Packet with Scapy
- The process of constructing a packet using Scapy is discussed, emphasizing the need to define both IP and TCP layers with specific values.
- The encapsulation in Scapy is represented visually with a bar indicating that TCP is nested within IP.
Key Parameters for Packet Construction
- Important parameters include destination IP (DST), which should be set to the target router's address.
- For TCP, source port needs to be defined as a random value above 1024 to avoid standard service ports; destination port is typically set to 80.
Finalizing Packet Details
- Additional details such as flags are specified; for example, setting it as SYN indicates it's part of an initial connection request.
- A random source port can be generated programmatically from available ranges (1024 - 65535).
Sending and Receiving Packets
- To send packets and await responses, Scapy's
SR1function is utilized. This allows sending a packet while waiting for an acknowledgment or response.
- Timeout settings can be adjusted to manage how long the script waits for a response before concluding whether a port is open or closed.
Handling Responses and Errors
- If no response is received (
None), it indicates that either the port is filtered or there was no reply at all.
- Error handling mechanisms are suggested for cases where responses do not contain expected attributes due to lack of communication.
Port Scanning Techniques
Understanding Port States
- The discussion begins with the importance of identifying various port states: open, filtered, closed, or unresponsive. The goal is to analyze all possible outcomes during a scan.
- A focus on TCP layer communication is introduced, emphasizing the need to capture SYN-ACK packets to determine responses accurately.
Capturing and Analyzing TCP Responses
- The method for checking if a captured response is a SYN-ACK involves examining specific flags in the TCP header (notably 0x12).
- If a SYN-ACK is received, it indicates an open port; thus, the next step would be sending a reset packet to terminate the connection gracefully.
Constructing Reset Packets
- Instructions are provided on how to construct a reset packet within both IP and TCP layers. This includes specifying source and destination ports.
- The reset packet's flag should be set correctly (e.g., 0x4), ensuring that it communicates effectively with the target system.
Interpreting Scan Results
- If no SYN-ACK is received but instead a RST ACK (reset acknowledgment), this indicates that the port is closed.
- A practical example illustrates scanning port 83 and receiving an RST ACK response as confirmation of its closed state.
Handling Unknown States
- In cases where neither open nor closed conditions are met, the status defaults to unknown. This highlights potential limitations in determining port states.
- A comparison with Nmap reveals that while this method may be stealthier than traditional scans, it lacks some of Nmap's comprehensive testing capabilities.
Finalizing Output Display
- Emphasis on displaying results clearly for each scanned port—showing whether they are open or closed based on responses received.
- Adjustments can be made to filter out unnecessary output noise by only reporting relevant findings such as open ports.
Enhancing User Experience
- Suggestions include refining output logic so that only meaningful data appears in results, improving clarity for users conducting scans.
Implementing Threads for Parallel Tasks
Introduction to Threading
- The speaker introduces the concept of implementing threads, emphasizing their ability to perform multiple tasks in parallel, which enhances speed and efficiency.
- A change in structure is necessary, particularly regarding ports, which will be represented as an iterable for use with the
mapfunction.
Setting Up Port Scanning
- The range for port scanning is set from 1 to 65535; however, only the first 100 ports are targeted for efficiency.
- The speaker discusses using a context manager with
concurrent.futures.ThreadPoolExecutor, allowing automatic closure of resources similar to file handling.
Executing Parallel Tasks
- Responses from concurrent tasks will be stored in a tuple containing relevant information about each task's execution.
- The
mapfunction requires two parameters: a function and an iterable (in this case, the list of ports).
Defining Functions and Lambda Expressions
- Each port will have an associated function defined by a lambda expression that processes individual ports.
- This anonymous function takes a parameter 'P' representing each port and performs operations on it.
Collecting Results
- The lambda function returns a tuple containing the port number and its state (open or closed), utilizing another function called
scanner.
- By passing target information along with the current port to the scanner function, it determines whether each port is open or closed.
Displaying Results
- A loop iterates through responses to display results only if there are valid outputs indicating that a port is open.
- If no valid response exists (e.g., "port closed"), those results are not displayed.
Performance Testing
- After implementing threading, performance testing shows significant speed improvements compared to sequential processing.
- Caution is advised when increasing concurrent tasks; too many may lead to false negatives regarding open ports.
Analysis of Network Performance
Overview of Network Scanning
- The speaker discusses the impact of increasing the number of ports scanned, noting that more extensive scanning can lead to worse results. A target of 100 ports is suggested as optimal for effective analysis.
- The focus shifts to examining the first 500 ports, with an emphasis on monitoring how long the scan takes. The speaker expresses confidence that it should not take much time.
- Specific ports, namely 53 and 80, are highlighted as significant in this context, indicating their relevance in network performance assessments.
Caution in Network Testing
- The speaker mentions a cautious approach to scanning due to sensitivity concerns with their internet service provider, Andorra Telecom. This highlights the importance of considering external factors when conducting network tests.
- As the video concludes, the speaker reflects on personal preparations for an upcoming dinner while expressing hope that viewers have learned from the content presented.