proxy

package
v0.0.0-...-7e01349 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Addon

type Addon interface {
	// A client has connected to mitmproxy. Note that a connection can correspond to multiple HTTP requests.
	ClientConnected(*ClientConn)

	// A client connection has been closed (either by us or the client).
	ClientDisconnected(*ClientConn)

	// Mitmproxy has connected to a server.
	ServerConnected(*ConnContext)

	// A server connection has been closed (either by us or the server).
	ServerDisconnected(*ConnContext)

	// The TLS handshake with the server has been completed successfully.
	TlsEstablishedServer(*ConnContext)

	// HTTP request headers were successfully read. At this point, the body is empty.
	Requestheaders(*Flow)

	// The full HTTP request has been read.
	Request(*Flow)

	// HTTP response headers were successfully read. At this point, the body is empty.
	Responseheaders(*Flow)

	// The full HTTP response has been read.
	Response(*Flow)

	// Stream request body modifier
	StreamRequestModifier(*Flow, io.Reader) io.Reader

	// Stream response body modifier
	StreamResponseModifier(*Flow, io.Reader) io.Reader

	// onAccessProxyServer
	AccessProxyServer(req *http.Request, res http.ResponseWriter)

	WebSocketStart(*Flow)
	WebSocketMessage(*Flow)
	WebSocketEnd(*Flow)

	// Server-Sent Events hooks
	// SSE stream started (detected text/event-stream content type)
	SSEStart(*Flow)
	// Each SSE event received (access via f.SSE.Events[len(f.SSE.Events)-1])
	SSEMessage(*Flow)
	// SSE stream ended
	SSEEnd(*Flow)

	// HTTP request failed with error
	RequestError(*Flow, error)

	// HTTP CONNECT request failed with error
	HTTPConnectError(*Flow, error)
}

type BaseAddon

type BaseAddon struct{}

BaseAddon do nothing

func (*BaseAddon) AccessProxyServer

func (addon *BaseAddon) AccessProxyServer(req *http.Request, res http.ResponseWriter)

func (*BaseAddon) ClientConnected

func (addon *BaseAddon) ClientConnected(*ClientConn)

func (*BaseAddon) ClientDisconnected

func (addon *BaseAddon) ClientDisconnected(*ClientConn)

func (*BaseAddon) HTTPConnectError

func (addon *BaseAddon) HTTPConnectError(*Flow, error)

func (*BaseAddon) Request

func (addon *BaseAddon) Request(*Flow)

func (*BaseAddon) RequestError

func (addon *BaseAddon) RequestError(*Flow, error)

func (*BaseAddon) Requestheaders

func (addon *BaseAddon) Requestheaders(*Flow)

func (*BaseAddon) Response

func (addon *BaseAddon) Response(*Flow)

func (*BaseAddon) Responseheaders

func (addon *BaseAddon) Responseheaders(*Flow)

func (*BaseAddon) SSEEnd

func (addon *BaseAddon) SSEEnd(*Flow)

func (*BaseAddon) SSEMessage

func (addon *BaseAddon) SSEMessage(*Flow)

func (*BaseAddon) SSEStart

func (addon *BaseAddon) SSEStart(*Flow)

func (*BaseAddon) ServerConnected

func (addon *BaseAddon) ServerConnected(*ConnContext)

func (*BaseAddon) ServerDisconnected

func (addon *BaseAddon) ServerDisconnected(*ConnContext)

func (*BaseAddon) StreamRequestModifier

func (addon *BaseAddon) StreamRequestModifier(f *Flow, in io.Reader) io.Reader

func (*BaseAddon) StreamResponseModifier

func (addon *BaseAddon) StreamResponseModifier(f *Flow, in io.Reader) io.Reader

func (*BaseAddon) TlsEstablishedServer

func (addon *BaseAddon) TlsEstablishedServer(*ConnContext)

func (*BaseAddon) WebSocketEnd

func (addon *BaseAddon) WebSocketEnd(*Flow)

func (*BaseAddon) WebSocketMessage

func (addon *BaseAddon) WebSocketMessage(*Flow)

func (*BaseAddon) WebSocketStart

func (addon *BaseAddon) WebSocketStart(*Flow)

type ClientConn

type ClientConn struct {
	Id                 uuid.UUID
	Conn               net.Conn
	Tls                bool
	NegotiatedProtocol string
	UpstreamCert       bool // Connect to upstream server to look up certificate details. Default: True
	// contains filtered or unexported fields
}

client connection

func (*ClientConn) MarshalJSON

func (c *ClientConn) MarshalJSON() ([]byte, error)

type ConnContext

type ConnContext struct {
	ClientConn *ClientConn   `json:"clientConn"`
	ServerConn *ServerConn   `json:"serverConn"`
	Intercept  bool          `json:"intercept"` // Indicates whether to parse HTTPS
	FlowCount  atomic.Uint32 `json:"-"`         // Number of HTTP requests made on the same connection
	// contains filtered or unexported fields
}

connection context

func (*ConnContext) Id

func (connCtx *ConnContext) Id() uuid.UUID

type Flow

type Flow struct {
	Id          uuid.UUID
	ConnContext *ConnContext
	Request     *Request
	Response    *Response
	WebScoket   *WebSocketData
	SSE         *SSEData // Server-Sent Events data

	// https://docs.mitmproxy.org/stable/overview-features/#streaming
	// 如果为 true,则不缓冲 Request.Body 和 Response.Body,且不进入之后的 Addon.Request 和 Addon.Response
	Stream            bool
	UseSeparateClient bool // use separate http client to send http request
	StartTime         time.Time
	// contains filtered or unexported fields
}

flow

func (*Flow) Done

func (f *Flow) Done() <-chan struct{}

func (*Flow) MarshalJSON

func (f *Flow) MarshalJSON() ([]byte, error)

type InstanceLogAddon

type InstanceLogAddon struct {
	BaseAddon
	// contains filtered or unexported fields
}

InstanceLogAddon logs with instance identification

func NewInstanceLogAddonWithFile

func NewInstanceLogAddonWithFile(addr string, instanceName string, logFilePath string) *InstanceLogAddon

NewInstanceLogAddonWithFile creates a new instance-aware log addon with file output

func (*InstanceLogAddon) ClientConnected

func (addon *InstanceLogAddon) ClientConnected(client *ClientConn)

func (*InstanceLogAddon) ClientDisconnected

func (addon *InstanceLogAddon) ClientDisconnected(client *ClientConn)

func (*InstanceLogAddon) HTTPConnectError

func (addon *InstanceLogAddon) HTTPConnectError(f *Flow, err error)

func (*InstanceLogAddon) Request

func (addon *InstanceLogAddon) Request(f *Flow)

func (*InstanceLogAddon) RequestError

func (addon *InstanceLogAddon) RequestError(f *Flow, err error)

func (*InstanceLogAddon) Requestheaders

func (addon *InstanceLogAddon) Requestheaders(f *Flow)

func (*InstanceLogAddon) Response

func (addon *InstanceLogAddon) Response(f *Flow)

func (*InstanceLogAddon) ServerConnected

func (addon *InstanceLogAddon) ServerConnected(connCtx *ConnContext)

func (*InstanceLogAddon) ServerDisconnected

func (addon *InstanceLogAddon) ServerDisconnected(connCtx *ConnContext)

func (*InstanceLogAddon) SetLogger

func (addon *InstanceLogAddon) SetLogger(logger *InstanceLogger)

SetLogger allows setting a custom instance logger

func (*InstanceLogAddon) TlsEstablishedServer

func (addon *InstanceLogAddon) TlsEstablishedServer(connCtx *ConnContext)

type InstanceLogger

type InstanceLogger struct {
	InstanceID   string
	InstanceName string
	Port         string
	LogFilePath  string
	// contains filtered or unexported fields
}

func NewInstanceLogger

func NewInstanceLogger(addr string, instanceName string) *InstanceLogger

NewInstanceLogger creates a logger with instance identification

func NewInstanceLoggerWithFile

func NewInstanceLoggerWithFile(addr string, instanceName string, logFilePath string) *InstanceLogger

NewInstanceLoggerWithFile creates a logger with instance identification and optional file output

func (*InstanceLogger) Debug

func (il *InstanceLogger) Debug(args ...interface{})

Debug logs at debug level

func (*InstanceLogger) Debugf

func (il *InstanceLogger) Debugf(format string, args ...interface{})

Debugf logs formatted at debug level

func (*InstanceLogger) Error

func (il *InstanceLogger) Error(args ...interface{})

Error logs at error level

func (*InstanceLogger) Errorf

func (il *InstanceLogger) Errorf(format string, args ...interface{})

Errorf logs formatted at error level

func (*InstanceLogger) Fatal

func (il *InstanceLogger) Fatal(args ...interface{})

Fatal logs at fatal level

func (*InstanceLogger) Fatalf

func (il *InstanceLogger) Fatalf(format string, args ...interface{})

Fatalf logs formatted at fatal level

func (*InstanceLogger) GetEntry

func (il *InstanceLogger) GetEntry() *log.Entry

GetEntry returns the underlying logrus entry

func (*InstanceLogger) Info

func (il *InstanceLogger) Info(args ...interface{})

Info logs at info level

func (*InstanceLogger) Infof

func (il *InstanceLogger) Infof(format string, args ...interface{})

Infof logs formatted at info level

func (*InstanceLogger) Warn

func (il *InstanceLogger) Warn(args ...interface{})

Warn logs at warn level

func (*InstanceLogger) Warnf

func (il *InstanceLogger) Warnf(format string, args ...interface{})

Warnf logs formatted at warn level

func (*InstanceLogger) WithFields

func (il *InstanceLogger) WithFields(fields log.Fields) *log.Entry

WithFields adds additional fields to the logger

type LogAddon

type LogAddon struct {
	BaseAddon
}

LogAddon log connection and flow

func (*LogAddon) ClientConnected

func (addon *LogAddon) ClientConnected(client *ClientConn)

func (*LogAddon) ClientDisconnected

func (addon *LogAddon) ClientDisconnected(client *ClientConn)

func (*LogAddon) HTTPConnectError

func (addon *LogAddon) HTTPConnectError(f *Flow, err error)

func (*LogAddon) RequestError

func (addon *LogAddon) RequestError(f *Flow, err error)

func (*LogAddon) Requestheaders

func (addon *LogAddon) Requestheaders(f *Flow)

func (*LogAddon) Response

func (addon *LogAddon) Response(f *Flow)

func (*LogAddon) SSEEnd

func (addon *LogAddon) SSEEnd(f *Flow)

SSEEnd 记录 SSE 流结束

func (*LogAddon) SSEMessage

func (addon *LogAddon) SSEMessage(f *Flow)

SSEMessage 记录 SSE 事件

func (*LogAddon) SSEStart

func (addon *LogAddon) SSEStart(f *Flow)

SSEStart 记录 SSE 流开始

func (*LogAddon) ServerConnected

func (addon *LogAddon) ServerConnected(connCtx *ConnContext)

func (*LogAddon) ServerDisconnected

func (addon *LogAddon) ServerDisconnected(connCtx *ConnContext)

func (*LogAddon) WebSocketEnd

func (addon *LogAddon) WebSocketEnd(f *Flow)

WebSocketEnd 记录 WebSocket 连接结束

func (*LogAddon) WebSocketMessage

func (addon *LogAddon) WebSocketMessage(f *Flow)

WebSocketMessage 记录 WebSocket 消息

func (*LogAddon) WebSocketStart

func (addon *LogAddon) WebSocketStart(f *Flow)

WebSocketStart 记录 WebSocket 连接建立

type Options

type Options struct {
	Debug             int
	Addr              string
	StreamLargeBodies int64 // 当请求或响应体大于此字节时,转为 stream 模式
	SslInsecure       bool
	CaRootPath        string
	NewCaFunc         func() (cert.CA, error) // 创建 Ca 的函数
	Upstream          string
	LogFilePath       string // Path to write logs to file

	// ServerTLSHandshake, when non-nil, replaces the default crypto/tls outbound
	// TLS handshake with a caller-supplied implementation.
	// Typical use: inject a uTLS (bogdanfinn/utls or refraction-networking/utls)
	// handshake to mimic a specific browser's TLS/JA3 fingerprint.
	// Can also be set after NewProxy via WithServerTLSHandshake.
	ServerTLSHandshake ServerTLSHandshakeFunc

	// ServerH2ClientFactory, when non-nil, replaces the default http2.Transport
	// used for upstream HTTP/2 connections. The factory receives the already-established
	// TLS connection (from ServerTLSHandshake or default handshake) and must return
	// an *http.Client whose Transport speaks HTTP/2 over that connection.
	//
	// Typical use: inject a bogdanfinn/fhttp based transport to mimic Chrome's
	// HTTP/2 SETTINGS / WINDOW_UPDATE / PRIORITY fingerprint.
	// Can also be set after NewProxy via WithServerH2ClientFactory.
	ServerH2ClientFactory func(tlsConn net.Conn) *http.Client
}

type Proxy

type Proxy struct {
	Opts    *Options
	Version string
	Addons  []Addon
	// contains filtered or unexported fields
}

func NewProxy

func NewProxy(opts *Options) (*Proxy, error)

func (*Proxy) AddAddon

func (proxy *Proxy) AddAddon(addon Addon)

func (*Proxy) Close

func (proxy *Proxy) Close() error

func (*Proxy) GetCertificate

func (proxy *Proxy) GetCertificate() x509.Certificate

func (*Proxy) GetCertificateByCN

func (proxy *Proxy) GetCertificateByCN(commonName string) (*tls.Certificate, error)

func (*Proxy) SetAuthProxy

func (proxy *Proxy) SetAuthProxy(fn func(res http.ResponseWriter, req *http.Request) (bool, error))

func (*Proxy) SetShouldInterceptRule

func (proxy *Proxy) SetShouldInterceptRule(rule func(req *http.Request) bool)

func (*Proxy) SetUpstreamProxy

func (proxy *Proxy) SetUpstreamProxy(fn func(req *http.Request) (*url.URL, error))

func (*Proxy) Shutdown

func (proxy *Proxy) Shutdown(ctx context.Context) error

func (*Proxy) Start

func (proxy *Proxy) Start() error

func (*Proxy) WithServerH2ClientFactory

func (proxy *Proxy) WithServerH2ClientFactory(fn func(tlsConn net.Conn) *http.Client) *Proxy

WithServerH2ClientFactory sets a pluggable HTTP/2 client factory and returns the Proxy for chaining. When set, the proxy calls fn instead of using the built-in http2.Transport for every upstream HTTP/2 connection.

The factory receives the already-established TLS connection (after the TLS handshake is complete) and must return an *http.Client whose Transport speaks HTTP/2 over that connection.

Typical use: inject a bogdanfinn/fhttp based transport to mimic Chrome's HTTP/2 SETTINGS / WINDOW_UPDATE / PRIORITY fingerprint.

func (*Proxy) WithServerTLSHandshake

func (proxy *Proxy) WithServerTLSHandshake(fn ServerTLSHandshakeFunc) *Proxy

WithServerTLSHandshake sets a pluggable outbound TLS handshake function and returns the Proxy for chaining. When set, the proxy calls fn instead of the built-in crypto/tls handshake for every HTTPS upstream connection, allowing callers to substitute uTLS or any other TLS implementation without this library importing it.

Example (bogdanfinn/utls, Chrome 146 fingerprint):

proxy.WithServerTLSHandshake(func(ctx context.Context, raw net.Conn, sni string, _ *tls.ClientHelloInfo) (net.Conn, *tls.ConnectionState, error) {
    uc := utls.UClient(raw, &utls.Config{ServerName: sni, InsecureSkipVerify: false}, utls.HelloChrome_146)
    if err := uc.HandshakeContext(ctx); err != nil { return nil, nil, err }
    st := uc.ConnectionState()
    return uc, &st, nil
})

func (*Proxy) WithServerTlsConfig

func (proxy *Proxy) WithServerTlsConfig(fn func(*tls.ClientHelloInfo) *tls.Config) *Proxy

WithServerTlsConfig sets a factory that returns the *tls.Config used when connecting to upstream servers via the built-in crypto/tls path. Deprecated: prefer WithServerTLSHandshake for full control over the handshake. Returns the Proxy for chaining.

type Request

type Request struct {
	Method string
	URL    *url.URL
	Proto  string
	Header http.Header
	Body   []byte
	// contains filtered or unexported fields
}

flow http request

func (*Request) DecodedBody

func (req *Request) DecodedBody() ([]byte, error)

func (*Request) MarshalJSON

func (req *Request) MarshalJSON() ([]byte, error)

func (*Request) Raw

func (r *Request) Raw() *http.Request

func (*Request) UnmarshalJSON

func (req *Request) UnmarshalJSON(data []byte) error

type Response

type Response struct {
	StatusCode int         `json:"statusCode"`
	Header     http.Header `json:"header"`
	Body       []byte      `json:"-"`
	BodyReader io.Reader
	// contains filtered or unexported fields
}

flow http response

func (*Response) DecodedBody

func (r *Response) DecodedBody() ([]byte, error)

func (*Response) IsTextContentType

func (r *Response) IsTextContentType() bool

func (*Response) ReplaceToDecodedBody

func (r *Response) ReplaceToDecodedBody()

type SSEData

type SSEData struct {
	Events []*SSEEvent
	// contains filtered or unexported fields
}

SSEData holds all SSE events for a flow

type SSEEvent

type SSEEvent struct {
	ID    string    `json:"id,omitempty"`    // event id
	Event string    `json:"event,omitempty"` // event type (default: "message")
	Data  string    `json:"data"`            // event data
	Retry int       `json:"retry,omitempty"` // retry interval in milliseconds
	Raw   string    `json:"raw"`             // raw event text
	Time  time.Time `json:"timestamp"`       // when this event was received
}

SSEEvent represents a single Server-Sent Event

type ServerConn

type ServerConn struct {
	Id      uuid.UUID
	Address string
	Conn    net.Conn
	// contains filtered or unexported fields
}

server connection

func (*ServerConn) MarshalJSON

func (c *ServerConn) MarshalJSON() ([]byte, error)

func (*ServerConn) TlsState

func (c *ServerConn) TlsState() *tls.ConnectionState

type ServerTLSHandshakeFunc

type ServerTLSHandshakeFunc func(
	ctx context.Context,
	rawConn net.Conn,
	serverName string,
	clientHello *tls.ClientHelloInfo,
) (net.Conn, *tls.ConnectionState, error)

ServerTLSHandshakeFunc is the signature for a pluggable outbound TLS handshake.

  • rawConn – the already-established TCP connection to the upstream server
  • serverName – SNI from the browser's ClientHello
  • clientHello – the full ClientHello received from the browser (nil in lazy mode)

The function must complete the TLS handshake and return:

  • a net.Conn wrapping rawConn with TLS applied
  • the resulting *tls.ConnectionState (needed for ALPN negotiation and addons)
  • any error

This keeps the proxy library free of any specific TLS fingerprinting dependency. Supply an implementation via Options.ServerTLSHandshake or WithServerTLSHandshake.

type UpstreamCertAddon

type UpstreamCertAddon struct {
	BaseAddon
	UpstreamCert bool // Connect to upstream server to look up certificate details.
}

func NewUpstreamCertAddon

func NewUpstreamCertAddon(upstreamCert bool) *UpstreamCertAddon

func (*UpstreamCertAddon) ClientConnected

func (addon *UpstreamCertAddon) ClientConnected(conn *ClientConn)

type WebSocketData

type WebSocketData struct {
	Messages []*WebSocketMessage
	// contains filtered or unexported fields
}

type WebSocketMessage

type WebSocketMessage struct {
	Type       int
	Content    []byte
	FromClient bool
	Timestamp  time.Time
}

func (*WebSocketMessage) MarshalJSON

func (m *WebSocketMessage) MarshalJSON() ([]byte, error)

Jump to

Keyboard shortcuts

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