go-socks5/request.go

385 lines
11 KiB
Go
Raw Normal View History

2014-01-23 19:29:13 +00:00
package socks5
import (
2020-04-19 09:08:22 +00:00
"context"
2014-01-23 20:04:20 +00:00
"fmt"
"io"
2014-01-23 19:29:13 +00:00
"net"
2014-01-23 21:42:35 +00:00
"strings"
2020-04-20 08:19:51 +00:00
"sync"
2014-01-23 19:29:13 +00:00
)
2014-01-23 20:04:20 +00:00
var (
2020-04-22 02:15:40 +00:00
errUnrecognizedAddrType = fmt.Errorf("Unrecognized address type")
2014-01-23 20:04:20 +00:00
)
2020-04-19 14:30:45 +00:00
// AddressRewriter is used to rewrite a destination transparently
type AddressRewriter interface {
Rewrite(ctx context.Context, request *Request) (context.Context, *AddrSpec)
}
// A Request represents request received by a server
type Request struct {
2020-04-19 13:37:05 +00:00
Header
// AuthContext provided during negotiation
AuthContext *AuthContext
2020-04-23 02:15:02 +00:00
// LocalAddr of the the network server listen
LocalAddr net.Addr
// RemoteAddr of the the network that sent the request
RemoteAddr net.Addr
// DestAddr of the actual destination (might be affected by rewrite)
2020-04-22 02:15:40 +00:00
DestAddr *AddrSpec
// Reader connect of request
Reader io.Reader
2020-04-23 02:15:02 +00:00
// RawDestAddr of the desired destination
2020-04-22 02:15:40 +00:00
RawDestAddr *AddrSpec
}
2014-01-23 22:07:39 +00:00
type conn interface {
Write([]byte) (int, error)
RemoteAddr() net.Addr
}
// NewRequest creates a new Request from the tcp connection
2020-04-19 15:40:14 +00:00
func NewRequest(bufConn io.Reader) (*Request, error) {
2020-04-20 01:21:29 +00:00
/*
The SOCKS request is formed as follows:
+----+-----+-------+------+----------+----------+
|VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
*/
2020-04-20 08:42:10 +00:00
hd, err := Parse(bufConn)
if err != nil {
return nil, err
2020-04-19 13:55:14 +00:00
}
2020-04-21 06:03:20 +00:00
if hd.Command != CommandConnect && hd.Command != CommandBind && hd.Command != CommandAssociate {
2020-04-20 09:09:16 +00:00
return nil, fmt.Errorf("unrecognized command[%d]", hd.Command)
}
2020-04-19 13:37:05 +00:00
return &Request{
2020-04-22 02:15:40 +00:00
Header: hd,
RawDestAddr: &hd.Address,
Reader: bufConn,
2020-04-19 13:37:05 +00:00
}, nil
}
// handleRequest is used for request processing after authentication
2020-04-19 14:30:45 +00:00
func (s *Server) handleRequest(write io.Writer, req *Request) error {
ctx := context.Background()
2014-01-23 21:11:58 +00:00
// Resolve the address if we have a FQDN
2020-04-22 02:15:40 +00:00
dest := req.RawDestAddr
2014-01-24 00:46:32 +00:00
if dest.FQDN != "" {
2020-04-22 02:15:40 +00:00
_ctx, addr, err := s.resolver.Resolve(ctx, dest.FQDN)
2014-01-23 21:11:58 +00:00
if err != nil {
2020-04-22 02:32:03 +00:00
if err := SendReply(write, req.Header, RepHostUnreachable); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
2014-01-23 21:11:58 +00:00
}
2020-04-19 14:30:45 +00:00
return fmt.Errorf("failed to resolve destination[%v], %v", dest.FQDN, err)
2014-01-23 21:11:58 +00:00
}
2020-04-22 02:15:40 +00:00
ctx = _ctx
2014-01-24 00:46:32 +00:00
dest.IP = addr
2014-01-23 21:11:58 +00:00
}
2014-01-24 00:55:08 +00:00
// Apply any address rewrites
2020-04-22 02:15:40 +00:00
req.DestAddr = req.RawDestAddr
2020-04-20 13:17:38 +00:00
if s.rewriter != nil {
2020-04-22 02:15:40 +00:00
ctx, req.DestAddr = s.rewriter.Rewrite(ctx, req)
2014-01-24 00:55:08 +00:00
}
2014-01-24 00:46:32 +00:00
2020-04-21 12:27:02 +00:00
// Check if this is allowed
2020-04-22 02:15:40 +00:00
_ctx, ok := s.rules.Allow(ctx, req)
if !ok {
2020-04-22 02:32:03 +00:00
if err := SendReply(write, req.Header, RepRuleFailure); err != nil {
2020-04-21 12:27:02 +00:00
return fmt.Errorf("failed to send reply, %v", err)
}
2020-04-22 02:15:40 +00:00
return fmt.Errorf("bind to %v blocked by rules", req.RawDestAddr)
2020-04-21 12:27:02 +00:00
}
2020-04-22 02:15:40 +00:00
ctx = _ctx
2020-04-21 12:27:02 +00:00
2014-01-23 20:04:20 +00:00
// Switch on the command
switch req.Command {
2020-04-21 06:03:20 +00:00
case CommandConnect:
2020-04-22 02:15:40 +00:00
if s.userConnectHandle != nil {
return s.userConnectHandle(ctx, write, req)
}
2020-04-19 14:30:45 +00:00
return s.handleConnect(ctx, write, req)
2020-04-21 06:03:20 +00:00
case CommandBind:
2020-04-22 02:15:40 +00:00
if s.userBindHandle != nil {
return s.userBindHandle(ctx, write, req)
}
2020-04-19 14:30:45 +00:00
return s.handleBind(ctx, write, req)
2020-04-21 06:03:20 +00:00
case CommandAssociate:
2020-04-22 02:15:40 +00:00
if s.userAssociateHandle != nil {
return s.userAssociateHandle(ctx, write, req)
}
2020-04-19 14:30:45 +00:00
return s.handleAssociate(ctx, write, req)
2014-01-23 20:04:20 +00:00
default:
2020-04-22 02:32:03 +00:00
if err := SendReply(write, req.Header, RepCommandNotSupported); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
2014-01-23 21:42:35 +00:00
}
2020-04-19 14:30:45 +00:00
return fmt.Errorf("unsupported command[%v]", req.Command)
2014-01-23 20:04:20 +00:00
}
}
// handleConnect is used to handle a connect command
func (s *Server) handleConnect(ctx context.Context, writer io.Writer, req *Request) error {
2014-01-23 21:42:35 +00:00
// Attempt to connect
2020-04-20 13:17:38 +00:00
dial := s.dial
2016-02-04 19:25:27 +00:00
if dial == nil {
dial = func(ctx context.Context, net_, addr string) (net.Conn, error) {
return net.Dial(net_, addr)
}
2016-02-04 19:25:27 +00:00
}
2020-04-23 03:50:51 +00:00
target, err := dial(ctx, "tcp", req.DestAddr.String())
2014-01-23 21:42:35 +00:00
if err != nil {
msg := err.Error()
2020-04-22 02:32:03 +00:00
resp := RepHostUnreachable
2014-01-23 21:42:35 +00:00
if strings.Contains(msg, "refused") {
2020-04-22 02:32:03 +00:00
resp = RepConnectionRefused
2014-01-23 21:42:35 +00:00
} else if strings.Contains(msg, "network is unreachable") {
2020-04-22 02:32:03 +00:00
resp = RepNetworkUnreachable
2014-01-23 21:42:35 +00:00
}
2020-04-22 02:15:40 +00:00
if err := SendReply(writer, req.Header, resp); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
2014-01-23 21:42:35 +00:00
}
2020-04-22 02:15:40 +00:00
return fmt.Errorf("connect to %v failed, %v", req.RawDestAddr, err)
2014-01-23 21:42:35 +00:00
}
defer target.Close()
// Send success
2020-04-22 02:32:03 +00:00
if err := SendReply(writer, req.Header, RepSuccess, target.LocalAddr()); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
2014-01-23 21:42:35 +00:00
}
// Start proxying
errCh := make(chan error, 2)
2020-04-20 08:52:29 +00:00
2020-04-22 02:15:40 +00:00
s.submit(func() { errCh <- s.Proxy(target, req.Reader) })
s.submit(func() { errCh <- s.Proxy(writer, target) })
2014-01-23 21:42:35 +00:00
// Wait
for i := 0; i < 2; i++ {
e := <-errCh
if e != nil {
// return from this function closes target (and conn).
return e
}
2014-01-23 21:42:35 +00:00
}
return nil
2014-01-23 20:04:20 +00:00
}
// handleBind is used to handle a connect command
2020-04-22 02:32:03 +00:00
func (s *Server) handleBind(_ context.Context, writer io.Writer, req *Request) error {
2014-01-23 21:42:35 +00:00
// TODO: Support bind
2020-04-22 02:32:03 +00:00
if err := SendReply(writer, req.Header, RepCommandNotSupported); err != nil {
2020-04-19 14:30:45 +00:00
return fmt.Errorf("failed to send reply: %v", err)
2014-01-23 21:42:35 +00:00
}
2014-01-23 20:04:20 +00:00
return nil
}
// handleAssociate is used to handle a connect command
func (s *Server) handleAssociate(ctx context.Context, writer io.Writer, req *Request) error {
// Attempt to connect
2020-04-20 13:17:38 +00:00
dial := s.dial
if dial == nil {
dial = func(ctx context.Context, net_, addr string) (net.Conn, error) {
return net.Dial(net_, addr)
}
}
2020-04-23 03:50:51 +00:00
target, err := dial(ctx, "udp", req.DestAddr.String())
if err != nil {
msg := err.Error()
2020-04-22 02:32:03 +00:00
resp := RepHostUnreachable
if strings.Contains(msg, "refused") {
2020-04-22 02:32:03 +00:00
resp = RepConnectionRefused
} else if strings.Contains(msg, "network is unreachable") {
2020-04-22 02:32:03 +00:00
resp = RepNetworkUnreachable
}
2020-04-22 02:15:40 +00:00
if err := SendReply(writer, req.Header, resp); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
}
2020-04-22 02:15:40 +00:00
return fmt.Errorf("connect to %v failed, %v", req.RawDestAddr, err)
}
defer target.Close()
2020-04-22 02:15:40 +00:00
targetUDP, ok := target.(*net.UDPConn)
if !ok {
2020-04-22 02:32:03 +00:00
if err := SendReply(writer, req.Header, RepServerFailure); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
}
return fmt.Errorf("dial udp invalid")
}
2020-04-20 09:09:16 +00:00
bindLn, err := net.ListenUDP("udp", nil)
if err != nil {
2020-04-22 02:32:03 +00:00
if err := SendReply(writer, req.Header, RepServerFailure); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
}
return fmt.Errorf("listen udp failed, %v", err)
}
2020-04-20 12:41:58 +00:00
defer bindLn.Close()
2020-04-22 02:15:40 +00:00
s.logger.Errorf("target addr %v, listen addr: %s", targetUDP.RemoteAddr(), bindLn.LocalAddr())
// send BND.ADDR and BND.PORT, client must
2020-04-22 02:32:03 +00:00
if err = SendReply(writer, req.Header, RepSuccess, bindLn.LocalAddr()); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
2014-01-23 21:42:35 +00:00
}
2020-04-20 08:52:29 +00:00
s.submit(func() {
2020-04-20 12:41:58 +00:00
/*
The SOCKS UDP request/response is formed as follows:
+-----+------+-------+----------+----------+----------+
| RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
+-----+------+-------+----------+----------+----------+
| 2 | 1 | X'00' | Variable | 2 | Variable |
+-----+------+-------+----------+----------+----------+
*/
// read from client and write to remote server
2020-04-20 08:19:51 +00:00
conns := sync.Map{}
2020-04-20 12:41:58 +00:00
bufPool := s.bufferPool.Get()
defer func() {
2020-04-22 02:15:40 +00:00
targetUDP.Close()
2020-04-20 12:41:58 +00:00
bindLn.Close()
s.bufferPool.Put(bufPool)
}()
for {
2020-04-20 12:41:58 +00:00
buf := bufPool[:cap(bufPool)]
n, srcAddr, err := bindLn.ReadFrom(buf)
if err != nil {
2020-04-24 01:08:15 +00:00
if strings.Contains(err.Error(), "use of closed network connection") {
s.logger.Errorf("read data from bind listen address %s failed, %v", bindLn.LocalAddr(), err)
return
}
continue
}
2020-04-20 13:17:38 +00:00
2020-04-23 15:17:54 +00:00
pk := NewEmptyPacket()
2020-04-24 01:08:15 +00:00
if err := pk.Parse(buf[:n]); err != nil {
2020-04-20 12:41:58 +00:00
continue
}
2020-04-20 08:19:51 +00:00
// 把消息写给remote sever
2020-04-23 15:17:54 +00:00
if _, err := targetUDP.Write(pk.Data); err != nil {
2020-04-22 02:15:40 +00:00
s.logger.Errorf("write data to remote %s failed, %v", targetUDP.RemoteAddr(), err)
return
}
2020-04-20 08:19:51 +00:00
if _, ok := conns.LoadOrStore(srcAddr.String(), struct{}{}); !ok {
2020-04-20 08:52:29 +00:00
s.submit(func() {
2020-04-20 08:19:51 +00:00
// read from remote server and write to client
2020-04-20 12:41:58 +00:00
bufPool := s.bufferPool.Get()
defer func() {
2020-04-22 02:15:40 +00:00
targetUDP.Close()
2020-04-20 12:41:58 +00:00
bindLn.Close()
s.bufferPool.Put(bufPool)
}()
2020-04-20 08:19:51 +00:00
for {
2020-04-20 12:41:58 +00:00
buf := bufPool[:cap(bufPool)]
2020-04-22 02:15:40 +00:00
n, remote, err := targetUDP.ReadFrom(buf)
2020-04-20 08:19:51 +00:00
if err != nil {
2020-04-22 02:15:40 +00:00
s.logger.Errorf("read data from remote %s failed, %v", targetUDP.RemoteAddr(), err)
2020-04-20 08:19:51 +00:00
return
}
2020-04-23 15:17:54 +00:00
pkb, err := NewPacket(remote.String(), buf[:n])
if err != nil {
continue
}
2020-04-20 12:41:58 +00:00
tmpBufPool := s.bufferPool.Get()
proBuf := tmpBufPool
2020-04-23 15:40:00 +00:00
proBuf = append(proBuf, pkb.Header()...)
2020-04-23 15:17:54 +00:00
proBuf = append(proBuf, pkb.Data...)
2020-04-20 12:41:58 +00:00
if _, err := bindLn.WriteTo(proBuf, srcAddr); err != nil {
s.bufferPool.Put(tmpBufPool)
2020-04-20 13:17:38 +00:00
s.logger.Errorf("write data to client %s failed, %v", bindLn.LocalAddr(), err)
2020-04-20 08:19:51 +00:00
return
}
2020-04-20 12:41:58 +00:00
s.bufferPool.Put(tmpBufPool)
2020-04-20 08:19:51 +00:00
}
2020-04-20 08:52:29 +00:00
})
}
}
2020-04-20 08:52:29 +00:00
})
buf := s.bufferPool.Get()
2020-04-20 08:19:51 +00:00
defer func() {
s.bufferPool.Put(buf)
}()
for {
2020-04-22 02:15:40 +00:00
_, err := req.Reader.Read(buf[:cap(buf)])
if err != nil {
return err
}
}
2014-01-23 19:29:13 +00:00
}
2014-01-23 20:04:20 +00:00
2020-04-22 02:15:40 +00:00
// SendReply is used to send a reply message
func SendReply(w io.Writer, head Header, resp uint8, bindAddr ...net.Addr) error {
2020-04-20 01:21:29 +00:00
/*
The SOCKS response is formed as follows:
+----+-----+-------+------+----------+----------+
|VER | CMD | RSV | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
*/
2020-04-19 13:37:05 +00:00
2020-04-20 01:41:06 +00:00
head.Command = resp
2020-04-19 15:40:14 +00:00
if len(bindAddr) == 0 {
2020-04-21 06:03:20 +00:00
head.addrType = ATYPIPv4
2020-04-20 01:21:29 +00:00
head.Address.IP = []byte{0, 0, 0, 0}
head.Address.Port = 0
2020-04-19 15:40:14 +00:00
} else {
2020-04-20 08:19:51 +00:00
addrSpec := AddrSpec{}
if tcpAddr, ok := bindAddr[0].(*net.TCPAddr); ok && tcpAddr != nil {
addrSpec.IP = tcpAddr.IP
addrSpec.Port = tcpAddr.Port
} else if udpAddr, ok := bindAddr[0].(*net.UDPAddr); ok && udpAddr != nil {
addrSpec.IP = udpAddr.IP
addrSpec.Port = udpAddr.Port
} else {
addrSpec.IP = []byte{0, 0, 0, 0}
addrSpec.Port = 0
}
2020-04-19 15:40:14 +00:00
switch {
case addrSpec.FQDN != "":
2020-04-21 06:03:20 +00:00
head.addrType = ATYPDomain
2020-04-20 01:21:29 +00:00
head.Address.FQDN = addrSpec.FQDN
head.Address.Port = addrSpec.Port
2020-04-19 15:40:14 +00:00
case addrSpec.IP.To4() != nil:
2020-04-21 06:03:20 +00:00
head.addrType = ATYPIPv4
2020-04-20 01:21:29 +00:00
head.Address.IP = addrSpec.IP.To4()
head.Address.Port = addrSpec.Port
2020-04-19 15:40:14 +00:00
case addrSpec.IP.To16() != nil:
2020-04-21 06:03:20 +00:00
head.addrType = ATYPIPV6
2020-04-20 01:21:29 +00:00
head.Address.IP = addrSpec.IP.To16()
head.Address.Port = addrSpec.Port
2020-04-19 15:40:14 +00:00
default:
return fmt.Errorf("failed to format address[%v]", bindAddr)
}
2014-01-23 20:04:20 +00:00
2020-04-20 08:19:51 +00:00
}
2014-01-23 20:04:20 +00:00
// Send the message
2020-04-20 01:21:29 +00:00
_, err := w.Write(head.Bytes())
2014-01-23 20:04:20 +00:00
return err
}
2014-01-23 21:42:35 +00:00
type closeWriter interface {
CloseWrite() error
}
2020-04-22 02:15:40 +00:00
// Proxy is used to suffle data from src to destination, and sends errors
2014-01-23 21:42:35 +00:00
// down a dedicated channel
2020-04-22 02:15:40 +00:00
func (s *Server) Proxy(dst io.Writer, src io.Reader) error {
2020-04-20 01:41:06 +00:00
buf := s.bufferPool.Get()
defer s.bufferPool.Put(buf)
_, err := io.CopyBuffer(dst, src, buf[:cap(buf)])
if tcpConn, ok := dst.(closeWriter); ok {
tcpConn.CloseWrite()
}
return err
2014-01-23 21:42:35 +00:00
}