gost

package module
v2.6.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2018 License: MIT Imports: 54 Imported by: 0

README

gost - GO Simple Tunnel

GO语言实现的安全隧道

GoDoc Build Status Go Report Card GitHub release Snap Status Docker Build Status

English README

特性

Wiki站点: https://docs.ginuerzh.xyz/gost/

Google讨论组: https://groups.google.com/d/forum/go-gost

Telegram讨论群: https://t.me/gogost

安装

二进制文件

https://github.com/ginuerzh/gost/releases

源码编译
go get -u github.com/ginuerzh/gost/cmd/gost
Docker
docker pull ginuerzh/gost
Ubuntu商店
sudo snap install gost

快速上手

不设置转发代理
  • 作为标准HTTP/SOCKS5代理
gost -L=:8080
  • 设置代理认证信息
gost -L=admin:123456@localhost:8080
  • 多端口监听
gost -L=http2://:443 -L=socks5://:1080 -L=ss://aes-128-cfb:123456@:8338
设置转发代理
gost -L=:8080 -F=192.168.1.1:8081
  • 转发代理认证
gost -L=:8080 -F=http://admin:123456@192.168.1.1:8081
设置多级转发代理(代理链)
gost -L=:8080 -F=quic://192.168.1.1:6121 -F=socks5+wss://192.168.1.2:1080 -F=http2://192.168.1.3:443 ... -F=a.b.c.d:NNNN

gost按照-F设置的顺序通过代理链将请求最终转发给a.b.c.d:NNNN处理,每一个转发代理可以是任意HTTP/HTTPS/HTTP2/SOCKS4/SOCKS5/Shadowsocks类型代理。

本地端口转发(TCP)
gost -L=tcp://:2222/192.168.1.1:22 [-F=...]

将本地TCP端口2222上的数据(通过代理链)转发到192.168.1.1:22上。当代理链末端(最后一个-F参数)为SSH转发通道类型时,gost会直接使用SSH的本地端口转发功能:

gost -L=tcp://:2222/192.168.1.1:22 -F forward+ssh://:2222
本地端口转发(UDP)
gost -L=udp://:5353/192.168.1.1:53?ttl=60 [-F=...]

将本地UDP端口5353上的数据(通过代理链)转发到192.168.1.1:53上。 每条转发通道都有超时时间,当超过此时间,且在此时间段内无任何数据交互,则此通道将关闭。可以通过ttl参数来设置超时时间,默认值为60秒。

注: 转发UDP数据时,如果有代理链,则代理链的末端(最后一个-F参数)必须是gost SOCKS5类型代理,gost会使用UDP over TCP方式进行转发。

远程端口转发(TCP)
gost -L=rtcp://:2222/192.168.1.1:22 [-F=... -F=socks5://172.24.10.1:1080]

将172.24.10.1:2222上的数据(通过代理链)转发到192.168.1.1:22上。当代理链末端(最后一个-F参数)为SSH转发通道类型时,gost会直接使用SSH的远程端口转发功能:

gost -L=rtcp://:2222/192.168.1.1:22 -F forward+ssh://:2222
远程端口转发(UDP)
gost -L=rudp://:5353/192.168.1.1:53?ttl=60 [-F=... -F=socks5://172.24.10.1:1080]

将172.24.10.1:5353上的数据(通过代理链)转发到192.168.1.1:53上。 每条转发通道都有超时时间,当超过此时间,且在此时间段内无任何数据交互,则此通道将关闭。可以通过ttl参数来设置超时时间,默认值为60秒。

注: 转发UDP数据时,如果有代理链,则代理链的末端(最后一个-F参数)必须是GOST SOCKS5类型代理,gost会使用UDP-over-TCP方式进行转发。

HTTP2

gost的HTTP2支持两种模式:

  • 作为标准的HTTP2代理,并向下兼容HTTPS代理。
  • 作为通道传输其他协议。
代理模式

服务端:

gost -L=http2://:443

客户端:

gost -L=:8080 -F=http2://server_ip:443
通道模式

服务端:

gost -L=h2://:443

客户端:

gost -L=:8080 -F=h2://server_ip:443
QUIC

gost对QUIC的支持是基于quic-go库。

服务端:

gost -L=quic://:6121

客户端:

gost -L=:8080 -F=quic://server_ip:6121

注: QUIC模式只能作为代理链的第一个节点。

KCP

gost对KCP的支持是基于kcp-gokcptun库。

服务端:

gost -L=kcp://:8388

客户端:

gost -L=:8080 -F=kcp://server_ip:8388

gost会自动加载当前工作目录中的kcp.json(如果存在)配置文件,或者可以手动通过参数指定配置文件路径:

gost -L=kcp://:8388?c=/path/to/conf/file

注: KCP模式只能作为代理链的第一个节点。

SSH

gost的SSH支持两种模式:

  • 作为转发通道,配合本地/远程TCP端口转发使用。
  • 作为通道传输其他协议。
转发模式

服务端:

gost -L=forward+ssh://:2222

客户端:

gost -L=rtcp://:1222/:22 -F=forward+ssh://server_ip:2222
通道模式

服务端:

gost -L=ssh://:2222

客户端:

gost -L=:8080 -F=ssh://server_ip:2222?ping=60

可以通过ping参数设置心跳包发送周期,单位为秒。默认不发送心跳包。

透明代理

基于iptables的透明代理。

gost -L=redirect://:12345 -F=http2://server_ip:443
obfs4

此功能由@isofew贡献。

服务端:

gost -L=obfs4://:443

当服务端运行后会在控制台打印出连接地址供客户端使用:

obfs4://:443/?cert=4UbQjIfjJEQHPOs8vs5sagrSXx1gfrDCGdVh2hpIPSKH0nklv1e4f29r7jb91VIrq4q5Jw&iat-mode=0

客户端:

gost -L=:8888 -F='obfs4://server_ip:443?cert=4UbQjIfjJEQHPOs8vs5sagrSXx1gfrDCGdVh2hpIPSKH0nklv1e4f29r7jb91VIrq4q5Jw&iat-mode=0'

加密机制

HTTP

对于HTTP可以使用TLS加密整个通讯过程,即HTTPS代理:

服务端:

gost -L=https://:443

客户端:

gost -L=:8080 -F=http+tls://server_ip:443
HTTP2

gost的HTTP2代理模式仅支持使用TLS加密的HTTP2协议,不支持明文HTTP2传输。

gost的HTTP2通道模式支持加密(h2)和明文(h2c)两种模式。

SOCKS5

gost支持标准SOCKS5协议的no-auth(0x00)和user/pass(0x02)方法,并在此基础上扩展了两个:tls(0x80)和tls-auth(0x82),用于数据加密。

服务端:

gost -L=socks5://:1080

客户端:

gost -L=:8080 -F=socks5://server_ip:1080

如果两端都是gost(如上)则数据传输会被加密(协商使用tls或tls-auth方法),否则使用标准SOCKS5进行通讯(no-auth或user/pass方法)。

Shadowsocks

gost对shadowsocks的支持是基于shadowsocks-go库。

服务端:

gost -L=ss://chacha20:123456@:8338

客户端:

gost -L=:8080 -F=ss://chacha20:123456@server_ip:8338
Shadowsocks UDP relay

目前仅服务端支持UDP Relay。

服务端:

gost -L=ssu://chacha20:123456@:8338
TLS

gost内置了TLS证书,如果需要使用其他TLS证书,有两种方法:

  • 在gost运行目录放置cert.pem(公钥)和key.pem(私钥)两个文件即可,gost会自动加载运行目录下的cert.pem和key.pem文件。
  • 使用参数指定证书文件路径:
gost -L="http2://:443?cert=/path/to/my/cert/file&key=/path/to/my/key/file"

对于客户端可以通过secure参数开启服务器证书和域名校验:

gost -L=:8080 -F="http2://server_domain_name:443?secure=true"

对于客户端可以指定CA证书进行证书锁定(Certificate Pinning):

gost -L=:8080 -F="http2://:443?ca=ca.pem"

证书锁定功能由@sheerun贡献

Documentation

Index

Constants

View Source
const (
	// MethodTLS is an extended SOCKS5 method for TLS.
	MethodTLS uint8 = 0x80
	// MethodTLSAuth is an extended SOCKS5 method for TLS+AUTH.
	MethodTLSAuth uint8 = 0x82
	// MethodMux is an extended SOCKS5 method for stream multiplexing.
	MethodMux = 0x88
)
View Source
const (
	// CmdMuxBind is an extended SOCKS5 request CMD for
	// multiplexing transport with the binding server.
	CmdMuxBind uint8 = 0xF2
	// CmdUDPTun is an extended SOCKS5 request CMD for UDP over TCP.
	CmdUDPTun uint8 = 0xF3
)
View Source
const (
	DirectForwardRequest       = "direct-tcpip"         // RFC 4254 7.2
	RemoteForwardRequest       = "tcpip-forward"        // RFC 4254 7.1
	ForwardedTCPReturnRequest  = "forwarded-tcpip"      // RFC 4254 7.2
	CancelRemoteForwardRequest = "cancel-tcpip-forward" // RFC 4254 7.1

	GostSSHTunnelRequest = "gost-tunnel" // extended request type for ssh tunnel
)

Applicable SSH Request types for Port Forwarding - RFC 4254 7.X

View Source
const Version = "2.6.1"

Version is the gost version.

Variables

View Source
var (
	// KeepAliveTime is the keep alive time period for TCP connection.
	KeepAliveTime = 180 * time.Second
	// DialTimeout is the timeout of dial.
	DialTimeout = 30 * time.Second
	// ReadTimeout is the timeout for reading.
	ReadTimeout = 30 * time.Second
	// WriteTimeout is the timeout for writing.
	WriteTimeout = 60 * time.Second
	// PingTimeout is the timeout for pinging.
	PingTimeout = 30 * time.Second
	// PingRetries is the reties of ping.
	PingRetries = 1
)
View Source
var (
	// DefaultTLSConfig is a default TLS config for internal use.
	DefaultTLSConfig *tls.Config

	// DefaultUserAgent is the default HTTP User-Agent header used by HTTP and websocket.
	DefaultUserAgent = "Chrome/60.0.3112.90"
)
View Source
var (
	// DefaultResolverTimeout is the default timeout for name resolution.
	DefaultResolverTimeout = 30 * time.Second
	// DefaultResolverTTL is the default cache TTL for name resolution.
	DefaultResolverTTL = 60 * time.Second
)
View Source
var Debug bool

Debug is a flag that enables the debug log.

View Source
var DefaultClient = &Client{Connector: HTTPConnector(nil), Transporter: TCPTransporter()}

DefaultClient is a standard HTTP proxy client.

View Source
var (
	// DefaultKCPConfig is the default KCP config.
	DefaultKCPConfig = &KCPConfig{
		Key:          "it's a secrect",
		Crypt:        "aes",
		Mode:         "fast",
		MTU:          1350,
		SndWnd:       1024,
		RcvWnd:       1024,
		DataShard:    10,
		ParityShard:  3,
		DSCP:         0,
		NoComp:       false,
		AckNodelay:   false,
		NoDelay:      0,
		Interval:     50,
		Resend:       0,
		NoCongestion: 0,
		SockBuf:      4194304,
		KeepAlive:    10,
		SnmpLog:      "",
		SnmpPeriod:   60,
		Signal:       false,
	}
)
View Source
var (
	// ErrEmptyChain is an error that implies the chain is empty.
	ErrEmptyChain = errors.New("empty chain")
)
View Source
var (
	// ErrNoneAvailable indicates there is no node available.
	ErrNoneAvailable = errors.New("none available")
)
View Source
var (
	// KCPSalt is the default salt for KCP cipher.
	KCPSalt = "kcp-go"
)

Functions

func Can

func Can(action string, addr string, whitelist, blacklist *Permissions) bool

Can tests whether the given action and address is allowed by the whitelist and blacklist.

func Connect

func Connect(conn net.Conn, addr string) (net.Conn, error)

Connect connects to the address addr via the DefaultClient.

func Dial

func Dial(addr string, options ...DialOption) (net.Conn, error)

Dial connects to the address addr via the DefaultClient.

func GenCertificate

func GenCertificate() (cert tls.Certificate, err error)

GenCertificate generates a random TLS certificate.

func Handshake

func Handshake(conn net.Conn, options ...HandshakeOption) (net.Conn, error)

Handshake performs a handshake via the DefaultClient.

func Obfs4Init

func Obfs4Init(node Node, isServeNode bool) error

Obfs4Init initializes the obfs client or server based on isServeNode

func PeriodReload

func PeriodReload(r Reloader, configFile string) error

PeriodReload reloads the config periodically according to the period of the reloader.

func SetLogger

func SetLogger(logger log.Logger)

SetLogger sets a new logger for internal log system.

Types

type Bypass

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

Bypass is a filter for address (IP or domain). It contains a list of matchers.

func NewBypass

func NewBypass(reversed bool, matchers ...Matcher) *Bypass

NewBypass creates and initializes a new Bypass using matchers as its match rules. The rules will be reversed if the reversed is true.

func NewBypassPatterns

func NewBypassPatterns(reversed bool, patterns ...string) *Bypass

NewBypassPatterns creates and initializes a new Bypass using matcher patterns as its match rules. The rules will be reversed if the reverse is true.

func (*Bypass) AddMatchers

func (bp *Bypass) AddMatchers(matchers ...Matcher)

AddMatchers appends matchers to the bypass matcher list.

func (*Bypass) Contains

func (bp *Bypass) Contains(addr string) bool

Contains reports whether the bypass includes addr.

func (*Bypass) Matchers

func (bp *Bypass) Matchers() []Matcher

Matchers return the bypass matcher list.

func (*Bypass) Period

func (bp *Bypass) Period() time.Duration

Period returns the reload period

func (*Bypass) Reload

func (bp *Bypass) Reload(r io.Reader) error

Reload parses config from r, then live reloads the bypass.

func (*Bypass) Reversed

func (bp *Bypass) Reversed() bool

Reversed reports whether the rules of the bypass are reversed.

func (*Bypass) String

func (bp *Bypass) String() string

type Chain

type Chain struct {
	Retries int
	// contains filtered or unexported fields
}

Chain is a proxy chain that holds a list of proxy nodes.

func NewChain

func NewChain(nodes ...Node) *Chain

NewChain creates a proxy chain with a list of proxy nodes.

func (*Chain) AddNode

func (c *Chain) AddNode(nodes ...Node)

AddNode appends the node(s) to the chain.

func (*Chain) AddNodeGroup

func (c *Chain) AddNodeGroup(groups ...*NodeGroup)

AddNodeGroup appends the group(s) to the chain.

func (*Chain) Conn

func (c *Chain) Conn(opts ...ChainOption) (conn net.Conn, err error)

Conn obtains a handshaked connection to the last node of the chain.

func (*Chain) Dial

func (c *Chain) Dial(addr string, opts ...ChainOption) (conn net.Conn, err error)

Dial connects to the target address addr through the chain. If the chain is empty, it will use the net.Dial directly.

func (*Chain) IsEmpty

func (c *Chain) IsEmpty() bool

IsEmpty checks if the chain is empty. An empty chain means that there is no proxy node or node group in the chain.

func (*Chain) LastNode

func (c *Chain) LastNode() Node

LastNode returns the last node of the node list. If the chain is empty, an empty node will be returned. If the last node is a node group, the first node in the group will be returned.

func (*Chain) LastNodeGroup

func (c *Chain) LastNodeGroup() *NodeGroup

LastNodeGroup returns the last group of the group list.

func (*Chain) NodeGroups

func (c *Chain) NodeGroups() []*NodeGroup

NodeGroups returns the list of node group.

func (*Chain) Nodes

func (c *Chain) Nodes() (nodes []Node)

Nodes returns the proxy nodes that the chain holds. The first node in each group will be returned.

type ChainOption

type ChainOption func(opts *ChainOptions)

ChainOption allows a common way to set chain options.

func HostsChainOption

func HostsChainOption(hosts *Hosts) ChainOption

HostsChainOption specifies the hosts used by Chain.Dial.

func ResolverChainOption

func ResolverChainOption(resolver Resolver) ChainOption

ResolverChainOption specifies the Resolver used by Chain.Dial.

func RetryChainOption

func RetryChainOption(retries int) ChainOption

RetryChainOption specifies the times of retry used by Chain.Dial.

func TimeoutChainOption

func TimeoutChainOption(timeout time.Duration) ChainOption

TimeoutChainOption specifies the timeout used by Chain.Dial.

type ChainOptions

type ChainOptions struct {
	Retries  int
	Timeout  time.Duration
	Hosts    *Hosts
	Resolver Resolver
}

ChainOptions holds options for Chain.

type Client

type Client struct {
	Connector   Connector
	Transporter Transporter
}

Client is a proxy client. A client is divided into two layers: connector and transporter. Connector is responsible for connecting to the destination address through this proxy. Transporter performs a handshake with this proxy.

func (*Client) Connect

func (c *Client) Connect(conn net.Conn, addr string, options ...ConnectOption) (net.Conn, error)

Connect connects to the address addr via the proxy over connection conn.

func (*Client) Dial

func (c *Client) Dial(addr string, options ...DialOption) (net.Conn, error)

Dial connects to the target address.

func (*Client) Handshake

func (c *Client) Handshake(conn net.Conn, options ...HandshakeOption) (net.Conn, error)

Handshake performs a handshake with the proxy over connection conn.

type ConnectOption

type ConnectOption func(opts *ConnectOptions)

ConnectOption allows a common way to set ConnectOptions.

func AddrConnectOption

func AddrConnectOption(addr string) ConnectOption

AddrConnectOption specifies the corresponding address of the target.

type ConnectOptions

type ConnectOptions struct {
	Addr string
}

ConnectOptions describes the options for Connector.Connect.

type Connector

type Connector interface {
	Connect(conn net.Conn, addr string, options ...ConnectOption) (net.Conn, error)
}

Connector is responsible for connecting to the destination address.

func ForwardConnector

func ForwardConnector() Connector

ForwardConnector creates a Connector for data forward client.

func HTTP2Connector

func HTTP2Connector(user *url.Userinfo) Connector

HTTP2Connector creates a Connector for HTTP2 proxy client. It accepts an optional auth info for HTTP Basic Authentication.

func HTTPConnector

func HTTPConnector(user *url.Userinfo) Connector

HTTPConnector creates a Connector for HTTP proxy client. It accepts an optional auth info for HTTP Basic Authentication.

func SNIConnector

func SNIConnector(host string) Connector

SNIConnector creates a Connector for SNI proxy client.

func SOCKS4AConnector

func SOCKS4AConnector() Connector

SOCKS4AConnector creates a Connector for SOCKS4A proxy client.

func SOCKS4Connector

func SOCKS4Connector() Connector

SOCKS4Connector creates a Connector for SOCKS4 proxy client.

func SOCKS5Connector

func SOCKS5Connector(user *url.Userinfo) Connector

SOCKS5Connector creates a connector for SOCKS5 proxy client. It accepts an optional auth info for SOCKS5 Username/Password Authentication.

func SSHDirectForwardConnector

func SSHDirectForwardConnector() Connector

SSHDirectForwardConnector creates a Connector for SSH TCP direct port forwarding.

func SSHRemoteForwardConnector

func SSHRemoteForwardConnector() Connector

SSHRemoteForwardConnector creates a Connector for SSH TCP remote port forwarding.

func ShadowConnector

func ShadowConnector(cipher *url.Userinfo) Connector

ShadowConnector creates a Connector for shadowsocks proxy client. It accepts a cipher info for shadowsocks data encryption/decryption. The cipher must not be nil.

type DialOption

type DialOption func(opts *DialOptions)

DialOption allows a common way to set DialOptions.

func ChainDialOption

func ChainDialOption(chain *Chain) DialOption

ChainDialOption specifies a chain used by Transporter.Dial

func TimeoutDialOption

func TimeoutDialOption(timeout time.Duration) DialOption

TimeoutDialOption specifies the timeout used by Transporter.Dial

type DialOptions

type DialOptions struct {
	Timeout time.Duration
	Chain   *Chain
}

DialOptions describes the options for Transporter.Dial.

type FIFOStrategy

type FIFOStrategy struct{}

FIFOStrategy is a strategy for node selector. The node will be selected from first to last, and will stick to the selected node until it is failed.

func (*FIFOStrategy) Apply

func (s *FIFOStrategy) Apply(nodes []Node) Node

Apply applies the fifo strategy for the nodes.

func (*FIFOStrategy) String

func (s *FIFOStrategy) String() string

type FailFilter

type FailFilter struct {
	MaxFails    int
	FailTimeout time.Duration
}

FailFilter filters the dead node. A node is marked as dead if its failed count is greater than MaxFails.

func (*FailFilter) Filter

func (f *FailFilter) Filter(nodes []Node) []Node

Filter filters nodes.

func (*FailFilter) String

func (f *FailFilter) String() string

type Filter

type Filter interface {
	Filter([]Node) []Node
	String() string
}

Filter is used to filter a node during the selection process

type Handler

type Handler interface {
	Init(options ...HandlerOption)
	Handle(net.Conn)
}

Handler is a proxy server handler

func AutoHandler

func AutoHandler(opts ...HandlerOption) Handler

AutoHandler creates a server Handler for auto proxy server.

func HTTP2Handler

func HTTP2Handler(opts ...HandlerOption) Handler

HTTP2Handler creates a server Handler for HTTP2 proxy server.

func HTTPHandler

func HTTPHandler(opts ...HandlerOption) Handler

HTTPHandler creates a server Handler for HTTP proxy server.

func SNIHandler

func SNIHandler(opts ...HandlerOption) Handler

SNIHandler creates a server Handler for SNI proxy server.

func SOCKS4Handler

func SOCKS4Handler(opts ...HandlerOption) Handler

SOCKS4Handler creates a server Handler for SOCKS4(A) proxy server.

func SOCKS5Handler

func SOCKS5Handler(opts ...HandlerOption) Handler

SOCKS5Handler creates a server Handler for SOCKS5 proxy server.

func SSHForwardHandler

func SSHForwardHandler(opts ...HandlerOption) Handler

SSHForwardHandler creates a server Handler for SSH port forwarding server.

func ShadowHandler

func ShadowHandler(opts ...HandlerOption) Handler

ShadowHandler creates a server Handler for shadowsocks proxy server.

func ShadowUDPdHandler

func ShadowUDPdHandler(opts ...HandlerOption) Handler

ShadowUDPdHandler creates a server Handler for shadowsocks UDP relay server.

func TCPDirectForwardHandler

func TCPDirectForwardHandler(raddr string, opts ...HandlerOption) Handler

TCPDirectForwardHandler creates a server Handler for TCP port forwarding server. The raddr is the remote address that the server will forward to. NOTE: as of 2.6, remote address can be a comma-separated address list.

func TCPRedirectHandler

func TCPRedirectHandler(opts ...HandlerOption) Handler

TCPRedirectHandler creates a server Handler for TCP redirect server.

func TCPRemoteForwardHandler

func TCPRemoteForwardHandler(raddr string, opts ...HandlerOption) Handler

TCPRemoteForwardHandler creates a server Handler for TCP remote port forwarding server. The raddr is the remote address that the server will forward to. NOTE: as of 2.6, remote address can be a comma-separated address list.

func UDPDirectForwardHandler

func UDPDirectForwardHandler(raddr string, opts ...HandlerOption) Handler

UDPDirectForwardHandler creates a server Handler for UDP port forwarding server. The raddr is the remote address that the server will forward to. NOTE: as of 2.6, remote address can be a comma-separated address list.

func UDPRemoteForwardHandler

func UDPRemoteForwardHandler(raddr string, opts ...HandlerOption) Handler

UDPRemoteForwardHandler creates a server Handler for UDP remote port forwarding server. The raddr is the remote address that the server will forward to. NOTE: as of 2.6, remote address can be a comma-separated address list.

type HandlerOption

type HandlerOption func(opts *HandlerOptions)

HandlerOption allows a common way to set handler options.

func AddrHandlerOption

func AddrHandlerOption(addr string) HandlerOption

AddrHandlerOption sets the Addr option of HandlerOptions.

func BlacklistHandlerOption

func BlacklistHandlerOption(blacklist *Permissions) HandlerOption

BlacklistHandlerOption sets the Blacklist option of HandlerOptions.

func BypassHandlerOption

func BypassHandlerOption(bypass *Bypass) HandlerOption

BypassHandlerOption sets the bypass option of HandlerOptions.

func ChainHandlerOption

func ChainHandlerOption(chain *Chain) HandlerOption

ChainHandlerOption sets the Chain option of HandlerOptions.

func HostsHandlerOption

func HostsHandlerOption(hosts *Hosts) HandlerOption

HostsHandlerOption sets the Hosts option of HandlerOptions.

func ProbeResistHandlerOption

func ProbeResistHandlerOption(pr string) HandlerOption

ProbeResistHandlerOption adds the probe resistance for HTTP proxy.

func ResolverHandlerOption

func ResolverHandlerOption(resolver Resolver) HandlerOption

ResolverHandlerOption sets the resolver option of HandlerOptions.

func RetryHandlerOption

func RetryHandlerOption(retries int) HandlerOption

RetryHandlerOption sets the retry option of HandlerOptions.

func StrategyHandlerOption

func StrategyHandlerOption(strategy Strategy) HandlerOption

StrategyHandlerOption sets the strategy option of HandlerOptions.

func TLSConfigHandlerOption

func TLSConfigHandlerOption(config *tls.Config) HandlerOption

TLSConfigHandlerOption sets the TLSConfig option of HandlerOptions.

func TimeoutHandlerOption

func TimeoutHandlerOption(timeout time.Duration) HandlerOption

TimeoutHandlerOption sets the timeout option of HandlerOptions.

func UsersHandlerOption

func UsersHandlerOption(users ...*url.Userinfo) HandlerOption

UsersHandlerOption sets the Users option of HandlerOptions.

func WhitelistHandlerOption

func WhitelistHandlerOption(whitelist *Permissions) HandlerOption

WhitelistHandlerOption sets the Whitelist option of HandlerOptions.

type HandlerOptions

type HandlerOptions struct {
	Addr        string
	Chain       *Chain
	Users       []*url.Userinfo
	TLSConfig   *tls.Config
	Whitelist   *Permissions
	Blacklist   *Permissions
	Strategy    Strategy
	Bypass      *Bypass
	Retries     int
	Timeout     time.Duration
	Resolver    Resolver
	Hosts       *Hosts
	ProbeResist string
}

HandlerOptions describes the options for Handler.

type HandshakeOption

type HandshakeOption func(opts *HandshakeOptions)

HandshakeOption allows a common way to set HandshakeOptions.

func AddrHandshakeOption

func AddrHandshakeOption(addr string) HandshakeOption

AddrHandshakeOption specifies the server address

func HostHandshakeOption

func HostHandshakeOption(host string) HandshakeOption

HostHandshakeOption specifies the hostname

func IntervalHandshakeOption

func IntervalHandshakeOption(interval time.Duration) HandshakeOption

IntervalHandshakeOption specifies the interval time used by Transporter.Handshake

func KCPConfigHandshakeOption

func KCPConfigHandshakeOption(config *KCPConfig) HandshakeOption

KCPConfigHandshakeOption specifies the KCP config used by KCP handshake

func QUICConfigHandshakeOption

func QUICConfigHandshakeOption(config *QUICConfig) HandshakeOption

QUICConfigHandshakeOption specifies the QUIC config used by QUIC handshake

func RetryHandshakeOption

func RetryHandshakeOption(retry int) HandshakeOption

RetryHandshakeOption specifies the times of retry used by Transporter.Handshake

func TLSConfigHandshakeOption

func TLSConfigHandshakeOption(config *tls.Config) HandshakeOption

TLSConfigHandshakeOption specifies the TLS config used by Transporter.Handshake

func TimeoutHandshakeOption

func TimeoutHandshakeOption(timeout time.Duration) HandshakeOption

TimeoutHandshakeOption specifies the timeout used by Transporter.Handshake

func UserHandshakeOption

func UserHandshakeOption(user *url.Userinfo) HandshakeOption

UserHandshakeOption specifies the user used by Transporter.Handshake

func WSOptionsHandshakeOption

func WSOptionsHandshakeOption(options *WSOptions) HandshakeOption

WSOptionsHandshakeOption specifies the websocket options used by websocket handshake

type HandshakeOptions

type HandshakeOptions struct {
	Addr       string
	Host       string
	User       *url.Userinfo
	Timeout    time.Duration
	Interval   time.Duration
	Retry      int
	TLSConfig  *tls.Config
	WSOptions  *WSOptions
	KCPConfig  *KCPConfig
	QUICConfig *QUICConfig
}

HandshakeOptions describes the options for handshake.

type Host

type Host struct {
	IP       net.IP
	Hostname string
	Aliases  []string
}

Host is a static mapping from hostname to IP.

type Hosts

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

Hosts is a static table lookup for hostnames. For each host a single line should be present with the following information: IP_address canonical_hostname [aliases...] Fields of the entry are separated by any number of blanks and/or tab characters. Text from a "#" character until the end of the line is a comment, and is ignored.

func NewHosts

func NewHosts(hosts ...Host) *Hosts

NewHosts creates a Hosts with optional list of host

func (*Hosts) AddHost

func (h *Hosts) AddHost(host ...Host)

AddHost adds host(s) to the host table.

func (*Hosts) Lookup

func (h *Hosts) Lookup(host string) (ip net.IP)

Lookup searches the IP address corresponds to the given host from the host table.

func (*Hosts) Period

func (h *Hosts) Period() time.Duration

Period returns the reload period

func (*Hosts) Reload

func (h *Hosts) Reload(r io.Reader) error

Reload parses config from r, then live reloads the hosts.

type KCPConfig

type KCPConfig struct {
	Key          string `json:"key"`
	Crypt        string `json:"crypt"`
	Mode         string `json:"mode"`
	MTU          int    `json:"mtu"`
	SndWnd       int    `json:"sndwnd"`
	RcvWnd       int    `json:"rcvwnd"`
	DataShard    int    `json:"datashard"`
	ParityShard  int    `json:"parityshard"`
	DSCP         int    `json:"dscp"`
	NoComp       bool   `json:"nocomp"`
	AckNodelay   bool   `json:"acknodelay"`
	NoDelay      int    `json:"nodelay"`
	Interval     int    `json:"interval"`
	Resend       int    `json:"resend"`
	NoCongestion int    `json:"nc"`
	SockBuf      int    `json:"sockbuf"`
	KeepAlive    int    `json:"keepalive"`
	SnmpLog      string `json:"snmplog"`
	SnmpPeriod   int    `json:"snmpperiod"`
	Signal       bool   `json:"signal"` // Signal enables the signal SIGUSR1 feature.
}

KCPConfig describes the config for KCP.

func (*KCPConfig) Init

func (c *KCPConfig) Init()

Init initializes the KCP config.

type Listener

type Listener interface {
	net.Listener
}

Listener is a proxy server listener, just like a net.Listener.

func H2CListener

func H2CListener(addr string) (Listener, error)

H2CListener creates a Listener for HTTP2 h2c tunnel server.

func H2Listener

func H2Listener(addr string, config *tls.Config) (Listener, error)

H2Listener creates a Listener for HTTP2 h2 tunnel server.

func HTTP2Listener

func HTTP2Listener(addr string, config *tls.Config) (Listener, error)

HTTP2Listener creates a Listener for HTTP2 proxy server.

func KCPListener

func KCPListener(addr string, config *KCPConfig) (Listener, error)

KCPListener creates a Listener for KCP proxy server.

func MTLSListener

func MTLSListener(addr string, config *tls.Config) (Listener, error)

MTLSListener creates a Listener for multiplex-TLS proxy server.

func MWSListener

func MWSListener(addr string, options *WSOptions) (Listener, error)

MWSListener creates a Listener for multiplex-websocket proxy server.

func MWSSListener

func MWSSListener(addr string, tlsConfig *tls.Config, options *WSOptions) (Listener, error)

MWSSListener creates a Listener for multiplex-websocket secure proxy server.

func Obfs4Listener

func Obfs4Listener(addr string) (Listener, error)

Obfs4Listener creates a Listener for obfs4 server.

func ObfsHTTPListener

func ObfsHTTPListener(addr string) (Listener, error)

ObfsHTTPListener creates a Listener for HTTP obfuscating tunnel server.

func QUICListener

func QUICListener(addr string, config *QUICConfig) (Listener, error)

QUICListener creates a Listener for QUIC proxy server.

func SSHTunnelListener

func SSHTunnelListener(addr string, config *SSHConfig) (Listener, error)

SSHTunnelListener creates a Listener for SSH tunnel server.

func ShadowUDPListener

func ShadowUDPListener(addr string, cipher *url.Userinfo, ttl time.Duration) (Listener, error)

ShadowUDPListener creates a Listener for shadowsocks UDP relay server.

func TCPListener

func TCPListener(addr string) (Listener, error)

TCPListener creates a Listener for TCP proxy server.

func TCPRemoteForwardListener

func TCPRemoteForwardListener(addr string, chain *Chain) (Listener, error)

TCPRemoteForwardListener creates a Listener for TCP remote port forwarding server.

func TLSListener

func TLSListener(addr string, config *tls.Config) (Listener, error)

TLSListener creates a Listener for TLS proxy server.

func UDPDirectForwardListener

func UDPDirectForwardListener(addr string, ttl time.Duration) (Listener, error)

UDPDirectForwardListener creates a Listener for UDP port forwarding server.

func UDPRemoteForwardListener

func UDPRemoteForwardListener(addr string, chain *Chain, ttl time.Duration) (Listener, error)

UDPRemoteForwardListener creates a Listener for UDP remote port forwarding server.

func WSListener

func WSListener(addr string, options *WSOptions) (Listener, error)

WSListener creates a Listener for websocket proxy server.

func WSSListener

func WSSListener(addr string, tlsConfig *tls.Config, options *WSOptions) (Listener, error)

WSSListener creates a Listener for websocket secure proxy server.

type LogLogger

type LogLogger struct {
}

LogLogger uses the standard log package as the logger

func (*LogLogger) Log

func (l *LogLogger) Log(v ...interface{})

Log uses the standard log library log.Output

func (*LogLogger) Logf

func (l *LogLogger) Logf(format string, v ...interface{})

Logf uses the standard log library log.Output

type Matcher

type Matcher interface {
	Match(v string) bool
	String() string
}

Matcher is a generic pattern matcher, it gives the match result of the given pattern for specific v.

func CIDRMatcher

func CIDRMatcher(inet *net.IPNet) Matcher

CIDRMatcher creates a Matcher for a specific CIDR notation IP address.

func DomainMatcher

func DomainMatcher(pattern string) Matcher

DomainMatcher creates a Matcher for a specific domain pattern, the pattern can be a plain domain such as 'example.com', a wildcard such as '*.exmaple.com' or a special wildcard '.example.com'.

func IPMatcher

func IPMatcher(ip net.IP) Matcher

IPMatcher creates a Matcher for a specific IP address.

func NewMatcher

func NewMatcher(pattern string) Matcher

NewMatcher creates a Matcher for the given pattern. The acutal Matcher depends on the pattern: IP Matcher if pattern is a valid IP address. CIDR Matcher if pattern is a valid CIDR address. Domain Matcher if both of the above are not.

type NameServer

type NameServer struct {
	Addr     string
	Protocol string
	Hostname string // for TLS handshake verification
}

NameServer is a name server. Currently supported protocol: TCP, UDP and TLS.

func (NameServer) String

func (ns NameServer) String() string

type Node

type Node struct {
	ID               int
	Addr             string
	Host             string
	Protocol         string
	Transport        string
	Remote           string // remote address, used by tcp/udp port forwarding
	User             *url.Userinfo
	Values           url.Values
	DialOptions      []DialOption
	HandshakeOptions []HandshakeOption
	Client           *Client

	Bypass *Bypass
	// contains filtered or unexported fields
}

Node is a proxy node, mainly used to construct a proxy chain.

func ParseNode

func ParseNode(s string) (node Node, err error)

ParseNode parses the node info. The proxy node string pattern is [scheme://][user:pass@host]:port. Scheme can be divided into two parts by character '+', such as: http+tls.

func (*Node) Clone

func (node *Node) Clone() Node

Clone clones the node, it will prevent data race.

func (*Node) Get

func (node *Node) Get(key string) string

Get returns node parameter specified by key.

func (*Node) GetBool

func (node *Node) GetBool(key string) bool

GetBool likes Get, but convert parameter value to bool.

func (*Node) GetInt

func (node *Node) GetInt(key string) int

GetInt likes Get, but convert parameter value to int.

func (*Node) String

func (node *Node) String() string

type NodeGroup

type NodeGroup struct {
	ID int
	// contains filtered or unexported fields
}

NodeGroup is a group of nodes.

func NewNodeGroup

func NewNodeGroup(nodes ...Node) *NodeGroup

NewNodeGroup creates a node group

func (*NodeGroup) AddNode

func (group *NodeGroup) AddNode(node ...Node)

AddNode appends node or node list into group node.

func (*NodeGroup) GetNode

func (group *NodeGroup) GetNode(i int) Node

GetNode returns a copy of the node specified by index in the group.

func (*NodeGroup) MarkDeadNode

func (group *NodeGroup) MarkDeadNode(nid int)

MarkDeadNode marks the node with ID nid status to dead.

func (*NodeGroup) Next

func (group *NodeGroup) Next() (node Node, err error)

Next selects a node from group. It also selects IP if the IP list exists.

func (*NodeGroup) Nodes

func (group *NodeGroup) Nodes() []Node

Nodes returns the node list in the group

func (*NodeGroup) ResetDeadNode

func (group *NodeGroup) ResetDeadNode(nid int)

ResetDeadNode resets the node with ID nid status.

func (*NodeGroup) SetNodes

func (group *NodeGroup) SetNodes(nodes ...Node)

SetNodes replaces the group nodes to the specified nodes.

func (*NodeGroup) SetSelector

func (group *NodeGroup) SetSelector(selector NodeSelector, opts ...SelectOption)

SetSelector sets node selector with options for the group.

type NodeSelector

type NodeSelector interface {
	Select(nodes []Node, opts ...SelectOption) (Node, error)
}

NodeSelector as a mechanism to pick nodes and mark their status.

type NopLogger

type NopLogger struct {
}

NopLogger is a dummy logger that discards the log outputs

func (*NopLogger) Log

func (l *NopLogger) Log(v ...interface{})

Log does nothing

func (*NopLogger) Logf

func (l *NopLogger) Logf(format string, v ...interface{})

Logf does nothing

type PasswordCallbackFunc

type PasswordCallbackFunc func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error)

PasswordCallbackFunc is a callback function used by SSH server.

type Permission

type Permission struct {
	Actions StringSet
	Hosts   StringSet
	Ports   PortSet
}

Permission is a rule for blacklist and whitelist.

type Permissions

type Permissions []Permission

Permissions is a set of Permission.

func ParsePermissions

func ParsePermissions(s string) (*Permissions, error)

ParsePermissions parses the s to a Permissions.

func (*Permissions) Can

func (ps *Permissions) Can(action string, host string, port int) bool

Can tests whether the given action and host:port is allowed by this Permissions.

type PortRange

type PortRange struct {
	Min, Max int
}

PortRange specifies the range of port, such as 1000-2000.

func ParsePortRange

func ParsePortRange(s string) (*PortRange, error)

ParsePortRange parses the s to a PortRange. The s may be a '*' means 0-65535.

func (*PortRange) Contains

func (ir *PortRange) Contains(value int) bool

Contains checks whether the value is within this range.

type PortSet

type PortSet []PortRange

PortSet is a set of PortRange

func ParsePortSet

func ParsePortSet(s string) (*PortSet, error)

ParsePortSet parses the s to a PortSet. The s shoud be a comma separated string.

func (*PortSet) Contains

func (ps *PortSet) Contains(value int) bool

Contains checks whether the value is within this port set.

type QUICConfig

type QUICConfig struct {
	TLSConfig   *tls.Config
	Timeout     time.Duration
	KeepAlive   bool
	IdleTimeout time.Duration
	Key         []byte
}

QUICConfig is the config for QUIC client and server

type RandomStrategy

type RandomStrategy struct {
	Seed int64
	// contains filtered or unexported fields
}

RandomStrategy is a strategy for node selector. The node will be selected randomly.

func (*RandomStrategy) Apply

func (s *RandomStrategy) Apply(nodes []Node) Node

Apply applies the random strategy for the nodes.

func (*RandomStrategy) String

func (s *RandomStrategy) String() string

type ReloadResolver

type ReloadResolver interface {
	Resolver
	Reloader
}

ReloadResolver is resolover that support live reloading

func NewResolver

func NewResolver(timeout, ttl time.Duration, servers ...NameServer) ReloadResolver

NewResolver create a new Resolver with the given name servers and resolution timeout.

type Reloader

type Reloader interface {
	Reload(r io.Reader) error
	Period() time.Duration
}

Reloader is the interface for objects that support live reloading.

type Resolver

type Resolver interface {
	// Resolve returns a slice of that host's IPv4 and IPv6 addresses.
	Resolve(host string) ([]net.IP, error)
}

Resolver is a name resolver for domain name. It contains a list of name servers.

type RoundStrategy

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

RoundStrategy is a strategy for node selector. The node will be selected by round-robin algorithm.

func (*RoundStrategy) Apply

func (s *RoundStrategy) Apply(nodes []Node) Node

Apply applies the round-robin strategy for the nodes.

func (*RoundStrategy) String

func (s *RoundStrategy) String() string

type SSHConfig

type SSHConfig struct {
	Users     []*url.Userinfo
	TLSConfig *tls.Config
}

SSHConfig holds the SSH tunnel server config

type SelectOption

type SelectOption func(*SelectOptions)

SelectOption is the option used when making a select call.

func WithFilter

func WithFilter(f ...Filter) SelectOption

WithFilter adds a filter function to the list of filters used during the Select call.

func WithStrategy

func WithStrategy(s Strategy) SelectOption

WithStrategy sets the selector strategy

type SelectOptions

type SelectOptions struct {
	Filters  []Filter
	Strategy Strategy
}

SelectOptions is the options for node selection.

type Server

type Server struct {
	Listener Listener
	// contains filtered or unexported fields
}

Server is a proxy server.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the address of the server

func (*Server) Close

func (s *Server) Close() error

Close closes the server

func (*Server) Init

func (s *Server) Init(opts ...ServerOption)

Init intializes server with given options.

func (*Server) Serve

func (s *Server) Serve(h Handler, opts ...ServerOption) error

Serve serves as a proxy server.

type ServerOption

type ServerOption func(opts *ServerOptions)

ServerOption allows a common way to set server options.

type ServerOptions

type ServerOptions struct {
	Bypass *Bypass
}

ServerOptions holds the options for Server.

type Strategy

type Strategy interface {
	Apply([]Node) Node
	String() string
}

Strategy is a selection strategy e.g random, round-robin.

type StringSet

type StringSet []string

StringSet is a set of string.

func ParseStringSet

func ParseStringSet(s string) (*StringSet, error)

ParseStringSet parses the s to a StringSet. The s shoud be a comma separated string.

func (*StringSet) Contains

func (ss *StringSet) Contains(subj string) bool

Contains checks whether the string subj within this StringSet.

type Transporter

type Transporter interface {
	Dial(addr string, options ...DialOption) (net.Conn, error)
	Handshake(conn net.Conn, options ...HandshakeOption) (net.Conn, error)
	// Indicate that the Transporter supports multiplex
	Multiplex() bool
}

Transporter is responsible for handshaking with the proxy server.

func H2CTransporter

func H2CTransporter() Transporter

H2CTransporter creates a Transporter that is used by HTTP2 h2c tunnel client.

func H2Transporter

func H2Transporter(config *tls.Config) Transporter

H2Transporter creates a Transporter that is used by HTTP2 h2 tunnel client.

func HTTP2Transporter

func HTTP2Transporter(config *tls.Config) Transporter

HTTP2Transporter creates a Transporter that is used by HTTP2 h2 proxy client.

func KCPTransporter

func KCPTransporter(config *KCPConfig) Transporter

KCPTransporter creates a Transporter that is used by KCP proxy client.

func MTLSTransporter

func MTLSTransporter() Transporter

MTLSTransporter creates a Transporter that is used by multiplex-TLS proxy client.

func MWSSTransporter

func MWSSTransporter(opts *WSOptions) Transporter

MWSSTransporter creates a Transporter that is used by multiplex-websocket secure proxy client.

func MWSTransporter

func MWSTransporter(opts *WSOptions) Transporter

MWSTransporter creates a Transporter that is used by multiplex-websocket proxy client.

func Obfs4Transporter

func Obfs4Transporter() Transporter

Obfs4Transporter creates a Transporter that is used by obfs4 client.

func ObfsHTTPTransporter

func ObfsHTTPTransporter() Transporter

ObfsHTTPTransporter creates a Transporter that is used by HTTP obfuscating tunnel client.

func QUICTransporter

func QUICTransporter(config *QUICConfig) Transporter

QUICTransporter creates a Transporter that is used by QUIC proxy client.

func SSHForwardTransporter

func SSHForwardTransporter() Transporter

SSHForwardTransporter creates a Transporter that is used by SSH port forwarding server.

func SSHTunnelTransporter

func SSHTunnelTransporter() Transporter

SSHTunnelTransporter creates a Transporter that is used by SSH tunnel client.

func TCPTransporter

func TCPTransporter() Transporter

TCPTransporter creates a transporter for TCP proxy client.

func TLSTransporter

func TLSTransporter() Transporter

TLSTransporter creates a Transporter that is used by TLS proxy client.

func WSSTransporter

func WSSTransporter(opts *WSOptions) Transporter

WSSTransporter creates a Transporter that is used by websocket secure proxy client.

func WSTransporter

func WSTransporter(opts *WSOptions) Transporter

WSTransporter creates a Transporter that is used by websocket proxy client.

type WSOptions

type WSOptions struct {
	ReadBufferSize    int
	WriteBufferSize   int
	HandshakeTimeout  time.Duration
	EnableCompression bool
	UserAgent         string
}

WSOptions describes the options for websocket.

Directories

Path Synopsis
cmd
examples
ssh
ssu

Jump to

Keyboard shortcuts

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