mitm

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2026 License: MIT Imports: 20 Imported by: 0

README

mitm

A Man-in-the-Middle (MITM) HTTP/HTTPS proxy library for Go.

Features

  • Transparent TCP relay or full TLS interception per CONNECT tunnel
  • Unified request/response middleware pipeline for both plain-HTTP and HTTPS traffic
  • Upstream TLS connection pooling with cross-session reuse
  • Built-in middlewares for common use cases

Installation

go get github.com/aomori446/mitm

Quick Start

package main

import (
    "context"
    "os"
    "os/signal"
    "syscall"

    "github.com/aomori446/mitm"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    certMgr, _ := mitm.NewCertManager("testdata/ca.crt", "testdata/ca.key")

    handler := mitm.New(certMgr)

    // Starts proxy server with built-in graceful shutdown on ctx cancellation
    handler.ListenAndServe(ctx, ":8080")
}

Point your browser's proxy settings to localhost:8080 and install testdata/ca.crt as a trusted CA.

Note: mitm.Handler also implements http.Handler, so you can plug it into a custom http.Server or multiplexer if needed.

Middlewares

Register middlewares to inspect or modify traffic:

handler.UseRequest(func(ctx context.Context, req *http.Request) (*http.Request, *http.Response) {
    // Return a modified request, or short-circuit with a synthetic response.
    return req, nil
})

handler.UseResponse(func(ctx context.Context, resp *http.Response) (*http.Response, error) {
    // Return a modified response, or return an error to abort.
    return resp, nil
})

Middlewares are called in registration order. A non-nil *http.Response from a UseRequest middleware short-circuits the upstream request and sends the response directly to the client.

Built-in Middlewares

All middlewares live in github.com/aomori446/mitm/middleware.

Logger
onReq, onResp := middleware.Logger(slog.Default())
handler.UseRequest(onReq)
handler.UseResponse(onResp)

Logs method, URL, status code, content-type, and elapsed time.

Blocker
// Block by host pattern → 403 Forbidden
handler.UseRequest(middleware.Blocker("ads.example.com", "*.doubleclick.net"))

// Block with a content-appropriate empty response
handler.UseRequest(middleware.BlockerWith(
    middleware.RespondWithAuto(), // pixel / empty JS / empty CSS / empty HTML
    "*.googlesyndication.com",
))

// Block by custom match function
handler.UseRequest(middleware.BlockerFunc(
    middleware.RespondWithEmptyJS(),
    func(req *http.Request) bool {
        return strings.HasSuffix(req.URL.Path, "/analytics.js")
    },
))

Available BlockResponse helpers:

Helper Response
RespondWith403() 403 Forbidden
RespondWithPixel() 1×1 transparent GIF
RespondWithEmptyJS() // (empty JS)
RespondWithEmptyCSS() empty CSS
RespondWithEmptyHTML() <html></html>
RespondWithAuto() inferred from URL extension
Header
handler.UseRequest(middleware.SetRequestHeader("Authorization", "Bearer token"))
handler.UseRequest(middleware.RemoveRequestHeader("Cookie"))
handler.UseResponse(middleware.SetResponseHeader("X-Frame-Options", "DENY"))
handler.UseResponse(middleware.RemoveResponseHeader("Server"))
Dump
onReq, onResp := middleware.Dump(os.Stderr)
handler.UseRequest(onReq)
handler.UseResponse(onResp)

Writes each request and response in HTTP/1.1 wire format to the provided writer.

Generating a CA Certificate

go run ./examples/genca -cert testdata/ca.crt -key testdata/ca.key

Running the Example Proxy

go run ./examples/proxy -addr :8080 -ca-cert testdata/ca.crt -ca-key testdata/ca.key

Project Structure

cert.go        CA loading, per-host cert forging and caching
connect.go     CONNECT tunnel handling (MITM & TCP relay)
handler.go     Core proxy handler (ServeHTTP, ListenAndServe, middlewares)
relay.go       TCPRelay for transparent tunnelling
transport.go   Upstream connection pooling and middleware transport
middleware/    Middleware types and built-in middlewares
examples/      Runnable reference implementations

Requirements

  • Go 1.21+

License

(C) 2026 Aomori446, MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateCA

func GenerateCA(certOut, keyOut string) error

func Response

func Response(status int, contentType string, body io.ReadCloser) *http.Response

Response constructs a standard *http.Response helper.

Types

type CertManager

type CertManager struct {
	// contains filtered or unexported fields
}

func NewCertManager

func NewCertManager(certFile, keyFile string) (*CertManager, error)

func (*CertManager) TLSConfig

func (m *CertManager) TLSConfig() *tls.Config

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler is an http.Handler that acts as a forward proxy and performs TLS interception (MITM) on CONNECT tunnels when a CertManager is provided.

func New

func New(certMgr *CertManager) *Handler

New creates a Handler. Providing a non-nil certMgr enables TLS interception; passing nil falls back to a transparent TCP relay for CONNECT tunnels.

The caller should set http.Server.BaseContext to a context that is canceled on shutdown so that long-lived CONNECT tunnels are torn down promptly when the server stops.

func (*Handler) ListenAndServe

func (h *Handler) ListenAndServe(ctx context.Context, addr string) error

ListenAndServe starts an HTTP proxy server on the given network address. It uses ctx as the BaseContext for all incoming connections and shuts down gracefully when ctx is canceled.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler. CONNECT requests initiate a tunnel; all other methods run request middlewares then are proxied via the reverse proxy.

func (*Handler) UseRequest

func (h *Handler) UseRequest(fn RequestFunc)

UseRequest registers fn as a request middleware. Middlewares are called in registration order before each upstream request.

func (*Handler) UseResponse

func (h *Handler) UseResponse(fn ResponseFunc)

UseResponse registers fn as a response middleware. Middlewares are called in registration order after each upstream response.

type RequestFunc

type RequestFunc func(ctx context.Context, req *http.Request) (*http.Request, *http.Response)

RequestFunc is called before a request is forwarded to the upstream server.

type ResponseFunc

type ResponseFunc func(ctx context.Context, resp *http.Response) (*http.Response, error)

ResponseFunc is called after the upstream response is received and before it is written back to the client. The original request is available via resp.Request.

Directories

Path Synopsis
examples
blocker command
Command blocker demonstrates the Blocker interceptor with various response helpers.
Command blocker demonstrates the Blocker interceptor with various response helpers.
dump command
Command dump demonstrates the Dump interceptor, which prints every proxied request and response in HTTP/1.1 wire format to stderr.
Command dump demonstrates the Dump interceptor, which prints every proxied request and response in HTTP/1.1 wire format to stderr.
genca command
Command genca generates a self-signed ECDSA CA certificate and private key for use with the MITM proxy.
Command genca generates a self-signed ECDSA CA certificate and private key for use with the MITM proxy.
header command
Command header demonstrates the Header interceptor helpers: injecting headers into upstream requests and stripping or adding headers on responses.
Command header demonstrates the Header interceptor helpers: injecting headers into upstream requests and stripping or adding headers on responses.
logger command
Command logger demonstrates how to attach the Logger interceptor to a MITM proxy to log every proxied request and response.
Command logger demonstrates how to attach the Logger interceptor to a MITM proxy to log every proxied request and response.
proxy command
Command proxy is a minimal MITM HTTP/HTTPS proxy built on github.com/aomori446/mitm.
Command proxy is a minimal MITM HTTP/HTTPS proxy built on github.com/aomori446/mitm.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL