Lesson 1 / 10
Module 1Lesson 1⏱ 50 min study

Lesson 1: Network Architecture, Raw Sockets & Multi-Threaded Port Scanning

Deconstruct the Berkeley sockets API, analyze TCP 3-way handshake mechanics, and engineer high-concurrency port scanners and service banner grabbers.

✦ Key Architectural Takeaways
  • •The Berkeley sockets API provides raw operating system primitives (AF_INET, SOCK_STREAM, SOCK_RAW) for layer-3 and layer-4 network programming.
  • •Full TCP Connect scanning completes the entire 3-way handshake (SYN -> SYN/ACK -> ACK), which leaves persistent traces in server access logs.
  • •Half-open SYN scanning initiates the handshake with SYN and tears it down immediately with RST upon receiving SYN/ACK, minimizing application-layer logging.
  • •Banner grabbing extracts application identity, service version, and operating system build information from the initial service response banner.
  • •High-performance reconnaissance requires non-blocking sockets (select / poll) or thread pooling to scan thousands of ports in parallel without blocking on timeouts.

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:

ARCHITECTURE DIAGRAMSYSTEM SCHEMATIC
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:

  1. 1Address Family (`af`): Defines the network layer addressing scheme. socket.AF_INET specifies IPv4 addressing (32-bit addresses), while socket.AF_INET6 specifies IPv6 (128-bit addresses). socket.AF_PACKET (Linux only) enables direct access to raw Layer 2 data link frames.
  2. 2Socket Type (`type`): Dictates the transport protocol semantics. socket.SOCK_STREAM designates a connection-oriented, sequenced, and reliable TCP byte stream. socket.SOCK_DGRAM establishes connectionless, unreliable UDP datagram delivery. socket.SOCK_RAW bypasses 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:

ARCHITECTURE DIAGRAMSYSTEM SCHEMATIC
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:

PYTHONSYSTEM SCHEMATIC
#!/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).