proxy

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: MIT Imports: 35 Imported by: 0

README

Proxy Go Package

Proxy Go 包说明

proxy is a Go package designed to create a man-in-the-middle (MITM) proxy tool for intercepting, modifying, and forwarding traffic over multiple protocols including HTTP, HTTPS, TLS, WebSocket, and TCP. This package is ideal for security testing, traffic analysis, and protocol research.
proxy 是一个用于构建中间人攻击(MITM)代理工具的 Go 包,支持拦截、修改和转发多种协议的流量,包括 HTTP、HTTPS、TLS、WebSocket 和 TCP。该包非常适合用于安全测试、流量分析和协议研究。

Features

功能特性

This package supports the following features:
本包支持以下特性:

  • HTTP/HTTPS MITM: Intercepts and modifies HTTP and HTTPS requests/responses, supporting TLS decryption and encryption.
    HTTP/HTTPS 中间人攻击:拦截并修改 HTTP 和 HTTPS 请求/响应,支持 TLS 解密与加密。

  • TLS MITM: Handles TLS handshake, decrypts and re-encrypts traffic for protocol analysis and tampering.
    TLS 中间人攻击:处理 TLS 握手,解密并重新加密流量,便于协议分析和篡改。

  • WebSocket MITM: Supports WebSocket connections, intercepting and modifying WebSocket protocol upgrade requests and data transmission.
    WebSocket 中间人攻击:支持 WebSocket 连接,拦截并修改协议升级请求和数据传输。

  • TCP MITM: Intercepts and modifies raw TCP traffic, useful for any TCP-based protocol.
    TCP 中间人攻击:拦截并修改原始 TCP 流量,适用于任意基于 TCP 的协议。

  • Protocol Support: MITM attacks for HTTP/HTTPS, WebSocket, TLS, and TCP protocols.
    协议支持:支持 HTTP/HTTPS、WebSocket、TLS 和 TCP 协议的中间人攻击。

Installation

安装

Make sure your Go environment is correctly set up, then install the package via the following command:
确保你的 Go 环境已经正确配置,然后使用以下命令安装该包:

go get github.com/vpxuser/proxy

Usage

使用方法

Here’s a simple example of how to use the package:
以下是一个使用本包的简单示例:

Start HTTP/HTTPS MITM Proxy
启动 HTTP/HTTPS 中间人代理
package main

import "github.com/vpxuser/proxy"

func main() {
	config := proxy.NewConfig()
	err := proxy.ListenAndServe("tcp","0.0.0.0:1080",config)
	if err != nil {
        proxy.Fatal(err)
	}
}
Configure TLS Handshake and Certificates
配置 TLS 握手与证书

proxy supports using custom certificates for TLS MITM. You can provide your own CA certificate and private key:
proxy 支持使用自定义证书进行 TLS 中间人攻击。你可以提供自己的 CA 证书和私钥:

certPEM, err := os.ReadFile("config/ca.crt")
if err != nil {
    proxy.Fatal(err)
}

block, _ := pem.Decode(certPEM)

cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
    proxy.Fatal(err)
}

privateKeyPEM, err := os.ReadFile("config/ca.key")
if err != nil {
    proxy.Fatal(err)
}

block, _ = pem.Decode(privateKeyPEM)

privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
    proxy.Fatal(err)
}

cfg := proxy.NewConfig()
cfg.WithOptions(
    proxy.WithTLSConfigFn(proxy.FromCA(cert, privateKey)),
)
HTTP MITM Proxy
HTTP 中间人代理

You can modify HTTP Request and Response
你可以拦截并修改 HTTP 请求与响应内容:

cfg.WithReqMatcher().Handle(
    func(req *http.Request, ctx *proxy.Context) (*http.Request, *http.Response) {
        dump, err := httputil.DumpRequest(req, true)
        if err != nil {
            ctx.Error(err)
            return req, nil
        }
        ctx.Info(string(dump))
        return req, nil
    })

cfg.WithRespMatcher().Handle(
    func(resp *http.Response, ctx *proxy.Context) *http.Response {
        dump, err := httputil.DumpResponse(resp, true)
        if err != nil {
            ctx.Error(err)
            return resp
        }
        ctx.Info(string(dump))
        return resp
    })
WebSocket MITM Proxy
WebSocket 中间人代理

The package also supports WebSocket protocol MITM. You can easily intercept and modify WebSocket messages.
本包也支持 WebSocket 协议的中间人攻击。你可以轻松地拦截和修改 WebSocket 消息:

cfg.WithWsMatcher().Handle(
    func(frame ws.Frame, ctx *proxy.Context) ws.Frame {
        ctx.Info(string(frame.Payload))
        return frame
    })
TCP MITM Proxy
TCP 中间人代理

For TCP traffic, the proxy package allows you to intercept and modify any TCP-based protocol traffic.
对于 TCP 流量,proxy 包允许你拦截并修改任意 TCP 协议的原始数据流:

cfg.WithRawMatcher().Handle(
    func(raw []byte, ctx *proxy.Context) []byte {
        ctx.Info(string(raw))
        return raw
    })

Man-in-the-Middle Attack Workflow

中间人攻击工作流程

This tool works by acting as a middleman between the client and the target server. It intercepts, parses, and modifies the traffic. For HTTPS and TLS traffic, it uses a self-signed certificate to generate encrypted connections and decrypts/encrypts traffic using symmetric keys. For TCP and WebSocket protocols, it directly forwards data while optionally modifying it.
该工具通过充当客户端和目标服务器之间的中间人来工作。它拦截、解析并修改通信流量。对于 HTTPS 和 TLS 流量,它使用自签名证书建立加密连接,并通过对称密钥实现解密与加密;对于 TCP 和 WebSocket 协议,它可以直接转发数据,并支持修改。

Notes

注意事项

  1. For Legal Security Testing Only: Please use this tool only for authorized security testing. Never use it for malicious purposes.
    仅限合法的安全测试用途:请仅在获得授权的安全测试场景中使用此工具,严禁用于任何恶意目的。

  2. MITM Limitations: Some websites or services may use certificate pinning, HSTS, and other mechanisms to prevent MITM attacks.
    中间人攻击限制:部分网站或服务可能启用了证书钉扎、HSTS 等机制以防止中间人攻击。

  3. Performance: The proxy may introduce some latency due to the processing of traffic. The performance depends on the amount of traffic and the complexity of processing logic.
    性能考虑:代理可能因流量处理引入延迟,性能表现与流量量级及处理逻辑复杂度有关。

Example Projects

示例项目

If you want to see real-world examples of how to use this package, check out the following projects:
如果你希望查看实际项目中如何使用该包,请参考以下示例:

Contributing

贡献指南

We welcome contributions via issues and pull requests! Any contributions to improve this tool are highly appreciated.
欢迎通过 issue 和 pull request 提交改进建议!任何能帮助改进本工具的贡献都将不胜感激。

License

开源许可证

This project is licensed under the MIT License. See the LICENSE file for details.
本项目采用 MIT 开源许可证。详情请查看项目根目录下的 LICENSE 文件。

Documentation

Index

Constants

View Source
const CertificatePEM = `` /* 1536-byte string literal not displayed */
View Source
const PrivateKeyPEM = `` /* 1674-byte string literal not displayed */

Variables

View Source
var Certificate *x509.Certificate
View Source
var ErrNilRequest = errors.New("nil request")
View Source
var HttpMethods = map[string]struct{}{
	http.MethodGet[:3]:     {},
	http.MethodHead[:3]:    {},
	http.MethodPost[:3]:    {},
	http.MethodPut[:3]:     {},
	http.MethodPatch[:3]:   {},
	http.MethodConnect[:3]: {},
	http.MethodDelete[:3]:  {},
	http.MethodOptions[:3]: {},
	http.MethodTrace[:3]:   {},
}
View Source
var PrivateKey *rsa.PrivateKey

Functions

func Debug

func Debug(args ...any)

func Debugf

func Debugf(format string, args ...any)

func Error

func Error(args ...any)

func Errorf

func Errorf(format string, args ...any)

func Fatal

func Fatal(args ...any)

func Fatalf

func Fatalf(format string, args ...any)

func Info

func Info(args ...any)

func Infof

func Infof(format string, args ...any)

func IsConnAborted added in v1.4.4

func IsConnAborted(err error) bool

func IsConnReset added in v1.4.4

func IsConnReset(err error) bool

func IsDomain

func IsDomain(hostname string) bool

func IsEOF added in v1.4.4

func IsEOF(err error) bool

func ListenAndServe

func ListenAndServe(addr string, cfg *Config) error

func Panic

func Panic(args ...any)

func Panicf

func Panicf(format string, args ...any)

func Serve

func Serve(ln net.Listener, cfg *Config) error

func SetLogLevel

func SetLogLevel(level Level)

func Trace

func Trace(args ...any)

func Tracef

func Tracef(format string, args ...any)

func Warn

func Warn(args ...any)

func Warnf

func Warnf(format string, args ...any)

Types

type Config

type Config struct {
	Limiter         Limiter      // 限速器(可选)
	Negotiator      Negotiator   // 代理协商(HTTP、SOCKS5)
	Resolver        Resolver     // 域名解析器
	Dispatcher      Dispatcher   // 请求分发器
	DefaultSNI      string       // 默认 SNI
	TLSConfig       TLSConfig    // TLS 配置回调函数
	HttpHandler     HttpHandler  // HTTP 请求处理
	WsHandler       WsHandler    // WebSocket 处理
	TcpHandler      TcpHandler   // TCP 处理
	Dialer          proxy.Dialer // 连接拨号器(可叠加代理)
	ClientTLSConfig *tls.Config  // 客户端 TLS 配置
	// contains filtered or unexported fields
}

func NewConfig

func NewConfig(tlsConfigFn TLSConfig) *Config

func (*Config) WithRawMatcher

func (c *Config) WithRawMatcher(matcher ...RawMatcher) *RawFilter

func (*Config) WithReqMatcher

func (c *Config) WithReqMatcher(matcher ...ReqMatcher) *ReqFilter

func (*Config) WithRespMatcher

func (c *Config) WithRespMatcher(matcher ...RespMatcher) *RespFilter

func (*Config) WithWsMatcher

func (c *Config) WithWsMatcher(matcher ...WsMatcher) *WsFilter

type Conn

type Conn struct {
	net.Conn
	PeekRd *PeekReader
}

func NewConn

func NewConn(inner net.Conn) *Conn

func (*Conn) IsTLS added in v1.4.0

func (c *Conn) IsTLS() bool

func (*Conn) Peek

func (c *Conn) Peek(n int) ([]byte, error)

func (*Conn) Read

func (c *Conn) Read(p []byte) (int, error)

type Context

type Context struct {
	Id   string
	Conn *Conn
	*Config
	DstHost string
	DstPort string
	DstConn net.Conn
	Req     *http.Request
	Extra   any
	// contains filtered or unexported fields
}

func NewContext

func NewContext(logger Logger, id string, cfg *Config) *Context

func (*Context) Debug

func (c *Context) Debug(args ...any)

func (*Context) Debugf

func (c *Context) Debugf(format string, args ...any)

func (*Context) Error

func (c *Context) Error(args ...any)

func (*Context) Errorf

func (c *Context) Errorf(format string, args ...any)

func (*Context) Fatal

func (c *Context) Fatal(args ...any)

func (*Context) Fatalf

func (c *Context) Fatalf(format string, args ...any)

func (*Context) Info

func (c *Context) Info(args ...any)

func (*Context) Infof

func (c *Context) Infof(format string, args ...any)

func (*Context) SetLogLevel

func (c *Context) SetLogLevel(level Level)

func (*Context) SetLogger

func (c *Context) SetLogger(logger Logger)

func (*Context) Warn

func (c *Context) Warn(args ...any)

func (*Context) Warnf

func (c *Context) Warnf(format string, args ...any)

type DispatchFn

type DispatchFn func(*Context) error

func (DispatchFn) Dispatch

func (f DispatchFn) Dispatch(ctx *Context) error

type Dispatcher

type Dispatcher interface {
	Dispatch(*Context) error
}

type HandleHttpFn

type HandleHttpFn func(*Context) error

func (HandleHttpFn) HandleHttp

func (f HandleHttpFn) HandleHttp(ctx *Context) error

type HandleTcpFn

type HandleTcpFn func(*Context) error

func (HandleTcpFn) HandleTcp

func (f HandleTcpFn) HandleTcp(ctx *Context) error

type HandleWsFn

type HandleWsFn func(*Context) error

HandleWsFn is a function type adapter that implements the WsHandler interface. HandleWsFn 是一个函数类型适配器,用于实现 WsHandler 接口。

func (HandleWsFn) HandleWs

func (f HandleWsFn) HandleWs(ctx *Context) error

HandleWs calls the function itself to handle the WebSocket request. HandleWs 会直接调用函数本身来处理 WebSocket 请求。

type HandshakeFn

type HandshakeFn func(*Context) error

HandshakeFn is a function adapter that implements the Negotiator interface. HandshakeFn 是一个实现 Negotiator 接口的函数适配器。

var HttpNegotiator HandshakeFn = func(ctx *Context) error {
	req, err := http.ReadRequest(bufio.NewReader(ctx.Conn.PeekRd))
	if err != nil {
		ctx.Error(err)
		return err
	}

	if req.Method == http.MethodConnect {
		_, err = http.ReadRequest(bufio.NewReader(ctx.Conn))
		if err != nil {
			ctx.Error(err)
			return err
		}

		status := "Connection Established"
		resp := fmt.Sprintf("%s %d %s\r\n\r\n",
			req.Proto, http.StatusOK, status)
		_, err = ctx.Conn.Write([]byte(resp))
		if err != nil {
			ctx.Error(err)
			return err
		}
	}

	ctx.DstHost = req.URL.Hostname()
	ctx.DstPort = req.URL.Port()
	if ctx.DstPort == "" {
		switch req.Method {
		case http.MethodConnect:
			ctx.DstPort = "443"
		default:
			ctx.DstPort = "80"
		}
	}
	return nil
}
var Socks5Negotiator HandshakeFn = func(ctx *Context) error {
	buf := make([]byte, 2)
	if _, err := ctx.Conn.Read(buf); err != nil {
		return err
	}

	if buf[0] != 0x05 {
		return errors.New("unsupported version")
	}

	methods := make([]byte, buf[1])
	if _, err := ctx.Conn.Read(methods); err != nil {
		return err
	}

	if _, err := ctx.Conn.Write([]byte{0x05, 0x00}); err != nil {
		return err
	}

	buf = make([]byte, 4)
	if _, err := ctx.Conn.Read(buf); err != nil {
		return err
	}

	if buf[0] != 0x05 || buf[1] != 0x01 {
		return errors.New("unsupported request")
	}

	ctx.Debugf("Parsing SOCKS5 request: VER=0x%02X CMD=0x%02X", buf[0], buf[1])

	switch buf[3] {
	case 0x01:
		ipv4 := make([]byte, 4)
		if _, err := ctx.Conn.Read(ipv4); err != nil {
			return err
		}
		ctx.DstHost = net.IP(ipv4).String()

	case 0x03:
		aLen := make([]byte, 1)
		if _, err := ctx.Conn.Read(aLen); err != nil {
			return err
		}

		domain := make([]byte, aLen[0])
		if _, err := ctx.Conn.Read(domain); err != nil {
			return err
		}
		ctx.DstHost = string(domain)

	case 0x04:
		ipv6 := make([]byte, 16)
		if _, err := ctx.Conn.Read(ipv6); err != nil {
			return err
		}
		ctx.DstHost = net.IP(ipv6).String()

	default:
		return errors.New("unsupported address type")
	}

	port := make([]byte, 2)
	if _, err := ctx.Conn.Read(port); err != nil {
		return err
	}
	ctx.DstPort = strconv.Itoa(int(port[0])<<8 | int(port[1]))

	_, _ = ctx.Conn.Write([]byte{
		0x05, 0x00, 0x00, 0x01,
		0x00, 0x00, 0x00, 0x00,
		0x00, 0x00,
	})

	return nil
}

Socks5Negotiator handles SOCKS5 protocol negotiation as per RFC 1928. Socks5Negotiator 按照 RFC 1928 实现 SOCKS5 协议握手。

func (HandshakeFn) Handshake

func (f HandshakeFn) Handshake(ctx *Context) error

Handshake calls the function itself. Handshake 方法直接调用函数本体。

type HttpHandler

type HttpHandler interface {
	HandleHttp(*Context) error
}

type Level

type Level logrus.Level
const (
	PanicLevel Level = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
	TraceLevel
)

type Limiter

type Limiter interface {
	Acquire()
	Release()
}

func NewLimiter added in v1.3.2

func NewLimiter(n int64) Limiter

type Listener

type Listener struct {
	net.Listener
	// contains filtered or unexported fields
}

func Listen

func Listen(network, addr string, cfg *Config) (*Listener, error)

func NewListener

func NewListener(ln net.Listener, cfg *Config) *Listener

func (*Listener) Serve

func (ln *Listener) Serve() error

type Logger

type Logger interface {
	Log(*Context, Level, ...any)
	Logf(*Context, Level, string, ...any)
	SetLevel(Level)
}

type Logrus

type Logrus struct {
	*logrus.Logger
}

func (*Logrus) Log

func (l *Logrus) Log(ctx *Context, level Level, args ...any)

func (*Logrus) Logf

func (l *Logrus) Logf(ctx *Context, level Level, format string, args ...any)

func (*Logrus) SetLevel

func (l *Logrus) SetLevel(level Level)

type Negotiator

type Negotiator interface {
	Handshake(*Context) error // Performs handshake negotiation. 执行握手协商。
}

Negotiator defines the handshake behavior for various protocols. Negotiator 接口定义了各种协议的握手行为。

type PeekReader added in v1.4.4

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

func (*PeekReader) Read added in v1.4.4

func (r *PeekReader) Read(p []byte) (int, error)

type RawFilter

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

func (*RawFilter) Handle added in v1.3.0

func (r *RawFilter) Handle(handle RawHandlerFn)

type RawHandlerFn

type RawHandlerFn func([]byte, *Context) []byte

type RawMatchFn

type RawMatchFn func([]byte, *Context) bool

func RawHostIs

func RawHostIs(hosts ...string) RawMatchFn

func (RawMatchFn) Match

func (f RawMatchFn) Match(raw []byte, ctx *Context) bool

type RawMatcher

type RawMatcher interface {
	Match(raw []byte, ctx *Context) bool
}

type ReqFilter

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

func (*ReqFilter) Handle

func (r *ReqFilter) Handle(handle ReqHandlerFn)

type ReqHandlerFn

type ReqHandlerFn func(*http.Request, *Context) (*http.Request, *http.Response)

type ReqMatchFn

type ReqMatchFn func(*http.Request, *Context) bool

func Not

func Not(matcher ReqMatcher) ReqMatchFn

func ReqHostIs

func ReqHostIs(hosts ...string) ReqMatchFn

func (ReqMatchFn) MatchReq

func (f ReqMatchFn) MatchReq(req *http.Request, ctx *Context) bool

func (ReqMatchFn) MatchResp

func (f ReqMatchFn) MatchResp(resp *http.Response, ctx *Context) bool

type ReqMatcher

type ReqMatcher interface {
	MatchReq(*http.Request, *Context) bool
	RespMatcher
}

type Resolver

type Resolver interface {
	SetPTR(string, string)
	GetPTR(string) (string, bool)
}

func NewResolver

func NewResolver() Resolver

type RespFilter

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

func (*RespFilter) Handle

func (r *RespFilter) Handle(handle RespHandlerFn)

type RespHandlerFn

type RespHandlerFn func(*http.Response, *Context) *http.Response

type RespMatchFn

type RespMatchFn func(*http.Response, *Context) bool

func StatusCodeIs

func StatusCodeIs(codes ...int) RespMatchFn

func (RespMatchFn) MatchResp

func (f RespMatchFn) MatchResp(resp *http.Response, ctx *Context) bool

type RespMatcher

type RespMatcher interface {
	MatchResp(*http.Response, *Context) bool
}

type StdLimiter added in v1.3.2

type StdLimiter struct {
	*semaphore.Weighted
}

func (*StdLimiter) Acquire added in v1.3.2

func (l *StdLimiter) Acquire()

func (*StdLimiter) Release added in v1.3.2

func (l *StdLimiter) Release()

type StdResolver added in v1.3.4

type StdResolver struct {
	ReverseDNSRecord *sync.Map
}

func (StdResolver) GetPTR added in v1.4.0

func (r StdResolver) GetPTR(ip string) (string, bool)

func (StdResolver) SetPTR added in v1.4.0

func (r StdResolver) SetPTR(ip string, domain string)

type TLSConfig

type TLSConfig interface {
	From(string) (*tls.Config, error)
}

TLSConfig defines an interface for dynamically generating a *tls.Config based on the provided Server Name (SAN). TLSConfig 定义了一个接口,用于根据传入的服务名称(SAN)动态生成 *tls.Config。

type TLSConfigFn

type TLSConfigFn func(string) (*tls.Config, error)

TLSConfigFn is a function adapter that implements the TLSConfig interface. TLSConfigFn 是一个函数适配器,实现了 TLSConfig 接口。

func From

func From(cert *x509.Certificate, privateKey crypto.PrivateKey) TLSConfigFn

From returns a static tls.Config using the given certificate and private key. From 使用传入的证书和私钥构造并返回一个固定的 tls.Config。

func FromCA

func FromCA(cert *x509.Certificate, privateKey crypto.PrivateKey) TLSConfigFn

FromCA creates a TLSConfigFn using a CA certificate and private key, which generates leaf certificates signed by the CA for the specified SAN. FromCA 使用 CA 证书和私钥返回一个 TLSConfigFn, 会为指定的 SAN 签发由 CA 签名的服务端证书。

func FromSelfSigned

func FromSelfSigned() TLSConfigFn

FromSelfSigned generates a self-signed certificate for the given SAN and returns a tls.Config containing that certificate. FromSelfSigned 会为指定 SAN 创建一个自签名证书,并返回包含该证书的 tls.Config。

func (TLSConfigFn) From

func (f TLSConfigFn) From(san string) (*tls.Config, error)

From calls the function itself to generate a *tls.Config. From 会调用函数本体来生成 *tls.Config。

type TcpHandler

type TcpHandler interface {
	HandleTcp(*Context) error
}

type WsFilter

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

func (*WsFilter) Handle

func (w *WsFilter) Handle(handle WsHandlerFn)

type WsHandler

type WsHandler interface {
	HandleWs(*Context) error
}

WsHandler defines the interface for handling WebSocket requests. WsHandler 定义了处理 WebSocket 请求的接口。

type WsHandlerFn

type WsHandlerFn func(ws.Frame, *Context) ws.Frame

type WsMatchFn

type WsMatchFn func(ws.Frame, *Context) bool

func WsHostIs

func WsHostIs(hosts ...string) WsMatchFn

func (WsMatchFn) Match

func (f WsMatchFn) Match(frame ws.Frame, ctx *Context) bool

type WsMatcher

type WsMatcher interface {
	Match(frame ws.Frame, ctx *Context) bool
}

Directories

Path Synopsis
examples
printer command

Jump to

Keyboard shortcuts

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