Documentation
¶
Overview ¶
Package socks5 implements SOCKS version 5 (RFC 1928) with username/password authentication (RFC 1929): a message codec for clients and servers, and a configurable Server.
The codec functions read one message from an io.Reader or write one message to an io.Writer in a single Write call, so they work over any connection and leave timeouts and policy to the caller. A server handshake reads the client's methods, selects one, optionally authenticates, then reads the request and writes a reply:
methods, err := socks5.ReadMethods(conn) // then socks5.WriteMethod user, pass, err := socks5.ReadUserPass(conn) // then socks5.WriteUserPassStatus cmd, dst, err := socks5.ReadRequest(conn) // then socks5.WriteReply
A client mirrors it with WriteMethods, ReadMethod, WriteUserPass, ReadUserPassStatus, WriteRequest and ReadReply. ReadRequest4, WriteRequest4, WriteReply4 and ReadReply4 handle SOCKS4 and SOCKS4a. DecodeDatagram and AppendDatagram handle the header of UDP ASSOCIATE datagrams. Reserved fields and the username/password version byte are not checked on receipt, for compatibility with non-standard peers.
Dialer dials TCP connections through a SOCKS5, SOCKS4 or SOCKS4a proxy and opens UDP associations through a SOCKS5 one. Server serves CONNECT, UDP ASSOCIATE and, optionally, SOCKS4 and SOCKS4a clients; its Handshake and ServeRequest let a caller serve other commands itself. Both run over any net.Conn, so SOCKS over TLS only needs a TLS listener for the server, or a TLS dialer as the Dialer's Forward. Authentication, access control, dialing, relaying, the outbound side of UDP associations and the advertised addresses are all replaceable, and UDP associations can share one fixed port or get a socket each.
Settings: the zero value of a field selects its default, stated in the field's documentation; for timeouts and limits it is a safe bound unless the field says otherwise. A negative timeout means no timeout, as for http.Server.IdleTimeout. Other negative values are an error unless the field gives them a meaning. The zero value is not a safe bound for DatagramRelay.IdleTimeout, whose zero means no timeout, as the relay's caller usually bounds it.
Example ¶
A CONNECT handshake without authentication, client and server side.
package main
import (
"fmt"
"log"
"net"
"net/netip"
"slices"
"github.com/djylb/netx"
"github.com/djylb/netx/socks5"
)
func main() {
client, server := net.Pipe()
go func() {
defer func() { _ = server.Close() }()
methods, err := socks5.ReadMethods(server)
if err != nil || !slices.Contains(methods, socks5.MethodNoAuth) {
_ = socks5.WriteMethod(server, socks5.MethodNoAcceptable)
return
}
_ = socks5.WriteMethod(server, socks5.MethodNoAuth)
cmd, dst, err := socks5.ReadRequest(server)
if err != nil {
return
}
fmt.Println("server:", cmd, dst)
_ = socks5.WriteReply(server, socks5.ReplySucceeded, netx.Addr{IP: netip.MustParseAddr("192.0.2.1"), Port: 40000})
}()
if err := socks5.WriteMethods(client, socks5.MethodNoAuth); err != nil {
log.Fatal(err)
}
if _, err := socks5.ReadMethod(client); err != nil {
log.Fatal(err)
}
dst, _ := netx.ParseAddr("example.com:443")
if err := socks5.WriteRequest(client, socks5.CmdConnect, dst); err != nil {
log.Fatal(err)
}
bound, err := socks5.ReadReply(client)
fmt.Println("client: bound", bound, err)
}
Output: server: connect example.com:443 client: bound 192.0.2.1:40000 <nil>
Index ¶
- Constants
- Variables
- func AppendAddr(b []byte, a netx.Addr) ([]byte, error)
- func AppendDatagram(b []byte, addr netx.Addr, payload []byte) ([]byte, error)
- func DecodeAddr(b []byte) (netx.Addr, int, error)
- func DecodeDatagram(b []byte) (addr netx.Addr, n int, err error)
- func ListenAssociationUDP(ctx context.Context, req *Request) (net.PacketConn, error)
- func ReadAddr(r io.Reader) (netx.Addr, error)
- func ReadReply(r io.Reader) (netx.Addr, error)
- func ReadReply4(r io.Reader) (netx.Addr, error)
- func ReadUserPass(r io.Reader) (user, password string, err error)
- func ReadUserPassStatus(r io.Reader) error
- func WriteMethod(w io.Writer, m Method) error
- func WriteMethods(w io.Writer, methods ...Method) error
- func WriteReply(w io.Writer, rep Reply, bound netx.Addr) error
- func WriteReply4(w io.Writer, rep Reply, bound netx.Addr) error
- func WriteRequest(w io.Writer, cmd Command, dst netx.Addr) error
- func WriteRequest4(w io.Writer, cmd Command, dst netx.Addr, userID string) error
- func WriteUserPass(w io.Writer, user, password string) error
- func WriteUserPassStatus(w io.Writer, ok bool) error
- type Authenticator
- type Command
- type DatagramRelay
- type Dialer
- func (d *Dialer) Dial(network, address string) (net.Conn, error)
- func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)
- func (d *Dialer) Handshake(ctx context.Context, c net.Conn, cmd Command, dst netx.Addr) (netx.Addr, error)
- func (d *Dialer) ListenPacket(ctx context.Context) (*UDPConn, error)
- type Method
- type NoAuth
- type PacketConn
- type Reply
- type ReplyError
- type Request
- type Server
- func (s *Server) ActiveConns() int
- func (s *Server) Close() error
- func (s *Server) Handshake(ctx context.Context, c net.Conn) (*Request, error)
- func (s *Server) ListenAndServe(addr string) error
- func (s *Server) Serve(l net.Listener) error
- func (s *Server) ServeConn(ctx context.Context, c net.Conn) error
- func (s *Server) ServeRequest(ctx context.Context, req *Request) error
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) Validate() error
- type UDPConn
- func (u *UDPConn) AsNetPacketConn() net.PacketConn
- func (u *UDPConn) Close() error
- func (u *UDPConn) LocalAddr() net.Addr
- func (u *UDPConn) ReadFrom(p []byte) (int, netx.Addr, error)
- func (u *UDPConn) RelayAddr() netip.AddrPort
- func (u *UDPConn) SetDeadline(t time.Time) error
- func (u *UDPConn) SetReadDeadline(t time.Time) error
- func (u *UDPConn) SetWriteDeadline(t time.Time) error
- func (u *UDPConn) WriteTo(p []byte, dst netx.Addr) (int, error)
- type UserPassAuth
Examples ¶
Constants ¶
const ( DefaultHandshakeTimeout = 10 * time.Second DefaultDialTimeout = 10 * time.Second DefaultUDPIdleTimeout = 3 * time.Minute )
Default timeouts of a Server.
const DefaultUDPQueue = 128
DefaultUDPQueue is how many client datagrams a UDP association buffers when Server.UDPQueue is 0.
const MaxAddrLen = 1 + 1 + 255 + 2
MaxAddrLen is the length of the longest encoded address: the type byte, a length byte, a 255-byte domain name and the port.
const MaxDatagramHeaderLen = 3 + MaxAddrLen
MaxDatagramHeaderLen is the length of the longest UDP datagram header: two reserved bytes, the fragment number and an address.
const Version4 = 4
Version4 is the version byte of SOCKS4 and SOCKS4a requests.
const Version5 = 5
Version5 is the version byte of SOCKS5 messages.
Variables ¶
var ( // ErrVersion reports a message whose version byte is not 5. ErrVersion = errors.New("socks5: unsupported version") // ErrMalformed reports a message that violates the protocol. ErrMalformed = errors.New("socks5: malformed message") // ErrAddrType reports an address type other than IPv4, IPv6 or domain // name. A server answers it with ReplyAddrTypeNotSupported. ErrAddrType = errors.New("socks5: unsupported address type") // ErrInvalidAddr reports an address that cannot be encoded or parsed; // it is netx.ErrInvalidAddr. ErrInvalidAddr = netx.ErrInvalidAddr // ErrNoAcceptableMethod is returned by ReadMethod when the server accepts // none of the offered methods. ErrNoAcceptableMethod = errors.New("socks5: no acceptable authentication method") // ErrAuthFailed is returned by ReadUserPassStatus when the server rejects // the credentials. ErrAuthFailed = errors.New("socks5: authentication failed") // ErrFragmented is returned by DecodeDatagram for a datagram fragment. ErrFragmented = errors.New("socks5: fragmented datagram") // ErrReplied is returned by Request.Reply for a request that has // already got its last reply. ErrReplied = errors.New("socks5: request already replied to") )
var ErrDatagramTooLarge = errors.New("socks5: UDP datagram too large")
ErrDatagramTooLarge drops a datagram that fills the relay's whole buffer, which may have cut it short: it is longer than the largest UDP datagram.
var ErrLookupBusy = errors.New("socks5: too many datagrams wait for name lookups")
ErrLookupBusy drops a datagram to a name that a PacketConn of NewPacketConn is looking up, or is to look up, while it holds as many datagrams, or runs as many lookups, as it may.
var ErrServerClosed = errors.New("socks5: server closed")
ErrServerClosed is returned by Serve after Close.
Functions ¶
func AppendAddr ¶
AppendAddr appends the encoded address a (type, address and port) to b. IPv4-mapped IPv6 addresses are sent as IPv4 and zones are dropped; the zero Addr is sent as 0.0.0.0:0, the usual bound address of a failure reply. It returns ErrInvalidAddr for a name longer than 255 bytes.
func AppendDatagram ¶
AppendDatagram appends a UDP ASSOCIATE datagram for addr carrying payload to b. It returns ErrInvalidAddr for a domain name longer than 255 bytes.
func DecodeAddr ¶
DecodeAddr decodes the encoded address at the start of b and returns it with its encoded length. It returns ErrAddrType for an unknown address type and ErrMalformed for a truncated address or an empty domain name.
The address is normalised as described at netx.Addr: every IP address comes back as IP, also a domain name that is an IP literal, and other names in lower case, unresolved.
Example ¶
Decode an address embedded in a larger message.
package main
import (
"fmt"
"github.com/djylb/netx/socks5"
)
func main() {
msg := []byte{3, 11, 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'o', 'r', 'g', 0x01, 0xbb, 'm', 'o', 'r', 'e'}
addr, n, err := socks5.DecodeAddr(msg)
fmt.Println(addr, string(msg[n:]), err)
}
Output: example.org:443 more <nil>
func DecodeDatagram ¶
DecodeDatagram decodes the header of a UDP ASSOCIATE datagram and returns the address with the header's length; the payload is b[n:].
It returns ErrFragmented for a fragment number other than 0, since fragmentation is not supported, and ErrMalformed for a truncated header. The reserved field is ignored, which also accepts senders that store the payload length there.
Example ¶
package main
import (
"fmt"
"net/netip"
"github.com/djylb/netx"
"github.com/djylb/netx/socks5"
)
func main() {
packet, _ := socks5.AppendDatagram(nil, netx.Addr{IP: netip.MustParseAddr("198.51.100.7"), Port: 53}, []byte("query"))
dst, n, err := socks5.DecodeDatagram(packet)
fmt.Println(dst, string(packet[n:]), err)
}
Output: 198.51.100.7:53 query <nil>
func ListenAssociationUDP ¶
ListenAssociationUDP opens a UDP socket of its own for the association of req, on the IP address that the client reached the server at, the local address of the control connection, and a port that the system picks. It is a ListenUDP for a Server whose clients each get their own socket:
s := &socks5.Server{ListenUDP: socks5.ListenAssociationUDP}
A control connection without a local IP address, or with an unspecified one, gets a socket on all addresses, from netx.ListenEphemeralUDP.
func ReadAddr ¶
ReadAddr reads an encoded address, normalized as by DecodeAddr. It returns ErrAddrType for an unknown address type and ErrMalformed for an empty domain name.
func ReadReply ¶
ReadReply reads a server reply and returns the bound address. A reply other than ReplySucceeded is returned as a *ReplyError, also when its address, which servers often leave unset, cannot be read. The reserved byte is ignored.
func ReadReply4 ¶
ReadReply4 reads a SOCKS4 reply and returns the bound address. A reply other than Reply4Granted is returned as a *ReplyError. The version byte, which should be 0, is not checked, since some servers send 4.
func ReadUserPass ¶
ReadUserPass reads a username/password request. Its version byte is not checked, since some clients send 5 instead of 1.
func ReadUserPassStatus ¶
ReadUserPassStatus reads the server's answer to a username/password request and returns ErrAuthFailed if it is a failure. Its version byte is not checked.
func WriteMethod ¶
WriteMethod writes the server's method selection. MethodNoAcceptable tells the client that none of its methods were accepted; the server then closes the connection.
func WriteMethods ¶
WriteMethods writes a client's method selection message offering methods. It returns ErrMalformed if methods is empty or longer than 255.
func WriteReply ¶
WriteReply writes a server reply carrying the bound address. Failure replies usually carry the zero netx.Addr.
func WriteReply4 ¶
WriteReply4 writes a SOCKS4 reply carrying the bound address, which is sent as 0.0.0.0 unless it is IPv4. rep may be a SOCKS4 reply or, for servers that share code with SOCKS5, a SOCKS5 one: ReplySucceeded is sent as Reply4Granted and other SOCKS5 replies as Reply4Rejected.
func WriteRequest ¶
WriteRequest writes a client request for cmd to dst.
func WriteRequest4 ¶
WriteRequest4 writes a SOCKS4 request for cmd to dst, or a SOCKS4a request when dst is a domain name or an address of 0.0.0.x, which SOCKS4 reserves for SOCKS4a, with x not zero. It returns an error wrapping ErrAddrType for an IPv6 destination and ErrMalformed for a user ID or name that is too long or contains a NUL byte.
func WriteUserPass ¶
WriteUserPass writes a username/password request. It returns ErrMalformed if user or password is longer than 255 bytes.
Types ¶
type Authenticator ¶
type Authenticator interface {
// Method returns the method the authenticator implements.
Method() Method
// Authenticate runs the method's sub-negotiation on c after the server
// selected the method, and returns the client's identity.
Authenticate(ctx context.Context, c net.Conn) (user string, err error)
}
Authenticator authenticates clients with one method.
type Command ¶
type Command byte
Command is the command of a client request.
Commands defined by RFC 1928.
func ReadRequest ¶
ReadRequest reads a client request. The command is returned as sent; answer commands the server does not implement with ReplyCommandNotSupported. ErrAddrType is answered with ReplyAddrTypeNotSupported. The reserved byte is ignored.
func ReadRequest4 ¶
ReadRequest4 reads a SOCKS4 or SOCKS4a request and returns its command, destination and user ID. A SOCKS4a destination, signaled by an address of 0.0.0.x with x not zero, is returned by name, or by IP address when the name is an IP literal, as DecodeAddr does. The user ID is not authentication: SOCKS4 has none.
type DatagramRelay ¶
type DatagramRelay struct {
// Clock tells the time of IdleTimeout; the system clock if nil.
Clock timeshim.Clock
// Allow, if set, drops the datagrams to destinations it rejects. As with
// Server.AllowPacket, IP addresses come as IP and other names
// unresolved, so a policy on IP addresses must also check the addresses
// that names resolve to, in a PacketConn that resolves them.
Allow func(dst netx.Addr) bool
// Sent, if set, is called with the destination and payload length of
// each datagram that the PacketConn took.
Sent func(dst netx.Addr, n int)
// Received, if set, is called with the source and payload length of
// each reply written to the stream.
Received func(src netx.Addr, n int)
// OnError, if set, receives the errors that drop a datagram: a
// malformed one, a fragment (ErrFragmented), one that does not fit
// (ErrDatagramTooLarge), a failed send, an ICMP error that a send
// caused, or a reply that the stream did not take. The peer at the
// stream's other end can cause these at the rate it sends, so a
// handler that logs them should rate-limit. The error that ends the
// relay is returned by Relay instead.
OnError func(err error)
// IdleTimeout ends a relay that no datagram passed in either direction
// for this long, with netx.ErrRelayIdle; 0 or a negative value means no
// timeout, as the relay's caller usually bounds it. Datagrams dropped
// as invalid or by Allow do not count.
IdleTimeout time.Duration
}
DatagramRelay relays the datagrams of a UDP association between a stream that carries them with their RFC 1928 headers, one per message, and a PacketConn that sends them to their destinations; see Relay. Every field is optional. The zero DatagramRelay, and a nil one, relay every datagram. A DatagramRelay may serve many relays at once and must not be changed while any runs; its functions are called from the relays' goroutines and must then be safe for concurrent use.
func (*DatagramRelay) Relay ¶
func (r *DatagramRelay) Relay(ctx context.Context, stream io.ReadWriteCloser, out PacketConn) error
Relay relays datagrams between stream and out until one of them ends, and closes both when it returns.
Each Read of stream must return one datagram with its RFC 1928 header, and each Write sends one, as with a netx.FramedConn made with netx.WithFramedDatagrams, a UDP socket connected to the client, or a udpflow.PacketListener connection. Relay sends the payload of each datagram to its destination through out, and writes each reply that out receives to stream, headed by the reply's source. Datagrams whose fragment number is not 0 are dropped, as RFC 1928 lets a relay that does not reassemble fragments do, and so are truncated ones and ones longer than any UDP datagram; see OnError.
With out from NewPacketConn, the relay is a full-cone NAT: one socket sends every datagram, so all destinations see the same source address and port, and replies from any address and port are delivered, also from ones never sent to. Datagrams to a name are held while it is looked up, as NewPacketConn describes, and the others pass meanwhile; a reply always comes from an IP address. Another PacketConn, such as one that forwards the datagrams through a tunnel, must not block in WriteTo for long, which holds up the datagrams behind.
Relay holds two buffers of the largest datagram, which it reuses for every datagram without copying it or allocating. It returns once both directions have stopped: when ctx ends, returning context.Cause(ctx); when stream reaches EOF or either side is closed, returning nil; when either side fails, returning the error; or with netx.ErrRelayIdle after IdleTimeout. Errors caused by Relay closing the two sides are not reported. A receive error ends the relay, except one that a UDP socket reports for an ICMP error caused by an earlier datagram, such as a closed port, of which as many are skipped as datagrams were sent.
Lookups of names that NewPacketConn started may outlive Relay: closing out cancels them, and each ends within the lookup's timeout, DefaultDialTimeout, also with a resolver that does not see the cancellation at once; there are at most as many as NewPacketConn runs at once.
type Dialer ¶
type Dialer struct {
// Forward dials the proxy; nil means a zero net.Dialer.
Forward netx.ContextDialer
// Resolver, if set, resolves host names on the client so that the proxy
// receives addresses, as SOCKS4 servers without the 4a extension need.
// SOCKS4 uses the first IPv4 address, SOCKS5 the first address.
Resolver *net.Resolver
// ProxyAddr is the proxy's host:port.
ProxyAddr string
// Username and Password are offered with SOCKS5 username/password
// authentication (RFC 1929) when Username is not empty; no
// authentication is offered as well. SOCKS4 sends Username as the user
// ID and ignores Password.
Username string
Password string
// SOCKS4 speaks SOCKS4, or SOCKS4a for host names, instead of SOCKS5.
// IPv6 targets and UDP cannot be reached with it.
SOCKS4 bool
}
Dialer dials TCP connections through a SOCKS5, SOCKS4 or SOCKS4a proxy with the CONNECT command, and opens UDP associations through a SOCKS5 proxy with ListenPacket. Host names are sent to the proxy, which resolves them, unless Resolver is set.
For SOCKS over TLS, set Forward to a dialer that returns TLS connections, such as a *tls.Dialer or a tlsconn.Dialer.
Example ¶
Dial through a SOCKS5 proxy that resolves the host name.
package main
import (
"context"
"log"
"net"
"time"
"github.com/djylb/netx/socks5"
)
func main() {
d := &socks5.Dialer{
ProxyAddr: "127.0.0.1:1080",
Username: "alice",
Password: "secret",
Forward: &net.Dialer{Timeout: 10 * time.Second},
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
conn, err := d.DialContext(ctx, "tcp", "example.com:443")
if err != nil {
log.Fatal(err)
}
defer func() { _ = conn.Close() }()
}
Output:
Example (Socks4) ¶
Dial through a SOCKS4 proxy, resolving the host name locally for servers without the SOCKS4a extension.
package main
import (
"log"
"net"
"github.com/djylb/netx/socks5"
)
func main() {
d := &socks5.Dialer{
ProxyAddr: "127.0.0.1:1080",
SOCKS4: true,
Username: "alice", // the SOCKS4 user ID
Resolver: net.DefaultResolver,
}
conn, err := d.Dial("tcp", "example.com:80")
if err != nil {
log.Println(err)
return
}
defer func() { _ = conn.Close() }()
}
Output:
func (*Dialer) Dial ¶
Dial is DialContext with a background context, for code that expects a dialer without a context.
func (*Dialer) DialContext ¶
DialContext connects to address through the proxy: it dials the proxy with Forward and runs Handshake for CmdConnect. ctx bounds the whole dial, including name resolution, and the returned connection has no deadline set. A non-success reply is returned as a *ReplyError, and networks other than tcp, tcp4 and tcp6 as an error matching errors.ErrUnsupported.
func (*Dialer) Handshake ¶
func (d *Dialer) Handshake(ctx context.Context, c net.Conn, cmd Command, dst netx.Addr) (netx.Addr, error)
Handshake runs the client side of a request for cmd to dst on c, a connection to the proxy, and returns the bound address of the server's reply: for CmdConnect the address the proxy connects from, for CmdUDPAssociate the address to send datagrams to, which servers often leave unspecified. dst is sent as it is, without Resolver. SOCKS4 has no UDP ASSOCIATE and returns an error matching errors.ErrUnsupported for it.
ctx bounds the handshake as with netx.DoHandshake, and c has no deadline set after a success. A non-success reply is returned as a *ReplyError. On failure c is closed, as by netx.DoHandshake.
func (*Dialer) ListenPacket ¶
ListenPacket opens a UDP association through the SOCKS5 proxy: it dials the proxy with Forward, opens a local UDP socket with netx.ListenEphemeralUDP and runs Handshake for CmdUDPAssociate, announcing the socket's port. ctx bounds the setup only. The association lasts until the UDPConn is closed, which closes the control connection, or until the proxy ends the control connection, which closes the UDPConn.
The datagrams go from the local socket straight to the proxy's relay, and proxies accept them only from the IP address of the control connection, so Forward must reach the proxy from that address. SOCKS4 has no UDP and returns an error matching errors.ErrUnsupported.
A *UDPConn is a PacketConn, so a Server can relay its own clients' UDP associations through the proxy with it as DialPacket.
type Method ¶
type Method byte
Method is an authentication method.
const ( MethodNoAuth Method = 0x00 MethodGSSAPI Method = 0x01 MethodUserPass Method = 0x02 MethodNoAcceptable Method = 0xFF )
Methods defined by RFC 1928.
func ReadMethod ¶
ReadMethod reads the server's method selection. It returns ErrNoAcceptableMethod when the server selects MethodNoAcceptable. The caller should check that the method is one it offered.
func ReadMethods ¶
ReadMethods reads a client's version identifier/method selection message and returns the offered methods.
type NoAuth ¶
type NoAuth struct{}
NoAuth accepts clients without authentication.
func (NoAuth) Authenticate ¶
Authenticate accepts the client.
type PacketConn ¶
type PacketConn interface {
// WriteTo sends p to dst. It must not retain p, which the caller reuses
// once WriteTo returns.
WriteTo(p []byte, dst netx.Addr) (int, error)
// ReadFrom reads the next reply and returns its source.
ReadFrom(p []byte) (n int, src netx.Addr, err error)
// Close ends the association's outbound side and unblocks ReadFrom.
Close() error
}
PacketConn is the outbound side of a UDP association: it sends the client's datagrams to their destinations and receives the replies. Implementations may forward the datagrams elsewhere, such as through a tunnel; netx.Addr keeps domain names unresolved for that purpose.
func NewPacketConn ¶
func NewPacketConn(c *net.UDPConn) PacketConn
NewPacketConn returns a PacketConn that sends and receives through c, resolving domain names with net.DefaultResolver and caching the results for a minute, and failed lookups for five seconds. Close ends the lookups in progress. Replies from any source are delivered, as with a full-cone NAT.
WriteTo does not wait for a lookup: a datagram to a name that is not cached is copied and held until the name resolves, and then sent, in order with the later datagrams to the name, or dropped if it does not resolve; WriteTo reports the cached failure for the datagrams that follow. The lookups of up to 64 names run at once, each holding up to 16 datagrams, and up to 256 KiB of datagrams are held in all; WriteTo fails with ErrLookupBusy for a datagram beyond these bounds, which drops it, as a full socket buffer would. Close cancels the lookups, whose goroutines then end, each within DefaultDialTimeout also with a resolver that does not see the cancellation at once.
type Reply ¶
type Reply byte
Reply is the status field of a server reply.
const ( Reply4Granted Reply = 90 Reply4Rejected Reply = 91 Reply4IdentdUnreached Reply = 92 Reply4IdentdMismatch Reply = 93 )
SOCKS4 replies. They share the Reply type with SOCKS5, whose codes they do not overlap.
const ( ReplySucceeded Reply = 0 ReplyGeneralFailure Reply = 1 ReplyNotAllowed Reply = 2 ReplyNetworkUnreachable Reply = 3 ReplyHostUnreachable Reply = 4 ReplyConnectionRefused Reply = 5 ReplyTTLExpired Reply = 6 ReplyCommandNotSupported Reply = 7 ReplyAddrTypeNotSupported Reply = 8 )
Replies defined by RFC 1928.
func ReplyFor ¶
ReplyFor returns the SOCKS5 reply code that reports err to a client: the Reply of a *ReplyError (ReplyGeneralFailure if that is ReplySucceeded), ReplySucceeded for nil, and otherwise the closest code for a failed dial, such as ReplyConnectionRefused or ReplyHostUnreachable, or ReplyGeneralFailure. SOCKS4 codes in a *ReplyError, as from an upstream SOCKS4 Dialer, are translated: the identd failures to ReplyNotAllowed and others to ReplyGeneralFailure.
type ReplyError ¶
ReplyError reports a request that was not granted. ReadReply and ReadReply4 return it for a server reply other than a success, with Reply holding the code as sent, a SOCKS4 one for ReadReply4. A Server returns it for the requests it refuses, with Err holding the cause, such as the error of Allow or Dial, so that OnError sees both the reply and its reason.
func (*ReplyError) Error ¶
func (e *ReplyError) Error() string
type Request ¶
type Request struct {
// Conn is the client's connection, positioned after the request: it
// first returns the bytes a SOCKS4 client sent right after its request,
// which reading the request buffered, and writes go to the served
// connection. It is the connection to reply on and to relay.
Conn net.Conn
// User is the identity returned by the authenticator, empty without
// authentication. For SOCKS4 it is what the NoAuth authenticator
// returned.
User string
// UserID4 is the user ID of a SOCKS4 or SOCKS4a request, which the client
// sends without authentication; empty for SOCKS5.
UserID4 string
// Dst is the requested destination. For CmdUDPAssociate it is the address
// the client expects to send datagrams from, often the zero netx.Addr.
Dst netx.Addr
// Version is Version5, or Version4 for a SOCKS4 or SOCKS4a request.
Version byte
Command Command
// contains filtered or unexported fields
}
Request is a client request read by Server.Handshake.
func (*Request) Reply ¶
Reply sends a reply to r in its protocol version: for SOCKS4 code and bound are translated as by WriteReply4. A request gets one reply, except a BIND request, which gets two: the address the server listens on for the peer, and then the address of the peer that connected. A failure reply, which usually carries the zero netx.Addr, is the last one, and the connection is then closed. Calls after the last reply return ErrReplied. Reply is not safe for concurrent use.
type Server ¶
type Server struct {
// UDPSocket is the client-facing UDP socket shared by all associations,
// which the clients are told to send to. Datagrams are routed to an
// association by their source, which must have the IP address of its
// control connection: to the association that announced the source's port,
// else to the only association of that IP address that announced no port,
// else to the only one pending for that IP address. An announced port
// counts at the control connection's IP address whatever address comes with
// it, since clients behind a NAT announce their private address and clients
// that do not know theirs announce 0.0.0.0 or a name; a client that
// announces the control connection's own address and a port gets datagrams
// from that source alone, as no NAT rewrote it. A source that matches none
// of these, such as one of several associations that announced no port, is
// ambiguous while they wait for their first datagram, and its datagrams are
// dropped. A request whose control connection has no IP address, such as a
// tunneled stream, must announce one, or it fails; nothing proves that
// announcement, so such a client can claim the datagrams of any IP address,
// and its control connections must come from trusted clients only. Serve
// untrusted clients of that kind with ListenUDP, whose sockets are their
// own. Close closes UDPSocket.
UDPSocket net.PacketConn
// Clock tells the time of UDPIdleTimeout; the system clock if nil.
Clock timeshim.Clock
// Dial connects to the destination of a CONNECT request; nil dials it
// directly. ctx is bounded by DialTimeout. The error's ReplyFor code is
// sent to the client, so return a *ReplyError to choose it. The bound
// address of the reply is the connection's LocalAddr; to report another,
// such as for a target that is not a socket, return the connection
// wrapped by netx.NewAddrOverrideConn, which the relay sees through.
Dial func(ctx context.Context, req *Request) (net.Conn, error)
// AllowPacket, if set, drops the client datagrams to destinations it
// rejects. Like Allow, it sees IP addresses as IP and other names
// unresolved, so a policy on IP addresses must also check the addresses
// that names resolve to, in a DialPacket whose PacketConn resolves them.
AllowPacket func(req *Request, dst netx.Addr) bool
// RelayOptions, if set, returns options for the netx.Relay between
// req.Conn and the target of a CONNECT request, such as
// netx.WithRelayFlows for the allowance or byte count of req.User,
// netx.WithRelayGroup or netx.WithRelayIdleTimeout. They follow
// netx.WithRelayHalfClose, which the relay always has, so that a client
// that shuts down its writing side still gets the reply. As with TCP
// itself, a half-closed connection then lasts until the other side
// finishes or closes too; an idle timeout bounds how long an idle one may
// last. The relay ends, and both connections are closed, when Close is
// called. To relay in another way, wrap the target in Dial, or serve
// CONNECT in Handle.
RelayOptions func(req *Request) []netx.RelayOption
// OnError, if set, receives the errors that end connections accepted by
// Serve, with the client connection, and those that drop UDP datagrams,
// with the association's control connection. It is called from serving
// goroutines and must be safe for concurrent use. Errors that come once
// Close is called, which ends the connections and associations, are not
// reported, whatever they are. The package does not log; route errors
// to a logger such as log/slog here.
OnError func(c net.Conn, err error)
// ListenUDP, used when UDPSocket is nil, opens a UDP socket for one
// association, which the association owns; ListenAssociationUDP is one.
// Datagrams are taken as on UDPSocket, except that when neither the control
// connection nor the request gives the client's IP address, the first
// source that sends becomes the client.
ListenUDP func(ctx context.Context, req *Request) (net.PacketConn, error)
// UDPAddr returns the address a UDP ASSOCIATE reply tells the client to
// send to, given the association's socket address; nil uses that address
// with the control connection's local IP when it is unspecified.
UDPAddr func(req *Request, socket net.Addr) netx.Addr
// DialPacket opens the outbound side of a UDP association; nil uses a new
// UDP socket from netx.ListenEphemeralUDP through NewPacketConn. That
// socket reaches IPv4 and IPv6 targets where the system has dual-stack
// sockets; on OpenBSD, which has none, it is IPv4 only. ctx is bounded by
// DialTimeout and bounds the setup only. To relay through another SOCKS5
// proxy, return a Dialer's ListenPacket.
DialPacket func(ctx context.Context, req *Request) (PacketConn, error)
// Handle, if set, is called by ServeRequest for each request after Allow
// and before the built-in commands, so that a server can serve commands
// such as BIND itself, or take over CONNECT or UDP ASSOCIATE for some
// requests, while Serve, Shutdown and ActiveConns still cover their
// connections. When it returns handled true, or has replied with
// req.Reply whatever it returns, it has served the request: it replied,
// for BIND twice, and used req.Conn, which is closed when it returns,
// and its error ends the exchange as the built-in commands' errors do.
// Otherwise a non-nil error refuses the request with the error's
// ReplyFor code, and nil leaves it to the built-in commands. ctx ends,
// and req.Conn is closed, when Close is called.
Handle func(ctx context.Context, req *Request) (handled bool, err error)
// Allow is called by ServeRequest for each request. A non-nil error
// refuses it with the error's ReplyFor code, or ReplyNotAllowed when that
// is ReplyGeneralFailure.
//
// The request's Dst holds every IP address the client sends as IP,
// including IPv4-mapped IPv6 addresses and domain names that are IP
// literals, also with one trailing dot such as "127.0.0.1." (see
// DecodeAddr). Other names are not resolved: a policy on IP
// addresses must also check the addresses that names resolve to, in a
// Dial hook, for example with a net.Dialer Control function, since some
// resolvers turn legacy forms such as "127.1" or "0x7f.0.0.1" into
// addresses. The unspecified addresses 0.0.0.0 and :: reach the server's
// own host on many systems.
Allow func(ctx context.Context, req *Request) error
// Auth lists the accepted authentication methods in order of
// preference. Nil means NoAuth. An authenticator for MethodNoAuth, which
// may check the connection itself (its address or TLS state), also
// decides on SOCKS4 clients and on SOCKS5 clients whose method lists
// match no authenticator.
Auth []Authenticator
// HandshakeTimeout bounds the negotiation and request; 0 means
// DefaultHandshakeTimeout (10s), and a negative value means no timeout, as
// for http.Server.IdleTimeout.
HandshakeTimeout time.Duration
// UDPIdleTimeout ends a UDP association without datagrams in either
// direction, or without a first datagram, for this long, and closes its
// control connection; 0 means DefaultUDPIdleTimeout (3 minutes), and
// a negative value means no timeout, as for http.Server.IdleTimeout.
UDPIdleTimeout time.Duration
// DialTimeout bounds Dial and DialPacket; 0 means DefaultDialTimeout (10s),
// and a negative value means no timeout, as for http.Server.IdleTimeout.
// This differs from net.Dialer.Timeout, where 0 means no timeout.
DialTimeout time.Duration
// UDPQueue is how many client datagrams an association buffers; 0
// means DefaultUDPQueue (128). It has no unlimited setting: a negative
// queue is an error.
UDPQueue int
// SOCKS4 also serves SOCKS4 and SOCKS4a requests. They carry no
// credentials, so they are refused unless Auth has a MethodNoAuth
// authenticator, which then runs for them.
SOCKS4 bool
// UDPOutlivesControl keeps a UDP association after its control
// connection closes, until UDPIdleTimeout, for clients that close or
// half-close it right after the reply. By default the association ends
// with the control connection, as RFC 1928 specifies.
UDPOutlivesControl bool
// contains filtered or unexported fields
}
Server serves SOCKS5 clients, and SOCKS4 and SOCKS4a clients when enabled.
Every field is optional: the zero Server accepts clients without authentication, serves CONNECT with a direct dial, and refuses BIND and UDP ASSOCIATE. UDP ASSOCIATE is served once UDPSocket or ListenUDP is set. Other commands can be served by calling Handshake and then answering the request, or passing it to ServeRequest.
The server sets no limit on the connections or UDP associations of a client, each of which holds a few sockets and buffers; bound them in the listener passed to Serve or in Allow.
Example ¶
A SOCKS5 server with accounts, a destination policy and UDP on a fixed port.
package main
import (
"context"
"errors"
"log"
"net"
"github.com/djylb/netx/socks5"
)
func main() {
udp, err := net.ListenPacket("udp", ":1080")
if err != nil {
log.Fatal(err)
}
s := &socks5.Server{
Auth: []socks5.Authenticator{
socks5.Credentials(map[string]string{"alice": "secret"}),
},
Allow: func(_ context.Context, req *socks5.Request) error {
if req.Dst.Port == 25 {
return errors.New("no mail") // answered with ReplyNotAllowed
}
return nil
},
UDPSocket: udp, // every association uses this port
}
ln, err := net.Listen("tcp", ":1080")
if err != nil {
log.Fatal(err)
}
log.Fatal(s.Serve(ln))
}
Output:
Example (Hooks) ¶
Count the bytes each user sends, end idle connections, and report a bound address of our choosing in CONNECT replies.
package main
import (
"context"
"log"
"net"
"sync"
"time"
"github.com/djylb/netx"
"github.com/djylb/netx/socks5"
)
func main() {
var mu sync.Mutex
sent := map[string]int64{}
s := &socks5.Server{
Auth: []socks5.Authenticator{
socks5.Credentials(map[string]string{"alice": "secret", "bob": "hunter2"}),
},
Dial: func(ctx context.Context, req *socks5.Request) (net.Conn, error) {
var d net.Dialer
c, err := d.DialContext(ctx, "tcp", req.Dst.String())
if err != nil {
return nil, err
}
public := &net.TCPAddr{IP: net.IPv4(198, 51, 100, 1), Port: 1080}
return netx.NewAddrOverrideConn(c, public, nil), nil
},
RelayOptions: func(req *socks5.Request) []netx.RelayOption {
count := netx.RelayFlow{Done: func(n int64) error {
mu.Lock()
sent[req.User] += n
mu.Unlock()
return nil
}}
return []netx.RelayOption{
netx.WithRelayFlows(&count, nil),
netx.WithRelayIdleTimeout(5 * time.Minute),
}
},
}
ln, err := net.Listen("tcp", ":1080")
if err != nil {
log.Fatal(err)
}
log.Fatal(s.Serve(ln))
}
Output:
Example (Tls) ¶
Serve SOCKS5, SOCKS4 and SOCKS4a over TLS. Clients reach it with a TLS dialer as the Dialer's Forward, or the socks5+tls and socks4a+tls schemes of the proxydial package.
package main
import (
"crypto/tls"
"log"
"net"
"github.com/djylb/netx/socks5"
)
func main() {
cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
log.Fatal(err)
}
ln, err := net.Listen("tcp", ":1443")
if err != nil {
log.Fatal(err)
}
s := &socks5.Server{SOCKS4: true}
log.Fatal(s.Serve(tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cert}})))
}
Output:
func (*Server) ActiveConns ¶
ActiveConns returns the number of connections being served by Serve and ServeConn, the control connections of UDP associations among them.
func (*Server) Close ¶
Close stops the listeners passed to Serve, closes the connections being served, ends the UDP associations, closing UDPSocket, and ends the Handshake and ServeRequest calls in progress. A CONNECT tunnel ends with a reset, as netx.Relay ends when its context does, so that its peers do not take a cut transfer for a complete one. Serve then returns ErrServerClosed. Later calls, also of Shutdown, wait until the first has finished and return nil.
func (*Server) Handshake ¶
Handshake reads a client's method negotiation, authentication and request on c, in SOCKS5 or, when enabled, SOCKS4 or SOCKS4a, and returns the request without replying to it. HandshakeTimeout bounds it, after which it returns an error matching os.ErrDeadlineExceeded, and ctx and Close end it too. Failures that the protocol answers, such as no acceptable method, rejected credentials or a malformed request, are answered before it returns. c has no deadline set after a success.
On failure c is closed, as by netx.DoHandshake.
The request is served by ServeRequest, or by the caller, which replies with Request.Reply and reads and writes Request.Conn; Allow is then not called. A caller that serves connections itself, rather than with Serve or ServeConn, is not counted by ActiveConns and not waited for by Shutdown.
func (*Server) ListenAndServe ¶
ListenAndServe listens on the TCP address addr, ":1080" when empty, and serves the connections as Serve does. It returns ErrServerClosed after Shutdown or Close, or the error that ended listening or accepting.
func (*Server) Serve ¶
Serve accepts connections on l and serves each with ServeConn, under a context that Close cancels, in its own goroutine. It returns ErrServerClosed after Shutdown or Close, which close l, or the error that ended Accept. Accept errors for which netx.IsAcceptRetryable reports true, such as running out of file descriptors, are retried as netx.Accept does.
func (*Server) ServeConn ¶
ServeConn serves one client connection, as Handshake and ServeRequest do, and closes it. ctx ending ends the connection, as Close does. It returns the error that ended the exchange, if any. The connection counts in ActiveConns until ServeConn returns.
func (*Server) ServeRequest ¶
ServeRequest serves a request from Handshake and closes req.Conn. It calls Allow, then Handle, then serves CONNECT, and UDP ASSOCIATE when UDPSocket or ListenUDP is set; other commands, and UDP ASSOCIATE from SOCKS4, are answered with ReplyCommandNotSupported and returned as a *ReplyError. A refused request is returned as a *ReplyError whose Err is the cause. ctx and Close end it, closing req.Conn. It returns the error that ended the exchange, if any.
func (*Server) Shutdown ¶
Shutdown stops the server gracefully: it closes the listeners passed to Serve, which then returns ErrServerClosed, makes ServeConn refuse new connections, and waits until the connections being served end, the control connections of UDP associations among them; then it calls Close. When ctx ends first, Close ends the remaining connections and Shutdown returns ctx's error too.
type UDPConn ¶
type UDPConn struct {
// contains filtered or unexported fields
}
UDPConn is a UDP association opened by Dialer.ListenPacket. WriteTo sends datagrams through the proxy's relay and ReadFrom receives the replies, taking only datagrams from the relay. It is safe for concurrent use.
func (*UDPConn) AsNetPacketConn ¶
func (u *UDPConn) AsNetPacketConn() net.PacketConn
AsNetPacketConn returns u as a net.PacketConn, for code that sends and receives with net.Addr. Its ReadFrom reports a source with an IP address as a *net.UDPAddr and one with a domain name as a netx.Addr. Its WriteTo takes a netx.Addr, which keeps a domain name for the proxy to resolve, or any net.Addr whose String is "host:port", such as a *net.UDPAddr. Closing it closes u.
func (*UDPConn) Close ¶
Close ends the association: it closes the control connection and the local socket, which unblocks ReadFrom. Calls after the first return nil.
func (*UDPConn) ReadFrom ¶
ReadFrom reads the next reply into p and returns its source. A reply longer than p is truncated. Datagrams from other senders than the relay, and malformed or fragmented ones, are dropped. After the association ends it returns an error matching net.ErrClosed.
func (*UDPConn) SetDeadline ¶
SetDeadline sets the read and write deadlines of the local socket.
func (*UDPConn) SetReadDeadline ¶
SetReadDeadline sets the deadline for ReadFrom.
func (*UDPConn) SetWriteDeadline ¶
SetWriteDeadline sets the deadline for WriteTo.
type UserPassAuth ¶
type UserPassAuth struct {
// Check reports whether the credentials that the client sent on c are
// valid; ctx is bounded by the handshake. c tells the client's address,
// for rules per address. An error, such as an unreachable account
// backend, rejects the client too and is returned by Authenticate
// instead of ErrAuthFailed, so that it is not mistaken for a wrong
// password. Nil rejects all credentials. See Credentials for a fixed
// account list.
Check func(ctx context.Context, c net.Conn, user, password string) (bool, error)
}
UserPassAuth checks username/password credentials (RFC 1929).
func Credentials ¶
func Credentials(accounts map[string]string) UserPassAuth
Credentials returns a UserPassAuth that accepts the given user names and passwords, for a server with a fixed account list:
s := &socks5.Server{Auth: []socks5.Authenticator{socks5.Credentials(accounts)}}
It compares SHA-256 digests in constant time, and for unknown users compares against a digest of no account, so that the time taken tells neither the length of a password nor whether a user exists. accounts is read once; later changes to it are not seen. Its Check can be called by a Check of your own, such as one that also has rules per client address.
func (UserPassAuth) Authenticate ¶
Authenticate reads the credentials, checks them, answers the client and returns the user name, or ErrAuthFailed, or the error of Check.