or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

addons.mdcommands.mdconfiguration.mdconnections.mdcontent.mdflow-io.mdhttp-flows.mdindex.mdprotocols.md
tile.json

tessl/pypi-mitmproxy

An interactive, SSL/TLS-capable intercepting proxy for HTTP/1, HTTP/2, and WebSockets.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/mitmproxy@12.1.x

To install, run

npx @tessl/cli install tessl/pypi-mitmproxy@12.1.0

index.mddocs/

mitmproxy

A comprehensive HTTP/HTTPS/WebSocket proxy toolkit providing interactive proxy capabilities with real-time traffic interception, analysis, and modification. mitmproxy supports HTTP/1, HTTP/2, HTTP/3, and WebSocket protocols with full SSL/TLS capabilities, making it an essential tool for debugging, testing, and security analysis of web applications and APIs.

Package Information

  • Package Name: mitmproxy
  • Language: Python
  • Installation: pip install mitmproxy
  • Python Requirements: Python 3.12+

Core Imports

For HTTP flow handling:

from mitmproxy import http
from mitmproxy.http import HTTPFlow, Request, Response, Headers

For flow management:

from mitmproxy import flow
from mitmproxy.flow import Flow, Error

For connection handling:

from mitmproxy import connection
from mitmproxy.connection import Client, Server, ConnectionState

Basic Usage

Running mitmproxy Tools

mitmproxy provides three main command-line interfaces:

# Interactive console interface
mitmproxy

# Command-line dump tool
mitmdump

# Web-based interface
mitmweb

Basic HTTP Flow Interception

from mitmproxy import http

def request(flow: http.HTTPFlow) -> None:
    """Intercept and modify HTTP requests."""
    # Log all requests
    print(f"Request: {flow.request.method} {flow.request.url}")
    
    # Modify request headers
    flow.request.headers["X-Custom-Header"] = "Modified"
    
    # Block specific requests
    if "example.com" in flow.request.url:
        flow.response = http.Response.make(403, b"Blocked")

def response(flow: http.HTTPFlow) -> None:
    """Intercept and modify HTTP responses."""
    # Log responses
    print(f"Response: {flow.response.status_code} for {flow.request.url}")
    
    # Modify response content
    if flow.response.headers.get("content-type", "").startswith("application/json"):
        # Parse and modify JSON responses
        data = flow.response.json()
        data["intercepted"] = True
        flow.response.set_text(json.dumps(data))

Working with Flows Programmatically

from mitmproxy import io, http

# Read flows from file
with open("flows.mitm", "rb") as f:
    reader = io.FlowReader(f)
    for flow in reader.stream():
        if isinstance(flow, http.HTTPFlow):
            print(f"{flow.request.method} {flow.request.url}")

# Write flows to file
flows = []  # List of flows to save
with open("output.mitm", "wb") as f:
    writer = io.FlowWriter(f)
    for flow in flows:
        writer.add(flow)

Architecture

mitmproxy uses an event-driven architecture built around several key components:

  • Master: Central orchestrator managing the proxy server and addon system
  • Flow Types: Protocol-specific flow representations (HTTP, TCP, UDP, WebSocket)
  • Addon System: Extensible plugin architecture for custom functionality
  • Connection Management: Client/server connection abstraction and state tracking
  • Certificate Management: Dynamic SSL/TLS certificate generation and validation

The addon system provides hooks at every stage of the proxy lifecycle, enabling comprehensive traffic analysis, modification, and custom protocol handling.

Capabilities

HTTP Flow Management

Core HTTP proxy functionality including request/response interception, modification, and analysis. Supports HTTP/1, HTTP/2, and HTTP/3 protocols with comprehensive header and content manipulation.

class HTTPFlow(Flow):
    request: Request
    response: Optional[Response]
    error: Optional[Error]

class Request:
    def __init__(self, host: str, port: int, method: bytes, scheme: bytes, authority: bytes, path: bytes, http_version: bytes, headers: Headers, content: bytes, trailers: Optional[Headers], timestamp_start: float, timestamp_end: Optional[float]) -> None: ...

class Response:
    def __init__(self, http_version: bytes, status_code: int, reason: bytes, headers: Headers, content: bytes, trailers: Optional[Headers], timestamp_start: float, timestamp_end: float) -> None: ...

HTTP Flow Management

Connection Management

Client and server connection handling with support for transparent proxying, upstream proxies, and complex network topologies. Includes TLS/SSL certificate management and protocol detection.

class Client(Connection):
    address: Optional[Address]
    tls_established: bool
    certificate_list: Sequence[x509.Certificate]
    alpn: Optional[bytes]
    cipher: Optional[str]

class Server(Connection):
    address: Optional[Address]
    tls_established: bool
    certificate_list: Sequence[x509.Certificate]
    alpn: Optional[bytes]
    cipher: Optional[str]

Connection Management

Multi-Protocol Support

TCP, UDP, and WebSocket flow handling beyond HTTP, enabling comprehensive network traffic analysis and modification for various protocol types.

class TCPFlow(Flow):
    messages: List[TCPMessage]

class UDPFlow(Flow):
    messages: List[UDPMessage]

class WebSocketMessage:
    type: int
    content: bytes
    from_client: bool
    timestamp: float

Multi-Protocol Support

Flow I/O and Persistence

Reading and writing flows to files for replay, analysis, and testing. Supports filtering and format conversion for various use cases.

class FlowReader:
    def __init__(self, fo: BinaryIO) -> None: ...
    def stream(self) -> Iterator[Flow]: ...

class FlowWriter:
    def __init__(self, fo: BinaryIO) -> None: ...
    def add(self, flow: Flow) -> None: ...

def read_flows_from_paths(paths: Sequence[str]) -> Iterator[Flow]: ...

Flow I/O

Configuration and Options

Comprehensive configuration system with type-safe options for proxy behavior, TLS settings, network configuration, and addon parameters.

class Options:
    def __init__(self, **kwargs) -> None: ...
    def set(self, key: str, value: Any) -> None: ...
    def get(self, key: str) -> Any: ...

# Key configuration constants
CONF_DIR: str = "~/.mitmproxy"
CONF_BASENAME: str = "mitmproxy"
KEY_SIZE: int = 2048

Configuration

Addon Development

Extensible addon system for custom functionality with lifecycle hooks, event handling, and access to all proxy components. Includes built-in addons for common use cases.

def default_addons() -> List[Any]: ...

# Decorator for concurrent addon execution
def concurrent(func: Callable) -> Callable: ...

# Context access for addons
import mitmproxy.ctx as ctx

Addon Development

Content Processing

Flexible content viewing, transformation, and analysis with support for various data formats and encoding schemes. Includes syntax highlighting and interactive content exploration.

class Contentview:
    name: str
    content_types: List[str]
    
def add(view: Contentview) -> None: ...

# Encoding utilities
def encode(data: bytes, encoding: str) -> bytes: ...
def decode(data: bytes, encoding: str) -> bytes: ...

Content Processing

Command System

Type-safe command framework for interactive control and automation. Supports complex command composition and validation with built-in commands for all major operations.

class CommandManager:
    def execute(self, cmdstr: str) -> Any: ...
    def call(self, path: str, *args: Any) -> Any: ...

# Type system for commands
class TypeManager:
    def command(self, name: str) -> Callable: ...

Command System

Entry Points

mitmproxy provides three main entry points:

  • mitmproxy.tools.main:mitmproxy - Interactive console interface with full-screen TUI
  • mitmproxy.tools.main:mitmdump - Command-line interface for scripted operations
  • mitmproxy.tools.main:mitmweb - Web-based interface accessible via browser

Each entry point provides the same core functionality with different user interfaces optimized for specific use cases.