go-socks5/request.go

411 lines
12 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-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-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 != "" {
2020-04-20 13:17:38 +00:00
ctx_, addr, err := s.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
2020-04-20 13:17:38 +00:00
if s.rewriter != nil {
ctx, req.realDestAddr = 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
if ctx_, ok := s.rules.Allow(ctx, req); !ok {
if err := sendReply(write, req.Header, ruleFailure); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
}
return fmt.Errorf("bind to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
}
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-19 14:30:45 +00:00
return s.handleConnect(ctx, write, req)
2020-04-21 06:03:20 +00:00
case CommandBind:
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-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: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
}
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: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 {
// 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)
}
}
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 12:41:58 +00:00
defer bindLn.Close()
2020-04-20 13:17:38 +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-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() {
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() {
targetUdp.Close()
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-20 13:17:38 +00:00
s.logger.Errorf("read data from bind listen address %s failed, %v", bindLn.LocalAddr(), err)
return
}
2020-04-20 13:17:38 +00:00
2020-04-20 12:41:58 +00:00
if n <= 4+net.IPv4len+2 { // no data
continue
}
// ignore RSV,FRAG
addrType := buf[3]
addrLen := 0
headLen := 0
var addrSpc AddrSpec
2020-04-21 06:03:20 +00:00
if addrType == ATYPIPv4 {
2020-04-20 12:41:58 +00:00
headLen = 4 + net.IPv4len + 2
addrLen = net.IPv4len
addrSpc.IP = make(net.IP, net.IPv4len)
copy(addrSpc.IP, buf[4:4+net.IPv4len])
addrSpc.Port = buildPort(buf[4+net.IPv4len], buf[4+net.IPv4len+1])
2020-04-21 06:03:20 +00:00
} else if addrType == ATYPIPV6 {
2020-04-20 12:41:58 +00:00
headLen = 4 + net.IPv6len + 2
if n <= headLen {
continue
}
addrLen = net.IPv6len
addrSpc.IP = make(net.IP, net.IPv6len)
copy(addrSpc.IP, buf[4:4+net.IPv6len])
addrSpc.Port = buildPort(buf[4+net.IPv6len], buf[4+net.IPv6len+1])
2020-04-21 06:03:20 +00:00
} else if addrType == ATYPDomain {
2020-04-20 12:41:58 +00:00
addrLen = int(buf[4])
headLen = 4 + 1 + addrLen + 2
if n <= headLen {
continue
}
str := make([]byte, addrLen)
copy(str, buf[5:5+addrLen])
addrSpc.FQDN = string(str)
addrSpc.Port = buildPort(buf[5+addrLen], buf[5+addrLen+1])
} else {
continue
}
2020-04-20 08:19:51 +00:00
// 把消息写给remote sever
2020-04-20 12:41:58 +00:00
if _, err := targetUdp.Write(buf[headLen:n]); err != nil {
2020-04-20 13:17:38 +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() {
targetUdp.Close()
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)]
n, remote, err := targetUdp.ReadFrom(buf)
2020-04-20 08:19:51 +00:00
if err != nil {
2020-04-20 13:17:38 +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-20 12:41:58 +00:00
tmpBufPool := s.bufferPool.Get()
proBuf := tmpBufPool
rAddr, _ := net.ResolveUDPAddr("udp", remote.String())
hi, lo := breakPort(rAddr.Port)
if rAddr.IP.To4() != nil {
2020-04-21 06:03:20 +00:00
proBuf = append(proBuf, []byte{0, 0, 0, ATYPIPv4}...)
2020-04-20 12:41:58 +00:00
proBuf = append(proBuf, rAddr.IP.To4()...)
proBuf = append(proBuf, hi, lo)
} else if rAddr.IP.To16() != nil {
2020-04-21 06:03:20 +00:00
proBuf = append(proBuf, []byte{0, 0, 0, ATYPIPV6}...)
2020-04-20 12:41:58 +00:00
proBuf = append(proBuf, rAddr.IP.To16()...)
proBuf = append(proBuf, hi, lo)
} else { // should never happen
continue
}
proBuf = append(proBuf, buf[:n]...)
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-20 12:41:58 +00:00
_, err := req.bufConn.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
// 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-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
}
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
}