socks5

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

README

Go Socks5

Go-Socks5 provides the socks5 package that implements a SOCKS5 server.

SOCKS (Secure Sockets) is used to route traffic between a client and server through an intermediate proxy layer.

This can be used to bypass firewalls or NATs.

Before You Begin

This repository only provides a basic socks5 package written in Golang.

If you need a ready-to-use socks5 proxy server, please refer to: go-socks5-proxy.

Features

The package has the following features:

  • "No Auth" mode
  • User/Password authentication
  • Support for the CONNECT command
  • Rules to do granular filtering of commands
  • Custom DNS resolution
  • Unit tests

TODO

The package still needs the following:

  • Support for the BIND command
  • Support for the ASSOCIATE command

Example

Below is a simple example of usage

// Create a SOCKS5 server
conf := &socks5.Config{}
server, err := socks5.New(conf)
if err != nil {
  panic(err)
}

// Create SOCKS5 proxy on localhost port 8000
if err := server.ListenAndServe("tcp", "127.0.0.1:8000"); err != nil {
  panic(err)
}

Godoc

Remember to double-check the Godoc, as it will be auto-generated on pkg.go.dev.

Step 1: Install godoc

First, ensure that you have godoc installed. You can install it using the following command:

go install golang.org/x/tools/cmd/godoc@latest
Step 2: Run godoc Server

Next, run the godoc server to serve the documentation for your Go project:

godoc -http=:6060 -index

This command starts a web server on port 6060, serving the documentation for your Go project.

Reference

This repository was originally cloned from go-socks5 due to its long period of inactivity. It is a small yet elegant repo, and we aim to use it as a pilot project to transform it into a comprehensive library with thorough documentation and automation. We will also strive to optimize and enhance it using AI.

Documentation

Index

Constants

View Source
const (
	// NoAuth represents the "No Authentication" method.
	NoAuth = uint8(0)

	// UserPassAuth represents the "User/Password Authentication" method.
	UserPassAuth = uint8(2)
)
View Source
const (
	// Ver is socks protocol version
	Ver byte = 0x05

	// MethodNone is none method
	MethodNone byte = 0x00
	// MethodGSSAPI is gssapi method
	MethodGSSAPI byte = 0x01 // MUST support // todo
	// MethodUsernamePassword is username/assword auth method
	MethodUsernamePassword byte = 0x02 // SHOULD support
	// MethodUnsupportAll means unsupport all given methods
	MethodUnsupportAll byte = 0xFF

	// UserPassVer is username/password auth protocol version
	UserPassVer byte = 0x01
	// UserPassStatusSuccess is success status of username/password auth
	UserPassStatusSuccess byte = 0x00
	// UserPassStatusFailure is failure status of username/password auth
	UserPassStatusFailure byte = 0x01 // just other than 0x00

	// CmdConnect is connect command
	CmdConnect byte = 0x01
	// CmdBind is bind command
	CmdBind byte = 0x02
	// CmdUDP is UDP command
	CmdUDP byte = 0x03

	// ATYPIPv4 is ipv4 address type
	ATYPIPv4 byte = 0x01 // 4 octets
	// ATYPDomain is domain address type
	ATYPDomain byte = 0x03 // The first octet of the address field contains the number of octets of name that follow, there is no terminating NUL octet.
	// ATYPIPv6 is ipv6 address type
	ATYPIPv6 byte = 0x04 // 16 octets

	// RepSuccess means that success for repling
	RepSuccess byte = 0x00
	// RepServerFailure means the server failure
	RepServerFailure byte = 0x01
	// RepNotAllowed means the request not allowed
	RepNotAllowed byte = 0x02
	// RepNetworkUnreachable means the network unreachable
	RepNetworkUnreachable byte = 0x03
	// RepHostUnreachable means the host unreachable
	RepHostUnreachable byte = 0x04
	// RepConnectionRefused means the connection refused
	RepConnectionRefused byte = 0x05
	// RepTTLExpired means the TTL expired
	RepTTLExpired byte = 0x06
	// RepCommandNotSupported means the request command not supported
	RepCommandNotSupported byte = 0x07
	// RepAddressNotSupported means the request address not supported
	RepAddressNotSupported byte = 0x08
)
View Source
const (
	ConnectCommand   = uint8(1)
	BindCommand      = uint8(2)
	AssociateCommand = uint8(3)
)

Variables

View Source
var (
	// ErrUnsupportCmd is the error when got unsupport command
	ErrUnsupportCmd = errors.New("Unsupport Command")
	// ErrUserPassAuth is the error when got invalid username or password
	ErrUserPassAuth = errors.New("Invalid Username or Password for Auth")
)
View Source
var (
	// ErrVersion is version error
	ErrVersion = errors.New("Invalid Version")
	// ErrUserPassVersion is username/password auth version error
	ErrUserPassVersion = errors.New("Invalid Version of Username Password Auth")
	// ErrBadRequest is bad request error
	ErrBadRequest = errors.New("Bad Request")
)
View Source
var Debug bool
View Source
var DialTCP func(network string, laddr, raddr string) (net.Conn, error) = func(network string, laddr, raddr string) (net.Conn, error) {
	var la, ra *net.TCPAddr
	if laddr != "" {
		var err error
		la, err = net.ResolveTCPAddr(network, laddr)
		if err != nil {
			return nil, err
		}
	}
	a, err := Resolve(network, raddr)
	if err != nil {
		return nil, err
	}
	ra = a.(*net.TCPAddr)
	return net.DialTCP(network, la, ra)
}
View Source
var DialUDP func(network string, laddr, raddr string) (net.Conn, error) = func(network string, laddr, raddr string) (net.Conn, error) {
	var la, ra *net.UDPAddr
	if laddr != "" {
		var err error
		la, err = net.ResolveUDPAddr(network, laddr)
		if err != nil {
			return nil, err
		}
	}
	a, err := Resolve(network, raddr)
	if err != nil {
		return nil, err
	}
	ra = a.(*net.UDPAddr)
	return net.DialUDP(network, la, ra)
}
View Source
var (
	// ErrBadReply is the error when read reply
	ErrBadReply = errors.New("Bad Reply")
)
View Source
var Resolve func(network string, addr string) (net.Addr, error) = func(network string, addr string) (net.Addr, error) {
	if network == "tcp" {
		return net.ResolveTCPAddr("tcp", addr)
	}
	return net.ResolveUDPAddr("udp", addr)
}

Functions

func Command2String added in v1.1.1

func Command2String(cmd uint8) string

func ParseAddress added in v1.1.1

func ParseAddress(address string) (a byte, addr []byte, port []byte, err error)

ParseAddress format address x.x.x.x:xx to raw address. addr contains domain length

func ParseBytesAddress added in v1.1.1

func ParseBytesAddress(b []byte) (a byte, addr []byte, port []byte, err error)

bytes to address addr contains domain length

func Reply2String added in v1.1.1

func Reply2String(code uint8) string

func ToAddress added in v1.1.1

func ToAddress(a byte, addr []byte, port []byte) string

ToAddress format raw address to x.x.x.x:xx addr contains domain length

Types

type AddrSpec

type AddrSpec struct {
	FQDN string
	IP   net.IP
	Port int
}

AddrSpec is used to return the target AddrSpec which may be specified as IPv4, IPv6, or a FQDN

func (AddrSpec) Address

func (a AddrSpec) Address() string

Address returns a string suitable to dial; prefer returning IP-based address, fallback to FQDN

func (*AddrSpec) String

func (a *AddrSpec) String() string

type AddressRewriter

type AddressRewriter interface {
	Rewrite(ctx context.Context, request *Request) (context.Context, *AddrSpec)
}

AddressRewriter is used to rewrite a destination transparently

type AuthContext

type AuthContext struct {
	// Method is the authentication method used.
	Method uint8

	// Payload contains additional information provided during the authentication process.
	// The keys depend on the used authentication method.
	// For UserPassAuth, it contains the username.
	Payload map[string]string
}

AuthContext encapsulates authentication state provided during negotiation.

type Authenticator

type Authenticator interface {
	// Authenticate performs the authentication process using the provided reader and writer.
	// It returns an AuthContext if the authentication is successful, and an error if it fails.
	Authenticate(reader io.Reader, writer io.Writer) (*AuthContext, error)

	// GetCode returns the authentication method code.
	GetCode() uint8
}

Authenticator is an interface for handling authentication. It provides methods to authenticate a connection and to get the authentication method code.

type BindCallBackFun added in v1.1.0

type BindCallBackFun func(bindAddr string)

BindCallBackFun is a function type for the callback that will be triggered when a bind operation is successful.

var BindCallBack BindCallBackFun

BindCallBack is a global variable that stores the callback function for bind operations.

type BytesPool added in v1.1.1

type BytesPool interface {
	Get() []byte
	Put([]byte)
}

BytesPool is an interface for getting and returning temporary bytes for use by io.CopyBuffer.

type Client added in v1.1.1

type Client struct {
	Server   string
	UserName string
	Password string
	// On cmd UDP, let server control the tcp and udp connection relationship
	TCPConn       net.Conn
	UDPConn       net.Conn
	RemoteAddress net.Addr
	TCPTimeout    int
	UDPTimeout    int
	Dst           string
}

Client is socks5 client wrapper

func NewClient added in v1.1.1

func NewClient(addr, username, password string, tcpTimeout, udpTimeout int) (*Client, error)

This is just create a client, you need to use Dial to create conn

func (*Client) Close added in v1.1.1

func (c *Client) Close() error

func (*Client) Dial added in v1.1.1

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

func (*Client) DialWithLocalAddr added in v1.1.1

func (c *Client) DialWithLocalAddr(network, src, dst string, remoteAddr net.Addr) (net.Conn, error)

If you want to send address that expects to use to send UDP, just assign it to src, otherwise it will send zero address. Recommend specifying the src address in a non-NAT environment, and leave it blank in other cases.

func (*Client) LocalAddr added in v1.1.1

func (c *Client) LocalAddr() net.Addr

func (*Client) Negotiate added in v1.1.1

func (c *Client) Negotiate(laddr net.Addr) error

func (*Client) Read added in v1.1.1

func (c *Client) Read(b []byte) (int, error)

func (*Client) RemoteAddr added in v1.1.1

func (c *Client) RemoteAddr() net.Addr

func (*Client) Request added in v1.1.1

func (c *Client) Request(r *RequestC) (*Reply, error)

func (*Client) SetDeadline added in v1.1.1

func (c *Client) SetDeadline(t time.Time) error

func (*Client) SetReadDeadline added in v1.1.1

func (c *Client) SetReadDeadline(t time.Time) error

func (*Client) SetWriteDeadline added in v1.1.1

func (c *Client) SetWriteDeadline(t time.Time) error

func (*Client) Write added in v1.1.1

func (c *Client) Write(b []byte) (int, error)

type Config

type Config struct {
	// AuthMethods can be provided to implement custom authentication.
	// By default, "auth-less" mode is enabled.
	// For password-based auth use UserPassAuthenticator.
	AuthMethods []Authenticator

	// If provided, username/password authentication is enabled,
	// by appending a UserPassAuthenticator to AuthMethods. If not provided,
	// and AuthMethods is nil, then "auth-less" mode is enabled.
	Credentials CredentialStore

	// Resolver can be provided to do custom name resolution.
	// Defaults to DNSResolver if not provided.
	Resolver NameResolver

	// Rules is provided to enable custom logic around permitting
	// various commands. If not provided, PermitAll is used.
	Rules RuleSet

	// Rewriter can be used to transparently rewrite addresses.
	// This is invoked before the RuleSet is invoked.
	// Defaults to NoRewrite.
	Rewriter AddressRewriter

	// BindIP is used for bind or UDP associate.
	BindIP net.IP

	// Logger can be used to provide a custom log target.
	// Defaults to stdout.
	Logger *log.Logger

	// Dial is an optional function for dialing out.
	Dial func(ctx context.Context, network, addr string) (net.Conn, error)

	// Mem is the memory allocator.
	Mem MemMgr
}

Config is used to setup and configure a Server.

type CredentialStore

type CredentialStore interface {
	// Valid checks if the given user and password combination is valid.
	// It returns true if the combination is valid, and false otherwise.
	Valid(user, password string) bool
}

CredentialStore is an interface used to support user/password authentication. It provides a method to validate a user and password combination.

type DNSResolver

type DNSResolver struct{}

DNSResolver is a struct that implements the NameResolver interface using the system's DNS resolver. It resolves hostnames to IP addresses using the standard library's net package.

func (DNSResolver) Resolve

func (d DNSResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error)

Resolve resolves the given domain name to an IP address using the system's DNS resolver. It returns the resolved IP address and any error encountered during the resolution process.

type Datagram added in v1.1.0

type Datagram struct {

	// RSV is a reserved field, should be set to 0x00 0x00.
	Rsv []byte
	// Frag is the fragment identifier. 0x00 for a complete packet, 1-127 for fragments.
	Frag byte
	// ATyp specifies the type of the DST.ADDR field:
	// - 0x01: IPv4 address
	// - 0x03: Domain name
	// - 0x04: IPv6 address
	ATyp byte
	// DstAddr is the target address the packet is destined for.
	DstAddr []byte
	// DstPort is the target port the packet is destined for.
	DstPort []byte
	// Data is the actual payload to be transmitted.
	Data []byte
	// contains filtered or unexported fields
}

Datagram represents a SOCKS5 UDP request or response.

func NewDatagram added in v1.1.0

func NewDatagram(ctx context.Context, memCreater MemAllocation, aTyp byte, dstAddr, dstPort, data []byte) *Datagram

SOCKS5 UDP Datagram Format: +-----+------+------+----------+----------+----------+ | RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | +-----+------+------+----------+----------+----------+ | 2 | 1 | 1 | Variable | 2 | Variable | +-----+------+------+----------+----------+----------+

func NewDatagramFromByte added in v1.1.0

func NewDatagramFromByte(ctx context.Context, memCreater MemAllocation, bs []byte) (*Datagram, error)

SOCKS5 UDP Datagram Format: +-----+------+------+----------+----------+----------+ | RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | +-----+------+------+----------+----------+----------+ | 2 | 1 | 1 | Variable | 2 | Variable | +-----+------+------+----------+----------+----------+

func (*Datagram) Address added in v1.1.0

func (d *Datagram) Address() string

Address returns the destination address and port in string format.

type DatagramC added in v1.1.1

type DatagramC struct {
	Rsv     []byte // 0x00 0x00
	Frag    byte
	Atyp    byte
	DstAddr []byte
	DstPort []byte // 2 bytes
	Data    []byte
}

Datagram is the UDP packet

func NewDatagramC added in v1.1.1

func NewDatagramC(atyp byte, dstaddr []byte, dstport []byte, data []byte) *DatagramC

NewDatagram return datagram packet can be writed into client, dstaddr should not have domain length

func NewDatagramFromBytes added in v1.1.1

func NewDatagramFromBytes(bb []byte) (*DatagramC, error)

func (*DatagramC) Address added in v1.1.1

func (d *DatagramC) Address() string

Address return datagram address like ip:xx

func (*DatagramC) Bytes added in v1.1.1

func (d *DatagramC) Bytes() []byte

Bytes return []byte

type Dialer added in v1.1.1

type Dialer struct {
	// ProxyNetwork network between a proxy server and a client
	ProxyNetwork string
	// ProxyAddress proxy server address
	ProxyAddress string
	// ProxyDial specifies the optional dial function for
	// establishing the transport connection.
	ProxyDial func(ctx context.Context, network string, address string) (net.Conn, error)
	// ProxyPacketDial specifies the optional proxyPacketDial function for
	// establishing the transport connection.
	ProxyPacketDial func(ctx context.Context, network string, address string) (net.PacketConn, error)
	// Username use username authentication if not empty
	Username string
	// Password use password authentication if not empty,
	// only valid if username is set
	Password string
	// IsResolve resolve domain name on locally
	IsResolve bool
	// Resolver optionally specifies an alternate resolver to use
	Resolver *net.Resolver
	// Timeout is the maximum amount of time a dial will wait for
	// a connect to complete. The default is no timeout
	Timeout time.Duration
}

Dialer is a SOCKS5 dialer.

func NewDialer added in v1.1.1

func NewDialer(addr string) (*Dialer, error)

NewDialer returns a new Dialer that dials through the provided proxy server's network and address.

func (*Dialer) Dial added in v1.1.1

func (d *Dialer) Dial(network, address string) (net.Conn, error)

Dial connects to the provided address on the provided network.

func (*Dialer) DialContext added in v1.1.1

func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext connects to the provided address on the provided network.

func (*Dialer) Listen added in v1.1.1

func (d *Dialer) Listen(ctx context.Context, network, address string) (net.Listener, error)

type Mem

type Mem struct{}

Mem is a simple implementation of the MemAllocation interface. It uses the built-in `make` function to allocate memory and does nothing for deallocation.

func (*Mem) Alloc

func (m *Mem) Alloc(ctx context.Context, size int) []byte

Alloc allocates a slice of bytes of the specified size using the built-in `make` function. It does not perform any special handling for the context.

func (*Mem) Free

func (m *Mem) Free(ctx context.Context, bs []byte)

Free is a no-op function for deallocating memory. It does not perform any actual deallocation and ignores the provided context.

type MemAllocation

type MemAllocation interface {
	// Alloc allocates a slice of bytes of the specified size.
	// ctx can be used to control the allocation process, such as for timeouts or cancellations.
	Alloc(ctx context.Context, size int) []byte

	// Free deallocates the provided slice of bytes.
	// ctx can be used to control the deallocation process, such as for timeouts or cancellations.
	Free(ctx context.Context, bs []byte)
}

MemAllocation is an interface for managing memory allocation and deallocation. It provides methods to allocate and free memory.

type MemMgr

type MemMgr interface {
	// Create creates a new MemAllocation instance.
	// ctx can be used to control the creation process, such as for timeouts or cancellations.
	Create(ctx context.Context) MemAllocation
}

MemMgr is an interface for managing memory allocators. It provides a method to create a new MemAllocation instance.

type NameResolver

type NameResolver interface {
	// Resolve resolves the given domain name to an IP address.
	// ctx can be used to control the resolution process, such as for timeouts or cancellations.
	Resolve(ctx context.Context, name string) (context.Context, net.IP, error)
}

NameResolver is an interface used to implement custom name resolution. It provides a method to resolve a domain name to an IP address.

type NegotiationReply added in v1.1.1

type NegotiationReply struct {
	Ver    byte
	Method byte
}

NegotiationReply is the negotiation reply packet

func NewNegotiationReplyFrom added in v1.1.1

func NewNegotiationReplyFrom(r io.Reader) (*NegotiationReply, error)

NewNegotiationReplyFrom read negotiation reply packet from server

type NegotiationRequest added in v1.1.1

type NegotiationRequest struct {
	Ver      byte
	NMethods byte
	Methods  []byte // 1-255 bytes
}

NegotiationRequest is the negotiation reqeust packet

func NewNegotiationRequest added in v1.1.1

func NewNegotiationRequest(methods []byte) *NegotiationRequest

NewNegotiationRequest return negotiation request packet can be writed into server

func (*NegotiationRequest) WriteTo added in v1.1.1

func (r *NegotiationRequest) WriteTo(w io.Writer) (int64, error)

WriteTo write negotiation request packet into server

type NoAuthAuthenticator

type NoAuthAuthenticator struct{}

NoAuthAuthenticator is an implementation of the Authenticator interface for the "No Authentication" method.

func (NoAuthAuthenticator) Authenticate

func (a NoAuthAuthenticator) Authenticate(reader io.Reader, writer io.Writer) (*AuthContext, error)

Authenticate implements the Authenticator interface for the "No Authentication" method. It always returns a successful AuthContext with the NoAuth method and an empty payload.

func (NoAuthAuthenticator) GetCode

func (a NoAuthAuthenticator) GetCode() uint8

GetCode returns the authentication method code for the "No Authentication" method.

type PermitCommand

type PermitCommand struct {
	// EnableConnect specifies whether the CONNECT command is allowed.
	EnableConnect bool

	// EnableBind specifies whether the BIND command is allowed.
	EnableBind bool

	// EnableAssociate specifies whether the ASSOCIATE command is allowed.
	EnableAssociate bool
}

PermitCommand is an implementation of the RuleSet interface which enables filtering of supported commands.

func (*PermitCommand) Allow

func (p *PermitCommand) Allow(ctx context.Context, req *Request) (context.Context, bool)

Allow determines whether the given request should be allowed based on the configured command rules. It returns a new context and a boolean indicating whether the request is allowed.

type Reply added in v1.1.1

type Reply struct {
	Ver  byte
	Rep  byte
	Rsv  byte // 0x00
	Atyp byte
	// CONNECT socks server's address which used to connect to dst addr
	// BIND ...
	// UDP socks server's address which used to connect to dst addr
	BndAddr []byte
	// CONNECT socks server's port which used to connect to dst addr
	// BIND ...
	// UDP socks server's port which used to connect to dst addr
	BndPort []byte // 2 bytes
}

Reply is the reply packet

func NewReplyFrom added in v1.1.1

func NewReplyFrom(r io.Reader) (*Reply, error)

NewReplyFrom read reply packet from server

func (*Reply) Address added in v1.1.1

func (r *Reply) Address() string

Address return request address like ip:xx

type Request

type Request struct {
	// Protocol version
	Version uint8
	// Requested command
	Command uint8
	// AuthContext provided during negotiation
	AuthContext *AuthContext
	// AddrSpec of the the network that sent the request
	RemoteAddr *AddrSpec
	// AddrSpec of the desired destination
	DestAddr *AddrSpec
	// contains filtered or unexported fields
}

A Request represents request received by a server

func NewRequest

func NewRequest(bufConn io.Reader) (*Request, error)

NewRequest creates a new Request from the tcp connection

type RequestC added in v1.1.1

type RequestC struct {
	Ver     byte
	Cmd     byte
	Rsv     byte // 0x00
	Atyp    byte
	DstAddr []byte
	DstPort []byte // 2 bytes
}

Request is the request packet

func NewRequest2 added in v1.1.1

func NewRequest2(cmd byte, atyp byte, dstaddr []byte, dstport []byte) *RequestC

NewRequest return request packet can be writed into server, dstaddr should not have domain length

func (*RequestC) Address added in v1.1.1

func (r *RequestC) Address() string

Address return request address like ip:xx

func (*RequestC) WriteTo added in v1.1.1

func (r *RequestC) WriteTo(w io.Writer) (int64, error)

WriteTo write request packet into server

type RuleSet

type RuleSet interface {
	// Allow determines whether the given request should be allowed.
	// It returns a new context and a boolean indicating whether the request is allowed.
	Allow(ctx context.Context, req *Request) (context.Context, bool)
}

RuleSet is an interface used to provide custom rules to allow or prohibit actions. It provides a method to determine whether a given request should be allowed.

func PermitAll

func PermitAll() RuleSet

PermitAll returns a RuleSet which allows all types of connections.

func PermitNone

func PermitNone() RuleSet

PermitNone returns a RuleSet which disallows all types of connections.

type Server

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

Server is responsible for accepting connections and handling the details of the SOCKS5 protocol.

func New

func New(conf *Config) (*Server, error)

New creates a new Server instance and potentially returns an error if the configuration is invalid.

It ensures that the following defaults are set if not explicitly provided in the configuration:

  • At least one authentication method is enabled. If no methods are specified, it defaults to using a UserPassAuthenticator if credentials are provided, or a NoAuthAuthenticator if no credentials are provided.
  • A DNS resolver is set. If not provided, it defaults to a DNSResolver.
  • A rule set is set. If not provided, it defaults to PermitAll.
  • A log target is set. If not provided, it defaults to logging to standard output with standard log flags.

Parameters:

conf - The configuration for the server.

Returns:

A new Server instance and any error that might have occurred.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(network, addr string) error

ListenAndServe creates a listener on the specified network address and starts serving connections. It is a convenience function that calls net.Listen and then Serve.

network and addr are the network type and address to listen on, respectively. For example, "tcp" and "0.0.0.0:8080".

ListenAndServe returns an error if it fails to create the listener or if there is an error serving connections.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve accepts incoming connections from the provided listener and handles them. It runs in a loop, accepting connections and spawning a goroutine to handle each one using ServeConn.

Serve returns an error if there is an error accepting a connection.

func (*Server) ServeConn

func (s *Server) ServeConn(conn net.Conn) error

ServeConn handles a single connection. It reads from the connection, processes the SOCKS5 protocol, and handles the request.

ServeConn performs the following steps:

  • Check the IP allowlist.
  • Reads the version byte from the connection.
  • Checks if the version is compatible with SOCKS5.
  • Authenticates the connection based on the server's configuration.
  • Reads the client's request.
  • Processes the client's request and sends the appropriate response.

ServeConn returns an error if any step fails.

func (*Server) SetIPAllowlist

func (s *Server) SetIPAllowlist(allowedIPs []net.IP)

SetIPAllowlist sets the function to check if a given IP is allowed. It takes a list of allowed IPs and updates the server's IP allowlist function accordingly.

type StaticCredentials

type StaticCredentials map[string]string

StaticCredentials is an implementation of the CredentialStore interface that uses a map to store user credentials. It enables direct use of a map as a credential store.

func (StaticCredentials) Valid

func (s StaticCredentials) Valid(user, password string) bool

Valid checks if the given user and password combination is valid. It returns true if the user exists in the map and the password matches, and false otherwise.

type UDPConn added in v1.1.1

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

func NewUDPConn added in v1.1.1

func NewUDPConn(raw net.PacketConn, proxyAddress net.Addr, defaultTarget net.Addr) (*UDPConn, error)

func (*UDPConn) Read added in v1.1.1

func (c *UDPConn) Read(b []byte) (int, error)

Read implements the net.Conn Read method.

func (*UDPConn) ReadFrom added in v1.1.1

func (c *UDPConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)

ReadFrom implements the net.PacketConn ReadFrom method.

func (*UDPConn) ReadFromUDP added in v1.1.1

func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error)

ReadFromUDP implements the net.UDPConn ReadFromUDP method.

func (*UDPConn) ReadMsgUDP added in v1.1.1

func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)

ReadMsgUDP implements the net.UDPConn ReadMsgUDP method.

func (*UDPConn) RemoteAddr added in v1.1.1

func (c *UDPConn) RemoteAddr() net.Addr

RemoteAddr implements the net.Conn RemoteAddr method.

func (*UDPConn) SetDeadline added in v1.1.1

func (c *UDPConn) SetDeadline(t time.Time) error

SetDeadline implements the Conn SetDeadline method.

func (*UDPConn) SetReadBuffer added in v1.1.1

func (c *UDPConn) SetReadBuffer(bytes int) error

SetReadBuffer implements the net.UDPConn SetReadBuffer method.

func (*UDPConn) SetReadDeadline added in v1.1.1

func (c *UDPConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*UDPConn) SetWriteBuffer added in v1.1.1

func (c *UDPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer implements the net.UDPConn SetWriteBuffer method.

func (*UDPConn) SetWriteDeadline added in v1.1.1

func (c *UDPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*UDPConn) Write added in v1.1.1

func (c *UDPConn) Write(b []byte) (int, error)

Write implements the net.Conn Write method.

func (*UDPConn) WriteMsgUDP added in v1.1.1

func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)

WriteMsgUDP implements the net.UDPConn WriteMsgUDP method.

func (*UDPConn) WriteTo added in v1.1.1

func (c *UDPConn) WriteTo(p []byte, addr net.Addr) (n int, err error)

WriteTo implements the net.PacketConn WriteTo method.

func (*UDPConn) WriteToUDP added in v1.1.1

func (c *UDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error)

WriteToUDP implements the net.UDPConn WriteToUDP method.

type UdpAssociate added in v1.1.0

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

UdpAssociate manages a collection of UdpPeer instances.

func NewUdpAssociate added in v1.1.0

func NewUdpAssociate() *UdpAssociate

NewUdpAssociate creates a new UdpAssociate instance.

func (*UdpAssociate) CloseAll added in v1.1.0

func (ua *UdpAssociate) CloseAll()

CloseAll closes all target connections in the collection.

func (*UdpAssociate) Del added in v1.1.0

func (ua *UdpAssociate) Del(key string)

Del removes a UdpPeer from the collection.

func (*UdpAssociate) Get added in v1.1.0

func (ua *UdpAssociate) Get(key string) (*UdpPeer, bool)

Get retrieves a UdpPeer from the collection.

func (*UdpAssociate) Set added in v1.1.0

func (ua *UdpAssociate) Set(key string, u *UdpPeer)

Set adds or updates a UdpPeer in the collection.

type UdpPeer added in v1.1.0

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

UdpPeer records information about a client connection.

type UdpServer added in v1.1.0

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

UdpServer represents a UDP server that can handle UDP connections.

func UdpInstance added in v1.1.0

func UdpInstance() *UdpServer

UdpInstance returns the global UdpServer instance.

func (*UdpServer) Close added in v1.1.0

func (us *UdpServer) Close() error

Close closes the UDP connection. It returns an error if the connection cannot be closed.

func (*UdpServer) Listen added in v1.1.0

func (us *UdpServer) Listen(network, addr string) error

Listen initializes the UDP server by binding it to the specified network address. It returns an error if the server cannot be bound to the specified address.

func (*UdpServer) LocalAddr added in v1.1.0

func (us *UdpServer) LocalAddr() net.Addr

LocalAddr returns the local address to which the UDP server is bound.

func (*UdpServer) ReadFromUdp added in v1.1.0

func (us *UdpServer) ReadFromUdp(bs []byte) (int, *net.UDPAddr, error)

ReadFromUdp reads a UDP packet from the underlying UDP connection. It returns the number of bytes read, the remote address from which the packet was received, and any error encountered.

func (*UdpServer) WriteToUDP added in v1.1.0

func (us *UdpServer) WriteToUDP(bs []byte, addr *net.UDPAddr) (int, error)

WriteToUDP writes a UDP packet to the specified remote address. It returns the number of bytes written and any error encountered.

type UserPassAuthenticator

type UserPassAuthenticator struct {
	// Credentials is the credential store used to validate user credentials.
	Credentials CredentialStore
}

UserPassAuthenticator is an implementation of the Authenticator interface for the "User/Password Authentication" method.

func (UserPassAuthenticator) Authenticate

func (a UserPassAuthenticator) Authenticate(reader io.Reader, writer io.Writer) (*AuthContext, error)

Authenticate performs the user/password authentication process. It verifies the user credentials and returns an AuthContext if successful.

func (UserPassAuthenticator) GetCode

func (a UserPassAuthenticator) GetCode() uint8

GetCode returns the authentication method code for the "User/Password Authentication" method.

type UserPassNegotiationReply added in v1.1.1

type UserPassNegotiationReply struct {
	Ver    byte
	Status byte
}

UserPassNegotiationReply is the negotiation username/password reply packet

func NewUserPassNegotiationReplyFrom added in v1.1.1

func NewUserPassNegotiationReplyFrom(r io.Reader) (*UserPassNegotiationReply, error)

NewUserPassNegotiationReplyFrom read user password negotiation reply packet from server

type UserPassNegotiationRequest added in v1.1.1

type UserPassNegotiationRequest struct {
	Ver    byte
	Ulen   byte
	Uname  []byte // 1-255 bytes
	Plen   byte
	Passwd []byte // 1-255 bytes
}

UserPassNegotiationRequest is the negotiation username/password reqeust packet

func NewUserPassNegotiationRequest added in v1.1.1

func NewUserPassNegotiationRequest(username []byte, password []byte) *UserPassNegotiationRequest

NewUserPassNegotiationRequest return user password negotiation request packet can be writed into server

func (*UserPassNegotiationRequest) WriteTo added in v1.1.1

func (r *UserPassNegotiationRequest) WriteTo(w io.Writer) (int64, error)

WriteTo write user password negotiation request packet into server

Jump to

Keyboard shortcuts

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