go-socks5/request.go

320 lines
9.1 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"
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-19 13:55:14 +00:00
var hd Header
var err error
2020-04-19 15:40:14 +00:00
// Read the version and command
2020-04-20 01:21:29 +00:00
tmp := make([]byte, headVERLen+headCMDLen)
2020-04-19 15:40:14 +00:00
if _, err = io.ReadFull(bufConn, tmp); err != nil {
return nil, fmt.Errorf("failed to get header version and command, %v", err)
2020-04-19 13:55:14 +00:00
}
2020-04-19 15:40:14 +00:00
hd.Version = tmp[0]
hd.Command = tmp[1]
2020-04-19 13:55:14 +00:00
if hd.Version != socks5Version && hd.Version != socks4Version {
2020-04-19 14:30:45 +00:00
return nil, fmt.Errorf("unrecognized SOCKS version[%d]", hd.Version)
2020-04-19 13:55:14 +00:00
}
if hd.Command != ConnectCommand && hd.Command != BindCommand && hd.Command != AssociateCommand {
2020-04-19 14:30:45 +00:00
return nil, fmt.Errorf("unrecognized command[%d]", hd.Command)
2020-04-19 13:55:14 +00:00
}
if hd.Version == socks4Version && hd.Command == AssociateCommand {
return nil, fmt.Errorf("wrong version for command")
2014-01-23 20:04:20 +00:00
}
2020-04-19 13:55:14 +00:00
if hd.Version == socks4Version {
2020-04-19 15:40:14 +00:00
// read port and ipv4 ip
2020-04-20 01:21:29 +00:00
tmp = make([]byte, headPORTLen+net.IPv4len)
2020-04-19 15:40:14 +00:00
if _, err = io.ReadFull(bufConn, tmp); err != nil {
return nil, fmt.Errorf("failed to get socks4 header port and ip, %v", err)
2020-04-19 15:40:14 +00:00
}
hd.Address.Port = buildPort(tmp[0], tmp[1])
hd.Address.IP = tmp[2:]
2020-04-19 13:55:14 +00:00
} else if hd.Version == socks5Version {
2020-04-20 01:21:29 +00:00
tmp = make([]byte, headRSVLen+headATYPLen)
2020-04-19 15:40:14 +00:00
if _, err = io.ReadFull(bufConn, tmp); err != nil {
return nil, fmt.Errorf("failed to get header RSV and address type, %v", err)
2020-04-19 15:40:14 +00:00
}
hd.Reserved = tmp[0]
hd.addrType = tmp[1]
2020-04-19 13:55:14 +00:00
switch hd.addrType {
case fqdnAddress:
2020-04-19 15:40:14 +00:00
if _, err = io.ReadFull(bufConn, tmp[:1]); err != nil {
return nil, fmt.Errorf("failed to get header, %v", err)
2020-04-19 15:40:14 +00:00
}
addrLen := int(tmp[0])
addr := make([]byte, addrLen+2)
if _, err = io.ReadFull(bufConn, addr); err != nil {
return nil, fmt.Errorf("failed to get header, %v", err)
2020-04-19 15:40:14 +00:00
}
hd.Address.FQDN = string(addr[:addrLen])
hd.Address.Port = buildPort(addr[addrLen], addr[addrLen+1])
2020-04-19 13:55:14 +00:00
case ipv4Address:
2020-04-20 01:21:29 +00:00
addr := make([]byte, net.IPv4len+2)
2020-04-19 15:40:14 +00:00
if _, err = io.ReadFull(bufConn, addr); err != nil {
return nil, fmt.Errorf("failed to get header, %v", err)
2020-04-19 15:40:14 +00:00
}
2020-04-20 01:21:29 +00:00
hd.Address.IP = addr[:net.IPv4len]
hd.Address.Port = buildPort(addr[net.IPv4len], addr[net.IPv4len+1])
2020-04-19 13:55:14 +00:00
case ipv6Address:
2020-04-20 01:21:29 +00:00
addr := make([]byte, net.IPv6len+2)
2020-04-19 15:40:14 +00:00
if _, err = io.ReadFull(bufConn, addr); err != nil {
return nil, fmt.Errorf("failed to get header, %v", err)
2020-04-19 15:40:14 +00:00
}
2020-04-20 01:21:29 +00:00
hd.Address.IP = addr[:net.IPv6len]
hd.Address.Port = buildPort(addr[net.IPv6len], addr[net.IPv6len+1])
2020-04-19 13:55:14 +00:00
default:
return nil, unrecognizedAddrType
}
}
2014-01-23 20:04:20 +00:00
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-19 15:40:14 +00:00
if err := sendReply(write, 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-19 15:40:14 +00:00
if err := sendReply(write, 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
2020-04-19 14:30:45 +00:00
func (s *Server) handleConnect(ctx context.Context, w 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 {
2020-04-19 15:40:14 +00:00
if err := sendReply(w, 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
}
2020-04-19 15:40:14 +00:00
if err := sendReply(w, 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
2020-04-19 15:40:14 +00:00
if err := sendReply(w, 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)
go proxy(target, req.bufConn, errCh)
2020-04-19 14:30:45 +00:00
go proxy(w, target, errCh)
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-19 14:30:45 +00:00
func (s *Server) handleBind(ctx context.Context, conn 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 {
2020-04-19 15:40:14 +00:00
if err := sendReply(conn, 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
2020-04-19 15:40:14 +00:00
if err := sendReply(conn, 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
2020-04-19 14:30:45 +00:00
func (s *Server) handleAssociate(ctx context.Context, conn 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 {
2020-04-19 15:40:14 +00:00
if err := sendReply(conn, 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
}
2014-01-23 21:42:35 +00:00
// TODO: Support associate
2020-04-19 15:40:14 +00:00
if err := sendReply(conn, commandNotSupported); err != nil {
return fmt.Errorf("failed to send reply, %v", err)
2014-01-23 21:42:35 +00:00
}
2014-01-23 19:29:13 +00:00
return nil
}
2014-01-23 20:04:20 +00:00
// sendReply is used to send a reply message
2020-04-19 15:40:14 +00:00
func sendReply(w io.Writer, 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:21:29 +00:00
head := Header{
Version: socks5Version,
Command: resp,
Reserved: 0,
}
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 if tcpAddr, ok := bindAddr[0].(*net.TCPAddr); !ok || tcpAddr == nil {
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 {
addrSpec := AddrSpec{IP: tcpAddr.IP, Port: tcpAddr.Port}
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
}
// 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 proxy(dst io.Writer, src io.Reader, errCh chan error) {
_, err := io.Copy(dst, src)
if tcpConn, ok := dst.(closeWriter); ok {
tcpConn.CloseWrite()
}
2014-01-23 22:07:39 +00:00
errCh <- err
2014-01-23 21:42:35 +00:00
}