sniffing

package
v0.28.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 41 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ProtoHTTP  = "http"
	ProtoTLS   = "tls"
	ProtoSSH   = "ssh"
	ProtoQUIC  = "quic"
	ProtoRedis = "redis"
)
View Source
const (
	// DefaultReadTimeout is the default timeout for reading data from connections.
	DefaultReadTimeout = 30 * time.Second

	// DefaultBodySize is the default HTTP body or websocket frame size to record.
	DefaultBodySize = 64 * 1024 // 64KB
	// MaxBodySize is the maximum HTTP body or websocket frame size to record.
	MaxBodySize = 1024 * 1024 // 1MB
	// DefaultSampleRate is the default websocket sample rate (samples per second).
	DefaultSampleRate = 10.0
)

Variables

View Source
var DefaultCertPool = tls_util.NewMemoryCertPool()

DefaultCertPool is the default in-memory certificate pool used for TLS MITM.

Functions

func ClampBodySize added in v0.28.1

func ClampBodySize(opts *recorder.Options) int

ClampBodySize returns the effective body capture size from recorder options, bounded by [DefaultBodySize, MaxBodySize]. Returns 0 if body recording is disabled.

func Dispatch added in v0.28.1

func Dispatch(s *Sniffer, ctx context.Context, network string, conn net.Conn, proto string, opts ...HandleOption) (handled bool, err error)

Dispatch routes a detected protocol to its registered handler. It returns (false, nil) when no handler is registered for proto, signalling the caller to fall through to raw forwarding.

func ParseRedisMetadata added in v0.28.1

func ParseRedisMetadata(r io.Reader, ro *xrecorder.HandlerRecorderObject) error

ParseRedisMetadata reads a single RESP message from r and populates ro.Redis with the extracted command and key.

r must provide exactly one RESP message — the caller is expected to wrap the conn with io.TeeReader(conn, buf) so that the bytes are both parsed and captured in buf for replay to the upstream.

On success, ro.Redis is non-nil. On error (malformed RESP, truncated message), ro.Redis is nil and the caller should fall back to raw forwarding.

func PopulateQUICClientHello added in v0.28.1

func PopulateQUICClientHello(dgram []byte, info *dissector.ClientHelloInfo, ro *xrecorder.HandlerRecorderObject)

PopulateQUICClientHello sets ro.Proto to ProtoQUIC and populates ro.TLS from the parsed QUIC ClientHello. dgram is the raw client datagram (stored as hex in ro.TLS.ClientHello). Values are the client-offered ones and may be overwritten by PopulateQUICServerHello with negotiated values later.

func PopulateQUICServerHello added in v0.28.1

func PopulateQUICServerHello(sh *dissector.ServerHelloInfo, ro *xrecorder.HandlerRecorderObject)

PopulateQUICServerHello overwrites ro.TLS fields with negotiated values from a parsed QUIC ServerHello. ro.TLS must already be set (typically by PopulateQUICClientHello).

func Register added in v0.28.1

func Register(proto string, fn HandleFunc)

Register associates a protocol with its handler. Duplicate registration panics, mirroring the house registry pattern.

func Sniff

func Sniff(ctx context.Context, r *bufio.Reader) (proto string, err error)

Types

type HandleFunc added in v0.28.1

type HandleFunc func(s *Sniffer, ctx context.Context, network string, conn net.Conn, opts ...HandleOption) error

HandleFunc handles a connection whose protocol has been detected as proto. The receiver s carries the per-connection Sniffer state (MITM certificate, HTTP cache, recorder, etc.).

func Get added in v0.28.1

func Get(proto string) (HandleFunc, bool)

Get returns the handler registered for proto.

type HandleOption

type HandleOption func(opts *HandleOptions)

HandleOption configures HandleOptions for sniffing handlers.

func WithBypass

func WithBypass(bypass bypass.Bypass) HandleOption

WithBypass sets the bypass rules for filtering requests by host.

func WithDial

func WithDial(dial func(ctx context.Context, network, address string) (net.Conn, error)) HandleOption

WithDial sets the dial function used to establish upstream connections.

func WithDialTLS

func WithDialTLS(dialTLS func(ctx context.Context, network, address string, cfg *tls.Config) (net.Conn, error)) HandleOption

WithDialTLS sets the dial function used for TLS-wrapped upstream connections.

func WithHTTPKeepalive added in v0.28.1

func WithHTTPKeepalive(keepalive bool) HandleOption

WithHTTPKeepalive enables or disables HTTP keep-alive on the upstream connection.

func WithHop added in v0.28.1

func WithHop(h hop.Hop) HandleOption

WithHop sets the hop used for node selection when routing requests.

func WithLog

func WithLog(log logger.Logger) HandleOption

WithLog sets the logger for the handler.

func WithNode added in v0.28.1

func WithNode(node *chain.Node) HandleOption

WithNode sets a pre-resolved chain node to connect to, bypassing hop selection.

func WithRecorderObject

func WithRecorderObject(ro *xrecorder.HandlerRecorderObject) HandleOption

WithRecorderObject sets the recorder object for capturing traffic metadata.

func WithService added in v0.28.1

func WithService(service string) HandleOption

WithService sets the service name for bypass and selection lookups.

type HandleOptions

type HandleOptions struct {
	Service string
	Dial    func(ctx context.Context, network, address string) (net.Conn, error)
	DialTLS func(ctx context.Context, network, address string, cfg *tls.Config) (net.Conn, error)

	HTTPKeepalive bool
	ReadTimeout   time.Duration

	Node *chain.Node
	Hop  hop.Hop

	Bypass         bypass.Bypass
	RecorderObject *xrecorder.HandlerRecorderObject
	Log            logger.Logger
}

HandleOptions holds configuration options for sniffing handlers. Fields are exported because forwarder's protocol handlers set them across the package boundary.

func (*HandleOptions) CheckBypass added in v0.28.1

func (ho *HandleOptions) CheckBypass(ctx context.Context, network, host string, opts ...bypass.Option) error

checkBypass reports whether the bypass in effect right now refuses host, returning xbypass.ErrBypass when it does.

Call it once per request, never once per connection. A bypass can be reloaded while a connection is open, and one connection can carry a different host per request: HTTP/1.1 keep-alive sends a Host per request and HTTP/2 an :authority per stream. A check performed only at connection setup authorizes the first request and then nothing.

type Sniffer

type Sniffer struct {
	Websocket           bool
	WebsocketSampleRate float64

	Recorder        recorder.Recorder
	RecorderOptions *recorder.Options
	SessionRecorder *xrecorder.SessionRecorder

	// MITM TLS termination
	Certificate        *x509.Certificate
	PrivateKey         crypto.PrivateKey
	NegotiatedProtocol string
	CertPool           tls_util.CertPool
	MitmBypass         bypass.Bypass

	// ReadTimeout is the deadline for reading the upstream response
	// headers during HTTP sniffing (http.ReadResponse) and the TLS
	// ServerHello during TLS sniffing. This timeout is applied once
	// per request/response pair in the HTTP keep-alive loop and cleared
	// after each response is received. It does NOT affect the client
	// connection or the response body transfer.
	// Default: DefaultReadTimeout (30s) if not set.
	ReadTimeout time.Duration

	// Cache, when non-nil, caches upstream HTTP responses. It is shared across
	// connections (built once per service), so all connections referencing the
	// same named cache share one store.
	Cache *httpcache.Cache
}

Sniffer handles HTTP and TLS traffic sniffing, recording, and MITM TLS termination for protocol-aware forwarding.

func (*Sniffer) HandleHTTP

func (h *Sniffer) HandleHTTP(ctx context.Context, network string, conn net.Conn, opts ...HandleOption) error

HandleHTTP sniffs and proxies an HTTP connection. It reads the initial request, applies bypass rules, and forwards traffic to the upstream.

func (*Sniffer) HandleRedis added in v0.28.1

func (h *Sniffer) HandleRedis(ctx context.Context, network string, conn net.Conn, opts ...HandleOption) error

HandleRedis proxies a sniffed Redis connection. It parses the first RESP message for metadata recording, then replays the captured bytes to the upstream and pipes traffic bidirectionally.

The network parameter is passed through to the injected dial function. Bypass checks are not performed here — Redis has no host concept for bypass to match against; protocol-based routing is handled by the hop selector in the forwarder path.

func (*Sniffer) HandleTLS

func (h *Sniffer) HandleTLS(ctx context.Context, network string, conn net.Conn, opts ...HandleOption) error

HandleTLS sniffs and proxies a TLS connection. It parses the ClientHello for SNI-based routing, optionally performs MITM TLS termination for HTTP content inspection, and records TLS handshake metadata.

Jump to

Keyboard shortcuts

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