ciproxy

package module
v0.0.0-...-55957db Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README




CiProxy

Introduce
ciproxy 是一个基于 TCP 实现的 Go 语言代理框架,支持 HTTP/HTTPS 代理、MITM 拦截、流量捕获与重放等功能 A Go proxy framework based on TCP, supporting HTTP/HTTPS proxy, MITM interception, traffic capture and replay

golang request open sourse (shields.io) github (shields.io) gitee (shields.io) git (shields.io) img

Features

  • 纯原生 Go 实现,无第三方依赖
  • 参考 Gin/Echo 框架设计的中间件系统
  • 支持多种代理模式:HTTP、HTTPS、HTTPS Sniff、TCP Tunnel、WebSocket
  • MITM 拦截:完整支持 HTTP/1.1 和 HTTP/2 流量拦截
  • 流量捕获与重放:支持请求/响应的捕获、存储和重放
  • 链式调用 API:优雅的服务器配置方式
  • 优雅关闭:支持信号处理和上下文取消
  • 配置系统:支持 JSON 配置文件

Proxy Methods

Method Description
HttpProxy HTTP 代理
HttpsProxy HTTPS 代理 (CONNECT 隧道)
HttpsSniffProxy HTTPS 嗅探代理
HttpsSniffDetailProxy HTTPS 详细嗅探代理
HttpInterceptProxy HTTPS MITM 拦截代理 (支持 HTTP/1.1 & HTTP/2)
TcpTunnelProxy TCP 隧道代理
WebsocketProxy WebSocket 代理
DefaultProxy 自定义代理模式

Install

go get github.com/opencvlzg/ciproxy

Quick Start

方式一:链式调用 (推荐)
package main

import (
    "github.com/opencvlzg/ciproxy"
)

func main() {
    // 使用链式调用创建服务器
    proxy := ciproxy.New().
        SetHost("127.0.0.1", "8080").
        SetMethod(ciproxy.HttpsProxy).
        Use(loggingMiddleware).
        Handle(customHandler)

    // 启动服务器
    proxy.Run()
}

func loggingMiddleware(ctx *ciproxy.Context) {
    ctx.Next()
}

func customHandler(ctx *ciproxy.Context) {
    // 自定义处理逻辑
    ctx.Next()
}
方式二:配置选项
package main

import (
    "github.com/opencvlzg/ciproxy"
)

func main() {
    proxy := ciproxy.New(
        ciproxy.WithHost("127.0.0.1", "8080"),
        ciproxy.WithMethod(ciproxy.HttpInterceptProxy),
        ciproxy.WithMaxConnections(10000),
    )

    proxy.Use(loggingMiddleware)
    proxy.Run()
}
方式三:向后兼容 API
package main

import (
    "flag"
    "github.com/opencvlzg/ciproxy"
)

func main() {
    ip := flag.String("ip", "127.0.0.1", "Server Ip Address")
    port := flag.String("port", "8080", "Server Port")
    method := flag.String("method", ciproxy.HttpsProxy, "Proxy Method")
    flag.Parse()

    proxyServe := ciproxy.ProxyServe{
        Ip:       *ip,
        Port:     *port,
        Method:   *method,
        Protocol: "TCP",
    }
    proxyServe.AddMiddleware(loggingMiddleware)
    proxyServe.Start()
}

MITM 拦截

package main

import (
    "github.com/opencvlzg/ciproxy"
    "github.com/opencvlzg/ciproxy/pkg/mitm"
    "github.com/opencvlzg/ciproxy/pkg/middleware"
)

func main() {
    // 创建 MITM 拦截器
    interceptor := mitm.NewInterceptor(&mitm.InterceptorConfig{
        EnableTrafficCapture: true,
        EnableHTTP2:          true,
    })

    // 添加拦截中间件
    interceptor.UseFunc(func(ctx *ciproxy.Context) *http.Response {
        // 修改请求或返回自定义响应
        if ctx.GetRequestHeader("X-Custom") == "" {
            ctx.SetRequestHeader("X-Custom", "injected")
        }
        return nil // 返回 nil 放行,返回 response 则阻断请求
    })

    // 启动代理服务器
    proxy := ciproxy.New().SetMethod(ciproxy.HttpInterceptProxy)
    proxy.Run()
}

流量捕获与重放

package main

import (
    "github.com/opencvlzg/ciproxy/pkg/transfer"
)

func main() {
    store := transfer.GetTrafficStore()

    // 捕获请求
    capturedReq := transfer.CaptureFromRequest(req)
    id := store.Capture(capturedReq)

    // 获取流量
    entry, ok := store.Get(id)

    // 列出所有流量
    entries := store.List()

    // 导出/导入
    data, _ := store.Export()
    store.Import(data)

    // 重放请求
    replayer := transfer.NewReplayer()
    resp, _ := replayer.Replay(entry)
}

内置中间件

import "github.com/opencvlzg/ciproxy/pkg/middleware/builtins"

// 日志中间件
proxy.Use(builtins.Logging())

// CORS 中间件
proxy.Use(builtins.CORS())

// 请求头修改
proxy.Use(builtins.SetHeader("X-Proxy", "CiProxy"))

// 请求体修改
proxy.Use(builtins.SetBody([]byte("modified body")))

// 请求阻断
proxy.Use(builtins.BlockWithStatus(403, "Forbidden"))

配置文件

{
  "ip": "127.0.0.1",
  "port": "8080",
  "protocol": "TCP",
  "method": "HttpInterceptProxy",
  "logPath": "log/proxy.log",
  "tls": {
    "certPath": "",
    "keyPath": ""
  },
  "timeout": {
    "connect": "10s",
    "read": "30s",
    "write": "30s"
  },
  "features": {
    "enableTrafficCapture": true,
    "enableTrafficReplay": true
  }
}

TLS 证书说明:默认使用内嵌证书,零配置开箱即用。如需使用自定义证书,设置 certPathkeyPath 即可。

加载配置:

config, _ := ciproxy.LoadConfig("config.json")
proxy := ciproxy.New(ciproxy.WithConfig(config))
proxy.Run()

Directory

├── cmd/                     # 示例程序
│   ├── custom_proxy_server/ # 自定义代理服务器
│   ├── generate_cert/       # 证书生成工具
│   ├── https_proxy_server/  # HTTPS 代理服务器
│   ├── https_sniff_proxy_server/ # HTTPS 嗅探代理
│   ├── tunnel_proxy_client/ # 隧道代理客户端
│   ├── tunnel_proxy_server/ # 隧道代理服务器
│   └── websocket_proxy_server/ # WebSocket 代理
├── pkg/                     # 核心包
│   ├── context/             # 请求上下文 (参考 Gin 设计)
│   ├── middleware/          # 中间件系统
│   │   └── builtins/        # 内置中间件
│   ├── module/              # 功能模块
│   │   └── mitm/            # MITM 拦截器
│   ├── transfer/            # 流量捕获与重放
│   └── util/                # 工具函数
├── ciproxy.go               # 入口文件
├── config.go                # 配置管理
├── constants.go             # 常量定义
├── errors.go                # 错误处理
├── logger.go                # 日志系统
├── proxy_handle.go          # 代理处理器
├── serve.go                 # 服务器核心实现
├── serve_handle.go          # 服务处理
├── traffic_handle.go        # 流量处理
└── go.mod

API Reference

ProxyServe
Method Description
New(opts...ServerOption) 创建服务器实例
Use(middleware...ProxyHandle) 添加中间件
Handle(handler ProxyHandle) 添加处理器
SetMethod(method string) 设置代理模式
SetHost(ip, port string) 设置监听地址
Start() error 启动服务器
Run() error 启动并阻塞
Shutdown(ctx context.Context) error 优雅关闭
Stats() ServerStats 获取统计信息
Context
Method Description
Next() 执行下一个处理器
Abort() 中断处理器链
GetRequest() *http.Request 获取请求
GetResponse() *http.Response 获取响应
GetRequestBody() []byte 获取请求体
SetRequestBody([]byte) 设置请求体
GetRequestHeader(key) string 获取请求头
SetRequestHeader(key, value) 设置请求头
BlockWithStatus(code, body) 阻断并返回响应

Todo

  • 完善文档和注释
  • 实现代理切换控制台
  • 添加更多使用示例
  • 性能优化
  • 单元测试覆盖

Contact

google email: cilanguser@gmail.com

License

CiProxy 遵循 MIT 开源协议

Documentation

Overview

Package ciproxy a proxy frame implement by tcp,udp

Package ciproxy proxyHandle 代理响应处理头

Package ciproxy 流量转发

Index

Constants

View Source
const (
	HttpProxy             = "HttpProxy"
	HttpsProxy            = "HttpsProxy"
	HttpsSniffProxy       = "HttpsSniffProxy"
	HttpsSniffDetailProxy = "HttpsSniffDetailProxy"
	HttpInterceptProxy    = "HttpInterceptProxy" // 新增:完整的 HTTPS MITM 拦截代理
	WebsocketProxy        = "WebsocketProxy"
	TcpNormalProxy        = "TcpNormal"
	TcpTunnelProxy        = "TcpTunnel"
	PortProxy             = "PortProxy"
	DefaultProxy          = "All"
)

ProxyMethod constant proxyMethod

View Source
const (
	ProxyVersion = "v0.0.0"
	ProxyMode    = "Debug"

	// DefaultIp DefaultPort defaultServerConfig
	DefaultIp   = "127.0.0.1"
	DefaultPort = ""

	ProxyOrganization = "www.cilang.buzz"
)

Proxy Config

View Source
const (
	DefaultConnectProtocol = "Tcp"
	DefaultOutTime         = 10 * time.Second
)

connectConfig Connect Config Constant

Variables

View Source
var (
	ErrInvalidRequest       = errors.New("invalid request")
	ErrConnectionFailed     = errors.New("remote connection failed")
	ErrTLSHandshakeFailed   = errors.New("TLS handshake failed")
	ErrCertificateLoad      = errors.New("certificate load failed")
	ErrProtocolNotSupported = errors.New("protocol not supported")
	ErrEntryNotFound        = errors.New("traffic entry not found")
)

标准错误定义

View Source
var DefaultConfig = ProxyConfig{
	IP:       DefaultIp,
	Port:     "8080",
	Protocol: DefaultConnectProtocol,
	Method:   HttpProxy,
	LogPath:  "",
	TLS: TLSConfig{

		CertPath: "",
		KeyPath:  "",
	},
	Timeout: TimeoutConfig{
		Connect: DefaultOutTime,
		Read:    30 * time.Second,
		Write:   30 * time.Second,
	},
	Features: FeatureFlags{
		EnableTrafficCapture: false,
		EnableTrafficReplay:  false,
		EnableTunnelCrypt:    false,
	},
}

DefaultConfig 默认配置

View Source
var DefaultWriter io.Writer = os.Stdout

DefaultWriter reference gin

View Source
var WithBufferSize = transfer.WithBufferSize

WithBufferSize 设置缓冲区大小

View Source
var WithCryptor = transfer.WithCryptor

WithCryptor 设置加密器

View Source
var WithDataCallback = transfer.WithDataCallback

WithDataCallback 设置数据回调

View Source
var WithErrorCallback = transfer.WithErrorCallback

WithErrorCallback 设置错误回调

Functions

func AddMITMMiddleware

func AddMITMMiddleware(mw middleware.Middleware)

AddMITMMiddleware 添加 MITM 中间件

func CryptTraffic

func CryptTraffic(data []byte, cryptor *TrafficCryptor) ([]byte, error)

CryptTraffic 流量加密

func DecryptTraffic

func DecryptTraffic(data []byte, cryptor *TrafficCryptor) ([]byte, error)

DecryptTraffic 流量解密

func GetInterceptor

func GetInterceptor() *mitm.Interceptor

GetInterceptor 获取全局拦截器实例

func HttpInterceptProxyHandle

func HttpInterceptProxyHandle(c *Context)

HttpInterceptProxyHandle 完整的 HTTPS MITM 拦截处理 支持请求/响应拦截、修改、流量捕获、HTTP/1.1 和 HTTP/2

func HttpProxyHandle

func HttpProxyHandle(c *Context)

HttpProxyHandle Http处理

func HttpsProxyHandle

func HttpsProxyHandle(c *Context)

HttpsProxyHandle Https处理

func HttpsSniffDetailProxyHandle

func HttpsSniffDetailProxyHandle(c *Context)

HttpsSniffDetailProxyHandle https中间人处理

func HttpsSniffProxyHandle

func HttpsSniffProxyHandle(c *Context)

HttpsSniffProxyHandle https中间人处理

func ServeProxy

func ServeProxy(p *ProxyServe)

ServeProxy 启动监听(向后兼容) Deprecated: 使用 ProxyServe.Start() 代替 迁移示例:

旧: ServeProxy(proxyServe)
新: proxyServe.Start()

func SetInterceptorConfig

func SetInterceptorConfig(config *mitm.InterceptorConfig)

SetInterceptorConfig 设置拦截器配置

func TeeDoRequestTransfer

func TeeDoRequestTransfer(c *Context)

TeeDoRequestTransfer traffic transfer 流量Io转发,手动处理请求

func TeeTransfer

func TeeTransfer(destination io.WriteCloser, source io.ReadCloser)

TeeTransfer traffic transfer 流量Io转发 使用 DefaultWriter 作为 tee 输出

func Transfer

func Transfer(destination io.WriteCloser, source io.ReadCloser)

Transfer traffic transfer 流量Io转发 注意:忽略错误以保持向后兼容

func TunnelProxyHandle

func TunnelProxyHandle(c *Context)

TunnelProxyHandle 加密代理

func TunnelTransfer

func TunnelTransfer(client, server io.ReadWriteCloser, cryptor *TrafficCryptor)

TunnelTransfer 加密流量转发

func WebsocketProxyHandle

func WebsocketProxyHandle(c *Context)

WebsocketProxyHandle websocket 代理

Types

type Context

type Context = context.Context

Context 请求上下文

type Cryptor

type Cryptor = transfer.Cryptor

Cryptor 加解密接口

type FeatureFlags

type FeatureFlags struct {
	EnableTrafficCapture bool `json:"enableTrafficCapture"`
	EnableTrafficReplay  bool `json:"enableTrafficReplay"`
	EnableTunnelCrypt    bool `json:"enableTunnelCrypt"`
}

FeatureFlags 功能开关

type FileWriter

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

FileWriter 文件写入器

func NewFileWriter

func NewFileWriter(path string) *FileWriter

NewFileWriter 创建文件写入器

func (*FileWriter) Write

func (w *FileWriter) Write(p []byte) (n int, err error)

Write 实现 io.Writer 接口

type LogLevel

type LogLevel int

LogLevel 日志级别

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

type Logger

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

Logger 结构化日志器

func GetLogger

func GetLogger() *Logger

GetLogger 获取默认日志器

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...interface{})

Debug 输出调试日志

func (*Logger) Error

func (l *Logger) Error(msg string, args ...interface{})

Error 输出错误日志

func (*Logger) Info

func (l *Logger) Info(msg string, args ...interface{})

Info 输出信息日志

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*Logger) SetOutput

func (l *Logger) SetOutput(w io.Writer)

SetOutput 设置输出目标

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...interface{})

Warn 输出警告日志

type Middleware

type Middleware = middleware.Middleware

Middleware 中间件接口

type MiddlewareFunc

type MiddlewareFunc = middleware.MiddlewareFunc

MiddlewareFunc 中间件函数类型

type NOPCryptor

type NOPCryptor = transfer.NOPCryptor

NOPCryptor 空加密器(不进行加密/解密操作)

type ProxyConfig

type ProxyConfig struct {
	// 网络设置
	IP       string `json:"ip"`
	Port     string `json:"port"`
	Protocol string `json:"protocol"`

	// 代理设置
	Method  string `json:"method"`
	LogPath string `json:"logPath"`

	// TLS设置
	TLS TLSConfig `json:"tls"`

	// 超时设置
	Timeout TimeoutConfig `json:"timeout"`

	// 功能开关
	Features FeatureFlags `json:"features"`
}

ProxyConfig 代理服务配置

func LoadConfig

func LoadConfig(path string) (*ProxyConfig, error)

LoadConfig 从文件加载配置

func (*ProxyConfig) Save

func (c *ProxyConfig) Save(path string) error

Save 保存配置到文件

func (*ProxyConfig) Validate

func (c *ProxyConfig) Validate() error

Validate 验证配置有效性

type ProxyError

type ProxyError struct {
	Op   string // 失败的操作
	Host string // 目标主机
	Err  error  // 底层错误
}

ProxyError 表示代理相关错误

func NewProxyError

func NewProxyError(op, host string, err error) *ProxyError

NewProxyError 创建新的代理错误

func (*ProxyError) Error

func (e *ProxyError) Error() string

func (*ProxyError) Unwrap

func (e *ProxyError) Unwrap() error

type ProxyHandle

type ProxyHandle = context.ProxyHandle

ProxyHandle 代理处理函数

type ProxyHandlersChain

type ProxyHandlersChain = context.ProxyHandlersChain

ProxyHandlersChain 处理器链

type ProxyServe

type ProxyServe struct {

	// ========== 向后兼容字段 ==========
	// Deprecated: 使用 config.IP 代替
	Ip string `json:"ip,omitempty"`
	// Deprecated: 使用 config.Port 代替
	Port string `json:"port,omitempty"`
	// Deprecated: 使用 config.Method 代替
	Method string `json:"method,omitempty"`
	// Deprecated: 使用 config.Protocol 代替
	Protocol string `json:"protocol,omitempty"`
	// Deprecated: 使用 config.LogPath 代替
	LogPath string `json:"logPath,omitempty"`
	// Deprecated: 内部使用
	Host string
	// Deprecated: 内部使用
	ProxyHandlersChain ProxyHandlersChain
	// contains filtered or unexported fields
}

ProxyServe 代理服务器

func Default

func Default() *ProxyServe

Default 返回默认服务实例

func New

func New(opts ...ServerOption) *ProxyServe

New 创建新的代理服务器实例

func NewProxyServe

func NewProxyServe() *ProxyServe

NewProxyServe 返回服务实例

func (*ProxyServe) AddHandle

func (s *ProxyServe) AddHandle(proxyHandle ProxyHandle)

AddHandle 设置自定义代理响应处理(从尾部添加) Deprecated: 使用 Handle() 代替

func (*ProxyServe) AddMiddleware

func (s *ProxyServe) AddMiddleware(proxyHandle ProxyHandle)

AddMiddleware 从头部添加中间件 Deprecated: 使用 Use() 代替

func (*ProxyServe) Handle

func (s *ProxyServe) Handle(handler ProxyHandle) *ProxyServe

Handle 添加处理器(链式调用)

func (*ProxyServe) IsRunning

func (s *ProxyServe) IsRunning() bool

IsRunning 检查服务器是否运行中

func (*ProxyServe) Run

func (s *ProxyServe) Run() error

Run 启动服务器并处理优雅关闭(便捷方法)

func (*ProxyServe) ServerHandleListen

func (s *ProxyServe) ServerHandleListen()

ServerHandleListen ServerHandle 服务代理处理 Deprecated: 使用 Start() 代替

func (*ProxyServe) SetHost

func (s *ProxyServe) SetHost(ip, port string) *ProxyServe

SetHost 设置监听地址(链式调用)

func (*ProxyServe) SetMaxConnections

func (s *ProxyServe) SetMaxConnections(max int64) *ProxyServe

SetMaxConnections 设置最大连接数(链式调用)

func (*ProxyServe) SetMethod

func (s *ProxyServe) SetMethod(method string) *ProxyServe

SetMethod 设置代理方法(链式调用)

func (*ProxyServe) Shutdown

func (s *ProxyServe) Shutdown(ctx context.Context) error

Shutdown 优雅关闭服务器

func (*ProxyServe) Start

func (s *ProxyServe) Start() error

Start 启动服务器

func (*ProxyServe) StartWithContext

func (s *ProxyServe) StartWithContext(ctx context.Context) error

StartWithContext 使用上下文启动服务器

func (*ProxyServe) Stats

func (s *ProxyServe) Stats() ServerStats

Stats 获取服务器统计信息

func (*ProxyServe) Use

func (s *ProxyServe) Use(middleware ...ProxyHandle) *ProxyServe

Use 添加中间件(链式调用)

type ServerOption

type ServerOption func(*ProxyServe)

ServerOption 服务器选项函数

func WithConfig

func WithConfig(cfg *ProxyConfig) ServerOption

WithConfig 使用配置

func WithHost

func WithHost(ip, port string) ServerOption

WithHost 设置监听地址

func WithLogger

func WithLogger(logger *Logger) ServerOption

WithLogger 使用自定义日志器

func WithMaxConnections

func WithMaxConnections(max int64) ServerOption

WithMaxConnections 设置最大连接数

func WithMethod

func WithMethod(method string) ServerOption

WithMethod 设置代理方法

type ServerStats

type ServerStats struct {
	TotalConnections  int64     // 总连接数
	ActiveConnections int64     // 当前活跃连接数
	FailedConnections int64     // 失败连接数
	BytesReceived     int64     // 接收字节数
	BytesSent         int64     // 发送字节数
	StartTime         time.Time // 启动时间
}

ServerStats 服务器统计信息

type TLSConfig

type TLSConfig struct {
	CertPath string `json:"certPath"`
	KeyPath  string `json:"keyPath"`
	CertData []byte `json:"certData,omitempty"`
	KeyData  []byte `json:"keyData,omitempty"`
}

TLSConfig TLS证书配置

type TimeoutConfig

type TimeoutConfig struct {
	Connect time.Duration `json:"connect"`
	Read    time.Duration `json:"read"`
	Write   time.Duration `json:"write"`
}

TimeoutConfig 超时配置

type TrafficCryptor

type TrafficCryptor = transfer.TrafficCryptor

TrafficCryptor 流量加密器

func NewTrafficCryptor

func NewTrafficCryptor(key []byte) (*TrafficCryptor, error)

NewTrafficCryptor 创建新的流量加密器

type TransferOption

type TransferOption = transfer.TransferOption

TransferOption 转发选项函数

type TransferOptions

type TransferOptions = transfer.TransferOptions

TransferOptions 转发选项

Directories

Path Synopsis
cmd
config_demo command
generate_cert command
middleware_demo command
traffic_replay command
pkg
util
Package util 生成Http响应内容
Package util 生成Http响应内容

Jump to

Keyboard shortcuts

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