ssproxy

package module
v0.0.0-...-13ffb82 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2019 License: MIT Imports: 36 Imported by: 0

README

ssproxy

Golang实现的socks5、http代理协议,支持黑名单和白名单。支持通过二级代理包括shadowsocks连接。

功能列表

  • 自动识别 HTTP 和 socks5 协议
  • 支持二级代理,可通过 shadowsocks 上网
  • 支持黑名单和白名单,规则基于 ad block
  • 支持多代理负载均衡
  • 支持默认二级代理,当直连失败会使用默认代理连接

使用

  1. 拉取源码
go get github.com/lifei6671/ssproxy
  1. 编译
go build -o=ssproxy main.go
  1. 配置

config/config.toml.example 重命名为 config/config.toml

  1. 启动
./ssproy run -config=./config/config.toml

License

MIT License

Documentation

Index

Constants

View Source
const (
	AuthUsernamePasswordVersion = 0x01
	AuthStatusSucceeded         = 0x00
)
View Source
const (
	AddrTypeIPv4 = 0x01
	AddrTypeFQDN = 0x03
	AddrTypeIPv6 = 0x04

	CmdConnect Command = 0x01 // establishes an active-open forward proxy connection
	CmdBind    Command = 0x02 // establishes a passive-open forward proxy connection
	CmdUdp             = 0x03

	AuthMethodNotRequired         AuthMethod = 0x00 // no authentication required
	AuthMethodUsernamePassword    AuthMethod = 0x02 // use username/password
	AuthMethodNoAcceptableMethods AuthMethod = 0xff // no acceptable authentication methods

	StatusSucceeded Reply = 0x00
)

Wire protocol constants.

View Source
const (
	Exact        = iota // string to match
	Wildcard     = iota // *
	Separator    = iota // ^
	StartAnchor  = iota // |
	DomainAnchor = iota // ||

	Root      = iota
	Substring = iota // Wildcard + Exact
)
View Source
const BurstLimit = 1000 * 1000 * 1000
View Source
const ByteSize = 4108

Variables

View Source
var (
	ErrAddrType               = errors.New("socks addr type not supported")
	ErrVer                    = errors.New("socks version not supported")
	ErrMethod                 = errors.New("socks only support 1 method now")
	ErrAuthExtraData          = errors.New("socks authentication get extra data")
	ErrReqExtraData           = errors.New("socks request get extra data")
	ErrCmd                    = errors.New("socks command not supported")
	ErrNoSupportedAuth        = errors.New("socks no supported authentication mechanism")
	ErrNoSupportedAccountAuth = errors.New("socks no supported account authentication")
	ErrClientNoResponse       = errors.New("socks client no response")
	ErrDomainForbidConnect    = errors.New("forbid domain connect")
	ErrUserAuthFailed         = errors.New("socks user authentication failed")
	ErrUnrecognizedAddrType   = errors.New("socks unrecognized address type")
	ErrEmptyPassword          = errors.New("socks authentication password is empty")
	ErrProxyClosed            = errors.New("proxy server closed")
	ErrNoSupportedProxyType   = errors.New("no supported proxy type")
)
View Source
var ErrorLogger *logs.Logger

ErrorLogger exported

View Source
var GeneralLogger *logs.Logger

Logger exported

View Source
var (
	NullOpts = RuleOpts{}
)

Functions

func CheckCipherMethod

func CheckCipherMethod(method string) error

func Pipe

func Pipe(reader io.Reader, writer io.Writer, trafficFunc TrafficFunc) (written int64, err error)

Types

type AuthMethod

type AuthMethod uint8

An AuthMethod represents a SOCKS authentication method.

type Cipher

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

func NewCipher

func NewCipher(method, password string) (c *Cipher, err error)

NewCipher creates a cipher that can be used in Dial() etc. Use cipher.Copy() to create a new cipher with the same method and password to avoid the cost of repeated cipher initialization.

func (*Cipher) Copy

func (c *Cipher) Copy() *Cipher

Copy creates a new cipher at it's initial state.

type Command

type Command int

A Command represents a SOCKS command.

func (Command) String

func (cmd Command) String() string

type ConnHandler

type ConnHandler func(conn net.Conn) error

type CryptoStreamer

type CryptoStreamer interface {
	EncryptStream(key, iv []byte) (cipher.Stream, error)
	DecryptStream(key, iv []byte) (cipher.Stream, error)
}

type HttpProxy

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

func NewHttpProxy

func NewHttpProxy() *HttpProxy

func (*HttpProxy) Forward

func (h *HttpProxy) Forward(response http.ResponseWriter, request *http.Request)

func (*HttpProxy) Listen

func (h *HttpProxy) Listen(network, address string) error

func (*HttpProxy) ServeHTTP

func (h *HttpProxy) ServeHTTP(response http.ResponseWriter, request *http.Request)

ServeHTTP implements HTTP Handler

func (*HttpProxy) SetRateLimit

func (h *HttpProxy) SetRateLimit(bytesPerSec float64)

type HttpProxyConn

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

func NewHttpProxyConn

func NewHttpProxyConn(conn net.Conn) *HttpProxyConn

func (*HttpProxyConn) SetRateLimit

func (conn *HttpProxyConn) SetRateLimit(bytesPerSec float64)

SetRateLimit 设置网速

func (*HttpProxyConn) Write

func (conn *HttpProxyConn) Write(p []byte) (int, error)

type InterruptedError

type InterruptedError struct {
	Duration time.Duration
	Rule     string
}

func (*InterruptedError) Error

func (e *InterruptedError) Error() string

type PasswordHandle

type PasswordHandle func(user string) (password string, err error)

type Pipeline

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

func NewPipeline

func NewPipeline(readDeadline time.Duration, writeDeadline time.Duration) *Pipeline

func (*Pipeline) Pipe

func (p *Pipeline) Pipe(local, remote net.Conn, trafficFunc TrafficFunc) (written int64, err error)

type ProxyConfig

type ProxyConfig struct {
	Listen    string                 `toml:"listen" json:"listen"`
	GFWList   string                 `toml:"gfw_list" json:"gfw_list"`
	GFWProxy  []string               `toml:"gfw_proxy" json:"gfw_proxy"`
	Proxy     map[string]ProxyTunnel `toml:"proxy" json:"proxy"`
	Rules     map[string]ProxyRule   `toml:"rule" json:"rule"`
	Blacklist []string               `toml:"blacklist" json:"blacklist"`
}

func (*ProxyConfig) Resolve

func (p *ProxyConfig) Resolve() (map[string]*ProxyRoute, error)

Resolve 解析白名单

func (*ProxyConfig) ResolveBlacklist

func (p *ProxyConfig) ResolveBlacklist() ([]*Rule, error)

ResolveBlacklist 解析黑名单

func (*ProxyConfig) String

func (p *ProxyConfig) String() string

type ProxyListener

type ProxyListener struct {
	net.TCPListener
}

🚀

type ProxyRoute

type ProxyRoute struct {
	Rule    *Rule
	Channel map[string]*ProxyTunnel
}

func (*ProxyRoute) String

func (proxy *ProxyRoute) String() string

type ProxyRule

type ProxyRule struct {
	//规则类型:默认 HostWildcardCondition 规则统配,HostRegexCondition:域名正则
	ConditionType string   `toml:"condition_type" json:"condition_type"`
	Pattern       []string `toml:"pattern" json:"pattern"`
}

type ProxyServer

type ProxyServer struct {
	Authenticate PasswordHandle

	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	// contains filtered or unexported fields
}

func NewProxyServer

func NewProxyServer() *ProxyServer

func (*ProxyServer) AddBlack

func (p *ProxyServer) AddBlack(rule *Rule) error

AddBlack 增加一条黑名单规则

func (*ProxyServer) AddConnectionWrappers

func (p *ProxyServer) AddConnectionWrappers(handler ConnHandler) *ProxyServer

AddConnectionWrappers 增加连接的包装器

func (*ProxyServer) AddRule

func (p *ProxyServer) AddRule(route *ProxyRoute) error

func (*ProxyServer) Close

func (p *ProxyServer) Close() error

Close 关闭代理服务

func (*ProxyServer) Listen

func (p *ProxyServer) Listen(ctx context.Context, network, address string) error

func (*ProxyServer) SetDeadline

func (p *ProxyServer) SetDeadline(duration time.Duration) *ProxyServer

func (*ProxyServer) SetDefaultProxy

func (p *ProxyServer) SetDefaultProxy(tunnel *ProxyTunnel)

type ProxyTunnel

type ProxyTunnel struct {
	Name     string `toml:"name" json:"name"`
	Type     string `toml:"type" json:"type"`
	Addr     string `toml:"addr" json:"addr"`
	UserName string `toml:"username" json:"username"`
	Password string `toml:"password" json:"password"`
}

func (*ProxyTunnel) DialTimeout

func (tunnel *ProxyTunnel) DialTimeout(network string, address string, timeout time.Duration) (conn net.Conn, err error)

DialTimeout 连接到远程代理,并设置超时时间

func (*ProxyTunnel) String

func (tunnel *ProxyTunnel) String() string

type Reply

type Reply uint8

A Reply represents a SOCKS command reply code.

func (Reply) String

func (code Reply) String() string

type Request

type Request struct {
	// URL is matched against rule parts. Mandatory.
	URL string
	// Domain is matched against optional domain or third-party rules
	Domain string
	// ContentType is matched against optional content rules. This
	// information is often available only in client responses. Filters
	// may be applied twice, once at request time, once at response time.
	ContentType string
	// OriginDomain is matched against optional third-party rules.
	OriginDomain string

	// Timeout is the maximum amount of time a single matching can take.
	Timeout   time.Duration
	CheckFreq int

	// GenericBlock is true if rules not matching a specific domain are to be
	// ignored. If nil, the matcher will determine it internally based on
	// $genericblock options.
	GenericBlock *bool
}

Request defines client request properties to be matched against a set of rules.

func (*Request) HasGenericBlock

func (rq *Request) HasGenericBlock() bool

type Rule

type Rule struct {
	// The original string representation
	Raw string
	// Exception is true for exclusion rules (prefixed with "@@")
	Exception bool
	// Parts is the sequence of RulePart matching URLs
	Parts []RulePart
	// Opts are optional rules applied to content
	Opts RuleOpts
}

Rule represents a complete adblockplus rule.

func ParseRule

func ParseRule(s string) (*Rule, error)

ParseRule parses a single rule.

func ParseRules

func ParseRules(r io.Reader) ([]*Rule, error)

ParseRules returns the sequence of rules extracted from supplied reader content.

func (*Rule) HasContentOpts

func (r *Rule) HasContentOpts() bool

func (*Rule) HasUnsupportedOpts

func (r *Rule) HasUnsupportedOpts() bool

type RuleMatcher

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

RuleMatcher implements a complete set of include and exclude AdblockPlus rules.

func NewMatcher

func NewMatcher() *RuleMatcher

NewMatcher returns a new empty matcher.

func NewMatcherFromFiles

func NewMatcherFromFiles(paths ...string) (*RuleMatcher, int, error)

func (*RuleMatcher) AddRule

func (m *RuleMatcher) AddRule(rule *Rule, ruleId int) error

AddRule adds a rule to the matcher. Supplied rule identifier will be returned by Match().

func (*RuleMatcher) Match

func (m *RuleMatcher) Match(rq *Request) (bool, int, error)

Match applies include and exclude rules on supplied request. If the request is accepted, it returns true and the matching rule identifier.

func (*RuleMatcher) String

func (m *RuleMatcher) String() string

String returns a textual representation of the include and exclude rules, matching request with or without content.

type RuleOpts

type RuleOpts struct {
	Raw              string
	Collapse         *bool
	Document         bool
	Domains          []string
	ElemHide         bool
	Font             *bool
	GenericBlock     bool
	GenericHide      bool
	Image            *bool
	Media            *bool
	Object           *bool
	ObjectSubRequest *bool
	Other            *bool
	Ping             *bool
	Popup            *bool
	Script           *bool
	Stylesheet       *bool
	SubDocument      *bool
	ThirdParty       *bool
	Websocket        *bool
	WebRTC           *bool
	XmlHttpRequest   *bool
}

RuleOpts defines custom rules applied to content once the URL part has been matched by the RuleParts.

func NewRuleOpts

func NewRuleOpts(s string) (RuleOpts, error)

NewRuleOpts parses the rule part following the '$' separator and return content matching options.

type RulePart

type RulePart struct {
	// Rule type, like Exact, Wildcard, etc.
	Type int
	// Rule part string representation
	Value string
}

RulePart is the base component of rules. It represents a single matching element, like an exact match, a wildcard, a domain anchor...

type Socks5Conn

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

func NewSocks5Conn

func NewSocks5Conn(conn net.Conn, method AuthMethod) *Socks5Conn

NewSocks5Conn 初始化一个socks5协议的连接,并指定支持的认证方式

func (*Socks5Conn) Authenticate

func (conn *Socks5Conn) Authenticate(handle PasswordHandle) error

Authenticate 如果是用户名认证,则需要调用该方法进行认证

func (*Socks5Conn) Forward

func (conn *Socks5Conn) Forward() error

func (*Socks5Conn) Handshake

func (conn *Socks5Conn) Handshake() error

Handshake 握手阶段

func (*Socks5Conn) SetRateLimit

func (conn *Socks5Conn) SetRateLimit(bytesPerSec float64)

SetRateLimit 设置网速

func (*Socks5Conn) Write

func (conn *Socks5Conn) Write(p []byte) (int, error)

type SocksConn

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

func NewProxyConn

func NewProxyConn(conn net.Conn) *SocksConn

func (*SocksConn) SetRateLimit

func (c *SocksConn) SetRateLimit(bytesPerSec float64)

SetRateLimit 设置网速

func (*SocksConn) Write

func (c *SocksConn) Write(p []byte) (int, error)

type SocksProxyTCPConn

type SocksProxyTCPConn struct {
	SocksConn
}

type SocksProxyUDPConn

type SocksProxyUDPConn struct {
	SocksConn
}

type SocksVersion

type SocksVersion uint8
const (
	Socks5Version SocksVersion = 0x05
	Socks4Version SocksVersion = 0x04
)

type TrafficFunc

type TrafficFunc func(n int)

type UsernamePassword

type UsernamePassword struct {
	Username string
	Password string
}

func (*UsernamePassword) Authenticate

func (up *UsernamePassword) Authenticate(rw io.ReadWriter, auth AuthMethod) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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