### Layer Configuration Examples Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Examples of initializing WinDivert with different layer options. ```python # Capture IP packets (default) w = pydivert.WinDivert("tcp", layer=pydivert.Layer.NETWORK) # Capture connection flows (requires WinDivert 2.2+) w = pydivert.WinDivert("tcp", layer=pydivert.Layer.FLOW) # Monitor socket events (requires WinDivert 2.2+) w = pydivert.WinDivert("tcp", layer=pydivert.Layer.SOCKET) # Monitor forwarded packets w = pydivert.WinDivert("ip", layer=pydivert.Layer.NETWORK_FORWARD) ``` -------------------------------- ### Flag Configuration Examples Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Examples of initializing WinDivert with different flag options. ```python # Sniff mode (non-blocking, original traffic continues) w = pydivert.WinDivert("tcp", flags=pydivert.Flag.SNIFF) ``` -------------------------------- ### Install PyDivert using uv Source: https://github.com/ffalcinelli/pydivert/blob/main/README.md Install PyDivert using uv, a fast Python package installer. Ensure uv is installed and configured. ```bash uv add pydivert ``` -------------------------------- ### Install PyDivert Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md Install the PyDivert library using pip. ```bash pip install pydivert ``` -------------------------------- ### Priority Configuration Examples Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Examples of setting different priority levels for WinDivert capture handles. ```python # High priority handle (sees packets first) capture_first = pydivert.WinDivert("tcp", priority=100) # Lower priority (sees packets after higher priority) inspect_later = pydivert.WinDivert("tcp", priority=50) # Negative priority (sees packets last) log_only = pydivert.WinDivert("tcp", priority=-100) ``` -------------------------------- ### WinDivert Initialization Examples Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Demonstrates initializing WinDivert with different filter configurations. ```python # Capture HTTP only w = pydivert.WinDivert("tcp.DstPort == 80") # Capture HTTPS w = pydivert.WinDivert("tcp.DstPort == 443") # Capture everything w = pydivert.WinDivert("true") # Deny specific source w = pydivert.WinDivert("ip.SrcAddr != 1.2.3.4") # Block DNS queries w = pydivert.WinDivert("udp.DstPort == 53", flags=pydivert.Flag.DROP) ``` -------------------------------- ### Install PyDivert for Development Source: https://github.com/ffalcinelli/pydivert/blob/main/GEMINI.md Installs PyDivert with extra dependencies for development, testing, documentation, linting, and type checking using uv. ```bash uv sync --extra test --extra docs --extra lint --extra typecheck ``` -------------------------------- ### Filter Examples Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Examples of WinDivert filter strings for various network traffic patterns. ```python # Protocol filters "tcp" # All TCP packets "udp" # All UDP packets "tcp and udp" # Both TCP and UDP "icmp" # ICMP packets "ip" # All IP packets # Port filters "tcp.DstPort == 80" # HTTP traffic (destination) "tcp.SrcPort == 22" # SSH source "tcp.DstPort in [80, 443, 8080]" # Multiple ports # IP address filters "ip.SrcAddr == 192.168.1.1" # From specific IP "ip.DstAddr == 8.8.8.8" # To specific IP "ip.SrcAddr == 192.168.0.0/16" # Subnet match # Complex filters "tcp.DstPort == 80 and ip.SrcAddr == 192.168.1.0/24" "(tcp and tcp.DstPort in [80, 443]) or (udp and udp.DstPort == 53)" # Payload filters "tcp.PayloadLength > 0" # Has payload "ip.TTL < 64" # Low TTL ``` -------------------------------- ### Minimum Packet Capture Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md A basic example demonstrating how to capture a single TCP packet and print its source address and port. ```python import pydivert with pydivert.WinDivert("tcp") as w: packet = w.recv() print(f"Captured: {packet.src_addr}:{packet.src_port}") w.send(packet) ``` -------------------------------- ### PyDivert Documentation Structure Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/README.md This section details the organization of the PyDivert documentation, including core API references, types, configuration, utilities, and usage patterns. It also provides a quick lookup guide and common task examples. ```APIDOC ## PyDivert Documentation Overview This document provides a structured guide to the PyDivert technical reference documentation. ### Core API Reference - **[windivert.md](windivert.md)**: WinDivert class reference (constructor, methods like open(), close(), recv(), send(), static methods, context manager, iterator support, signatures, examples). - **[packet.md](packet.md)**: Packet class reference (constructor, properties, metadata, network/transport access, convenience properties, checksum handling, filter matching, pattern matching). - **[packet_headers.md](packet_headers.md)**: Network protocol headers reference (IPv4Header, IPv6Header, TCPHeader, UDPHeader, ICMPHeader classes, property tables, examples). ### Types and Configuration - **[types.md](types.md)**: Enumerations and constants (Layer, Flag, RecvFlag, Param, Direction, Protocol, CalcChecksumsOption enums, value tables, bitwise operations). - **[configuration.md](configuration.md)**: Constructor options and runtime parameters (WinDivert() parameters, filter syntax, layer selection, priority, flag combinations, runtime tuning, common patterns). ### Utilities and Patterns - **[service_management.md](service_management.md)**: Service control reference (is_registered(), stop_service(), register(), unregister() methods, Windows API details, fallbacks, permissions). - **[examples_patterns.md](examples_patterns.md)**: Usage patterns and examples (15 common patterns, anti-patterns, best practices, performance, typical tasks). ### Document Structure Format Each API reference document follows a consistent format: ``` # Class/Module Name ## Overview Brief description and import path ## Constructor/Function Signature Complete signature with type hints ## Parameters Table | Name | Type | Default | Description | ## Return Value Type and description ## Example Code Realistic usage examples ## Properties/Methods Full reference for each public member ## Source Reference File paths and line numbers ``` ### Quick Lookup Guide - **WinDivert usage**: [windivert.md](windivert.md) - **Packet data access**: [packet.md](packet.md) - **Header access**: [packet_headers.md](packet_headers.md) - **Enums**: [types.md](types.md) - **Configuration**: [configuration.md](configuration.md) - **Code examples**: [examples_patterns.md](examples_patterns.md) - **Service management**: [service_management.md](service_management.md) ### Common Tasks Examples - **Capture HTTP traffic**: [INDEX.md - Capture HTTP Traffic](INDEX.md#capture-http-traffic), [examples_patterns.md - Basic Packet Capture](examples_patterns.md#1-basic-packet-capture-and-re-injection) - **Block specific IPs**: [configuration.md - Flag.DROP](configuration.md#flag), [examples_patterns.md - Traffic Filtering](examples_patterns.md#2-traffic-filtering-block-specific-ips) - **Modify packet payload**: [packet.md - payload property](packet.md#payload), [examples_patterns.md - Payload Modification](examples_patterns.md#4-payload-modification) - **Use async processing**: [windivert.md - recv_async/send_async](windivert.md#recv_async), [examples_patterns.md - Async Processing](examples_patterns.md#9-async-processing) - **Validate filter syntax**: [windivert.md - check_filter](windivert.md#check_filter), [examples_patterns.md - Filter Validation](examples_patterns.md#13-filter-validation-before-use) ``` -------------------------------- ### Minimum Payload Modification Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md A concise example for intercepting TCP packets, searching for a specific byte string in the payload, and replacing it. ```python import pydivert with pydivert.WinDivert("tcp.PayloadLength > 0") as w: for packet in w: if packet.payload and b"secret" in packet.payload: packet.payload = packet.payload.replace(b"secret", b"REDACTED") w.send(packet) ``` -------------------------------- ### Packet Direction Usage Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Demonstrates how to use the Direction enumeration to check packet direction and log traffic information. ```python with pydivert.WinDivert("tcp.DstPort == 80") as w: for packet in w: if packet.direction == pydivert.Direction.OUTBOUND: print(f"Request: {packet.src_addr}:{packet.src_port} -> {packet.dst_addr}:{packet.dst_port}") else: print(f"Response: {packet.dst_addr}:{packet.dst_port} <- {packet.src_addr}:{packet.src_port}") w.send(packet) ``` -------------------------------- ### Protocol Identification Usage Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Shows how to use the Protocol enumeration to identify and log TCP, UDP, or ICMP packets. ```python with pydivert.WinDivert("true") as w: for packet in w: ipproto, offset = packet.protocol if ipproto == pydivert.Protocol.TCP: print(f"TCP: {packet.src_port} -> {packet.dst_port}") elif ipproto == pydivert.Protocol.UDP: print(f"UDP: {packet.src_port} -> {packet.dst_port}") elif ipproto == pydivert.Protocol.ICMP: print("ICMP") w.send(packet) ``` -------------------------------- ### Minimum Packet Drop Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md Demonstrates dropping all traffic from a specific IP address using the `Flag.DROP` option within a context manager. ```python import pydivert # Drop all traffic from specific IP with pydivert.WinDivert( "ip.SrcAddr == 1.2.3.4", flags=pydivert.Flag.DROP ) as w: for packet in w: pass # Packet is dropped ``` -------------------------------- ### Basic Packet Capture and Send Example Source: https://github.com/ffalcinelli/pydivert/blob/main/docs/index.html Demonstrates how to open a WinDivert handle, capture packets, and send them back into the network stack. This is useful for inspecting and manipulating network traffic. ```python with pydivert.WinDivert() as w: for packet in w: print(packet) w.send(packet) ``` -------------------------------- ### IntFlag Bitwise Operations Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Demonstrates how to perform bitwise operations on IntFlag enums, such as combining, checking, and removing flags. ```python # Combine flags flags = pydivert.Flag.SNIFF | pydivert.Flag.FRAGMENTS # Check if flag is set if flags & pydivert.Flag.SNIFF: print("Sniff mode enabled") # Remove flag flags &= ~pydivert.Flag.SNIFF ``` -------------------------------- ### Run PyDivert Tests in Vagrant VM Source: https://github.com/ffalcinelli/pydivert/blob/main/GEMINI.md Starts a Vagrant VM and runs the PyDivert tests within it, setting the UV_PROJECT_ENVIRONMENT and changing directory. ```bash vagrant powershell -c '$env:UV_PROJECT_ENVIRONMENT="C:/pydivert_venv"; cd C:/pydivert; uv run pytest' ``` -------------------------------- ### is_registered Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Checks if the WinDivert service is currently installed and registered on the system. ```APIDOC ## is_registered() ### Description Checks if the WinDivert service is currently installed and registered on the system. ### Method Signature ```python @staticmethod def is_registered() -> bool ``` ### Returns bool - True if service is registered, False otherwise ### Example ```python if pydivert.WinDivert.is_registered(): print("WinDivert is ready") else: print("WinDivert not installed") ``` ``` -------------------------------- ### Recalculate Checksums Usage Example Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Demonstrates how to use CalcChecksumsOption to recalculate packet checksums, excluding specific protocols like TCP. ```python from pydivert import CalcChecksumsOption packet = w.recv() # Recalculate all checksums except TCP packet.recalculate_checksums( flags=CalcChecksumsOption.NO_TCP_CHECKSUM ) w.send(packet, recalculate_checksum=False) # Recalculate multiple selectively packet.recalculate_checksums( flags=CalcChecksumsOption.NO_TCP_CHECKSUM | CalcChecksumsOption.NO_UDP_CHECKSUM ) ``` -------------------------------- ### Async Packet Processing Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/README.md This example demonstrates asynchronous packet processing using `recv_async` and `send_async`. It's suitable for high-throughput scenarios where non-blocking operations are crucial. ```python import asyncio from pydivert import WinDivert async def main(): w = WinDivert() await w.open() async def process_packet(packet): # Process packet asynchronously await w.send(packet) await w.recv_async(callback=process_packet) asyncio.run(main()) ``` -------------------------------- ### Get Packet Representation Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Returns a detailed string representation of the packet, showing all its fields. ```python packet = w.recv() print(repr(packet)) # Packet({'ipv4': {...}, 'tcp': {...}, ...}) ``` -------------------------------- ### Get and Set Runtime Parameters Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Query and modify runtime parameters like queue length, time, and size using get_param() and set_param(). Adjust these to optimize performance and memory usage. ```python with pydivert.WinDivert("true") as w: # Get current values queue_len = w.get_param(pydivert.Param.QUEUE_LEN) queue_time = w.get_param(pydivert.Param.QUEUE_TIME) queue_size = w.get_param(pydivert.Param.QUEUE_SIZE) # Set new values w.set_param(pydivert.Param.QUEUE_LEN, 2048) w.set_param(pydivert.Param.QUEUE_TIME, 1024) ``` -------------------------------- ### Get and Set Packet Direction Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Illustrates how to check the direction of a packet (inbound or outbound) and how to change it before sending the packet. ```python packet = w.recv() if packet.direction == pydivert.Direction.OUTBOUND: print("Outbound packet") else: print("Inbound packet") # Change direction packet.direction = pydivert.Direction.INBOUND w.send(packet) ``` -------------------------------- ### Using RecvFlag for Non-blocking Receive Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Example showing how to use RecvFlag.NO_BLOCK with the recv_ex() method for non-blocking packet reception. This allows the program to continue execution if no packet is immediately available. ```python # Non-blocking receive from pydivert import RecvFlag with pydivert.WinDivert("true") as w: packet = w.recv_ex(flags=RecvFlag.NO_BLOCK) if packet: print(f"Received: {packet}") else: print("No packet available") ``` -------------------------------- ### Combine Multiple Flags Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Combine SNIFF, FRAGMENTS, and NO_INSTALL flags for advanced traffic capture and control. NO_INSTALL prevents automatic driver installation. ```python w = pydivert.WinDivert( "tcp", flags=pydivert.Flag.SNIFF | pydivert.Flag.FRAGMENTS | pydivert.Flag.NO_INSTALL ) ``` -------------------------------- ### interface Property Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Gets or sets the interface index and sub-interface index where the packet was captured. ```APIDOC ## interface ### Description The interface index and sub-interface index where the packet was captured. ### Type tuple[int, int] - (if_idx, sub_if_idx) ### Example ```python packet = w.recv() if_idx, sub_if_idx = packet.interface print(f"Captured on interface {if_idx}.{sub_if_idx}") # Modify for re-injection packet.interface = (2, 0) w.send(packet) ``` ``` -------------------------------- ### Get and Set Packet Interface Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Shows how to access the capture interface details (index and sub-index) of a packet and how to modify it before re-injecting the packet. ```python packet = w.recv() if_idx, sub_if_idx = packet.interface print(f"Captured on interface {if_idx}.{sub_if_idx}") # Modify for re-injection packet.interface = (2, 0) w.send(packet) ``` -------------------------------- ### Create WinDivert Handle with Filter Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Instantiate WinDivert to capture packets matching a specific filter. This example captures TCP traffic destined for port 80 and re-injects it. ```python import pydivert # Capture only HTTP traffic with pydivert.WinDivert("tcp.DstPort == 80") as w: for packet in w: print(f"Captured: {packet}") w.send(packet) ``` -------------------------------- ### Parse ICMPv6 Packet Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet_headers.md Example of receiving an ICMPv6 packet and printing its type. Use the 'icmpv6' filter when opening WinDivert. ```python with pydivert.WinDivert("icmpv6") as w: packet = w.recv() if packet.icmpv6: print(f"ICMPv6 Type: {packet.icmpv6.type}") ``` -------------------------------- ### is_registered() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/service_management.md Checks if the WinDivert service is currently installed and registered on the system using the Windows Service Control Manager (SCM) API. ```APIDOC ## is_registered() ### Description Checks if the WinDivert service is currently installed and registered on the system using the Windows Service Control Manager (SCM) API. ### Method `pydivert.WinDivert.is_registered()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pydivert import WinDivert if WinDivert.is_registered(): print("WinDivert is installed") else: print("WinDivert not found") ``` ### Response #### Success Response - **bool**: True if service is registered, False otherwise #### Response Example ```json true ``` ### Raises None (returns False on error) ``` -------------------------------- ### get_param() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Retrieves a WinDivert parameter value. Used to get configuration values like queue length or time. ```APIDOC ## get_param() ### Description Retrieves a WinDivert parameter value. ### Method Signature ```python def get_param(self, name: Param) -> int ``` ### Parameters #### Parameters - **name** (Param) - Required - Parameter name (e.g., Param.QUEUE_LEN, Param.QUEUE_TIME, Param.QUEUE_SIZE). ### Returns - int - the parameter value. ### Raises - RuntimeError - if handle is not open. - OSError - on WinDivert driver error. ### Example ```python with pydivert.WinDivert("true") as w: queue_len = w.get_param(pydivert.Param.QUEUE_LEN) print(f"Queue length: {queue_len}") ``` ``` -------------------------------- ### Check WinDivert Service Registration Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/service_management.md Checks if the WinDivert service is installed and registered on the system. This is a static method of the WinDivert class. ```python from pydivert import WinDivert if WinDivert.is_registered(): print("WinDivert is installed") with WinDivert("tcp") as w: for packet in w: w.send(packet) else: print("WinDivert not found") ``` -------------------------------- ### Basic Packet Capture and Re-injection Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/README.md This snippet demonstrates a fundamental pattern for capturing network packets and then re-injecting them. It's a common starting point for many network manipulation tasks. ```python from pydivert import WinDivert with WinDivert() as w: for packet in w.recv(): # Process packet here w.send(packet) ``` -------------------------------- ### ip_checksum Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Checks if the IP checksum was verified by hardware offloading. Supports both getting and setting this property. ```APIDOC ## ip_checksum ### Description Whether the IP checksum was verified by hardware offloading. ### Type bool ``` -------------------------------- ### Using Param Enum to Set WinDivert Parameters Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Demonstrates using the Param enumeration to get and set WinDivert handle parameters, such as queue length and time. This allows tuning of packet buffering. ```python with pydivert.WinDivert("true") as w: # Get current parameters queue_len = w.get_param(pydivert.Param.QUEUE_LEN) print(f"Queue length: {queue_len}") # Increase queue w.set_param(pydivert.Param.QUEUE_LEN, 2048) w.set_param(pydivert.Param.QUEUE_TIME, 1024) for packet in w: w.send(packet) ``` -------------------------------- ### Access and Modify IPv6 Header Fields Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet_headers.md Shows how to access and modify fields of an IPv6 header. This example retrieves the hop limit, then sets a new hop limit and destination address. ```python with pydivert.WinDivert("ipv6") as w: packet = w.recv() if packet.ipv6: print(f"Hop limit: {packet.ipv6.hop_limit}") packet.ipv6.hop_limit = 32 packet.ipv6.dst_addr = "2001:db8::2" w.send(packet) ``` -------------------------------- ### Filter by IP Source Address Source: https://github.com/ffalcinelli/pydivert/blob/main/docs/FILTER_LANGUAGE.md Example of filtering packets based on the source IP address. This targets IPv4 and IPv6. ```WinDivert Filter Language ip.SrcAddr == 192.168.1.1 ``` -------------------------------- ### Get WinDivert Queue Length Parameter Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Use `get_param()` to retrieve WinDivert driver parameter values, such as the queue length. This is useful for monitoring or understanding driver behavior. ```python with pydivert.WinDivert("true") as w: queue_len = w.get_param(pydivert.Param.QUEUE_LEN) print(f"Queue length: {queue_len}") ``` -------------------------------- ### Using Layer Enum for Packet Capture Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/types.md Example demonstrating how to use the Layer enumeration to specify the network layer when creating a WinDivert handle. This snippet shows capturing TCP packets at the network layer. ```python with pydivert.WinDivert("tcp", layer=pydivert.Layer.NETWORK) as w: for packet in w: w.send(packet) # Flow events (requires WinDivert 2.2+) with pydivert.WinDivert("tcp", layer=pydivert.Layer.FLOW) as w: for flow_event in w: print(f"Flow event: {flow_event.event}") ``` -------------------------------- ### Structural Pattern Matching with pydivert Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet_headers.md Utilizes Python 3.10+ structural pattern matching to filter and identify packets based on IP address, port, and protocol. Requires 'tcp' filter for this specific example. ```python from pydivert.packet.tcp import TCPHeader from pydivert.packet.ip import IPv4Header with pydivert.WinDivert("tcp") as w: for packet in w: match packet: case Packet( ipv4=IPv4Header(src_addr="192.168.1.0/24"), tcp=TCPHeader(dst_port=443) ): print("Local HTTPS traffic") case Packet(tcp=TCPHeader(dst_port=80)): print("HTTP traffic") case Packet(udp=_): print("UDP packet") w.send(packet) ``` -------------------------------- ### Create and Use Packet Instance Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Demonstrates how to create a Packet instance programmatically with raw bytes and how to receive and process packets using WinDivert. ```python import pydivert # Create a raw packet (must be valid IP/TCP/UDP format) raw_packet = bytes.fromhex("4500002e000040004006...") # Valid IPv4+TCP packet packet = pydivert.Packet( raw_packet, direction=pydivert.Direction.OUTBOUND, interface=(1, 0) ) # Use packet from WinDivert with pydivert.WinDivert("tcp") as w: packet = w.recv() print(f"Captured: {packet.src_addr}:{packet.src_port} -> {packet.dst_addr}:{packet.dst_port}") ``` -------------------------------- ### Traffic Filtering to Block Specific IPs Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/README.md This example shows how to filter network traffic to block packets originating from or destined for specific IP addresses. It utilizes the DROP flag for effective blocking. ```python from pydivert import WinDivert, ntohs, AF_INET from ipaddress import ip_address # Block traffic to/from 1.2.3.4 filter_str = "inbound and ip.addr == 1.2.3.4 or outbound and ip.addr == 1.2.3.4" with WinDivert(filter_str, 0) as w: for packet in w.recv(): if packet.direction == "outbound": # Block outbound packets to 1.2.3.4 packet.action = packet.DROP elif packet.direction == "inbound": # Block inbound packets from 1.2.3.4 packet.action = packet.DROP w.send(packet) ``` -------------------------------- ### Build PyDivert Documentation Source: https://github.com/ffalcinelli/pydivert/blob/main/GEMINI.md Builds the project documentation using the provided Python script. ```bash uv run python docs/build.py ``` -------------------------------- ### timestamp Property Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Gets or sets the capture timestamp from QueryPerformanceCounter. ```APIDOC ## timestamp ### Description The capture timestamp from QueryPerformanceCounter. ### Type int ### Example ```python packet = w.recv() print(f"Captured at: {packet.timestamp}") ``` ``` -------------------------------- ### direction Property Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Gets or sets the packet direction (inbound or outbound). ```APIDOC ## direction ### Description The packet direction (inbound or outbound). See Direction enum. ### Type Direction ### Example ```python packet = w.recv() if packet.direction == pydivert.Direction.OUTBOUND: print("Outbound packet") else: print("Inbound packet") # Change direction packet.direction = pydivert.Direction.INBOUND w.send(packet) ``` ``` -------------------------------- ### Typical WinDivert Service Lifecycle Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/service_management.md Demonstrates the common pattern for checking if WinDivert is registered, optionally pre-registering it, using it within a context manager, and finally unregistering it. The driver auto-registers on first use, making pre-registration optional. ```python import pydivert # Check if registered if not pydivert.WinDivert.is_registered(): # Pre-register (optional, driver auto-registers on first use) pydivert.WinDivert.register() # Use WinDivert with pydivert.WinDivert("tcp") as w: for packet in w: w.send(packet) # Unregister (optional, usually left installed) pydivert.WinDivert.unregister() ``` -------------------------------- ### layer Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Retrieves the WinDivert layer that captured this packet. Supports both getting and setting the layer. ```APIDOC ## layer ### Description The WinDivert layer that captured this packet. ### Type Layer (NETWORK, NETWORK_FORWARD, FLOW, SOCKET, REFLECT) ### Example ```python if packet.layer == pydivert.Layer.NETWORK: print("Network layer packet") ``` ``` -------------------------------- ### Get WinDivert Address Structure Source: https://github.com/ffalcinelli/pydivert/blob/main/docs/index.html Retrieves the interface and direction of a packet as a WINDIVERT_ADDRESS structure. ```python wd_addr ``` -------------------------------- ### open() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Opens a WinDivert handle for the given filter, allowing packet capture and injection. Requires administrator privileges. ```APIDOC ## open() ### Description Opens a WinDivert handle for the given filter. Diverted packets are captured and made available via `recv()`. Requires administrator privileges. ### Returns None ### Raises RuntimeError - if handle is already open or WinDivert driver not installed ### Note Automatically called when using the context manager (`with` statement). ### Example ```python w = pydivert.WinDivert("tcp.DstPort == 443") w.open() try: packet = w.recv() finally: w.close() ``` ``` -------------------------------- ### event Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Gets or sets the WinDivert event type, applicable for FLOW, SOCKET, and REFLECT layers. ```APIDOC ## event ### Description The WinDivert event type (for FLOW, SOCKET, REFLECT layers). ### Type int ``` -------------------------------- ### register() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/service_management.md Pre-registers the WinDivert service. This is usually not needed as the driver auto-registers on first handle open. ```APIDOC ## register() ### Description Pre-registers the WinDivert service. This is usually not needed as the driver auto-registers on first handle open. ### Method `pydivert.WinDivert.register()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python try: pydivert.WinDivert.register() print("Registered successfully") except OSError as e: print(f"Registration failed: {e}") ``` ### Response #### Success Response None ### Raises - **OSError**: if registration fails ``` -------------------------------- ### udp_checksum Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Checks if the UDP checksum was verified by hardware offloading. Supports both getting and setting this property. ```APIDOC ## udp_checksum ### Description Whether the UDP checksum was verified by hardware offloading. ### Type bool ``` -------------------------------- ### Run PyDivert Tests with Vagrant Source: https://github.com/ffalcinelli/pydivert/blob/main/README.md Execute PyDivert tests on a Windows 11 VM using Vagrant. This requires Admin privileges and sets up the project environment within the VM. ```bash vagrant up vagrant powershell -c "$env:UV_PROJECT_ENVIRONMENT=\"C:/pydivert_venv\"; cd C:/pydivert; uv run pytest" ``` -------------------------------- ### tcp_checksum Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Checks if the TCP checksum was verified by hardware offloading. Supports both getting and setting this property. ```APIDOC ## tcp_checksum ### Description Whether the TCP checksum was verified by hardware offloading. ### Type bool ``` -------------------------------- ### Async Context Manager for WinDivert Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Shows how to use WinDivert with asyncio's async context managers for asynchronous operations. ```python async with pydivert.WinDivert("tcp") as w: async for packet in w: await w.send_async(packet) ``` -------------------------------- ### is_impostor Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Indicates whether the packet is an impostor (spoofed) packet. Supports both getting and setting this property. ```APIDOC ## is_impostor ### Description Whether the packet is an impostor packet (spoofed). ### Type bool ### Example ```python if packet.is_impostor: print("Potential spoofed packet") ``` ``` -------------------------------- ### is_loopback Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Checks if the packet is a loopback packet (destined for 127.0.0.0/8 or ::1). Supports both getting and setting this property. ```APIDOC ## is_loopback ### Description Whether the packet is a loopback packet (127.0.0.0/8 or ::1). ### Type bool ### Example ```python if packet.is_loopback: print("Loopback packet") ``` ``` -------------------------------- ### Run PyDivert Tests Source: https://github.com/ffalcinelli/pydivert/blob/main/GEMINI.md Executes the test suite for PyDivert using uv. Note that most tests require administrator privileges. ```bash uv run pytest ``` -------------------------------- ### Get WinDivert Parameter Source: https://github.com/ffalcinelli/pydivert/blob/main/docs/index.html Retrieves a specific parameter from the WinDivert handle. Refer to pydivert.Param for a list of available parameters. ```python param_value = w.get_param(pydivert.Param.SOCKET) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md Command to execute the test suite for PyDivert using `uv` and `pytest`. Requires Administrator privileges. ```bash uv sync --extra test uv run pytest ``` -------------------------------- ### Simple Firewall to Drop Packets Source: https://github.com/ffalcinelli/pydivert/blob/main/README.md Implement a basic firewall by capturing packets from a specific IP address and not re-injecting them, effectively dropping the traffic. ```python import pydivert # Block all traffic from a specific IP address with pydivert.WinDivert("ip.SrcAddr == 1.2.3.4") as w: for packet in w: print(f"Blocking packet from {packet.src_addr}") # Packet is dropped here ``` -------------------------------- ### Create WinDivert Handle with Flags and Async Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Instantiate WinDivert with specific flags for sniffing and handling fragmented packets, using an asynchronous interface for packet processing. ```python import pydivert # Capture with flags with pydivert.WinDivert( "tcp", layer=pydivert.Layer.NETWORK, flags=pydivert.Flag.SNIFF | pydivert.Flag.FRAGMENTS ) as w: async for packet in w: await w.send_async(packet) ``` -------------------------------- ### Get WinDivert Handle Representation Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Retrieves a string representation of the WinDivert handle, showing its state, filter, layer, and other properties. ```python w = pydivert.WinDivert("tcp.DstPort == 80") print(repr(w)) # ``` -------------------------------- ### is_sniffed Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Determines if the packet was obtained via sniffing (Flag.SNIFF mode) rather than diversion. Supports both getting and setting this property. ```APIDOC ## is_sniffed ### Description Whether the packet was sniffed (Flag.SNIFF mode) rather than diverted. ### Type bool ``` -------------------------------- ### Transparent Proxy: Capture and Modify Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/configuration.md Create a transparent proxy by capturing packets, modifying their payload, and then sending them. This is useful for content filtering or modification. ```python # Capture and modify with pydivert.WinDivert("tcp.DstPort == 80") as w: for packet in w: if b"Host:" in packet.payload: # Modify request packet.payload = packet.payload.replace( b"Host: example.com", b"Host: proxy.local" ) w.send(packet) ``` -------------------------------- ### Asynchronous Packet Processing Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md Shows how to process network packets asynchronously using `asyncio` and PyDivert's async context manager and send method. ```python import asyncio import pydivert async def process(): async with pydivert.WinDivert("tcp") as w: async for packet in w: # Async work here await w.send_async(packet) asyncio.run(process()) ``` -------------------------------- ### Get WinDivertAddress Structure Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Retrieves the internal WinDivertAddress structure for advanced usage, providing access to low-level network interface information. ```python @property def wd_addr(self) -> WinDivertAddress ``` ```python addr = packet.wd_addr print(f"Interface: {addr.Network.IfIdx}") ``` -------------------------------- ### Open WinDivert Handle Manually Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Manually open a WinDivert handle for capturing packets destined for port 443. Ensure to close the handle afterwards or use a context manager. ```python w = pydivert.WinDivert("tcp.DstPort == 443") w.open() try: packet = w.recv() finally: w.close() ``` -------------------------------- ### send_async() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Asynchronously injects a packet using Windows Overlapped I/O. Does not block the event loop. ```APIDOC ## send_async() ### Description Asynchronously injects a packet using Windows Overlapped I/O. Does not block the event loop. ### Method Signature ```python async def send_async( self, packet: Packet, recalculate_checksum: bool = True ) -> int ``` ### Parameters #### Parameters - **packet** (Packet) - Required - The packet to inject. - **recalculate_checksum** (bool) - Optional - Whether to recalculate checksums before sending. Defaults to True. ### Returns - int - coroutine that resolves to the number of bytes sent. ### Raises - RuntimeError - if handle is not open. - OSError - on WinDivert driver error. - asyncio.CancelledError - if cancelled. ### Example ```python import asyncio import pydivert async def main(): async with pydivert.WinDivert("tcp") as w: async for packet in w: await w.send_async(packet) asyncio.run(main()) ``` ``` -------------------------------- ### Modify Packet Payload Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/INDEX.md This example shows how to intercept packets, modify their payload content, and then send them on their way. It targets TCP packets with a payload. ```python with pydivert.WinDivert("tcp.PayloadLength > 0") as w: for packet in w: if packet.payload: packet.payload = packet.payload.replace(b"old", b"new") w.send(packet) ``` -------------------------------- ### Manual Resource Management for Packet Handling Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/README.md Manual approach to managing WinDivert resources. Requires explicit calls to open() and close() to manage the divert handle. Use this pattern when more control over the divert handle's lifecycle is needed. ```python w = pydivert.WinDivert("tcp") w.open() try: for packet in w: w.send(packet) finally: w.close() ``` -------------------------------- ### Get and Set Destination Port Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Accesses or modifies the destination port for TCP or UDP packets. Returns None if the packet is not TCP or UDP. ```python @property def dst_port(self) -> int | None @dst_port.setter def dst_port(self, val: int) -> None ``` ```python if packet.dst_port == 443: print("HTTPS traffic") packet.dst_port = 8443 # Redirect ``` -------------------------------- ### send() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Synchronously injects a packet into the network stack. Packets are recalculated for checksums by default. Injected packets may be diverted again by lower-priority handles. ```APIDOC ## send() ### Description Synchronously injects a packet into the network stack. Packets are recalculated for checksums by default. Injected packets may be diverted again by lower-priority handles. ### Method Signature ```python def send(self, packet: Packet, recalculate_checksum: bool = True) -> int ``` ### Parameters #### Parameters - **packet** (Packet) - Required - The packet to inject. - **recalculate_checksum** (bool) - Optional - Whether to recalculate TCP/UDP/ICMP/IP checksums before sending. Set False to preserve original checksums. Defaults to True. ### Returns - int - the number of bytes actually sent. ### Raises - RuntimeError - if handle is not open. - OSError - on WinDivert driver error. ### Example ```python with pydivert.WinDivert("tcp.DstPort == 80") as w: for packet in w: # Modify the packet packet.dst_port = 8080 # Send back (checksum auto-recalculated) bytes_sent = w.send(packet) print(f"Sent {bytes_sent} bytes") ``` ``` -------------------------------- ### Get and Set Source Port Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Accesses or modifies the source port for TCP or UDP packets. Returns None if the packet is not TCP or UDP. ```python @property def src_port(self) -> int | None @src_port.setter def src_port(self, val: int) -> None ``` ```python if packet.src_port == 53: print("DNS query from", packet.src_addr) ``` -------------------------------- ### Get and Set Destination IP Address Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Accesses or modifies the destination IP address of the packet. Returns None if the packet is not IPv4 or IPv6. ```python @property def dst_addr(self) -> str | None @dst_addr.setter def dst_addr(self, val: str) -> None ``` ```python print(f"Destination: {packet.dst_addr}") if packet.dst_addr == "1.2.3.4": packet.payload = b"MODIFIED" ``` -------------------------------- ### Synchronously Inject Packet with WinDivert Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Use `send()` to inject a packet into the network stack synchronously. Checksums are recalculated by default. This is suitable for straightforward packet injection scenarios. ```python with pydivert.WinDivert("tcp.DstPort == 80") as w: for packet in w: # Modify the packet packet.dst_port = 8080 # Send back (checksum auto-recalculated) bytes_sent = w.send(packet) print(f"Sent {bytes_sent} bytes") ``` -------------------------------- ### Get and Set Source IP Address Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Accesses or modifies the source IP address of the packet. Returns None if the packet is not IPv4 or IPv6. ```python @property def src_addr(self) -> str | None @src_addr.setter def src_addr(self, val: str) -> None ``` ```python print(f"Source: {packet.src_addr}") packet.src_addr = "192.168.1.100" w.send(packet) ``` -------------------------------- ### Check WinDivert Service Registration (Static Method) Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/service_management.md A convenience wrapper around `service.is_registered()` provided as a static method of the WinDivert class. ```python if pydivert.WinDivert.is_registered(): print("Ready to use") ``` -------------------------------- ### WinDivert Constructor Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Creates a WinDivert handle for packet capture and injection with specified filter, layer, priority, and flags. ```APIDOC ## WinDivert() ### Description Creates a WinDivert handle for packet capture and injection. ### Parameters #### Parameters - **filter** (str) - Optional - Packet filter string matching the WinDivert filter language. Examples: "tcp.DstPort == 80", "ip.SrcAddr == 1.2.3.4" - **layer** (Layer) - Optional - The WinDivert layer for capture. Options: NETWORK (IP packets), NETWORK_FORWARD, FLOW (connection events), SOCKET (socket events), REFLECT (reflected events). - **priority** (int) - Optional - Handle priority as int16. Higher priority handles see packets first. Range: -32768 to 32767. - **flags** (Flag) - Optional - Bitwise OR combination of Flag options (SNIFF, DROP, RECV_ONLY, SEND_ONLY, NO_INSTALL, FRAGMENTS). ### Returns WinDivert instance ### Raises RuntimeError - if attempting to open an already-open handle ### Example ```python import pydivert # Capture only HTTP traffic with pydivert.WinDivert("tcp.DstPort == 80") as w: for packet in w: print(f"Captured: {packet}") w.send(packet) # Capture with flags with pydivert.WinDivert( "tcp", layer=pydivert.Layer.NETWORK, flags=pydivert.Flag.SNIFF | pydivert.Flag.FRAGMENTS ) as w: async for packet in w: await w.send_async(packet) ``` ``` -------------------------------- ### Context Manager Pattern for Packet Handling Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/README.md Recommended pattern for managing WinDivert resources. Automatically handles opening and closing the divert handle, ensuring proper cleanup. Use this for simplified and safe packet processing. ```python with pydivert.WinDivert("tcp") as w: for packet in w: w.send(packet) # Handle auto-closes ``` -------------------------------- ### Get and Set Packet Payload Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Accesses or modifies the payload data of TCP, UDP, ICMP, or ICMPv6 packets. Returns None if the packet has no payload. ```python @property def payload(self) -> bytes | None @payload.setter def payload(self, val: bytes | bytearray | memoryview) -> None ``` ```python if packet.payload and b"secret" in packet.payload: packet.payload = b"REDACTED_DATA" + packet.payload[13:] w.send(packet) ``` -------------------------------- ### Get IP Protocol and Header Offset Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md Retrieves the IP protocol number and the byte offset to the protocol header. Returns None for both if the packet is invalid. ```python @property def protocol(self) -> tuple[int | None, int | None] ``` ```python proto, offset = packet.protocol if proto == pydivert.Protocol.TCP: print("TCP packet") ``` -------------------------------- ### WinDivert Iterator Support Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Demonstrates iterating over packets received by WinDivert, which repeatedly calls recv(). ```python with pydivert.WinDivert("tcp") as w: for packet in w: print(packet) w.send(packet) ``` -------------------------------- ### Get WinDivert Event Type Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md The `event` property returns the WinDivert event type, which is relevant for packets captured at the FLOW, SOCKET, or REFLECT layers. ```python event_type = packet.event print(f"WinDivert event type: {event_type}") ``` -------------------------------- ### Monitor Flow Events with PyDivert Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/examples_patterns.md Use Layer.FLOW to monitor connection establishment and closure events. This is more efficient than packet-level monitoring for tracking connections. Requires WinDivert 2.2+. ```python with pydivert.WinDivert("tcp", layer=pydivert.Layer.FLOW) as w: for event in w: if event.event == 1: # WINDIVERT_EVENT_FLOW_ESTABLISHED print(f"Connection established: {event.flow}") elif event.event == 2: # WINDIVERT_EVENT_FLOW_DELETED print(f"Connection closed: {event.flow}") ``` -------------------------------- ### Get Packet Layer Information Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/packet.md The `layer` property returns the WinDivert layer that captured the packet. It can be one of NETWORK, NETWORK_FORWARD, FLOW, SOCKET, or REFLECT. ```python if packet.layer == pydivert.Layer.NETWORK: print("Network layer packet") ``` -------------------------------- ### send_ex() Source: https://github.com/ffalcinelli/pydivert/blob/main/_autodocs/windivert.md Extended send function supporting overlapped I/O. This is an advanced function for manual overlapped I/O management. ```APIDOC ## send_ex() ### Description Extended send function supporting overlapped I/O. Use `send()` or `send_async()` for typical use cases. ### Method Signature ```python def send_ex( self, packet: Packet, recalculate_checksum: bool = True, flags: int = 0, overlapped: Overlapped | None = None ) -> int | None ``` ### Parameters #### Parameters - **packet** (Packet) - Required - The packet to inject. - **recalculate_checksum** (bool) - Optional - Whether to recalculate checksums. Defaults to True. - **flags** (int) - Optional - Send flags (reserved for future use, should be 0). Defaults to 0. - **overlapped** (Overlapped | None) - Optional - Optional Overlapped structure for overlapped I/O. Defaults to None. ### Returns - int | None - the number of bytes sent, or None if ERROR_IO_PENDING and overlapped is provided. ### Raises - RuntimeError - if handle is not open. - OSError - on WinDivert driver error. ### Note Advanced function for manual overlapped I/O management. Use `send()` or `send_async()` for typical use cases. ```