1. Network Communications & The Berkeley Sockets API
In offensive security, standard user-space tools like nmap and netcat are indispensable, but understanding the foundational operating system network stack allows security engineers to construct bespoke reconnaissance tools that bypass signature-based intrusion detection systems.
The Berkeley Sockets API serves as the universal operating system interface for network communication. A socket is an endpoint for bidirectional inter-process communication across a network:
Client Process Server Daemon
[ Application ] [ Application ]
| |
v (Socket API) v (Socket API)
[ TCP / IP Stack ] <====== Physical Cable / Wi-Fi =====> [ TCP / IP Stack ]When instantiating a socket in Python 3, two primary parameters dictate its behavior:
- 1Address Family (`af`): Defines the network layer addressing scheme.
socket.AF_INETspecifies IPv4 addressing (32-bit addresses), whilesocket.AF_INET6specifies IPv6 (128-bit addresses).socket.AF_PACKET(Linux only) enables direct access to raw Layer 2 data link frames. - 2Socket Type (`type`): Dictates the transport protocol semantics.
socket.SOCK_STREAMdesignates a connection-oriented, sequenced, and reliable TCP byte stream.socket.SOCK_DGRAMestablishes connectionless, unreliable UDP datagram delivery.socket.SOCK_RAWbypasses the transport layer, permitting manual header crafting.
2. Deconstructing the TCP Three-Way Handshake
Transmission Control Protocol (TCP) guarantees reliable data delivery across inherently unreliable IP networks through a stateful connection establishment ritual called the Three-Way Handshake:
Client (Initiator) Server (Listener)
| |
| ------------- 1. TCP SYN (Seq = X) ---------------> | [LISTEN]
| |
| <------ 2. TCP SYN-ACK (Seq = Y, Ack = X + 1) ----- | [SYN-RCVD]
[ESTAB] | |
| ------------- 3. TCP ACK (Seq = X + 1) -----------> | [ESTAB]
| |
| <============ Bidirectional Data Flow ============> |Scanning Paradigms: Full Connect vs. Half-Open SYN Scan
- Full TCP Connect Scan (`SOCK_STREAM`):
The scanner issues a system connect() call, completing all three steps of the handshake. While reliable and executable without administrative privileges, completing the handshake triggers the target daemon's application-layer logger (e.g., Apache, OpenSSH, or MySQL logs the incoming connection).
- Half-Open TCP SYN Stealth Scan:
The scanner transmits a raw TCP SYN packet. If the target port is open, the server responds with SYN-ACK. Instead of sending the concluding ACK, the scanner immediately transmits a RST (Reset) flag. The target operating system tears down the nascent half-open connection before handing it off to the listening daemon, completely avoiding application-level audit logging!
3. Engineering a Multi-Threaded Port Scanner in Python 3
A naive, sequential port scanner testing ports 1 through 1024 with a 1-second socket timeout takes over 17 minutes to complete. By utilizing Python's concurrent.futures.ThreadPoolExecutor, we can probe hundreds of ports concurrently within seconds:
#!/usr/bin/env python3
"""
High-Performance Multi-Threaded TCP Port Scanner & Banner Grabber
Author: Yehia Elghaly / Offensive Security Engineering
"""
import socket
import sys
from concurrent.futures import ThreadPoolExecutor
def grab_banner(target_host: str, target_port: int, timeout: float = 1.5) -> str:
"""Attempts to read the initial service identification banner."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(timeout)
sock.connect((target_host, target_port))
# Send generic probe to elicit banner for quiet protocols
sock.sendall(b"HEAD / HTTP/1.0\r\n\r\n")
banner = sock.recv(1024).decode('utf-8', errors='ignore').strip()
return banner.split('\n')[0] if banner else "No Banner"
except Exception:
return "Unknown Service"
def scan_port(target_host: str, target_port: int) -> None:
"""Probes a single TCP port and grabs banner if open."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(1.0)
result = sock.connect_ex((target_host, target_port))
if result == 0:
banner = grab_banner(target_host, target_port)
print(f"[+] Port {target_port:<5}/TCP : OPEN | Banner: {banner}")
except socket.error:
pass
def main():
target = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
ports = range(20, 1025)
max_workers = 100
print(f"[*] Commencing multi-threaded scan against: {target}")
print(f"[*] Thread Pool Concurrency: {max_workers} worker threads")
with ThreadPoolExecutor(max_workers=max_workers) as executor:
for port in ports:
executor.submit(scan_port, target, port)
if __name__ == "__main__":
main()The sock.connect_ex() method is critical here: rather than raising an unhandled socket.error exception when a port is closed (which induces massive Python interpreter overhead), it returns an integer C-level errno directly (returning 0 on success and 111 / WSAECONNREFUSED on failure).