go-socks5/request.go

364 lines
10 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 (
unrecognizedAddrType = fmt.Errorf("Unrecognized address type")
)
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
// AddrSpec of the the network that sent the request
RemoteAddr *AddrSpec
// AddrSpec of the desired destination
DestAddr *AddrSpec
// AddrSpec of the actual destination (might be affected by rewrite)
realDestAddr *AddrSpec
bufConn io.Reader
}
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-20 09:09:16 +00:00
if hd.Command != ConnectCommand && hd.Command != BindCommand && hd.Command != AssociateCommand {
return nil, fmt.Errorf("unrecognized command[%d]", hd.Command)
}
2020-04-19 13:37:05 +00:00
return &Request{
2020-04-19 15:40:14 +00:00
Header: hd,
2020-04-19 13:55:14 +00:00
DestAddr: &hd.Address,
bufConn: 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
dest := req.DestAddr
2014-01-24 00:46:32 +00:00
if dest.FQDN != "" {
ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
2014-01-23 21:11:58 +00:00
if err != nil {
2020-04-20 01:41:06 +00:00
if err := sendReply(write, req.Header, hostUnreachable); 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
}
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
req.realDestAddr = req.DestAddr
2014-01-24 00:55:08 +00:00
if s.config.Rewriter != nil {
ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req)
2014-01-24 00:55:08 +00:00
}
2014-01-24 00:46:32 +00:00
2014-01-23 20:04:20 +00:00
// Switch on the command
switch req.Command {
case ConnectCommand:
2020-04-19 14:30:45 +00:00
return s.handleConnect(ctx, write, req)
case BindCommand:
2020-04-19 14:30:45 +00:00
return s.handleBind(ctx, write, req)
case AssociateCommand:
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-20 01:41:06 +00:00
if err := sendReply(write, req.Header, commandNotSupported); 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:11:58 +00:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
if err := sendReply(writer, req.Header, ruleFailure); 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("connect to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
2014-01-23 21:11:58 +00:00
}
2014-01-23 21:42:35 +00:00
// Attempt to connect
2016-02-04 19:25:27 +00:00
dial := s.config.Dial
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
}
target, err := dial(ctx, "tcp", req.realDestAddr.Address())
2014-01-23 21:42:35 +00:00
if err != nil {
msg := err.Error()
resp := hostUnreachable
if strings.Contains(msg, "refused") {
resp = connectionRefused
} else if strings.Contains(msg, "network is unreachable") {
resp = networkUnreachable
}
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
}
return fmt.Errorf("connect to %v failed, %v", req.DestAddr, err)
2014-01-23 21:42:35 +00:00
}
defer target.Close()
// Send success
if err := sendReply(writer, req.Header, successReply, 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
s.submit(func() { errCh <- s.proxy(target, req.bufConn) })
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
func (s *Server) handleBind(ctx context.Context, writer io.Writer, req *Request) error {
2014-01-23 21:11:58 +00:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
if err := sendReply(writer, req.Header, ruleFailure); 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("bind to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
2014-01-23 21:11:58 +00:00
}
2014-01-23 21:42:35 +00:00
// TODO: Support bind
if err := sendReply(writer, req.Header, commandNotSupported); 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 {
/*
The SOCKS associate request/response is formed as follows:
+-----+------+-------+----------+----------+----------+
| RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
+-----+------+-------+----------+----------+----------+
| 2 | 1 | X'00' | 1 | 2 | Variable |
+-----+------+-------+----------+----------+----------+
*/
2014-01-23 21:11:58 +00:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
if err := sendReply(writer, req.Header, ruleFailure); err != nil {
2020-04-19 14:30:45 +00:00
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("associate to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
2014-01-23 21:11:58 +00:00
}
// Attempt to connect
dial := s.config.Dial
if dial == nil {
dial = func(ctx context.Context, net_, addr string) (net.Conn, error) {
return net.Dial(net_, addr)
}
}
target, err := dial(ctx, "udp", req.realDestAddr.Address())
if err != nil {
msg := err.Error()
resp := hostUnreachable
if strings.Contains(msg, "refused") {
resp = connectionRefused
} else if strings.Contains(msg, "network is unreachable") {
resp = networkUnreachable
}
if err := sendReply(writer, req.Header, resp); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
}
return fmt.Errorf("connect to %v failed, %v", req.DestAddr, err)
}
defer target.Close()
targetUdp, ok := target.(*net.UDPConn)
if !ok {
if err := sendReply(writer, req.Header, serverFailure); 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 {
if err := sendReply(writer, req.Header, serverFailure); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
}
return fmt.Errorf("listen udp failed, %v", err)
}
2020-04-20 08:19:51 +00:00
s.config.Logger.Errorf("target addr %v, listen addr: %s", targetUdp.RemoteAddr(), bindLn.LocalAddr())
// send BND.ADDR and BND.PORT, client must
2020-04-20 08:19:51 +00:00
if err = sendReply(writer, req.Header, successReply, 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() {
// read from client and write to remote server
2020-04-20 08:19:51 +00:00
conns := sync.Map{}
buf := s.bufferPool.Get()
defer s.bufferPool.Put(buf)
for {
2020-04-20 08:19:51 +00:00
n, srcAddr, err := bindLn.ReadFrom(buf[:cap(buf)])
if err != nil {
2020-04-20 08:19:51 +00:00
s.config.Logger.Errorf("read data from bind listen address %s failed, %v", bindLn.LocalAddr(), err)
return
}
2020-04-20 08:19:51 +00:00
// 把消息写给remote sever
if _, err := targetUdp.Write(buf[:n]); err != nil {
s.config.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
buf := s.bufferPool.Get()
defer s.bufferPool.Put(buf)
for {
n, _, err := targetUdp.ReadFrom(buf[:cap(buf)])
if err != nil {
s.config.Logger.Errorf("read data from remote %s failed, %v", targetUdp.RemoteAddr(), err)
return
}
if _, err := bindLn.WriteTo(buf[:n], srcAddr); err != nil {
s.config.Logger.Errorf("write data to client %s failed, %v", bindLn.LocalAddr(), err)
return
}
}
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 {
_, err := req.bufConn.Read(buf)
if err != nil {
return err
}
}
2014-01-23 19:29:13 +00:00
}
2014-01-23 20:04:20 +00:00
// sendReply is used to send a reply message
2020-04-20 01:41:06 +00:00
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-19 13:37:05 +00:00
head.addrType = ipv4Address
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 != "":
head.addrType = fqdnAddress
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:
head.addrType = ipv4Address
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:
head.addrType = ipv6Address
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
}
2014-01-23 21:42:35 +00:00
// proxy is used to suffle data from src to destination, and sends errors
// down a dedicated channel
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
}