โ† Back to home
Python Sockets Requests Automation CVE DevSecOps
Intermediate

Custom Vulnerability Scanner (Python)

Oct 5, 2024

Creating your own vulnerability scanner gives you absolute control over your audits. Unlike heavy commercial solutions, a Python scanner can be lightweight, stealthy, and tailored to search for specific attack vectors. In this guide, we will build a modular scanner architecture.

1. Networking Basics: Port Scanning with Sockets

The core of any scanner is discovering open doors. We use Python's native socket library to attempt a TCP 3-Way Handshake.

import socket
from concurrent.futures import ThreadPoolExecutor

def scan_port(ip, port):
    # AF_INET for IPv4, SOCK_STREAM for TCP
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(1.0) # Avoid hanging indefinitely
            if s.connect_ex((ip, port)) == 0:
                print(f"[+] Port {port} OPEN")
                return port
    except Exception:
        pass
    return None

# Use multithreading for speed
target = "10.10.10.50"
with ThreadPoolExecutor(max_workers=50) as executor:
    for port in range(1, 1024):
        executor.submit(scan_port, target, port)

2. Banner Grabbing (Version Extraction)

Knowing port 22 is open isn't enough; we need the SSH version to cross-reference with CVE databases.

def grab_banner(ip, port):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(2.0)
            s.connect((ip, port))
            banner = s.recv(1024).decode().strip()
            print(f"[+] Banner on {port}: {banner}")
    except Exception as e:
        pass

3. Web Analysis with Requests

We delegate HTTP/HTTPS scanning to the requests library to search for insecure headers or exposed paths.

import requests

def analyze_headers(url):
    try:
        # verify=False is useful for local self-signed certs
        response = requests.get(url, timeout=5, verify=False)
        headers = response.headers
        
        security_headers = ['Strict-Transport-Security', 'X-Frame-Options']
        for header in security_headers:
            if header not in headers:
                print(f"[!] ALERT: Missing {header} header")
    except requests.exceptions.RequestException:
        pass

๐Ÿ”ด Secure Development Simulator

Our Python scanner's HTTP module is crashing in production. As the Lead Developer, you must debug the code, identify the correct requests and sockets parameters, and ensure the tool audits correctly.

>_ START CTF 12 CHALLENGE

4. Architecture & Performance